@mastra/auth-workos 1.1.2 → 1.2.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,89 @@
1
1
  # @mastra/auth-workos
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Added `MastraFGAWorkos` provider for Fine-Grained Authorization using the WorkOS Authorization API. Implements `IFGAManager` interface with support for: ([#15410](https://github.com/mastra-ai/mastra/pull/15410))
8
+ - Authorization checks (`check()`, `require()`, `filterAccessible()`)
9
+ - Resource management (`createResource()`, `getResource()`, `listResources()`, `updateResource()`, `deleteResource()`)
10
+ - Role assignments (`assignRole()`, `removeRole()`, `listRoleAssignments()`)
11
+ - `resourceMapping` and `permissionMapping` for translating Mastra resource types and permissions to WorkOS resource type slugs and permission slugs
12
+ - Organization scoping that denies access when the user is not a member of the configured organization
13
+ - Bearer-token / verified JWT support that carries service-token FGA context such as organization membership IDs, while ignoring JWT-derived memberships unless organization claims are trusted
14
+ - Membership caching and batched accessible-resource discovery for lower per-request latency
15
+ - Tenant inference and parent-resource filtering for scoped access checks
16
+ - Paginated organization membership lookup and limited concurrent FGA checks when filtering accessible resources
17
+ - Typed permission constants accepted in `permissionMapping`
18
+
19
+ ```typescript
20
+ import { MastraFGAWorkos } from '@mastra/auth-workos';
21
+
22
+ const fga = new MastraFGAWorkos({
23
+ organizationId: 'org_abc123',
24
+ resourceMapping: {
25
+ agent: { fgaResourceType: 'team', deriveId: ctx => ctx.user.teamId },
26
+ },
27
+ permissionMapping: {
28
+ 'agents:execute': 'manage-workflows',
29
+ },
30
+ });
31
+
32
+ // Check whether a user can execute an agent
33
+ const allowed = await fga.check(user, {
34
+ resource: { type: 'agent', id: 'my-agent' },
35
+ permission: 'agents:execute',
36
+ });
37
+ ```
38
+
39
+ ### Patch Changes
40
+
41
+ - Updated dependencies [[`6dcd65f`](https://github.com/mastra-ai/mastra/commit/6dcd65f2a34069e6dc43ba35f1d11119b9b40bef), [`86c0298`](https://github.com/mastra-ai/mastra/commit/86c0298e647306423c842f9d5ac827bd616bd13d), [`c05c9a1`](https://github.com/mastra-ai/mastra/commit/c05c9a13230988cef6d438a62f37760f31927bc7), [`ca28c23`](https://github.com/mastra-ai/mastra/commit/ca28c232a2f18801a6cf20fe053479237b4d4fb0), [`e24aacb`](https://github.com/mastra-ai/mastra/commit/e24aacba07bd66f5d95b636dc24016fca26b52cf), [`7679a63`](https://github.com/mastra-ai/mastra/commit/7679a634eae8e8ca459fd87538fdf72b4389b07f), [`7fce309`](https://github.com/mastra-ai/mastra/commit/7fce30912b14170bfc41f0ac736cca0f39fe0cd4), [`1d64a76`](https://github.com/mastra-ai/mastra/commit/1d64a765861a0772ea187bab76e5ed37bf82d042), [`1c2dda8`](https://github.com/mastra-ai/mastra/commit/1c2dda805fbfccc0abf55d4cb20cc34402dc3f0c), [`c721164`](https://github.com/mastra-ai/mastra/commit/c7211643f7ac861f83b19a3757cc921487fc9d75), [`1b55954`](https://github.com/mastra-ai/mastra/commit/1b559541c1e08a10e49d01ffc51a634dfc37a286), [`7997c2e`](https://github.com/mastra-ai/mastra/commit/7997c2e55ddd121562a4098cd8d2b89c68433bf1), [`5adc55e`](https://github.com/mastra-ai/mastra/commit/5adc55e63407be8ee977914957d68bcc2a075ceb), [`7679a63`](https://github.com/mastra-ai/mastra/commit/7679a634eae8e8ca459fd87538fdf72b4389b07f), [`a0d9b6d`](https://github.com/mastra-ai/mastra/commit/a0d9b6d6b810aeaa9e177a0dcc99a4402e609634), [`e97ccb9`](https://github.com/mastra-ai/mastra/commit/e97ccb900f8b7a390ce82c9f8eb8d6eb2c5e3777), [`c5daf48`](https://github.com/mastra-ai/mastra/commit/c5daf48556e98c46ae06caf00f92c249912007e9), [`70017d7`](https://github.com/mastra-ai/mastra/commit/70017d72ab741b5d7040e2a15c251a317782e39e), [`cd96779`](https://github.com/mastra-ai/mastra/commit/cd9677937f113b2856dc8b9f3d4bdabcee58bb2e), [`b0c7022`](https://github.com/mastra-ai/mastra/commit/b0c70224f80dad7c0cdbfb22cbff22e0f75c064f), [`e4942bc`](https://github.com/mastra-ai/mastra/commit/e4942bc7fdc903572f7d84f26d5e15f9d39c763d)]:
42
+ - @mastra/core@1.32.0
43
+ - @mastra/auth@1.0.2
44
+
45
+ ## 1.2.0-alpha.0
46
+
47
+ ### Minor Changes
48
+
49
+ - Added `MastraFGAWorkos` provider for Fine-Grained Authorization using the WorkOS Authorization API. Implements `IFGAManager` interface with support for: ([#15410](https://github.com/mastra-ai/mastra/pull/15410))
50
+ - Authorization checks (`check()`, `require()`, `filterAccessible()`)
51
+ - Resource management (`createResource()`, `getResource()`, `listResources()`, `updateResource()`, `deleteResource()`)
52
+ - Role assignments (`assignRole()`, `removeRole()`, `listRoleAssignments()`)
53
+ - `resourceMapping` and `permissionMapping` for translating Mastra resource types and permissions to WorkOS resource type slugs and permission slugs
54
+ - Organization scoping that denies access when the user is not a member of the configured organization
55
+ - Bearer-token / verified JWT support that carries service-token FGA context such as organization membership IDs, while ignoring JWT-derived memberships unless organization claims are trusted
56
+ - Membership caching and batched accessible-resource discovery for lower per-request latency
57
+ - Tenant inference and parent-resource filtering for scoped access checks
58
+ - Paginated organization membership lookup and limited concurrent FGA checks when filtering accessible resources
59
+ - Typed permission constants accepted in `permissionMapping`
60
+
61
+ ```typescript
62
+ import { MastraFGAWorkos } from '@mastra/auth-workos';
63
+
64
+ const fga = new MastraFGAWorkos({
65
+ organizationId: 'org_abc123',
66
+ resourceMapping: {
67
+ agent: { fgaResourceType: 'team', deriveId: ctx => ctx.user.teamId },
68
+ },
69
+ permissionMapping: {
70
+ 'agents:execute': 'manage-workflows',
71
+ },
72
+ });
73
+
74
+ // Check whether a user can execute an agent
75
+ const allowed = await fga.check(user, {
76
+ resource: { type: 'agent', id: 'my-agent' },
77
+ permission: 'agents:execute',
78
+ });
79
+ ```
80
+
81
+ ### Patch Changes
82
+
83
+ - Updated dependencies [[`86c0298`](https://github.com/mastra-ai/mastra/commit/86c0298e647306423c842f9d5ac827bd616bd13d), [`7fce309`](https://github.com/mastra-ai/mastra/commit/7fce30912b14170bfc41f0ac736cca0f39fe0cd4), [`7997c2e`](https://github.com/mastra-ai/mastra/commit/7997c2e55ddd121562a4098cd8d2b89c68433bf1), [`e97ccb9`](https://github.com/mastra-ai/mastra/commit/e97ccb900f8b7a390ce82c9f8eb8d6eb2c5e3777), [`c5daf48`](https://github.com/mastra-ai/mastra/commit/c5daf48556e98c46ae06caf00f92c249912007e9), [`cd96779`](https://github.com/mastra-ai/mastra/commit/cd9677937f113b2856dc8b9f3d4bdabcee58bb2e)]:
84
+ - @mastra/core@1.32.0-alpha.2
85
+ - @mastra/auth@1.0.2
86
+
3
87
  ## 1.1.2
4
88
 
5
89
  ### Patch Changes
package/README.md CHANGED
@@ -1,13 +1,14 @@
1
1
  # @mastra/auth-workos
2
2
 
3
- A WorkOS authentication provider for Mastra, enabling seamless integration of WorkOS authentication and authorization in your applications.
3
+ A WorkOS integration for Mastra that supports authentication, role-based access control (RBAC), and Fine-Grained Authorization (FGA).
4
4
 
5
5
  ## Features
6
6
 
7
7
  - 🔐 WorkOS authentication integration
8
8
  - 👥 User management and organization membership support
9
9
  - 🔑 JWT token verification using WorkOS JWKS
10
- - 👮‍♂️ Role-based authorization with admin role support
10
+ - 👮 Role-based authorization with `MastraRBACWorkos`
11
+ - 🔒 Fine-Grained Authorization with `MastraFGAWorkos`
11
12
 
12
13
  ## Installation
13
14
 
@@ -23,7 +24,8 @@ pnpm add @mastra/auth-workos
23
24
 
24
25
  ```typescript
25
26
  import { Mastra } from '@mastra/core/mastra';
26
- import { MastraAuthWorkos } from '@mastra/auth-workos';
27
+ import { MastraFGAPermissions } from '@mastra/core/auth/ee';
28
+ import { MastraAuthWorkos, MastraFGAWorkos } from '@mastra/auth-workos';
27
29
 
28
30
  // Initialize with environment variables
29
31
  const auth = new MastraAuthWorkos();
@@ -32,6 +34,7 @@ const auth = new MastraAuthWorkos();
32
34
  const auth = new MastraAuthWorkos({
33
35
  apiKey: 'your_workos_api_key',
34
36
  clientId: 'your_workos_client_id',
37
+ redirectUri: 'https://your-app.com/auth/callback',
35
38
  });
36
39
 
37
40
  // Enable auth in Mastra
@@ -43,6 +46,36 @@ const mastra = new Mastra({
43
46
  });
44
47
  ```
45
48
 
49
+ `MastraAuthWorkos` authorizes any authenticated WorkOS user by default.
50
+
51
+ If you also use `MastraFGAWorkos`, set `fetchMemberships: true` so Mastra loads organization memberships during authentication:
52
+
53
+ ```typescript
54
+ const auth = new MastraAuthWorkos({
55
+ apiKey: 'your_workos_api_key',
56
+ clientId: 'your_workos_client_id',
57
+ redirectUri: 'https://your-app.com/auth/callback',
58
+ fetchMemberships: true,
59
+ });
60
+
61
+ const fga = new MastraFGAWorkos({
62
+ apiKey: 'your_workos_api_key',
63
+ clientId: 'your_workos_client_id',
64
+ resourceMapping: {
65
+ thread: {
66
+ fgaResourceType: 'workspace-thread',
67
+ deriveId: ({ resourceId, user }) => resourceId ?? user.id,
68
+ },
69
+ },
70
+ permissionMapping: {
71
+ [MastraFGAPermissions.MEMORY_READ]: 'read',
72
+ [MastraFGAPermissions.MEMORY_WRITE]: 'update',
73
+ },
74
+ });
75
+ ```
76
+
77
+ `thread` is the canonical Mastra resource key for memory authorization. `MastraFGAWorkos` also accepts the legacy alias `memory` for backward compatibility.
78
+
46
79
  ## Configuration
47
80
 
48
81
  The package requires the following configuration:
@@ -51,6 +84,7 @@ The package requires the following configuration:
51
84
 
52
85
  - `WORKOS_API_KEY`: Your WorkOS API key
53
86
  - `WORKOS_CLIENT_ID`: Your WorkOS client ID
87
+ - `WORKOS_REDIRECT_URI`: Your WorkOS redirect URI when you use the built-in AuthKit session flow
54
88
 
55
89
  ### Options
56
90
 
@@ -60,15 +94,45 @@ You can also provide these values directly when initializing the provider:
60
94
  interface MastraAuthWorkosOptions {
61
95
  apiKey?: string;
62
96
  clientId?: string;
97
+ redirectUri?: string;
98
+ fetchMemberships?: boolean;
99
+ trustJwtClaims?: boolean;
100
+ jwtClaims?: {
101
+ userId?: string;
102
+ workosId?: string;
103
+ email?: string;
104
+ name?: string;
105
+ organizationId?: string;
106
+ organizationMembershipId?: string;
107
+ };
63
108
  }
64
109
  ```
65
110
 
111
+ ### Service tokens and custom JWT claims
112
+
113
+ If your WorkOS JWT template includes custom claims for service principals or pre-resolved FGA context, you can map them directly into the authenticated `WorkOSUser`:
114
+
115
+ ```typescript
116
+ const auth = new MastraAuthWorkos({
117
+ apiKey: 'your_workos_api_key',
118
+ clientId: 'your_workos_client_id',
119
+ redirectUri: 'https://your-app.com/auth/callback',
120
+ trustJwtClaims: true,
121
+ jwtClaims: {
122
+ organizationMembershipId: 'urn:mastra:organization_membership_id',
123
+ organizationId: 'org_id',
124
+ },
125
+ });
126
+ ```
127
+
128
+ With `trustJwtClaims: true`, Mastra can authenticate verified bearer tokens from a WorkOS custom JWT template even when `workos.userManagement.getUser()` is not the right lookup path, such as machine-to-machine or service-account tokens.
129
+
66
130
  ## API
67
131
 
68
- ### `authenticateToken(token: string): Promise<WorkosUser | null>`
132
+ ### `authenticateToken(token: string, request): Promise<WorkOSUser | null>`
69
133
 
70
134
  Verifies a JWT token using WorkOS JWKS and returns the user information if valid.
71
135
 
72
- ### `authorizeUser(user: WorkosUser): Promise<boolean>`
136
+ ### `authorizeUser(user: WorkOSUser, request): Promise<boolean>`
73
137
 
74
- Checks if a user has admin privileges by verifying their organization memberships and roles.
138
+ Authorizes an authenticated WorkOS user. By default, this returns `true` when the user has the required identifiers. Override this method in a subclass if you need stricter authorization.
@@ -10,7 +10,9 @@ import { MastraAuthProvider } from '@mastra/core/server';
10
10
  import { AuthService } from '@workos/authkit-session';
11
11
  import type { AuthKitConfig } from '@workos/authkit-session';
12
12
  import { WorkOS } from '@workos-inc/node';
13
+ import type { OrganizationMembership } from '@workos-inc/node';
13
14
  import type { HonoRequest } from 'hono';
15
+ import { LRUCache } from 'lru-cache';
14
16
  import type { WorkOSUser, MastraAuthWorkosOptions } from './types.js';
15
17
  /**
16
18
  * Mastra authentication provider for WorkOS.
@@ -37,6 +39,11 @@ export declare class MastraAuthWorkos extends MastraAuthProvider<WorkOSUser> imp
37
39
  protected ssoConfig: MastraAuthWorkosOptions['sso'];
38
40
  protected authService: AuthService<Request, Response>;
39
41
  protected config: AuthKitConfig;
42
+ protected fetchMemberships: boolean;
43
+ protected trustJwtClaims: boolean;
44
+ protected jwtClaimOptions?: MastraAuthWorkosOptions['jwtClaims'];
45
+ protected mapJwtPayloadToUser?: MastraAuthWorkosOptions['mapJwtPayloadToUser'];
46
+ protected membershipCache: LRUCache<string, OrganizationMembership[]>;
40
47
  constructor(options?: MastraAuthWorkosOptions);
41
48
  /**
42
49
  * Authenticate a bearer token or session cookie.
@@ -61,6 +68,13 @@ export declare class MastraAuthWorkos extends MastraAuthProvider<WorkOSUser> imp
61
68
  * Get the URL to the user's profile page.
62
69
  */
63
70
  getUserProfileUrl(user: EEUser): string;
71
+ private getMemberships;
72
+ private attachMembershipsIfNeeded;
73
+ private getSingleMembershipOrganizationId;
74
+ private resolveJwtPayloadUser;
75
+ private buildUserFromJwtClaims;
76
+ private mergeJwtPayloadUser;
77
+ private readJwtClaim;
64
78
  /**
65
79
  * Get the URL to redirect users to for SSO login.
66
80
  */
@@ -1 +1 @@
1
- {"version":3,"file":"auth-provider.d.ts","sourceRoot":"","sources":["../src/auth-provider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EACV,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,OAAO,EACP,iBAAiB,EACjB,cAAc,EACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAEnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAqB,MAAM,yBAAyB,CAAC;AACzE,OAAO,KAAK,EAAE,aAAa,EA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IAiClF;;OAEG;IACH,oBAAoB,IAAI,cAAc;IAyBtC;;;;;OAKG;IACG,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAczF;;;;OAIG;IACG,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAMlE;;OAEG;IACG,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD;;OAEG;IACG,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAKjE;;OAEG;IACH,uBAAuB,CAAC,QAAQ,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI;IAMzD;;OAEG;IACH,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAU3D;;OAEG;IACH,sBAAsB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAShD;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;OAEG;IACH,cAAc,IAAI,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC;IAIhD;;OAEG;IACH,WAAW,IAAI,MAAM;IAIrB;;OAEG;IACH,cAAc,IAAI,MAAM;CAGzB"}
@@ -0,0 +1,158 @@
1
+ /**
2
+ * WorkOS FGA provider for Mastra.
3
+ *
4
+ * Integrates WorkOS Authorization API with Mastra's FGA interface
5
+ * for permission-based, resource-level authorization.
6
+ *
7
+ * @license Mastra Enterprise License - see ee/LICENSE
8
+ */
9
+ import type { IFGAManager, FGACheckParams, FGAResource, FGACreateResourceParams, FGAUpdateResourceParams, FGADeleteResourceParams, FGAListResourcesOptions, FGARoleAssignment, FGARoleParams, FGAListRoleAssignmentsOptions, MastraFGAPermissionInput } from '@mastra/core/auth/ee';
10
+ import type { MastraFGAWorkosOptions, WorkOSUser } from './types.js';
11
+ export declare class WorkOSFGAResourceNotFoundError extends Error {
12
+ readonly status = 404;
13
+ readonly resourceType: string;
14
+ readonly resourceId: string;
15
+ constructor(resourceType: string, resourceId: string);
16
+ }
17
+ export declare class WorkOSFGAMembershipResolutionError extends Error {
18
+ readonly status = 500;
19
+ readonly userId?: string;
20
+ constructor(user: WorkOSUser);
21
+ }
22
+ /**
23
+ * WorkOS FGA provider using the new Authorization API.
24
+ *
25
+ * Uses `resourceMapping` to translate Mastra resource types to WorkOS FGA resource types
26
+ * and `permissionMapping` to translate Mastra permissions to WorkOS permission slugs.
27
+ *
28
+ * @example Basic usage
29
+ * ```typescript
30
+ * import { MastraFGAWorkos } from '@mastra/auth-workos';
31
+ * import { MastraFGAPermissions } from '@mastra/core/auth/ee';
32
+ *
33
+ * const fga = new MastraFGAWorkos({
34
+ * resourceMapping: {
35
+ * agent: { fgaResourceType: 'team', deriveId: (ctx) => ctx.user.teamId },
36
+ * workflow: { fgaResourceType: 'team', deriveId: (ctx) => ctx.user.teamId },
37
+ * thread: { fgaResourceType: 'workspace-thread', deriveId: ({ resourceId }) => resourceId },
38
+ * },
39
+ * permissionMapping: {
40
+ * [MastraFGAPermissions.AGENTS_EXECUTE]: 'manage-workflows',
41
+ * [MastraFGAPermissions.WORKFLOWS_EXECUTE]: 'manage-workflows',
42
+ * [MastraFGAPermissions.MEMORY_READ]: 'read',
43
+ * [MastraFGAPermissions.MEMORY_WRITE]: 'update',
44
+ * },
45
+ * });
46
+ * ```
47
+ *
48
+ * @example With Mastra server config
49
+ * ```typescript
50
+ * const mastra = new Mastra({
51
+ * server: {
52
+ * auth: new MastraAuthWorkos({ ... }),
53
+ * fga: new MastraFGAWorkos({
54
+ * resourceMapping: { ... },
55
+ * permissionMapping: { ... },
56
+ * }),
57
+ * },
58
+ * });
59
+ * ```
60
+ */
61
+ export declare class MastraFGAWorkos implements IFGAManager<WorkOSUser> {
62
+ private workos;
63
+ private organizationId?;
64
+ private resourceMapping;
65
+ private permissionMapping;
66
+ constructor(options: MastraFGAWorkosOptions);
67
+ /**
68
+ * Check if a user has permission on a resource.
69
+ *
70
+ * Resolves the user's organization membership ID, maps the permission
71
+ * via `permissionMapping`, and delegates to `workos.authorization.check()`.
72
+ */
73
+ check(user: WorkOSUser, params: FGACheckParams): Promise<boolean>;
74
+ /**
75
+ * Require that a user has permission, throwing FGADeniedError if not.
76
+ */
77
+ require(user: WorkOSUser, params: FGACheckParams): Promise<void>;
78
+ /**
79
+ * Filter resources to only those the user has permission to access.
80
+ *
81
+ * Uses WorkOS `listResourcesForMembership()` when the resource mapping can
82
+ * resolve a parent resource from user context. This avoids one check per
83
+ * resource for list endpoints like agents/workflows/tools.
84
+ *
85
+ * Falls back to per-resource `check()` calls when no parent resource can be
86
+ * resolved from the configured mapping.
87
+ */
88
+ filterAccessible<T extends {
89
+ id: string;
90
+ }>(user: WorkOSUser, resources: T[], resourceType: string, permission: MastraFGAPermissionInput): Promise<T[]>;
91
+ /**
92
+ * Create an authorization resource in WorkOS.
93
+ */
94
+ createResource(params: FGACreateResourceParams): Promise<FGAResource>;
95
+ /**
96
+ * Get an authorization resource by ID.
97
+ */
98
+ getResource(resourceId: string): Promise<FGAResource>;
99
+ /**
100
+ * List authorization resources with optional filters.
101
+ */
102
+ listResources(options?: FGAListResourcesOptions): Promise<FGAResource[]>;
103
+ /**
104
+ * Update an authorization resource.
105
+ */
106
+ updateResource(params: FGAUpdateResourceParams): Promise<FGAResource>;
107
+ /**
108
+ * Delete an authorization resource.
109
+ */
110
+ deleteResource(params: FGADeleteResourceParams): Promise<void>;
111
+ /**
112
+ * Assign a role to an organization membership on a resource.
113
+ */
114
+ assignRole(params: FGARoleParams): Promise<FGARoleAssignment>;
115
+ /**
116
+ * Remove a role assignment.
117
+ */
118
+ removeRole(params: FGARoleParams): Promise<void>;
119
+ /**
120
+ * List role assignments for an organization membership.
121
+ */
122
+ listRoleAssignments(options: FGAListRoleAssignmentsOptions): Promise<FGARoleAssignment[]>;
123
+ /**
124
+ * Resolve the organization membership ID from a user object.
125
+ * Looks for organizationMembershipId, then finds membership matching
126
+ * configured organizationId, then falls back to first membership.
127
+ *
128
+ * Returns undefined if no membership can be resolved, which causes
129
+ * authorization checks to deny access. Enable `fetchMemberships: true`
130
+ * on MastraAuthWorkos to populate the memberships field.
131
+ */
132
+ private resolveOrganizationMembershipId;
133
+ /**
134
+ * Map a Mastra permission string to a WorkOS permission slug via permissionMapping.
135
+ * Falls back to the original permission if no mapping is found.
136
+ */
137
+ private resolvePermission;
138
+ /**
139
+ * Resolve the parent resource context needed for WorkOS resource discovery.
140
+ */
141
+ private resolveParentResource;
142
+ /**
143
+ * Resolve the FGA resource ID using resourceMapping's deriveId function.
144
+ * Falls back to the original resource ID if no mapping is found.
145
+ */
146
+ private resolveResourceId;
147
+ private buildCheckOptions;
148
+ private getResourceMapping;
149
+ /**
150
+ * List accessible child resources for a membership, following pagination.
151
+ */
152
+ private listAccessibleResourceExternalIds;
153
+ /**
154
+ * Map a WorkOS AuthorizationResource to Mastra's FGAResource type.
155
+ */
156
+ private mapAuthorizationResource;
157
+ }
158
+ //# sourceMappingURL=fga-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fga-provider.d.ts","sourceRoot":"","sources":["../src/fga-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,WAAW,EACX,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,aAAa,EACb,6BAA6B,EAC7B,wBAAwB,EACzB,MAAM,sBAAsB,CAAC;AAI9B,OAAO,KAAK,EAAE,sBAAsB,EAA2B,UAAU,EAAE,MAAM,SAAS,CAAC;AAI3F,qBAAa,8BAA+B,SAAQ,KAAK;IACvD,QAAQ,CAAC,MAAM,OAAO;IACtB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ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