@mastra/auth-workos 1.6.4 → 1.6.5-alpha.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.js CHANGED
@@ -1,1941 +1,2042 @@
1
- import { verifyJwks } from '@mastra/auth';
2
- import { CookieSessionStorage, AuthService, sessionEncryption } from '@workos/authkit-session';
3
- import { WorkOS, GeneratePortalLinkIntent } from '@workos-inc/node';
4
- import { LRUCache } from 'lru-cache';
5
-
6
- // ../../packages/_internal-core/dist/chunk-3M4SEWMI.js
7
- var RegisteredLogger = {
8
- LLM: "LLM"};
9
- var LogLevel = {
10
- DEBUG: "debug",
11
- INFO: "info",
12
- WARN: "warn",
13
- ERROR: "error"};
1
+ import { verifyJwks } from "@mastra/auth";
2
+ import { AuthService, CookieSessionStorage, sessionEncryption } from "@workos/authkit-session";
3
+ import { GeneratePortalLinkIntent, WorkOS } from "@workos-inc/node";
4
+ import { LRUCache } from "lru-cache";
5
+ //#region ../../packages/_internal-core/dist/logger/index.js
6
+ /**
7
+ * Export a tracked exception through the adapter sink, mirroring the
8
+ * DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`
9
+ * when present on a MastraError-like value). Never throws into the caller.
10
+ */
11
+ function exportTrackedException(ctx, error, metadata) {
12
+ if (!ctx?.options.export) return;
13
+ try {
14
+ const mastraError = error;
15
+ ctx.getLogSink()?.error(error.message, {
16
+ ...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},
17
+ ...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},
18
+ ...mastraError.category !== void 0 ? { category: mastraError.category } : {},
19
+ ...mastraError.details !== void 0 ? { details: mastraError.details } : {},
20
+ ...error.cause instanceof Error ? { cause: error.cause.message } : {},
21
+ ...metadata
22
+ });
23
+ } catch {}
24
+ }
25
+ /**
26
+ * Adapt IMastraLogger's variadic args into the structured `data` payload of
27
+ * an exported log record. Extracts the first plain object as data,
28
+ * serializes an Error arg, and collects remaining primitives under `args`
29
+ * so the derived record preserves all context from the native call.
30
+ */
31
+ function buildLogRecordData(args) {
32
+ const objectData = args.find((arg) => arg !== null && typeof arg === "object" && !Array.isArray(arg) && !(arg instanceof Error));
33
+ const errorArg = args.find((arg) => arg instanceof Error);
34
+ const extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);
35
+ if (!objectData && !errorArg && extraArgs.length === 0) return void 0;
36
+ return {
37
+ ...objectData ?? {},
38
+ ...errorArg ? { error: {
39
+ name: errorArg.name,
40
+ message: errorArg.message,
41
+ stack: errorArg.stack
42
+ } } : {},
43
+ ...extraArgs.length > 0 ? { args: extraArgs } : {}
44
+ };
45
+ }
46
+ const RegisteredLogger = {
47
+ AGENT: "AGENT",
48
+ OBSERVABILITY: "OBSERVABILITY",
49
+ AUTH: "AUTH",
50
+ BROWSER: "BROWSER",
51
+ NETWORK: "NETWORK",
52
+ WORKFLOW: "WORKFLOW",
53
+ LLM: "LLM",
54
+ TTS: "TTS",
55
+ VOICE: "VOICE",
56
+ VECTOR: "VECTOR",
57
+ BUNDLER: "BUNDLER",
58
+ DEPLOYER: "DEPLOYER",
59
+ MEMORY: "MEMORY",
60
+ STORAGE: "STORAGE",
61
+ EMBEDDINGS: "EMBEDDINGS",
62
+ MCP_SERVER: "MCP_SERVER",
63
+ SERVER_CACHE: "SERVER_CACHE",
64
+ SERVER: "SERVER",
65
+ WORKSPACE: "WORKSPACE",
66
+ CHANNEL: "CHANNEL"
67
+ };
68
+ const LogLevel = {
69
+ DEBUG: "debug",
70
+ INFO: "info",
71
+ WARN: "warn",
72
+ ERROR: "error",
73
+ NONE: "silent"
74
+ };
14
75
  var MastraLogger = class {
15
- name;
16
- level;
17
- transports;
18
- constructor(options = {}) {
19
- this.name = options.name || "Mastra";
20
- this.level = options.level || LogLevel.ERROR;
21
- this.transports = new Map(Object.entries(options.transports || {}));
22
- }
23
- getTransports() {
24
- return this.transports;
25
- }
26
- trackException(_error, _metadata) {
27
- }
28
- async listLogs(transportId, params) {
29
- if (!transportId || !this.transports.has(transportId)) {
30
- return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };
31
- }
32
- return this.transports.get(transportId).listLogs?.(params) ?? {
33
- logs: [],
34
- total: 0,
35
- page: params?.page ?? 1,
36
- perPage: params?.perPage ?? 100,
37
- hasMore: false
38
- };
39
- }
40
- async listLogsByRunId({
41
- transportId,
42
- runId,
43
- fromDate,
44
- toDate,
45
- logLevel,
46
- filters,
47
- page,
48
- perPage
49
- }) {
50
- if (!transportId || !this.transports.has(transportId) || !runId) {
51
- return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };
52
- }
53
- return this.transports.get(transportId).listLogsByRunId?.({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {
54
- logs: [],
55
- total: 0,
56
- page: page ?? 1,
57
- perPage: perPage ?? 100,
58
- hasMore: false
59
- };
60
- }
76
+ name;
77
+ level;
78
+ transports;
79
+ constructor(options = {}) {
80
+ this.name = options.name || "Mastra";
81
+ this.level = options.level || LogLevel.ERROR;
82
+ this.transports = new Map(Object.entries(options.transports || {}));
83
+ }
84
+ getTransports() {
85
+ return this.transports;
86
+ }
87
+ trackException(_error, _metadata) {}
88
+ async listLogs(transportId, params) {
89
+ if (!transportId || !this.transports.has(transportId)) return {
90
+ logs: [],
91
+ total: 0,
92
+ page: params?.page ?? 1,
93
+ perPage: params?.perPage ?? 100,
94
+ hasMore: false
95
+ };
96
+ return this.transports.get(transportId).listLogs?.(params) ?? {
97
+ logs: [],
98
+ total: 0,
99
+ page: params?.page ?? 1,
100
+ perPage: params?.perPage ?? 100,
101
+ hasMore: false
102
+ };
103
+ }
104
+ async listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {
105
+ if (!transportId || !this.transports.has(transportId) || !runId) return {
106
+ logs: [],
107
+ total: 0,
108
+ page: page ?? 1,
109
+ perPage: perPage ?? 100,
110
+ hasMore: false
111
+ };
112
+ return this.transports.get(transportId).listLogsByRunId?.({
113
+ runId,
114
+ fromDate,
115
+ toDate,
116
+ logLevel,
117
+ filters,
118
+ page,
119
+ perPage
120
+ }) ?? {
121
+ logs: [],
122
+ total: 0,
123
+ page: page ?? 1,
124
+ perPage: perPage ?? 100,
125
+ hasMore: false
126
+ };
127
+ }
61
128
  };
62
- var ConsoleLogger = class _ConsoleLogger extends MastraLogger {
63
- component;
64
- filter;
65
- constructor(options = {}) {
66
- super(options);
67
- this.component = options.component;
68
- this.filter = options.filter;
69
- }
70
- child(componentOrBindings) {
71
- const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
72
- return new _ConsoleLogger({
73
- name: this.name,
74
- level: this.level,
75
- component,
76
- filter: this.filter
77
- });
78
- }
79
- shouldLog(level, message, args) {
80
- if (!this.filter) return true;
81
- try {
82
- return this.filter({ component: this.component, level, message, args });
83
- } catch (e) {
84
- console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
85
- return true;
86
- }
87
- }
88
- prefix() {
89
- return this.component ? `[${this.component}] ` : "";
90
- }
91
- debug(message, ...args) {
92
- if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) {
93
- console.info(`${this.prefix()}${message}`, ...args);
94
- }
95
- }
96
- info(message, ...args) {
97
- if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) {
98
- console.info(`${this.prefix()}${message}`, ...args);
99
- }
100
- }
101
- warn(message, ...args) {
102
- if ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) {
103
- console.warn(`${this.prefix()}${message}`, ...args);
104
- }
105
- }
106
- error(message, ...args) {
107
- if ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) {
108
- console.error(`${this.prefix()}${message}`, ...args);
109
- }
110
- }
111
- async listLogs(_transportId, _params) {
112
- return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };
113
- }
114
- async listLogsByRunId(_args) {
115
- return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };
116
- }
129
+ var ConsoleLogger = class ConsoleLogger extends MastraLogger {
130
+ component;
131
+ filter;
132
+ #adapterContext;
133
+ constructor(options = {}) {
134
+ super(options);
135
+ this.component = options.component;
136
+ this.filter = options.filter;
137
+ }
138
+ /**
139
+ * Adapter hook (see `AdaptableLogger`): enables native trace correlation
140
+ * (trace_id/span_id appended to console output) and observability export
141
+ * derived from the same record. Called by Mastra during setup.
142
+ */
143
+ __attachObservability(ctx) {
144
+ this.#adapterContext = ctx;
145
+ }
146
+ child(componentOrBindings) {
147
+ const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
148
+ const child = new ConsoleLogger({
149
+ name: this.name,
150
+ level: this.level,
151
+ component,
152
+ filter: this.filter
153
+ });
154
+ if (this.#adapterContext) child.__attachObservability(this.#adapterContext);
155
+ return child;
156
+ }
157
+ /**
158
+ * Native-record correlation: when a span is active, append the trace
159
+ * fields object to the console args so every destination sees them.
160
+ */
161
+ #correlate(args) {
162
+ const ctx = this.#adapterContext;
163
+ if (!ctx?.options.correlation) return args;
164
+ try {
165
+ const fields = ctx.resolveTraceFields();
166
+ return fields ? [...args, fields] : args;
167
+ } catch {
168
+ return args;
169
+ }
170
+ }
171
+ /**
172
+ * Export the record derived from the same native call to observability.
173
+ * Mirrors DualLogger semantics: export is independent of the console
174
+ * level filter, and never throws into the caller.
175
+ */
176
+ #export(level, message, args) {
177
+ const ctx = this.#adapterContext;
178
+ if (!ctx?.options.export) return;
179
+ try {
180
+ ctx.getLogSink()?.[level](message, buildLogRecordData(args));
181
+ } catch {}
182
+ }
183
+ shouldLog(level, message, args) {
184
+ if (!this.filter) return true;
185
+ try {
186
+ return this.filter({
187
+ component: this.component,
188
+ level,
189
+ message,
190
+ args
191
+ });
192
+ } catch (e) {
193
+ console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
194
+ return true;
195
+ }
196
+ }
197
+ prefix() {
198
+ return this.component ? `[${this.component}] ` : "";
199
+ }
200
+ debug(message, ...args) {
201
+ if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));
202
+ this.#export("debug", message, args);
203
+ }
204
+ info(message, ...args) {
205
+ if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));
206
+ this.#export("info", message, args);
207
+ }
208
+ warn(message, ...args) {
209
+ if ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));
210
+ this.#export("warn", message, args);
211
+ }
212
+ error(message, ...args) {
213
+ if ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));
214
+ this.#export("error", message, args);
215
+ }
216
+ trackException(error, metadata) {
217
+ exportTrackedException(this.#adapterContext, error, metadata);
218
+ }
219
+ async listLogs(_transportId, _params) {
220
+ return {
221
+ logs: [],
222
+ total: 0,
223
+ page: _params?.page ?? 1,
224
+ perPage: _params?.perPage ?? 100,
225
+ hasMore: false
226
+ };
227
+ }
228
+ async listLogsByRunId(_args) {
229
+ return {
230
+ logs: [],
231
+ total: 0,
232
+ page: _args.page ?? 1,
233
+ perPage: _args.perPage ?? 100,
234
+ hasMore: false
235
+ };
236
+ }
117
237
  };
118
-
119
- // ../../packages/_internal-core/dist/base/index.js
238
+ //#endregion
239
+ //#region ../../packages/_internal-core/dist/base/index.js
120
240
  var MastraBase = class {
121
- component = RegisteredLogger.LLM;
122
- logger;
123
- name;
124
- #rawConfig;
125
- constructor({
126
- component,
127
- name,
128
- rawConfig
129
- }) {
130
- this.component = component || RegisteredLogger.LLM;
131
- this.name = name;
132
- this.#rawConfig = rawConfig;
133
- this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
134
- }
135
- /**
136
- * Returns the raw storage configuration this primitive was created from,
137
- * or undefined if it was created from code.
138
- */
139
- toRawConfig() {
140
- return this.#rawConfig;
141
- }
142
- /**
143
- * Sets the raw storage configuration for this primitive.
144
- * @internal
145
- */
146
- __setRawConfig(rawConfig) {
147
- this.#rawConfig = rawConfig;
148
- }
149
- /**
150
- * Set the logger for the agent
151
- * @param logger
152
- */
153
- __setLogger(logger) {
154
- this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
155
- }
241
+ component = RegisteredLogger.LLM;
242
+ logger;
243
+ name;
244
+ #rawConfig;
245
+ constructor({ component, name, rawConfig }) {
246
+ this.component = component || RegisteredLogger.LLM;
247
+ this.name = name;
248
+ this.#rawConfig = rawConfig;
249
+ this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
250
+ }
251
+ /**
252
+ * Returns the raw storage configuration this primitive was created from,
253
+ * or undefined if it was created from code.
254
+ */
255
+ toRawConfig() {
256
+ return this.#rawConfig;
257
+ }
258
+ /**
259
+ * Sets the raw storage configuration for this primitive.
260
+ * @internal
261
+ */
262
+ __setRawConfig(rawConfig) {
263
+ this.#rawConfig = rawConfig;
264
+ }
265
+ /**
266
+ * Set the logger for the agent
267
+ * @param logger
268
+ */
269
+ __setLogger(logger) {
270
+ this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
271
+ }
156
272
  };
157
-
158
- // ../../packages/_internals/auth/dist/chunk-NJOKT6V5.js
273
+ //#endregion
274
+ //#region ../../packages/_internals/auth/dist/provider/index.js
159
275
  var MastraAuthProvider = class extends MastraBase {
160
- protected;
161
- public;
162
- constructor(options) {
163
- super({ component: "AUTH", name: options?.name });
164
- if (options?.authorizeUser) {
165
- this.authorizeUser = options.authorizeUser.bind(this);
166
- }
167
- this.protected = options?.protected;
168
- this.public = options?.public;
169
- this.mapUserToResourceId = options?.mapUserToResourceId;
170
- }
171
- registerOptions(opts) {
172
- if (opts?.authorizeUser) {
173
- this.authorizeUser = opts.authorizeUser.bind(this);
174
- }
175
- if (opts?.mapUserToResourceId) {
176
- this.mapUserToResourceId = opts.mapUserToResourceId;
177
- }
178
- if (opts?.protected) {
179
- this.protected = opts.protected;
180
- }
181
- if (opts?.public) {
182
- this.public = opts.public;
183
- }
184
- }
276
+ protected;
277
+ public;
278
+ constructor(options) {
279
+ super({
280
+ component: "AUTH",
281
+ name: options?.name
282
+ });
283
+ if (options?.authorizeUser) this.authorizeUser = options.authorizeUser.bind(this);
284
+ this.protected = options?.protected;
285
+ this.public = options?.public;
286
+ this.mapUserToResourceId = options?.mapUserToResourceId;
287
+ }
288
+ registerOptions(opts) {
289
+ if (opts?.authorizeUser) this.authorizeUser = opts.authorizeUser.bind(this);
290
+ if (opts?.mapUserToResourceId) this.mapUserToResourceId = opts.mapUserToResourceId;
291
+ if (opts?.protected) this.protected = opts.protected;
292
+ if (opts?.public) this.public = opts.public;
293
+ }
185
294
  };
295
+ //#endregion
296
+ //#region src/session-storage.ts
297
+ /**
298
+ * Hono/Web Request session storage adapter for WorkOS AuthKit.
299
+ *
300
+ * Implements the SessionStorage interface for standard Web Request/Response
301
+ * objects used by Hono and other modern frameworks.
302
+ */
303
+ /**
304
+ * Session storage adapter for Web Request/Response (used by Hono).
305
+ *
306
+ * Extracts session cookies from standard Request objects and
307
+ * builds Set-Cookie headers for Response objects.
308
+ */
186
309
  var WebSessionStorage = class extends CookieSessionStorage {
187
- constructor(config) {
188
- super(config);
189
- }
190
- /**
191
- * Extract a named cookie from a Request.
192
- *
193
- * @param request - Standard Web Request object
194
- * @param name - Cookie name
195
- * @returns The decoded cookie value or null if not present
196
- */
197
- async getCookie(request, name) {
198
- const cookieHeader = request.headers.get("Cookie");
199
- if (!cookieHeader) {
200
- return null;
201
- }
202
- const cookies = cookieHeader.split(";").reduce(
203
- (acc, cookie) => {
204
- const [cookieName, ...valueParts] = cookie.trim().split("=");
205
- if (cookieName) {
206
- acc[cookieName] = decodeURIComponent(valueParts.join("="));
207
- }
208
- return acc;
209
- },
210
- {}
211
- );
212
- return cookies[name] ?? null;
213
- }
310
+ constructor(config) {
311
+ super(config);
312
+ }
313
+ /**
314
+ * Extract a named cookie from a Request.
315
+ *
316
+ * @param request - Standard Web Request object
317
+ * @param name - Cookie name
318
+ * @returns The decoded cookie value or null if not present
319
+ */
320
+ async getCookie(request, name) {
321
+ const cookieHeader = request.headers.get("Cookie");
322
+ if (!cookieHeader) return null;
323
+ return cookieHeader.split(";").reduce((acc, cookie) => {
324
+ const [cookieName, ...valueParts] = cookie.trim().split("=");
325
+ if (cookieName) acc[cookieName] = decodeURIComponent(valueParts.join("="));
326
+ return acc;
327
+ }, {})[name] ?? null;
328
+ }
214
329
  };
215
-
216
- // src/types.ts
330
+ //#endregion
331
+ //#region src/types.ts
332
+ /**
333
+ * Maps a WorkOS User to EEUser format.
334
+ */
217
335
  function mapWorkOSUserToEEUser(user) {
218
- return {
219
- id: user.id,
220
- email: user.email,
221
- name: user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName || user.email,
222
- avatarUrl: user.profilePictureUrl ?? void 0,
223
- metadata: {
224
- workosId: user.id,
225
- emailVerified: user.emailVerified,
226
- createdAt: user.createdAt
227
- }
228
- };
336
+ return {
337
+ id: user.id,
338
+ email: user.email,
339
+ name: user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName || user.email,
340
+ avatarUrl: user.profilePictureUrl ?? void 0,
341
+ metadata: {
342
+ workosId: user.id,
343
+ emailVerified: user.emailVerified,
344
+ createdAt: user.createdAt
345
+ }
346
+ };
229
347
  }
230
-
231
- // src/auth-provider.ts
348
+ //#endregion
349
+ //#region src/auth-provider.ts
232
350
  function getWebRequest(request) {
233
- if (request instanceof Request) {
234
- return request;
235
- }
236
- return request.raw instanceof Request ? request.raw : void 0;
351
+ if (request instanceof Request) return request;
352
+ return request.raw instanceof Request ? request.raw : void 0;
237
353
  }
238
- var DEV_COOKIE_PASSWORD = crypto.randomUUID() + crypto.randomUUID();
239
- var MEMBERSHIP_CACHE_TTL_MS = 60 * 1e3;
240
- var MEMBERSHIP_CACHE_MAX_SIZE = 1e3;
354
+ /**
355
+ * Default cookie password for development (MUST be overridden in production).
356
+ * Generated once per process to ensure consistency during dev.
357
+ */
358
+ const DEV_COOKIE_PASSWORD = crypto.randomUUID() + crypto.randomUUID();
359
+ const MEMBERSHIP_CACHE_TTL_MS = 60 * 1e3;
360
+ const MEMBERSHIP_CACHE_MAX_SIZE = 1e3;
361
+ /** Pull a stable error code out of a WorkOS SDK error, if present. */
241
362
  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;
363
+ if (!error || typeof error !== "object") return void 0;
364
+ const e = error;
365
+ if (typeof e.code === "string") return e.code;
366
+ if (e.rawData && typeof e.rawData.code === "string") return e.rawData.code;
247
367
  }
368
+ /**
369
+ * True when `createOrganization` rejected because an org is already bound to
370
+ * this `externalId` — i.e. a prior bootstrap created the org but never attached
371
+ * the membership. The org can be recovered via `getOrganizationByExternalId`.
372
+ */
248
373
  function isExternalIdAlreadyUsed(error) {
249
- return workosErrorCode(error) === "external_id_already_used";
374
+ return workosErrorCode(error) === "external_id_already_used";
250
375
  }
376
+ /**
377
+ * True when `createOrganizationMembership` rejected because the user is already
378
+ * a member of the org. Safe to ignore: the desired end state already holds.
379
+ */
251
380
  function isMembershipAlreadyExists(error) {
252
- const code = workosErrorCode(error);
253
- return code === "organization_membership_already_exists" || code === "entity_already_exists";
381
+ const code = workosErrorCode(error);
382
+ return code === "organization_membership_already_exists" || code === "entity_already_exists";
254
383
  }
384
+ /**
385
+ * Mastra authentication provider for WorkOS.
386
+ *
387
+ * Uses WorkOS AuthKit with encrypted cookie-based sessions.
388
+ * Sessions are stored in cookies, so they persist across server restarts.
389
+ *
390
+ * @example Basic usage with SSO
391
+ * ```typescript
392
+ * import { MastraAuthWorkos } from '@mastra/auth-workos';
393
+ *
394
+ * const auth = new MastraAuthWorkos({
395
+ * apiKey: process.env.WORKOS_API_KEY,
396
+ * clientId: process.env.WORKOS_CLIENT_ID,
397
+ * redirectUri: 'https://myapp.com/auth/callback',
398
+ * cookiePassword: process.env.WORKOS_COOKIE_PASSWORD, // min 32 chars
399
+ * });
400
+ * ```
401
+ */
255
402
  var MastraAuthWorkos = class extends MastraAuthProvider {
256
- workos;
257
- clientId;
258
- redirectUri;
259
- ssoConfig;
260
- authService;
261
- config;
262
- fetchMemberships;
263
- trustJwtClaims;
264
- jwtClaimOptions;
265
- mapJwtPayloadToUser;
266
- membershipCache;
267
- constructor(options) {
268
- super({ name: options?.name ?? "workos" });
269
- const apiKey = options?.apiKey ?? process.env.WORKOS_API_KEY;
270
- const clientId = options?.clientId ?? process.env.WORKOS_CLIENT_ID;
271
- const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI ?? "";
272
- const cookiePassword = options?.session?.cookiePassword ?? process.env.WORKOS_COOKIE_PASSWORD ?? DEV_COOKIE_PASSWORD;
273
- if (!apiKey || !clientId) {
274
- throw new Error(
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."
276
- );
277
- }
278
- if (cookiePassword.length < 32) {
279
- throw new Error(
280
- "Cookie password must be at least 32 characters. Set WORKOS_COOKIE_PASSWORD environment variable or provide session.cookiePassword option."
281
- );
282
- }
283
- this.clientId = clientId;
284
- this.redirectUri = redirectUri;
285
- this.ssoConfig = options?.sso;
286
- this.fetchMemberships = options?.fetchMemberships ?? false;
287
- this.trustJwtClaims = options?.trustJwtClaims ?? false;
288
- this.jwtClaimOptions = options?.jwtClaims;
289
- this.mapJwtPayloadToUser = options?.mapJwtPayloadToUser;
290
- this.membershipCache = new LRUCache({
291
- max: MEMBERSHIP_CACHE_MAX_SIZE,
292
- ttl: MEMBERSHIP_CACHE_TTL_MS
293
- });
294
- this.workos = new WorkOS(apiKey, { clientId });
295
- this.config = {
296
- clientId,
297
- apiKey,
298
- redirectUri,
299
- cookiePassword,
300
- cookieName: options?.session?.cookieName ?? "wos_session",
301
- cookieMaxAge: options?.session?.maxAge ?? 60 * 60 * 24 * 400,
302
- // 400 days
303
- cookieSameSite: options?.session?.sameSite?.toLowerCase(),
304
- cookieDomain: void 0,
305
- apiHttps: true
306
- };
307
- const storage = new WebSessionStorage(this.config);
308
- this.authService = new AuthService(this.config, storage, this.workos, sessionEncryption);
309
- this.registerOptions(options);
310
- if (cookiePassword === DEV_COOKIE_PASSWORD) {
311
- console.warn(
312
- "[WorkOS] Using auto-generated cookie password for development. Sessions will not persist across server restarts. Set WORKOS_COOKIE_PASSWORD for persistent sessions."
313
- );
314
- }
315
- }
316
- // ============================================================================
317
- // MastraAuthProvider Implementation
318
- // ============================================================================
319
- /**
320
- * Authenticate a bearer token or session cookie.
321
- *
322
- * Uses AuthKit's withAuth() for cookie-based sessions, falls back to
323
- * JWT verification for bearer tokens.
324
- */
325
- async authenticateToken(token, request) {
326
- try {
327
- const webRequest = getWebRequest(request);
328
- const { auth } = webRequest ? await this.authService.withAuth(webRequest) : { auth: { user: null } };
329
- if (auth.user) {
330
- let memberships;
331
- if (this.fetchMemberships) {
332
- try {
333
- memberships = await this.getMemberships(auth.user.id);
334
- } catch {
335
- }
336
- }
337
- return {
338
- ...mapWorkOSUserToEEUser(auth.user),
339
- workosId: auth.user.id,
340
- organizationId: auth.organizationId,
341
- memberships
342
- };
343
- }
344
- if (token) {
345
- const jwksUri = this.workos.userManagement.getJwksUrl(this.clientId);
346
- const payload = await verifyJwks(token, jwksUri);
347
- const jwtUser = this.resolveJwtPayloadUser(payload);
348
- if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) {
349
- return await this.attachMembershipsIfNeeded(jwtUser);
350
- }
351
- if (payload?.sub) {
352
- try {
353
- const user = await this.workos.userManagement.getUser(payload.sub);
354
- let memberships;
355
- if (this.fetchMemberships) {
356
- try {
357
- memberships = await this.getMemberships(user.id);
358
- } catch {
359
- memberships = void 0;
360
- }
361
- }
362
- return this.mergeJwtPayloadUser(
363
- {
364
- ...mapWorkOSUserToEEUser(user),
365
- workosId: user.id,
366
- organizationId: this.getSingleMembershipOrganizationId(memberships),
367
- memberships
368
- },
369
- jwtUser,
370
- { trustOrganizationClaims: this.trustJwtClaims }
371
- );
372
- } catch {
373
- if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) {
374
- return await this.attachMembershipsIfNeeded(jwtUser);
375
- }
376
- return null;
377
- }
378
- }
379
- if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) {
380
- return await this.attachMembershipsIfNeeded(jwtUser);
381
- }
382
- }
383
- return null;
384
- } catch {
385
- return null;
386
- }
387
- }
388
- /**
389
- * Authorize a user for access.
390
- */
391
- async authorizeUser(user) {
392
- return !!user?.id && !!user?.workosId;
393
- }
394
- // ============================================================================
395
- // IUserProvider Implementation
396
- // ============================================================================
397
- /**
398
- * Get the current user from the request using AuthKit session.
399
- */
400
- async getCurrentUser(request) {
401
- try {
402
- const { auth, refreshedSessionData } = await this.authService.withAuth(request);
403
- if (!auth.user) {
404
- return null;
405
- }
406
- let organizationId = auth.organizationId;
407
- let memberships;
408
- if (this.fetchMemberships) {
409
- try {
410
- memberships = await this.getMemberships(auth.user.id);
411
- organizationId ??= this.getSingleMembershipOrganizationId(memberships);
412
- } catch {
413
- }
414
- }
415
- const user = {
416
- ...mapWorkOSUserToEEUser(auth.user),
417
- workosId: auth.user.id,
418
- organizationId,
419
- memberships
420
- };
421
- if (refreshedSessionData) {
422
- user._refreshedSessionData = refreshedSessionData;
423
- }
424
- return user;
425
- } catch {
426
- return null;
427
- }
428
- }
429
- /**
430
- * Get a user by their ID.
431
- */
432
- async getUser(userId) {
433
- try {
434
- const user = await this.workos.userManagement.getUser(userId);
435
- return {
436
- ...mapWorkOSUserToEEUser(user),
437
- workosId: user.id
438
- };
439
- } catch {
440
- return null;
441
- }
442
- }
443
- /**
444
- * Get the URL to the user's profile page.
445
- */
446
- getUserProfileUrl(user) {
447
- return `/profile/${user.id}`;
448
- }
449
- async getMemberships(userId) {
450
- const cached = this.membershipCache.get(userId);
451
- if (cached) {
452
- return cached;
453
- }
454
- try {
455
- const response = await this.workos.userManagement.listOrganizationMemberships({
456
- userId
457
- });
458
- const memberships = await response.autoPagination();
459
- this.membershipCache.set(userId, memberships);
460
- return memberships;
461
- } catch (error) {
462
- this.membershipCache.delete(userId);
463
- throw error;
464
- }
465
- }
466
- async attachMembershipsIfNeeded(user) {
467
- if (!this.fetchMemberships || user.organizationMembershipId) {
468
- return user;
469
- }
470
- try {
471
- const memberships = await this.getMemberships(user.workosId);
472
- return {
473
- ...user,
474
- organizationId: user.organizationId ?? this.getSingleMembershipOrganizationId(memberships),
475
- memberships
476
- };
477
- } catch {
478
- return user;
479
- }
480
- }
481
- getSingleMembershipOrganizationId(memberships) {
482
- return memberships?.length === 1 ? memberships[0]?.organizationId : void 0;
483
- }
484
- resolveJwtPayloadUser(payload) {
485
- if (!payload) {
486
- return null;
487
- }
488
- const mappedClaims = this.buildUserFromJwtClaims(payload);
489
- const customMappedClaims = this.mapJwtPayloadToUser?.(payload) ?? void 0;
490
- const combined = {
491
- ...payload,
492
- ...mappedClaims ?? {},
493
- ...customMappedClaims ?? {}
494
- };
495
- const id = typeof combined.id === "string" ? combined.id : void 0;
496
- const workosId = typeof combined.workosId === "string" ? combined.workosId : id;
497
- if (!id || !workosId) {
498
- return null;
499
- }
500
- const metadata = combined.metadata && typeof combined.metadata === "object" && !Array.isArray(combined.metadata) ? combined.metadata : void 0;
501
- return {
502
- ...combined,
503
- id,
504
- workosId,
505
- email: typeof combined.email === "string" ? combined.email : void 0,
506
- name: typeof combined.name === "string" ? combined.name : typeof combined.email === "string" ? combined.email : id,
507
- organizationId: typeof combined.organizationId === "string" ? combined.organizationId : void 0,
508
- organizationMembershipId: typeof combined.organizationMembershipId === "string" ? combined.organizationMembershipId : void 0,
509
- metadata: {
510
- ...metadata ?? {},
511
- workosId,
512
- ...typeof combined.organizationId === "string" ? { organizationId: combined.organizationId } : {},
513
- ...typeof combined.organizationMembershipId === "string" ? { organizationMembershipId: combined.organizationMembershipId } : {}
514
- }
515
- };
516
- }
517
- buildUserFromJwtClaims(payload) {
518
- const userId = this.readJwtClaim(payload, this.jwtClaimOptions?.userId) ?? this.readJwtClaim(payload, "sub");
519
- const workosId = this.readJwtClaim(payload, this.jwtClaimOptions?.workosId) ?? userId;
520
- if (!userId || !workosId) {
521
- return null;
522
- }
523
- return {
524
- id: userId,
525
- workosId,
526
- email: this.readJwtClaim(payload, this.jwtClaimOptions?.email) ?? this.readJwtClaim(payload, "email"),
527
- name: this.readJwtClaim(payload, this.jwtClaimOptions?.name) ?? this.readJwtClaim(payload, "name"),
528
- organizationId: this.readJwtClaim(payload, this.jwtClaimOptions?.organizationId) ?? this.readJwtClaim(payload, "org_id"),
529
- organizationMembershipId: this.readJwtClaim(payload, this.jwtClaimOptions?.organizationMembershipId)
530
- };
531
- }
532
- mergeJwtPayloadUser(user, jwtUser, options) {
533
- if (!jwtUser) {
534
- return user;
535
- }
536
- const trustOrganizationClaims = options?.trustOrganizationClaims ?? true;
537
- const jwtMetadata = { ...jwtUser.metadata ?? {} };
538
- if (!trustOrganizationClaims) {
539
- delete jwtMetadata.organizationId;
540
- delete jwtMetadata.organizationMembershipId;
541
- }
542
- return {
543
- ...jwtUser,
544
- ...user,
545
- organizationId: trustOrganizationClaims ? jwtUser.organizationId ?? user.organizationId : user.organizationId,
546
- organizationMembershipId: trustOrganizationClaims ? jwtUser.organizationMembershipId ?? user.organizationMembershipId : user.organizationMembershipId,
547
- memberships: trustOrganizationClaims ? user.memberships ?? jwtUser.memberships : user.memberships,
548
- metadata: {
549
- ...jwtMetadata,
550
- ...user.metadata ?? {}
551
- }
552
- };
553
- }
554
- readJwtClaim(payload, claimPath) {
555
- if (!claimPath) {
556
- return void 0;
557
- }
558
- let current = payload;
559
- for (const segment of claimPath.split(".")) {
560
- if (!current || typeof current !== "object" || !(segment in current)) {
561
- return void 0;
562
- }
563
- current = current[segment];
564
- }
565
- return typeof current === "string" ? current : void 0;
566
- }
567
- // ============================================================================
568
- // ISSOProvider Implementation
569
- // ============================================================================
570
- /**
571
- * Get the URL to redirect users to for SSO login.
572
- */
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
- }
580
- const baseOptions = {
581
- clientId: this.clientId,
582
- redirectUri: resolvedRedirectUri,
583
- state
584
- };
585
- if (this.ssoConfig?.connection) {
586
- return this.workos.userManagement.getAuthorizationUrl({
587
- ...baseOptions,
588
- connectionId: this.ssoConfig.connection
589
- });
590
- } else if (this.ssoConfig?.provider) {
591
- return this.workos.userManagement.getAuthorizationUrl({
592
- ...baseOptions,
593
- provider: this.ssoConfig.provider
594
- });
595
- } else if (this.ssoConfig?.defaultOrganization) {
596
- return this.workos.userManagement.getAuthorizationUrl({
597
- ...baseOptions,
598
- organizationId: this.ssoConfig.defaultOrganization
599
- });
600
- }
601
- return this.workos.userManagement.getAuthorizationUrl({
602
- ...baseOptions,
603
- provider: "authkit"
604
- });
605
- }
606
- /**
607
- * Handle the OAuth callback from WorkOS.
608
- *
609
- * Uses WorkOS SDK's authenticateWithCode directly instead of AuthKit's handleCallback.
610
- * AuthKit's handleCallback requires PKCE cookies that must be set during getLoginUrl()
611
- * and read during handleCallback(), but our ISSOProvider interface separates these
612
- * calls across different requests without cookie propagation.
613
- *
614
- * This approach was the original implementation before commit 6e4d4f5cf3 introduced
615
- * a regression by switching to AuthKit's handleCallback with dummy Request/Response
616
- * objects that couldn't provide the required PKCE cookies.
617
- */
618
- async handleCallback(code, _state) {
619
- const authResponse = await this.workos.userManagement.authenticateWithCode({
620
- clientId: this.clientId,
621
- code
622
- });
623
- const user = {
624
- ...mapWorkOSUserToEEUser(authResponse.user),
625
- workosId: authResponse.user.id,
626
- organizationId: authResponse.organizationId
627
- };
628
- const sessionData = {
629
- accessToken: authResponse.accessToken,
630
- refreshToken: authResponse.refreshToken,
631
- user: authResponse.user,
632
- organizationId: authResponse.organizationId,
633
- impersonator: authResponse.impersonator
634
- };
635
- const cookiePassword = this.config.cookiePassword;
636
- const cookieName = this.config.cookieName ?? "wos_session";
637
- let cookies;
638
- if (cookiePassword) {
639
- const encryptedSession = await sessionEncryption.sealData(sessionData, { password: cookiePassword });
640
- const cookieOptions = [
641
- `${cookieName}=${encryptedSession}`,
642
- "Path=/",
643
- "HttpOnly",
644
- `SameSite=${this.config.cookieSameSite ?? "Lax"}`,
645
- process.env["NODE_ENV"] === "production" ? "Secure" : ""
646
- ].filter(Boolean).join("; ");
647
- cookies = [cookieOptions];
648
- }
649
- return {
650
- user,
651
- tokens: {
652
- accessToken: authResponse.accessToken,
653
- refreshToken: authResponse.refreshToken
654
- },
655
- cookies
656
- };
657
- }
658
- /**
659
- * Get the URL to redirect users to for logout.
660
- * Extracts session ID from the request's JWT to build a valid WorkOS logout URL.
661
- *
662
- * @param redirectUri - URL to redirect to after logout
663
- * @param request - Request containing session cookie (needed to extract sid)
664
- * @returns Logout URL or null if no active session
665
- */
666
- async getLogoutUrl(redirectUri, request) {
667
- if (!request) {
668
- return null;
669
- }
670
- try {
671
- const { auth } = await this.authService.withAuth(request);
672
- if (!auth.user) {
673
- return null;
674
- }
675
- const [, payloadBase64] = auth.accessToken.split(".");
676
- if (!payloadBase64) {
677
- return null;
678
- }
679
- const payload = JSON.parse(atob(payloadBase64));
680
- const sessionId = payload.sid;
681
- if (!sessionId) {
682
- return null;
683
- }
684
- return this.workos.userManagement.getLogoutUrl({ sessionId, returnTo: redirectUri });
685
- } catch {
686
- return null;
687
- }
688
- }
689
- /**
690
- * Get the configuration for rendering the login button.
691
- */
692
- getLoginButtonConfig() {
693
- let text = "Sign in";
694
- if (this.ssoConfig?.provider) {
695
- const providerNames = {
696
- GoogleOAuth: "Google",
697
- MicrosoftOAuth: "Microsoft",
698
- GitHubOAuth: "GitHub",
699
- AppleOAuth: "Apple"
700
- };
701
- const providerName = providerNames[this.ssoConfig.provider];
702
- if (providerName) {
703
- text = `Sign in with ${providerName}`;
704
- }
705
- }
706
- return {
707
- provider: "workos",
708
- text
709
- };
710
- }
711
- // ============================================================================
712
- // ISessionProvider Implementation
713
- // ============================================================================
714
- /**
715
- * Create a new session for a user.
716
- *
717
- * Note: With AuthKit, sessions are created via handleCallback.
718
- * This method is kept for interface compatibility.
719
- */
720
- async createSession(userId, metadata) {
721
- const sessionId = crypto.randomUUID();
722
- const now = /* @__PURE__ */ new Date();
723
- const expiresAt = new Date(now.getTime() + this.config.cookieMaxAge * 1e3);
724
- return {
725
- id: sessionId,
726
- userId,
727
- createdAt: now,
728
- expiresAt,
729
- metadata
730
- };
731
- }
732
- /**
733
- * Validate a session.
734
- *
735
- * With AuthKit, sessions are validated via withAuth().
736
- */
737
- async validateSession(_sessionId) {
738
- return null;
739
- }
740
- /**
741
- * Destroy a session.
742
- */
743
- async destroySession(_sessionId) {
744
- }
745
- /**
746
- * Refresh a session.
747
- */
748
- async refreshSession(_sessionId) {
749
- return null;
750
- }
751
- /**
752
- * Extract session ID from a request.
753
- */
754
- getSessionIdFromRequest(_request) {
755
- return null;
756
- }
757
- /**
758
- * Get response headers to set the session cookie.
759
- */
760
- getSessionHeaders(session) {
761
- const sessionCookie = session._sessionCookie;
762
- if (sessionCookie) {
763
- return { "Set-Cookie": Array.isArray(sessionCookie) ? sessionCookie[0] : sessionCookie };
764
- }
765
- return {};
766
- }
767
- /**
768
- * Get response headers to clear the session cookie.
769
- */
770
- getClearSessionHeaders() {
771
- const cookieParts = [`${this.config.cookieName}=`, "Path=/", "Max-Age=0", "HttpOnly"];
772
- return { "Set-Cookie": cookieParts.join("; ") };
773
- }
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
- // ============================================================================
874
- // Helper Methods
875
- // ============================================================================
876
- /**
877
- * Get the underlying WorkOS client.
878
- */
879
- getWorkOS() {
880
- return this.workos;
881
- }
882
- /**
883
- * Get the AuthKit AuthService.
884
- */
885
- getAuthService() {
886
- return this.authService;
887
- }
888
- /**
889
- * Get the configured client ID.
890
- */
891
- getClientId() {
892
- return this.clientId;
893
- }
894
- /**
895
- * Get the configured redirect URI.
896
- */
897
- getRedirectUri() {
898
- return this.redirectUri;
899
- }
403
+ workos;
404
+ clientId;
405
+ redirectUri;
406
+ ssoConfig;
407
+ authService;
408
+ config;
409
+ fetchMemberships;
410
+ trustJwtClaims;
411
+ jwtClaimOptions;
412
+ mapJwtPayloadToUser;
413
+ membershipCache;
414
+ constructor(options) {
415
+ super({ name: options?.name ?? "workos" });
416
+ const apiKey = options?.apiKey ?? process.env.WORKOS_API_KEY;
417
+ const clientId = options?.clientId ?? process.env.WORKOS_CLIENT_ID;
418
+ const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI ?? "";
419
+ const cookiePassword = options?.session?.cookiePassword ?? process.env.WORKOS_COOKIE_PASSWORD ?? DEV_COOKIE_PASSWORD;
420
+ if (!apiKey || !clientId) throw new Error("WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables.");
421
+ if (cookiePassword.length < 32) throw new Error("Cookie password must be at least 32 characters. Set WORKOS_COOKIE_PASSWORD environment variable or provide session.cookiePassword option.");
422
+ this.clientId = clientId;
423
+ this.redirectUri = redirectUri;
424
+ this.ssoConfig = options?.sso;
425
+ this.fetchMemberships = options?.fetchMemberships ?? false;
426
+ this.trustJwtClaims = options?.trustJwtClaims ?? false;
427
+ this.jwtClaimOptions = options?.jwtClaims;
428
+ this.mapJwtPayloadToUser = options?.mapJwtPayloadToUser;
429
+ this.membershipCache = new LRUCache({
430
+ max: MEMBERSHIP_CACHE_MAX_SIZE,
431
+ ttl: MEMBERSHIP_CACHE_TTL_MS
432
+ });
433
+ this.workos = new WorkOS(apiKey, { clientId });
434
+ this.config = {
435
+ clientId,
436
+ apiKey,
437
+ redirectUri,
438
+ cookiePassword,
439
+ cookieName: options?.session?.cookieName ?? "wos_session",
440
+ cookieMaxAge: options?.session?.maxAge ?? 3600 * 24 * 400,
441
+ cookieSameSite: options?.session?.sameSite?.toLowerCase(),
442
+ cookieDomain: void 0,
443
+ apiHttps: true
444
+ };
445
+ const storage = new WebSessionStorage(this.config);
446
+ this.authService = new AuthService(this.config, storage, this.workos, sessionEncryption);
447
+ this.registerOptions(options);
448
+ if (cookiePassword === DEV_COOKIE_PASSWORD) console.warn("[WorkOS] Using auto-generated cookie password for development. Sessions will not persist across server restarts. Set WORKOS_COOKIE_PASSWORD for persistent sessions.");
449
+ }
450
+ /**
451
+ * Authenticate a bearer token or session cookie.
452
+ *
453
+ * Uses AuthKit's withAuth() for cookie-based sessions, falls back to
454
+ * JWT verification for bearer tokens.
455
+ */
456
+ async authenticateToken(token, request) {
457
+ try {
458
+ const webRequest = getWebRequest(request);
459
+ const { auth } = webRequest ? await this.authService.withAuth(webRequest) : { auth: { user: null } };
460
+ if (auth.user) {
461
+ let memberships;
462
+ if (this.fetchMemberships) try {
463
+ memberships = await this.getMemberships(auth.user.id);
464
+ } catch {}
465
+ return {
466
+ ...mapWorkOSUserToEEUser(auth.user),
467
+ workosId: auth.user.id,
468
+ organizationId: auth.organizationId,
469
+ memberships
470
+ };
471
+ }
472
+ if (token) {
473
+ const payload = await verifyJwks(token, this.workos.userManagement.getJwksUrl(this.clientId));
474
+ const jwtUser = this.resolveJwtPayloadUser(payload);
475
+ if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) return await this.attachMembershipsIfNeeded(jwtUser);
476
+ if (payload?.sub) try {
477
+ const user = await this.workos.userManagement.getUser(payload.sub);
478
+ let memberships;
479
+ if (this.fetchMemberships) try {
480
+ memberships = await this.getMemberships(user.id);
481
+ } catch {
482
+ memberships = void 0;
483
+ }
484
+ return this.mergeJwtPayloadUser({
485
+ ...mapWorkOSUserToEEUser(user),
486
+ workosId: user.id,
487
+ organizationId: this.getSingleMembershipOrganizationId(memberships),
488
+ memberships
489
+ }, jwtUser, { trustOrganizationClaims: this.trustJwtClaims });
490
+ } catch {
491
+ if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) return await this.attachMembershipsIfNeeded(jwtUser);
492
+ return null;
493
+ }
494
+ if (this.trustJwtClaims && jwtUser?.id && jwtUser?.workosId) return await this.attachMembershipsIfNeeded(jwtUser);
495
+ }
496
+ return null;
497
+ } catch {
498
+ return null;
499
+ }
500
+ }
501
+ /**
502
+ * Authorize a user for access.
503
+ */
504
+ async authorizeUser(user) {
505
+ return !!user?.id && !!user?.workosId;
506
+ }
507
+ /**
508
+ * Get the current user from the request using AuthKit session.
509
+ */
510
+ async getCurrentUser(request) {
511
+ try {
512
+ const { auth, refreshedSessionData } = await this.authService.withAuth(request);
513
+ if (!auth.user) return null;
514
+ let organizationId = auth.organizationId;
515
+ let memberships;
516
+ if (this.fetchMemberships) try {
517
+ memberships = await this.getMemberships(auth.user.id);
518
+ organizationId ??= this.getSingleMembershipOrganizationId(memberships);
519
+ } catch {}
520
+ const user = {
521
+ ...mapWorkOSUserToEEUser(auth.user),
522
+ workosId: auth.user.id,
523
+ organizationId,
524
+ memberships
525
+ };
526
+ if (refreshedSessionData) user._refreshedSessionData = refreshedSessionData;
527
+ return user;
528
+ } catch {
529
+ return null;
530
+ }
531
+ }
532
+ /**
533
+ * Get a user by their ID.
534
+ */
535
+ async getUser(userId) {
536
+ try {
537
+ const user = await this.workos.userManagement.getUser(userId);
538
+ return {
539
+ ...mapWorkOSUserToEEUser(user),
540
+ workosId: user.id
541
+ };
542
+ } catch {
543
+ return null;
544
+ }
545
+ }
546
+ /**
547
+ * Get the URL to the user's profile page.
548
+ */
549
+ getUserProfileUrl(user) {
550
+ return `/profile/${user.id}`;
551
+ }
552
+ async getMemberships(userId) {
553
+ const cached = this.membershipCache.get(userId);
554
+ if (cached) return cached;
555
+ try {
556
+ const memberships = await (await this.workos.userManagement.listOrganizationMemberships({ userId })).autoPagination();
557
+ this.membershipCache.set(userId, memberships);
558
+ return memberships;
559
+ } catch (error) {
560
+ this.membershipCache.delete(userId);
561
+ throw error;
562
+ }
563
+ }
564
+ async attachMembershipsIfNeeded(user) {
565
+ if (!this.fetchMemberships || user.organizationMembershipId) return user;
566
+ try {
567
+ const memberships = await this.getMemberships(user.workosId);
568
+ return {
569
+ ...user,
570
+ organizationId: user.organizationId ?? this.getSingleMembershipOrganizationId(memberships),
571
+ memberships
572
+ };
573
+ } catch {
574
+ return user;
575
+ }
576
+ }
577
+ getSingleMembershipOrganizationId(memberships) {
578
+ return memberships?.length === 1 ? memberships[0]?.organizationId : void 0;
579
+ }
580
+ resolveJwtPayloadUser(payload) {
581
+ if (!payload) return null;
582
+ const mappedClaims = this.buildUserFromJwtClaims(payload);
583
+ const customMappedClaims = this.mapJwtPayloadToUser?.(payload) ?? void 0;
584
+ const combined = {
585
+ ...payload,
586
+ ...mappedClaims ?? {},
587
+ ...customMappedClaims ?? {}
588
+ };
589
+ const id = typeof combined.id === "string" ? combined.id : void 0;
590
+ const workosId = typeof combined.workosId === "string" ? combined.workosId : id;
591
+ if (!id || !workosId) return null;
592
+ const metadata = combined.metadata && typeof combined.metadata === "object" && !Array.isArray(combined.metadata) ? combined.metadata : void 0;
593
+ return {
594
+ ...combined,
595
+ id,
596
+ workosId,
597
+ email: typeof combined.email === "string" ? combined.email : void 0,
598
+ name: typeof combined.name === "string" ? combined.name : typeof combined.email === "string" ? combined.email : id,
599
+ organizationId: typeof combined.organizationId === "string" ? combined.organizationId : void 0,
600
+ organizationMembershipId: typeof combined.organizationMembershipId === "string" ? combined.organizationMembershipId : void 0,
601
+ metadata: {
602
+ ...metadata ?? {},
603
+ workosId,
604
+ ...typeof combined.organizationId === "string" ? { organizationId: combined.organizationId } : {},
605
+ ...typeof combined.organizationMembershipId === "string" ? { organizationMembershipId: combined.organizationMembershipId } : {}
606
+ }
607
+ };
608
+ }
609
+ buildUserFromJwtClaims(payload) {
610
+ const userId = this.readJwtClaim(payload, this.jwtClaimOptions?.userId) ?? this.readJwtClaim(payload, "sub");
611
+ const workosId = this.readJwtClaim(payload, this.jwtClaimOptions?.workosId) ?? userId;
612
+ if (!userId || !workosId) return null;
613
+ return {
614
+ id: userId,
615
+ workosId,
616
+ email: this.readJwtClaim(payload, this.jwtClaimOptions?.email) ?? this.readJwtClaim(payload, "email"),
617
+ name: this.readJwtClaim(payload, this.jwtClaimOptions?.name) ?? this.readJwtClaim(payload, "name"),
618
+ organizationId: this.readJwtClaim(payload, this.jwtClaimOptions?.organizationId) ?? this.readJwtClaim(payload, "org_id"),
619
+ organizationMembershipId: this.readJwtClaim(payload, this.jwtClaimOptions?.organizationMembershipId)
620
+ };
621
+ }
622
+ mergeJwtPayloadUser(user, jwtUser, options) {
623
+ if (!jwtUser) return user;
624
+ const trustOrganizationClaims = options?.trustOrganizationClaims ?? true;
625
+ const jwtMetadata = { ...jwtUser.metadata ?? {} };
626
+ if (!trustOrganizationClaims) {
627
+ delete jwtMetadata.organizationId;
628
+ delete jwtMetadata.organizationMembershipId;
629
+ }
630
+ return {
631
+ ...jwtUser,
632
+ ...user,
633
+ organizationId: trustOrganizationClaims ? jwtUser.organizationId ?? user.organizationId : user.organizationId,
634
+ organizationMembershipId: trustOrganizationClaims ? jwtUser.organizationMembershipId ?? user.organizationMembershipId : user.organizationMembershipId,
635
+ memberships: trustOrganizationClaims ? user.memberships ?? jwtUser.memberships : user.memberships,
636
+ metadata: {
637
+ ...jwtMetadata,
638
+ ...user.metadata ?? {}
639
+ }
640
+ };
641
+ }
642
+ readJwtClaim(payload, claimPath) {
643
+ if (!claimPath) return;
644
+ let current = payload;
645
+ for (const segment of claimPath.split(".")) {
646
+ if (!current || typeof current !== "object" || !(segment in current)) return;
647
+ current = current[segment];
648
+ }
649
+ return typeof current === "string" ? current : void 0;
650
+ }
651
+ /**
652
+ * Get the URL to redirect users to for SSO login.
653
+ */
654
+ getLoginUrl(redirectUri, state) {
655
+ const resolvedRedirectUri = redirectUri || this.redirectUri;
656
+ if (!resolvedRedirectUri) throw new Error("WorkOS redirect URI is required. Provide it in the options, set the WORKOS_REDIRECT_URI environment variable, or call init() with a publicUrl.");
657
+ const baseOptions = {
658
+ clientId: this.clientId,
659
+ redirectUri: resolvedRedirectUri,
660
+ state
661
+ };
662
+ if (this.ssoConfig?.connection) return this.workos.userManagement.getAuthorizationUrl({
663
+ ...baseOptions,
664
+ connectionId: this.ssoConfig.connection
665
+ });
666
+ else if (this.ssoConfig?.provider) return this.workos.userManagement.getAuthorizationUrl({
667
+ ...baseOptions,
668
+ provider: this.ssoConfig.provider
669
+ });
670
+ else if (this.ssoConfig?.defaultOrganization) return this.workos.userManagement.getAuthorizationUrl({
671
+ ...baseOptions,
672
+ organizationId: this.ssoConfig.defaultOrganization
673
+ });
674
+ return this.workos.userManagement.getAuthorizationUrl({
675
+ ...baseOptions,
676
+ provider: "authkit"
677
+ });
678
+ }
679
+ /**
680
+ * Handle the OAuth callback from WorkOS.
681
+ *
682
+ * Uses WorkOS SDK's authenticateWithCode directly instead of AuthKit's handleCallback.
683
+ * AuthKit's handleCallback requires PKCE cookies that must be set during getLoginUrl()
684
+ * and read during handleCallback(), but our ISSOProvider interface separates these
685
+ * calls across different requests without cookie propagation.
686
+ *
687
+ * This approach was the original implementation before commit 6e4d4f5cf3 introduced
688
+ * a regression by switching to AuthKit's handleCallback with dummy Request/Response
689
+ * objects that couldn't provide the required PKCE cookies.
690
+ */
691
+ async handleCallback(code, _state) {
692
+ const authResponse = await this.workos.userManagement.authenticateWithCode({
693
+ clientId: this.clientId,
694
+ code
695
+ });
696
+ const user = {
697
+ ...mapWorkOSUserToEEUser(authResponse.user),
698
+ workosId: authResponse.user.id,
699
+ organizationId: authResponse.organizationId
700
+ };
701
+ const sessionData = {
702
+ accessToken: authResponse.accessToken,
703
+ refreshToken: authResponse.refreshToken,
704
+ user: authResponse.user,
705
+ organizationId: authResponse.organizationId,
706
+ impersonator: authResponse.impersonator
707
+ };
708
+ const cookiePassword = this.config.cookiePassword;
709
+ const cookieName = this.config.cookieName ?? "wos_session";
710
+ let cookies;
711
+ if (cookiePassword) cookies = [[
712
+ `${cookieName}=${await sessionEncryption.sealData(sessionData, { password: cookiePassword })}`,
713
+ "Path=/",
714
+ "HttpOnly",
715
+ `SameSite=${this.config.cookieSameSite ?? "Lax"}`,
716
+ process.env["NODE_ENV"] === "production" ? "Secure" : ""
717
+ ].filter(Boolean).join("; ")];
718
+ return {
719
+ user,
720
+ tokens: {
721
+ accessToken: authResponse.accessToken,
722
+ refreshToken: authResponse.refreshToken
723
+ },
724
+ cookies
725
+ };
726
+ }
727
+ /**
728
+ * Get the URL to redirect users to for logout.
729
+ * Extracts session ID from the request's JWT to build a valid WorkOS logout URL.
730
+ *
731
+ * @param redirectUri - URL to redirect to after logout
732
+ * @param request - Request containing session cookie (needed to extract sid)
733
+ * @returns Logout URL or null if no active session
734
+ */
735
+ async getLogoutUrl(redirectUri, request) {
736
+ if (!request) return null;
737
+ try {
738
+ const { auth } = await this.authService.withAuth(request);
739
+ if (!auth.user) return null;
740
+ const [, payloadBase64] = auth.accessToken.split(".");
741
+ if (!payloadBase64) return null;
742
+ const sessionId = JSON.parse(atob(payloadBase64)).sid;
743
+ if (!sessionId) return null;
744
+ return this.workos.userManagement.getLogoutUrl({
745
+ sessionId,
746
+ returnTo: redirectUri
747
+ });
748
+ } catch {
749
+ return null;
750
+ }
751
+ }
752
+ /**
753
+ * Get the configuration for rendering the login button.
754
+ */
755
+ getLoginButtonConfig() {
756
+ let text = "Sign in";
757
+ if (this.ssoConfig?.provider) {
758
+ const providerName = {
759
+ GoogleOAuth: "Google",
760
+ MicrosoftOAuth: "Microsoft",
761
+ GitHubOAuth: "GitHub",
762
+ AppleOAuth: "Apple"
763
+ }[this.ssoConfig.provider];
764
+ if (providerName) text = `Sign in with ${providerName}`;
765
+ }
766
+ return {
767
+ provider: "workos",
768
+ text
769
+ };
770
+ }
771
+ /**
772
+ * Create a new session for a user.
773
+ *
774
+ * Note: With AuthKit, sessions are created via handleCallback.
775
+ * This method is kept for interface compatibility.
776
+ */
777
+ async createSession(userId, metadata) {
778
+ const sessionId = crypto.randomUUID();
779
+ const now = /* @__PURE__ */ new Date();
780
+ return {
781
+ id: sessionId,
782
+ userId,
783
+ createdAt: now,
784
+ expiresAt: new Date(now.getTime() + this.config.cookieMaxAge * 1e3),
785
+ metadata
786
+ };
787
+ }
788
+ /**
789
+ * Validate a session.
790
+ *
791
+ * With AuthKit, sessions are validated via withAuth().
792
+ */
793
+ async validateSession(_sessionId) {
794
+ return null;
795
+ }
796
+ /**
797
+ * Destroy a session.
798
+ */
799
+ async destroySession(_sessionId) {}
800
+ /**
801
+ * Refresh a session.
802
+ */
803
+ async refreshSession(_sessionId) {
804
+ return null;
805
+ }
806
+ /**
807
+ * Extract session ID from a request.
808
+ */
809
+ getSessionIdFromRequest(_request) {
810
+ return null;
811
+ }
812
+ /**
813
+ * Get response headers to set the session cookie.
814
+ */
815
+ getSessionHeaders(session) {
816
+ const sessionCookie = session._sessionCookie;
817
+ if (sessionCookie) return { "Set-Cookie": Array.isArray(sessionCookie) ? sessionCookie[0] : sessionCookie };
818
+ return {};
819
+ }
820
+ /**
821
+ * Get response headers to clear the session cookie.
822
+ */
823
+ getClearSessionHeaders() {
824
+ return { "Set-Cookie": [
825
+ `${this.config.cookieName}=`,
826
+ "Path=/",
827
+ "Max-Age=0",
828
+ "HttpOnly"
829
+ ].join("; ") };
830
+ }
831
+ /**
832
+ * One-time host initialization. Resolves the redirect URI from the host's
833
+ * `publicUrl` (`<publicUrl>/auth/callback`) when it was not provided in the
834
+ * options or via `WORKOS_REDIRECT_URI`.
835
+ *
836
+ * Fails at prepare time rather than handing WorkOS an empty redirect URI on
837
+ * the first login (which breaks hosted login with an opaque provider error).
838
+ */
839
+ async init(ctx) {
840
+ if (!this.redirectUri && ctx.publicUrl) {
841
+ this.redirectUri = `${ctx.publicUrl}/auth/callback`;
842
+ this.config.redirectUri = this.redirectUri;
843
+ const storage = new WebSessionStorage(this.config);
844
+ this.authService = new AuthService(this.config, storage, this.workos, sessionEncryption);
845
+ }
846
+ if (!this.redirectUri) throw new Error("MastraAuthWorkos could not resolve a callback URL: pass `redirectUri` (WORKOS_REDIRECT_URI) or configure the host `publicUrl`.");
847
+ }
848
+ /**
849
+ * Ensure the user belongs to a WorkOS organization, creating a personal org
850
+ * on first use when they have none.
851
+ *
852
+ * - ≥1 membership → return the first org id (they already belong somewhere;
853
+ * we never auto-create when a membership exists).
854
+ * - 0 memberships → create a personal org + membership and return its id.
855
+ *
856
+ * Idempotency: the create call carries `externalId = userId` and a stable
857
+ * `idempotencyKey`, so concurrent/retried first logins never create duplicate
858
+ * personal orgs. If a prior run created the org but never attached the
859
+ * membership, the create rejects with `external_id_already_used`; we recover
860
+ * the existing org by `externalId` and (re)attach the membership instead of
861
+ * failing.
862
+ *
863
+ * Best-effort: any WorkOS error (e.g. API key lacking org-create permission)
864
+ * is swallowed and returns `undefined`, leaving the user in their no-org
865
+ * state rather than failing the request.
866
+ */
867
+ async ensureOrganization(userId) {
868
+ try {
869
+ const firstExisting = (await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination())).find((m) => m.organizationId)?.organizationId;
870
+ if (firstExisting) return firstExisting;
871
+ const label = (await this.workos.userManagement.getUser(userId).catch(() => null))?.email ?? userId;
872
+ let organizationId;
873
+ try {
874
+ organizationId = (await this.workos.organizations.createOrganization({
875
+ name: `${label}'s org`,
876
+ externalId: userId,
877
+ metadata: {
878
+ mastraPersonalOrg: "true",
879
+ workosUserId: userId
880
+ }
881
+ }, { idempotencyKey: `mastra-personal-org:${userId}` })).id;
882
+ } catch (error) {
883
+ if (!isExternalIdAlreadyUsed(error)) throw error;
884
+ organizationId = (await this.workos.organizations.getOrganizationByExternalId(userId)).id;
885
+ }
886
+ try {
887
+ await this.workos.userManagement.createOrganizationMembership({
888
+ organizationId,
889
+ userId
890
+ });
891
+ } catch (error) {
892
+ if (!isMembershipAlreadyExists(error)) throw error;
893
+ }
894
+ this.membershipCache.delete(userId);
895
+ return organizationId;
896
+ } catch (error) {
897
+ console.warn(`[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.`, error);
898
+ return;
899
+ }
900
+ }
901
+ /**
902
+ * Whether the user holds an admin-equivalent role (`admin` or `owner`) in
903
+ * the organization. Provider errors resolve to `false`.
904
+ */
905
+ async isOrganizationAdmin(organizationId, userId) {
906
+ try {
907
+ const membership = (await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination())).find((item) => item.organizationId === organizationId);
908
+ if (!membership) return false;
909
+ return (membership.roles?.length ? membership.roles.map((role) => role.slug) : [membership.role.slug]).some((slug) => slug === "admin" || slug === "owner");
910
+ } catch {
911
+ return false;
912
+ }
913
+ }
914
+ /**
915
+ * Get the underlying WorkOS client.
916
+ */
917
+ getWorkOS() {
918
+ return this.workos;
919
+ }
920
+ /**
921
+ * Get the AuthKit AuthService.
922
+ */
923
+ getAuthService() {
924
+ return this.authService;
925
+ }
926
+ /**
927
+ * Get the configured client ID.
928
+ */
929
+ getClientId() {
930
+ return this.clientId;
931
+ }
932
+ /**
933
+ * Get the configured redirect URI.
934
+ */
935
+ getRedirectUri() {
936
+ return this.redirectUri;
937
+ }
900
938
  };
901
-
902
- // ../../packages/_internals/auth/dist/chunk-LZCWL5CT.js
939
+ //#endregion
940
+ //#region ../../packages/_internals/auth/dist/ee-DXvSoTl7.js
941
+ /**
942
+ * FGA enforcement utility for checking fine-grained authorization.
943
+ *
944
+ * @license Mastra Enterprise License - see ee/LICENSE
945
+ */
946
+ /**
947
+ * Error thrown when an FGA authorization check is denied.
948
+ */
903
949
  var FGADeniedError = class extends Error {
904
- user;
905
- resource;
906
- permission;
907
- status;
908
- constructor(user, resource, permission, reason) {
909
- const userId = user?.id || user?.workosId || "unknown";
910
- const permissionLabel = Array.isArray(permission) ? `any of [${permission.join(", ")}]` : permission;
911
- super(
912
- reason ? `FGA authorization denied: ${reason}` : `FGA authorization denied: user ${userId} cannot ${permissionLabel} on ${resource.type}:${resource.id}`
913
- );
914
- this.name = "FGADeniedError";
915
- this.user = user;
916
- this.resource = resource;
917
- this.permission = permission;
918
- this.status = 403;
919
- }
920
- };
921
- var RESOURCE_EXPANSIONS = {
922
- stored: [
923
- "stored-agents",
924
- "stored-mcp-clients",
925
- "stored-prompt-blocks",
926
- "stored-scorers",
927
- "stored-skills",
928
- "stored-workspaces"
929
- ]
950
+ user;
951
+ resource;
952
+ permission;
953
+ status;
954
+ constructor(user, resource, permission, reason) {
955
+ const userId = user?.id || user?.workosId || "unknown";
956
+ const permissionLabel = Array.isArray(permission) ? `any of [${permission.join(", ")}]` : permission;
957
+ super(reason ? `FGA authorization denied: ${reason}` : `FGA authorization denied: user ${userId} cannot ${permissionLabel} on ${resource.type}:${resource.id}`);
958
+ this.name = "FGADeniedError";
959
+ this.user = user;
960
+ this.resource = resource;
961
+ this.permission = permission;
962
+ this.status = 403;
963
+ }
930
964
  };
965
+ /**
966
+ * Compound resource keys that expand to a set of per-family resources.
967
+ * A granted `stored:<action>` is treated as matching any `stored-<family>:<action>`
968
+ * (and `stored:*` matches any `stored-<family>:*`).
969
+ */
970
+ const RESOURCE_EXPANSIONS = { stored: [
971
+ "stored-agents",
972
+ "stored-mcp-clients",
973
+ "stored-prompt-blocks",
974
+ "stored-scorers",
975
+ "stored-skills",
976
+ "stored-workspaces"
977
+ ] };
978
+ /**
979
+ * Check if a permission matches (including wildcard support).
980
+ *
981
+ * Permission format: `{resource}:{action}[:{resource-id}]`
982
+ *
983
+ * Examples:
984
+ * - `*` matches everything
985
+ * - `agents:*` matches `agents:read`, `agents:read:my-agent`
986
+ * - `*:read` matches `agents:read`, `workflows:read` (action across all resources)
987
+ * - `agents:read` matches `agents:read`, `agents:read:my-agent`
988
+ * - `agents:read:my-agent` matches only `agents:read:my-agent`
989
+ * - `agents:*:my-agent` matches `agents:read:my-agent`, `agents:write:my-agent`
990
+ *
991
+ * @param userPermission - Permission the user has
992
+ * @param requiredPermission - Permission being checked
993
+ * @returns True if permission matches
994
+ */
931
995
  function matchesPermission(userPermission, requiredPermission) {
932
- if (userPermission === "*") {
933
- return true;
934
- }
935
- const grantedParts = userPermission.split(":");
936
- const requiredParts = requiredPermission.split(":");
937
- const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
938
- if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) {
939
- const aliased = [requiredParts[0], ...grantedParts.slice(1)].join(":");
940
- return matchesPermission(aliased, requiredPermission);
941
- }
942
- if (grantedParts.length < 2 || requiredParts.length < 2) {
943
- return userPermission === requiredPermission;
944
- }
945
- const [grantedResource, grantedAction, grantedId] = grantedParts;
946
- const [requiredResource, requiredAction, requiredId] = requiredParts;
947
- if (grantedResource === "*") {
948
- if (grantedAction === "*") {
949
- if (grantedId === void 0) {
950
- return true;
951
- }
952
- return grantedId === requiredId;
953
- }
954
- if (grantedAction !== requiredAction) {
955
- return false;
956
- }
957
- if (grantedId === void 0) {
958
- return true;
959
- }
960
- return grantedId === requiredId;
961
- }
962
- if (grantedResource !== requiredResource) {
963
- return false;
964
- }
965
- if (grantedAction === "*") {
966
- if (grantedId === void 0) {
967
- return true;
968
- }
969
- return grantedId === requiredId;
970
- }
971
- if (grantedAction !== requiredAction) {
972
- return false;
973
- }
974
- if (grantedId === void 0) {
975
- return true;
976
- }
977
- return grantedId === requiredId;
996
+ if (userPermission === "*") return true;
997
+ const grantedParts = userPermission.split(":");
998
+ const requiredParts = requiredPermission.split(":");
999
+ const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
1000
+ if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) return matchesPermission([requiredParts[0], ...grantedParts.slice(1)].join(":"), requiredPermission);
1001
+ if (grantedParts.length < 2 || requiredParts.length < 2) return userPermission === requiredPermission;
1002
+ const [grantedResource, grantedAction, grantedId] = grantedParts;
1003
+ const [requiredResource, requiredAction, requiredId] = requiredParts;
1004
+ if (grantedResource === "*") {
1005
+ if (grantedAction === "*") {
1006
+ if (grantedId === void 0) return true;
1007
+ return grantedId === requiredId;
1008
+ }
1009
+ if (grantedAction !== requiredAction) return false;
1010
+ if (grantedId === void 0) return true;
1011
+ return grantedId === requiredId;
1012
+ }
1013
+ if (grantedResource !== requiredResource) return false;
1014
+ if (grantedAction === "*") {
1015
+ if (grantedId === void 0) return true;
1016
+ return grantedId === requiredId;
1017
+ }
1018
+ if (grantedAction !== requiredAction) return false;
1019
+ if (grantedId === void 0) return true;
1020
+ return grantedId === requiredId;
978
1021
  }
1022
+ /**
1023
+ * Resolve permissions from user roles using a role mapping.
1024
+ *
1025
+ * This function translates provider-defined roles (from WorkOS, Okta, etc.)
1026
+ * to Mastra permissions using a configurable mapping.
1027
+ *
1028
+ * @example
1029
+ * ```typescript
1030
+ * const roleMapping = {
1031
+ * "Engineering": ["agents:*", "workflows:*"],
1032
+ * "Product": ["agents:read"],
1033
+ * "_default": [],
1034
+ * };
1035
+ *
1036
+ * // User has "Engineering" and "QA" roles
1037
+ * const permissions = resolvePermissionsFromMapping(
1038
+ * ["Engineering", "QA"],
1039
+ * roleMapping
1040
+ * );
1041
+ * // Result: ["agents:*", "workflows:*"] (QA is unmapped, gets _default)
1042
+ * ```
1043
+ *
1044
+ * @param roles - User's roles from the identity provider
1045
+ * @param mapping - Role to permission mapping
1046
+ * @returns Array of resolved permissions
1047
+ */
979
1048
  function resolvePermissionsFromMapping(roles, mapping) {
980
- const permissions = /* @__PURE__ */ new Set();
981
- const defaultPerms = mapping["_default"] ?? [];
982
- for (const role of roles) {
983
- const rolePerms = mapping[role];
984
- if (rolePerms) {
985
- for (const perm of rolePerms) {
986
- permissions.add(perm);
987
- }
988
- } else {
989
- for (const perm of defaultPerms) {
990
- permissions.add(perm);
991
- }
992
- }
993
- }
994
- return Array.from(permissions);
1049
+ const permissions = /* @__PURE__ */ new Set();
1050
+ const defaultPerms = mapping["_default"] ?? [];
1051
+ for (const role of roles) {
1052
+ const rolePerms = mapping[role];
1053
+ if (rolePerms) for (const perm of rolePerms) permissions.add(perm);
1054
+ else for (const perm of defaultPerms) permissions.add(perm);
1055
+ }
1056
+ return Array.from(permissions);
995
1057
  }
996
- var DEFAULT_CACHE_TTL_MS = 60 * 1e3;
997
- var DEFAULT_CACHE_MAX_SIZE = 1e3;
1058
+ /**
1059
+ * @mastra/core/auth/ee
1060
+ *
1061
+ * Enterprise authentication capabilities for Mastra.
1062
+ * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
1063
+ *
1064
+ * @license Mastra Enterprise License - see ee/LICENSE
1065
+ * @packageDocumentation
1066
+ */
1067
+ //#endregion
1068
+ //#region src/rbac-provider.ts
1069
+ /**
1070
+ * WorkOS RBAC provider that maps organization roles to Mastra permissions.
1071
+ *
1072
+ * This provider fetches organization memberships from WorkOS and translates
1073
+ * role slugs into Mastra permissions using a configurable role mapping.
1074
+ *
1075
+ * @example Basic usage
1076
+ * ```typescript
1077
+ * import { MastraRBACWorkos } from '@mastra/auth-workos';
1078
+ *
1079
+ * const rbac = new MastraRBACWorkos({
1080
+ * apiKey: process.env.WORKOS_API_KEY,
1081
+ * clientId: process.env.WORKOS_CLIENT_ID,
1082
+ * roleMapping: {
1083
+ * admin: ['*'],
1084
+ * member: ['agents:read', 'workflows:*'],
1085
+ * viewer: ['agents:read', 'workflows:read'],
1086
+ * _default: [],
1087
+ * },
1088
+ * });
1089
+ * ```
1090
+ *
1091
+ * @example With specific organization
1092
+ * ```typescript
1093
+ * const rbac = new MastraRBACWorkos({
1094
+ * apiKey: process.env.WORKOS_API_KEY,
1095
+ * clientId: process.env.WORKOS_CLIENT_ID,
1096
+ * organizationId: 'org_123456',
1097
+ * roleMapping: {
1098
+ * admin: ['*'],
1099
+ * member: ['agents:*'],
1100
+ * },
1101
+ * });
1102
+ * ```
1103
+ */
1104
+ /** Default cache TTL in milliseconds (60 seconds) */
1105
+ const DEFAULT_CACHE_TTL_MS = 60 * 1e3;
1106
+ /** Default max cache size (number of users) */
1107
+ const DEFAULT_CACHE_MAX_SIZE = 1e3;
998
1108
  var MastraRBACWorkos = class {
999
- workos;
1000
- options;
1001
- /**
1002
- * Single cache for roles (the expensive WorkOS API call).
1003
- * Permissions are derived from roles on-the-fly (cheap, synchronous).
1004
- * Storing promises handles concurrent request deduplication.
1005
- */
1006
- rolesCache;
1007
- /**
1008
- * Expose roleMapping for middleware access.
1009
- * This allows the authorization middleware to resolve permissions
1010
- * without needing to call the async methods.
1011
- */
1012
- get roleMapping() {
1013
- return this.options.roleMapping;
1014
- }
1015
- /**
1016
- * Create a new WorkOS RBAC provider.
1017
- *
1018
- * @param options - RBAC configuration options
1019
- */
1020
- constructor(options) {
1021
- const apiKey = options.apiKey ?? process.env.WORKOS_API_KEY;
1022
- const clientId = options.clientId ?? process.env.WORKOS_CLIENT_ID;
1023
- if (!apiKey || !clientId) {
1024
- throw new Error(
1025
- "WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables."
1026
- );
1027
- }
1028
- this.workos = new WorkOS(apiKey, { clientId });
1029
- this.options = options;
1030
- this.rolesCache = new LRUCache({
1031
- max: options.cache?.maxSize ?? DEFAULT_CACHE_MAX_SIZE,
1032
- ttl: options.cache?.ttlMs ?? DEFAULT_CACHE_TTL_MS
1033
- });
1034
- }
1035
- /**
1036
- * Get all roles for a user from their WorkOS organization memberships.
1037
- *
1038
- * Fetches organization memberships from WorkOS and extracts role slugs.
1039
- * If an organizationId is configured, only returns roles from that organization.
1040
- * Otherwise, returns roles from all organizations the user belongs to.
1041
- *
1042
- * Results are cached and concurrent requests are deduplicated.
1043
- *
1044
- * @param user - WorkOS user to get roles for
1045
- * @returns Array of role slugs
1046
- */
1047
- async getRoles(user) {
1048
- if (user.memberships && user.memberships.length > 0) {
1049
- return this.extractRolesFromMemberships(user);
1050
- }
1051
- const cacheKey = user.workosId ?? user.id;
1052
- const cached = this.rolesCache.get(cacheKey);
1053
- if (cached) {
1054
- return cached;
1055
- }
1056
- const rolesPromise = this.fetchRolesFromWorkOS(user);
1057
- this.rolesCache.set(cacheKey, rolesPromise);
1058
- return rolesPromise;
1059
- }
1060
- /**
1061
- * Fetch roles from WorkOS API.
1062
- */
1063
- async fetchRolesFromWorkOS(user) {
1064
- try {
1065
- const memberships = await this.workos.userManagement.listOrganizationMemberships({
1066
- userId: user.workosId
1067
- });
1068
- const relevantMemberships = this.options.organizationId ? memberships.data.filter((m) => m.organizationId === this.options.organizationId) : memberships.data;
1069
- return relevantMemberships.map((m) => m.role.slug);
1070
- } catch {
1071
- return [];
1072
- }
1073
- }
1074
- /**
1075
- * Check if a user has a specific role.
1076
- *
1077
- * @param user - WorkOS user to check
1078
- * @param role - Role slug to check for
1079
- * @returns True if user has the role
1080
- */
1081
- async hasRole(user, role) {
1082
- const roles = await this.getRoles(user);
1083
- return roles.includes(role);
1084
- }
1085
- /**
1086
- * Get all permissions for a user by mapping their WorkOS roles.
1087
- *
1088
- * Uses the configured roleMapping to translate WorkOS role slugs
1089
- * into Mastra permission strings. Roles are cached; permissions
1090
- * are derived on-the-fly (cheap, synchronous operation).
1091
- *
1092
- * If the user has no roles (no organization memberships), the
1093
- * _default permissions from the role mapping are applied.
1094
- *
1095
- * @param user - WorkOS user to get permissions for
1096
- * @returns Array of permission strings
1097
- */
1098
- async getPermissions(user) {
1099
- const roles = await this.getRoles(user);
1100
- if (roles.length === 0) {
1101
- return this.options.roleMapping["_default"] ?? [];
1102
- }
1103
- return resolvePermissionsFromMapping(roles, this.options.roleMapping);
1104
- }
1105
- /**
1106
- * Check if a user has a specific permission.
1107
- *
1108
- * Uses wildcard matching to check if any of the user's permissions
1109
- * grant access to the required permission.
1110
- *
1111
- * @param user - WorkOS user to check
1112
- * @param permission - Permission to check for (e.g., 'agents:read')
1113
- * @returns True if user has the permission
1114
- */
1115
- async hasPermission(user, permission) {
1116
- const permissions = await this.getPermissions(user);
1117
- return permissions.some((p) => matchesPermission(p, permission));
1118
- }
1119
- /**
1120
- * Check if a user has ALL of the specified permissions.
1121
- *
1122
- * @param user - WorkOS user to check
1123
- * @param permissions - Array of permissions to check for
1124
- * @returns True if user has all permissions
1125
- */
1126
- async hasAllPermissions(user, permissions) {
1127
- const userPermissions = await this.getPermissions(user);
1128
- return permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));
1129
- }
1130
- /**
1131
- * Check if a user has ANY of the specified permissions.
1132
- *
1133
- * @param user - WorkOS user to check
1134
- * @param permissions - Array of permissions to check for
1135
- * @returns True if user has at least one permission
1136
- */
1137
- async hasAnyPermission(user, permissions) {
1138
- const userPermissions = await this.getPermissions(user);
1139
- return permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));
1140
- }
1141
- /**
1142
- * Get all available roles defined in the role mapping.
1143
- *
1144
- * Returns role IDs and names derived from the roleMapping keys,
1145
- * excluding the `_default` fallback entry.
1146
- */
1147
- async getAvailableRoles() {
1148
- return Object.keys(this.options.roleMapping).filter((key) => key !== "_default").map((key) => ({ id: key, name: key.charAt(0).toUpperCase() + key.slice(1) }));
1149
- }
1150
- /**
1151
- * Get resolved permissions for a specific role.
1152
- *
1153
- * Looks up the role in the roleMapping and returns its permissions.
1154
- */
1155
- async getPermissionsForRole(roleId) {
1156
- return resolvePermissionsFromMapping([roleId], this.options.roleMapping);
1157
- }
1158
- /**
1159
- * Clear the roles cache.
1160
- *
1161
- * Call this when system-wide role changes occur.
1162
- * For individual user changes, prefer clearUserCache() instead.
1163
- */
1164
- clearCache() {
1165
- this.rolesCache.clear();
1166
- }
1167
- /**
1168
- * Clear cached roles for a specific user.
1169
- *
1170
- * Call this when a user's roles change to ensure fresh permission resolution
1171
- * on their next request. This is more efficient than clearing the entire cache.
1172
- *
1173
- * @param userId - The user ID to clear from cache
1174
- */
1175
- clearUserCache(userId) {
1176
- this.rolesCache.delete(userId);
1177
- }
1178
- /**
1179
- * Get cache statistics for monitoring.
1180
- *
1181
- * @returns Object with cache size and max size
1182
- */
1183
- getCacheStats() {
1184
- return {
1185
- size: this.rolesCache.size,
1186
- maxSize: this.rolesCache.max
1187
- };
1188
- }
1189
- /**
1190
- * Extract role slugs from memberships attached to the user object.
1191
- *
1192
- * @param user - WorkOS user with memberships
1193
- * @returns Array of role slugs
1194
- */
1195
- extractRolesFromMemberships(user) {
1196
- if (!user.memberships) {
1197
- return [];
1198
- }
1199
- const relevantMemberships = this.options.organizationId ? user.memberships.filter((m) => m.organizationId === this.options.organizationId) : user.memberships;
1200
- return relevantMemberships.map((m) => m.role.slug);
1201
- }
1109
+ workos;
1110
+ options;
1111
+ /**
1112
+ * Single cache for roles (the expensive WorkOS API call).
1113
+ * Permissions are derived from roles on-the-fly (cheap, synchronous).
1114
+ * Storing promises handles concurrent request deduplication.
1115
+ */
1116
+ rolesCache;
1117
+ /**
1118
+ * Expose roleMapping for middleware access.
1119
+ * This allows the authorization middleware to resolve permissions
1120
+ * without needing to call the async methods.
1121
+ */
1122
+ get roleMapping() {
1123
+ return this.options.roleMapping;
1124
+ }
1125
+ /**
1126
+ * Create a new WorkOS RBAC provider.
1127
+ *
1128
+ * @param options - RBAC configuration options
1129
+ */
1130
+ constructor(options) {
1131
+ const apiKey = options.apiKey ?? process.env.WORKOS_API_KEY;
1132
+ const clientId = options.clientId ?? process.env.WORKOS_CLIENT_ID;
1133
+ if (!apiKey || !clientId) throw new Error("WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables.");
1134
+ this.workos = new WorkOS(apiKey, { clientId });
1135
+ this.options = options;
1136
+ this.rolesCache = new LRUCache({
1137
+ max: options.cache?.maxSize ?? DEFAULT_CACHE_MAX_SIZE,
1138
+ ttl: options.cache?.ttlMs ?? DEFAULT_CACHE_TTL_MS
1139
+ });
1140
+ }
1141
+ /**
1142
+ * Get all roles for a user from their WorkOS organization memberships.
1143
+ *
1144
+ * Fetches organization memberships from WorkOS and extracts role slugs.
1145
+ * If an organizationId is configured, only returns roles from that organization.
1146
+ * Otherwise, returns roles from all organizations the user belongs to.
1147
+ *
1148
+ * Results are cached and concurrent requests are deduplicated.
1149
+ *
1150
+ * @param user - WorkOS user to get roles for
1151
+ * @returns Array of role slugs
1152
+ */
1153
+ async getRoles(user) {
1154
+ if (user.memberships && user.memberships.length > 0) return this.extractRolesFromMemberships(user);
1155
+ const cacheKey = user.workosId ?? user.id;
1156
+ const cached = this.rolesCache.get(cacheKey);
1157
+ if (cached) return cached;
1158
+ const rolesPromise = this.fetchRolesFromWorkOS(user);
1159
+ this.rolesCache.set(cacheKey, rolesPromise);
1160
+ return rolesPromise;
1161
+ }
1162
+ /**
1163
+ * Fetch roles from WorkOS API.
1164
+ */
1165
+ async fetchRolesFromWorkOS(user) {
1166
+ try {
1167
+ const memberships = await this.workos.userManagement.listOrganizationMemberships({ userId: user.workosId });
1168
+ return (this.options.organizationId ? memberships.data.filter((m) => m.organizationId === this.options.organizationId) : memberships.data).map((m) => m.role.slug);
1169
+ } catch {
1170
+ return [];
1171
+ }
1172
+ }
1173
+ /**
1174
+ * Check if a user has a specific role.
1175
+ *
1176
+ * @param user - WorkOS user to check
1177
+ * @param role - Role slug to check for
1178
+ * @returns True if user has the role
1179
+ */
1180
+ async hasRole(user, role) {
1181
+ return (await this.getRoles(user)).includes(role);
1182
+ }
1183
+ /**
1184
+ * Get all permissions for a user by mapping their WorkOS roles.
1185
+ *
1186
+ * Uses the configured roleMapping to translate WorkOS role slugs
1187
+ * into Mastra permission strings. Roles are cached; permissions
1188
+ * are derived on-the-fly (cheap, synchronous operation).
1189
+ *
1190
+ * If the user has no roles (no organization memberships), the
1191
+ * _default permissions from the role mapping are applied.
1192
+ *
1193
+ * @param user - WorkOS user to get permissions for
1194
+ * @returns Array of permission strings
1195
+ */
1196
+ async getPermissions(user) {
1197
+ const roles = await this.getRoles(user);
1198
+ if (roles.length === 0) return this.options.roleMapping["_default"] ?? [];
1199
+ return resolvePermissionsFromMapping(roles, this.options.roleMapping);
1200
+ }
1201
+ /**
1202
+ * Check if a user has a specific permission.
1203
+ *
1204
+ * Uses wildcard matching to check if any of the user's permissions
1205
+ * grant access to the required permission.
1206
+ *
1207
+ * @param user - WorkOS user to check
1208
+ * @param permission - Permission to check for (e.g., 'agents:read')
1209
+ * @returns True if user has the permission
1210
+ */
1211
+ async hasPermission(user, permission) {
1212
+ return (await this.getPermissions(user)).some((p) => matchesPermission(p, permission));
1213
+ }
1214
+ /**
1215
+ * Check if a user has ALL of the specified permissions.
1216
+ *
1217
+ * @param user - WorkOS user to check
1218
+ * @param permissions - Array of permissions to check for
1219
+ * @returns True if user has all permissions
1220
+ */
1221
+ async hasAllPermissions(user, permissions) {
1222
+ const userPermissions = await this.getPermissions(user);
1223
+ return permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));
1224
+ }
1225
+ /**
1226
+ * Check if a user has ANY of the specified permissions.
1227
+ *
1228
+ * @param user - WorkOS user to check
1229
+ * @param permissions - Array of permissions to check for
1230
+ * @returns True if user has at least one permission
1231
+ */
1232
+ async hasAnyPermission(user, permissions) {
1233
+ const userPermissions = await this.getPermissions(user);
1234
+ return permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));
1235
+ }
1236
+ /**
1237
+ * Get all available roles defined in the role mapping.
1238
+ *
1239
+ * Returns role IDs and names derived from the roleMapping keys,
1240
+ * excluding the `_default` fallback entry.
1241
+ */
1242
+ async getAvailableRoles() {
1243
+ return Object.keys(this.options.roleMapping).filter((key) => key !== "_default").map((key) => ({
1244
+ id: key,
1245
+ name: key.charAt(0).toUpperCase() + key.slice(1)
1246
+ }));
1247
+ }
1248
+ /**
1249
+ * Get resolved permissions for a specific role.
1250
+ *
1251
+ * Looks up the role in the roleMapping and returns its permissions.
1252
+ */
1253
+ async getPermissionsForRole(roleId) {
1254
+ return resolvePermissionsFromMapping([roleId], this.options.roleMapping);
1255
+ }
1256
+ /**
1257
+ * Clear the roles cache.
1258
+ *
1259
+ * Call this when system-wide role changes occur.
1260
+ * For individual user changes, prefer clearUserCache() instead.
1261
+ */
1262
+ clearCache() {
1263
+ this.rolesCache.clear();
1264
+ }
1265
+ /**
1266
+ * Clear cached roles for a specific user.
1267
+ *
1268
+ * Call this when a user's roles change to ensure fresh permission resolution
1269
+ * on their next request. This is more efficient than clearing the entire cache.
1270
+ *
1271
+ * @param userId - The user ID to clear from cache
1272
+ */
1273
+ clearUserCache(userId) {
1274
+ this.rolesCache.delete(userId);
1275
+ }
1276
+ /**
1277
+ * Get cache statistics for monitoring.
1278
+ *
1279
+ * @returns Object with cache size and max size
1280
+ */
1281
+ getCacheStats() {
1282
+ return {
1283
+ size: this.rolesCache.size,
1284
+ maxSize: this.rolesCache.max
1285
+ };
1286
+ }
1287
+ /**
1288
+ * Extract role slugs from memberships attached to the user object.
1289
+ *
1290
+ * @param user - WorkOS user with memberships
1291
+ * @returns Array of role slugs
1292
+ */
1293
+ extractRolesFromMemberships(user) {
1294
+ if (!user.memberships) return [];
1295
+ return (this.options.organizationId ? user.memberships.filter((m) => m.organizationId === this.options.organizationId) : user.memberships).map((m) => m.role.slug);
1296
+ }
1202
1297
  };
1203
- var FILTER_ACCESSIBLE_CHECK_CONCURRENCY = 5;
1298
+ //#endregion
1299
+ //#region src/fga-provider.ts
1300
+ /**
1301
+ * WorkOS FGA provider for Mastra.
1302
+ *
1303
+ * Integrates WorkOS Authorization API with Mastra's FGA interface
1304
+ * for permission-based, resource-level authorization.
1305
+ *
1306
+ * @license Mastra Enterprise License - see ee/LICENSE
1307
+ */
1308
+ const FILTER_ACCESSIBLE_CHECK_CONCURRENCY = 5;
1204
1309
  function isWorkOSResourceNotFoundError(error) {
1205
- return error?.status === 404 || error?.code === "entity_not_found";
1310
+ return error?.status === 404 || error?.code === "entity_not_found";
1206
1311
  }
1207
1312
  var WorkOSFGAResourceNotFoundError = class extends Error {
1208
- status = 404;
1209
- resourceType;
1210
- resourceId;
1211
- constructor(resourceType, resourceId) {
1212
- super(
1213
- `[MastraFGAWorkos] Resource '${resourceType}/${resourceId}' is not registered in WorkOS. Create the '${resourceType}' resource type in your WorkOS dashboard, then register '${resourceId}' using MastraFGAWorkos.createResource() or your seed script. See https://workos.com/docs/fga for setup instructions.`
1214
- );
1215
- this.name = "WorkOSFGAResourceNotFoundError";
1216
- this.resourceType = resourceType;
1217
- this.resourceId = resourceId;
1218
- }
1313
+ status = 404;
1314
+ resourceType;
1315
+ resourceId;
1316
+ constructor(resourceType, resourceId) {
1317
+ super(`[MastraFGAWorkos] Resource '${resourceType}/${resourceId}' is not registered in WorkOS. Create the '${resourceType}' resource type in your WorkOS dashboard, then register '${resourceId}' using MastraFGAWorkos.createResource() or your seed script. See https://workos.com/docs/fga for setup instructions.`);
1318
+ this.name = "WorkOSFGAResourceNotFoundError";
1319
+ this.resourceType = resourceType;
1320
+ this.resourceId = resourceId;
1321
+ }
1219
1322
  };
1220
1323
  var WorkOSFGAMembershipResolutionError = class extends Error {
1221
- status = 500;
1222
- userId;
1223
- constructor(user) {
1224
- super(
1225
- "[MastraFGAWorkos] Cannot resolve organization membership for user <redacted>. Ensure fetchMemberships is enabled on MastraAuthWorkos or provide organizationMembershipId on the user."
1226
- );
1227
- this.name = "WorkOSFGAMembershipResolutionError";
1228
- this.userId = user?.id ? "<redacted>" : void 0;
1229
- }
1324
+ status = 500;
1325
+ userId;
1326
+ constructor(user) {
1327
+ super("[MastraFGAWorkos] Cannot resolve organization membership for user <redacted>. Ensure fetchMemberships is enabled on MastraAuthWorkos or provide organizationMembershipId on the user.");
1328
+ this.name = "WorkOSFGAMembershipResolutionError";
1329
+ this.userId = user?.id ? "<redacted>" : void 0;
1330
+ }
1230
1331
  };
1332
+ /**
1333
+ * WorkOS FGA provider using the new Authorization API.
1334
+ *
1335
+ * Uses `resourceMapping` to translate Mastra resource types to WorkOS FGA resource types
1336
+ * and `permissionMapping` to translate Mastra permissions to WorkOS permission slugs.
1337
+ *
1338
+ * @example Basic usage
1339
+ * ```typescript
1340
+ * import { MastraFGAWorkos } from '@mastra/auth-workos';
1341
+ * import { MastraFGAPermissions } from '@internal/auth/ee';
1342
+ *
1343
+ * const fga = new MastraFGAWorkos({
1344
+ * resourceMapping: {
1345
+ * agent: { fgaResourceType: 'team', deriveId: (ctx) => ctx.user.teamId },
1346
+ * workflow: { fgaResourceType: 'team', deriveId: (ctx) => ctx.user.teamId },
1347
+ * thread: { fgaResourceType: 'workspace-thread', deriveId: ({ resourceId }) => resourceId },
1348
+ * },
1349
+ * permissionMapping: {
1350
+ * [MastraFGAPermissions.AGENTS_EXECUTE]: 'manage-workflows',
1351
+ * [MastraFGAPermissions.WORKFLOWS_EXECUTE]: 'manage-workflows',
1352
+ * [MastraFGAPermissions.MEMORY_READ]: 'read',
1353
+ * [MastraFGAPermissions.MEMORY_WRITE]: 'update',
1354
+ * },
1355
+ * });
1356
+ * ```
1357
+ *
1358
+ * @example With Mastra server config
1359
+ * ```typescript
1360
+ * const mastra = new Mastra({
1361
+ * server: {
1362
+ * auth: new MastraAuthWorkos({ ... }),
1363
+ * fga: new MastraFGAWorkos({
1364
+ * resourceMapping: { ... },
1365
+ * permissionMapping: { ... },
1366
+ * }),
1367
+ * },
1368
+ * });
1369
+ * ```
1370
+ */
1231
1371
  var MastraFGAWorkos = class {
1232
- workos;
1233
- organizationId;
1234
- resourceMapping;
1235
- permissionMapping;
1236
- requireForProtectedRoutes;
1237
- auditProtectedRoutes;
1238
- resolveRouteFGA;
1239
- validatePermissions;
1240
- constructor(options) {
1241
- const apiKey = options.apiKey ?? process.env.WORKOS_API_KEY;
1242
- const clientId = options.clientId ?? process.env.WORKOS_CLIENT_ID;
1243
- if (!apiKey || !clientId) {
1244
- throw new Error(
1245
- "WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables."
1246
- );
1247
- }
1248
- this.workos = new WorkOS(apiKey, { clientId });
1249
- this.organizationId = options.organizationId;
1250
- this.resourceMapping = options.resourceMapping ?? {};
1251
- this.permissionMapping = options.permissionMapping ?? {};
1252
- this.requireForProtectedRoutes = options.requireForProtectedRoutes;
1253
- this.auditProtectedRoutes = options.auditProtectedRoutes;
1254
- this.resolveRouteFGA = options.resolveRouteFGA;
1255
- this.validatePermissions = options.validatePermissions;
1256
- }
1257
- // ──────────────────────────────────────────────────────────────
1258
- // IFGAProvider — Read-only checks
1259
- // ──────────────────────────────────────────────────────────────
1260
- /**
1261
- * Check if a user has permission on a resource.
1262
- *
1263
- * Resolves the user's organization membership ID, maps the permission
1264
- * via `permissionMapping`, and delegates to `workos.authorization.check()`.
1265
- *
1266
- * When `params.permission` is an array, ANY-of semantics apply: returns true
1267
- * if any single permission in the array authorizes the user.
1268
- */
1269
- async check(user, params) {
1270
- const permissions = Array.isArray(params.permission) ? params.permission : [params.permission];
1271
- if (permissions.length === 0) return false;
1272
- for (const permission of permissions) {
1273
- const checkOptions = this.buildCheckOptions(user, { ...params, permission });
1274
- if (!checkOptions) continue;
1275
- try {
1276
- const result = await this.workos.authorization.check(checkOptions);
1277
- if (result.authorized) return true;
1278
- } catch (error) {
1279
- if (isWorkOSResourceNotFoundError(error)) continue;
1280
- throw error;
1281
- }
1282
- }
1283
- return false;
1284
- }
1285
- /**
1286
- * Require that a user has permission, throwing FGADeniedError if not.
1287
- *
1288
- * When `params.permission` is an array, ANY-of semantics apply: passes if any
1289
- * single permission authorizes the user; throws if none do.
1290
- */
1291
- async require(user, params) {
1292
- const permissions = Array.isArray(params.permission) ? params.permission : [params.permission];
1293
- if (permissions.length === 0) {
1294
- throw new FGADeniedError(user, params.resource, params.permission);
1295
- }
1296
- let lastError;
1297
- for (const permission of permissions) {
1298
- const checkOptions = this.buildCheckOptions(
1299
- user,
1300
- { ...params, permission },
1301
- { strictMembershipResolution: true }
1302
- );
1303
- if (!checkOptions) continue;
1304
- try {
1305
- const result = await this.workos.authorization.check(checkOptions);
1306
- if (result.authorized) return;
1307
- } catch (error) {
1308
- if (error instanceof FGADeniedError) throw error;
1309
- if (isWorkOSResourceNotFoundError(error)) continue;
1310
- lastError = error;
1311
- }
1312
- }
1313
- if (lastError) throw lastError;
1314
- throw new FGADeniedError(user, params.resource, params.permission);
1315
- }
1316
- /**
1317
- * Filter resources to only those the user has permission to access.
1318
- *
1319
- * Uses WorkOS `listResourcesForMembership()` when the resource mapping can
1320
- * resolve a parent resource from user context. This avoids one check per
1321
- * resource for list endpoints like agents/workflows/tools.
1322
- *
1323
- * Falls back to per-resource `check()` calls when no parent resource can be
1324
- * resolved from the configured mapping.
1325
- */
1326
- async filterAccessible(user, resources, resourceType, permission) {
1327
- if (resources.length === 0) return [];
1328
- const membershipId = this.resolveOrganizationMembershipId(user);
1329
- if (!membershipId) return [];
1330
- const permissionSlug = this.resolvePermission(permission);
1331
- const parentResource = resourceType === "thread" ? void 0 : this.resolveParentResource(user, resourceType);
1332
- if (parentResource) {
1333
- const accessibleIds = await this.listAccessibleResourceExternalIds({
1334
- organizationMembershipId: membershipId,
1335
- permissionSlug,
1336
- parentResourceExternalId: parentResource.externalId,
1337
- parentResourceTypeSlug: parentResource.typeSlug
1338
- });
1339
- return resources.filter((resource) => {
1340
- const mappedId = this.resolveResourceId(
1341
- user,
1342
- resourceType,
1343
- resource.id,
1344
- "resourceId" in resource && typeof resource.resourceId === "string" ? { resourceId: resource.resourceId } : void 0
1345
- );
1346
- return !!mappedId && accessibleIds.has(mappedId);
1347
- });
1348
- }
1349
- const checks = [];
1350
- for (let start = 0; start < resources.length; start += FILTER_ACCESSIBLE_CHECK_CONCURRENCY) {
1351
- const batch = resources.slice(start, start + FILTER_ACCESSIBLE_CHECK_CONCURRENCY);
1352
- const batchChecks = await Promise.all(
1353
- batch.map(async (resource) => {
1354
- const authorized = await this.check(user, {
1355
- resource: { type: resourceType, id: resource.id },
1356
- permission,
1357
- context: "resourceId" in resource && typeof resource.resourceId === "string" ? { resourceId: resource.resourceId } : void 0
1358
- });
1359
- return { resource, authorized };
1360
- })
1361
- );
1362
- checks.push(...batchChecks);
1363
- }
1364
- return checks.filter((c) => c.authorized).map((c) => c.resource);
1365
- }
1366
- // ──────────────────────────────────────────────────────────────
1367
- // IFGAManager — Write operations
1368
- // ──────────────────────────────────────────────────────────────
1369
- /**
1370
- * Create an authorization resource in WorkOS.
1371
- */
1372
- async createResource(params) {
1373
- const options = {
1374
- externalId: params.externalId,
1375
- name: params.name,
1376
- resourceTypeSlug: params.resourceTypeSlug,
1377
- organizationId: params.organizationId
1378
- };
1379
- if (params.description !== void 0) options.description = params.description;
1380
- if (params.parentResourceId) options.parentResourceId = params.parentResourceId;
1381
- if (params.parentResourceExternalId) {
1382
- options.parentResourceExternalId = params.parentResourceExternalId;
1383
- options.parentResourceTypeSlug = params.parentResourceTypeSlug;
1384
- }
1385
- const result = await this.workos.authorization.createResource(options);
1386
- return this.mapAuthorizationResource(result);
1387
- }
1388
- /**
1389
- * Get an authorization resource by ID.
1390
- */
1391
- async getResource(resourceId) {
1392
- const result = await this.workos.authorization.getResource(resourceId);
1393
- return this.mapAuthorizationResource(result);
1394
- }
1395
- /**
1396
- * List authorization resources with optional filters.
1397
- */
1398
- async listResources(options) {
1399
- const listOptions = {};
1400
- if (options?.organizationId) listOptions.organizationId = options.organizationId;
1401
- if (options?.resourceTypeSlug) listOptions.resourceTypeSlug = options.resourceTypeSlug;
1402
- if (options?.parentResourceId) listOptions.parentResourceId = options.parentResourceId;
1403
- if (options?.search) listOptions.search = options.search;
1404
- if (options?.limit) listOptions.limit = options.limit;
1405
- if (options?.after) listOptions.after = options.after;
1406
- const result = await this.workos.authorization.listResources(listOptions);
1407
- return result.data.map((r) => this.mapAuthorizationResource(r));
1408
- }
1409
- /**
1410
- * Update an authorization resource.
1411
- */
1412
- async updateResource(params) {
1413
- const options = { resourceId: params.resourceId };
1414
- if (params.name !== void 0) options.name = params.name;
1415
- if (params.description !== void 0) options.description = params.description;
1416
- const result = await this.workos.authorization.updateResource(options);
1417
- return this.mapAuthorizationResource(result);
1418
- }
1419
- /**
1420
- * Delete an authorization resource.
1421
- */
1422
- async deleteResource(params) {
1423
- if ("resourceId" in params && params.resourceId) {
1424
- await this.workos.authorization.deleteResource({ resourceId: params.resourceId });
1425
- } else if ("externalId" in params && params.externalId && params.resourceTypeSlug) {
1426
- await this.workos.authorization.deleteResourceByExternalId({
1427
- externalId: params.externalId,
1428
- resourceTypeSlug: params.resourceTypeSlug,
1429
- organizationId: params.organizationId
1430
- });
1431
- }
1432
- }
1433
- /**
1434
- * Assign a role to an organization membership on a resource.
1435
- */
1436
- async assignRole(params) {
1437
- const options = {
1438
- organizationMembershipId: params.organizationMembershipId,
1439
- roleSlug: params.roleSlug
1440
- };
1441
- if (params.resourceId) options.resourceId = params.resourceId;
1442
- if (params.resourceExternalId) {
1443
- options.resourceExternalId = params.resourceExternalId;
1444
- options.resourceTypeSlug = params.resourceTypeSlug;
1445
- }
1446
- const result = await this.workos.authorization.assignRole(options);
1447
- return {
1448
- id: result.id,
1449
- role: result.role,
1450
- resource: {
1451
- id: result.resource.id,
1452
- externalId: result.resource.externalId,
1453
- resourceTypeSlug: result.resource.resourceTypeSlug
1454
- }
1455
- };
1456
- }
1457
- /**
1458
- * Remove a role assignment.
1459
- */
1460
- async removeRole(params) {
1461
- const options = {
1462
- organizationMembershipId: params.organizationMembershipId,
1463
- roleSlug: params.roleSlug
1464
- };
1465
- if (params.resourceId) options.resourceId = params.resourceId;
1466
- if (params.resourceExternalId) {
1467
- options.resourceExternalId = params.resourceExternalId;
1468
- options.resourceTypeSlug = params.resourceTypeSlug;
1469
- }
1470
- await this.workos.authorization.removeRole(options);
1471
- }
1472
- /**
1473
- * List role assignments for an organization membership.
1474
- */
1475
- async listRoleAssignments(options) {
1476
- const result = await this.workos.authorization.listRoleAssignments({
1477
- organizationMembershipId: options.organizationMembershipId,
1478
- ...options.limit && { limit: options.limit },
1479
- ...options.after && { after: options.after }
1480
- });
1481
- return result.data.map((ra) => ({
1482
- id: ra.id,
1483
- role: ra.role,
1484
- resource: {
1485
- id: ra.resource.id,
1486
- externalId: ra.resource.externalId,
1487
- resourceTypeSlug: ra.resource.resourceTypeSlug
1488
- }
1489
- }));
1490
- }
1491
- // ──────────────────────────────────────────────────────────────
1492
- // Internal helpers
1493
- // ──────────────────────────────────────────────────────────────
1494
- /**
1495
- * Resolve the organization membership ID from a user object.
1496
- * Looks for organizationMembershipId, then finds membership matching
1497
- * configured organizationId, then falls back to first membership.
1498
- *
1499
- * Returns undefined if no membership can be resolved, which causes
1500
- * authorization checks to deny access. Enable `fetchMemberships: true`
1501
- * on MastraAuthWorkos to populate the memberships field.
1502
- */
1503
- resolveOrganizationMembershipId(user, options) {
1504
- if (user?.organizationMembershipId) return user.organizationMembershipId;
1505
- if (!user?.memberships?.length) {
1506
- console.warn(
1507
- "[MastraFGAWorkos] Cannot resolve organization membership for user <redacted>. Ensure fetchMemberships is enabled on MastraAuthWorkos when using FGA."
1508
- );
1509
- if (options?.strictMembershipResolution) {
1510
- throw new WorkOSFGAMembershipResolutionError(user);
1511
- }
1512
- return void 0;
1513
- }
1514
- if (this.organizationId) {
1515
- const match = user.memberships.find((m) => m.organizationId === this.organizationId);
1516
- if (match) return match.id;
1517
- console.warn("[MastraFGAWorkos] User <redacted> does not belong to configured organization <redacted>.");
1518
- if (options?.strictMembershipResolution) {
1519
- throw new WorkOSFGAMembershipResolutionError(user);
1520
- }
1521
- return void 0;
1522
- }
1523
- return user.memberships[0].id;
1524
- }
1525
- /**
1526
- * Map a Mastra permission string to a WorkOS permission slug via permissionMapping.
1527
- * Falls back to the original permission if no mapping is found.
1528
- */
1529
- resolvePermission(permission) {
1530
- return this.permissionMapping[permission] ?? permission;
1531
- }
1532
- /**
1533
- * Resolve the parent resource context needed for WorkOS resource discovery.
1534
- */
1535
- resolveParentResource(user, resourceType) {
1536
- const mapping = this.getResourceMapping(resourceType);
1537
- const externalId = mapping?.deriveId?.({ user });
1538
- const parentTypeSlug = mapping?.parentFgaResourceType ?? mapping?.parentResourceTypeSlug;
1539
- if (!mapping?.fgaResourceType || !externalId || !parentTypeSlug || parentTypeSlug === mapping.fgaResourceType) {
1540
- return void 0;
1541
- }
1542
- return {
1543
- externalId,
1544
- typeSlug: parentTypeSlug
1545
- };
1546
- }
1547
- /**
1548
- * Resolve the FGA resource ID using resourceMapping's deriveId function.
1549
- * Falls back to the original resource ID if no mapping is found.
1550
- */
1551
- resolveResourceId(user, resourceType, resourceId, context) {
1552
- const mapping = this.getResourceMapping(resourceType);
1553
- const derivedId = mapping?.deriveId?.({
1554
- user,
1555
- resourceId: context?.resourceId ?? resourceId,
1556
- requestContext: context?.requestContext
1557
- });
1558
- return derivedId ?? resourceId;
1559
- }
1560
- buildCheckOptions(user, params, options) {
1561
- const membershipId = this.resolveOrganizationMembershipId(user, options);
1562
- if (!membershipId) return null;
1563
- const permissionSlug = this.resolvePermission(params.permission);
1564
- const resourceId = this.resolveResourceId(user, params.resource.type, params.resource.id, params.context);
1565
- const checkOptions = {
1566
- organizationMembershipId: membershipId,
1567
- permissionSlug
1568
- };
1569
- if (!resourceId) {
1570
- return checkOptions;
1571
- }
1572
- const mapping = this.getResourceMapping(params.resource.type);
1573
- if (mapping) {
1574
- checkOptions.resourceExternalId = resourceId;
1575
- checkOptions.resourceTypeSlug = mapping.fgaResourceType;
1576
- } else {
1577
- checkOptions.resourceExternalId = params.resource.id;
1578
- checkOptions.resourceTypeSlug = params.resource.type;
1579
- }
1580
- return checkOptions;
1581
- }
1582
- getResourceMapping(resourceType) {
1583
- const aliases = resourceType === "agent" ? ["agent", "agents"] : resourceType === "workflow" ? ["workflow", "workflows"] : resourceType === "tool" ? ["tool", "tools"] : resourceType === "thread" ? ["thread", "threads", "memory"] : [resourceType];
1584
- for (const key of aliases) {
1585
- const mapping = this.resourceMapping[key];
1586
- if (mapping) {
1587
- return mapping;
1588
- }
1589
- }
1590
- return void 0;
1591
- }
1592
- /**
1593
- * List accessible child resources for a membership, following pagination.
1594
- */
1595
- async listAccessibleResourceExternalIds(params) {
1596
- const accessibleIds = /* @__PURE__ */ new Set();
1597
- let after;
1598
- do {
1599
- const result = await this.workos.authorization.listResourcesForMembership({
1600
- organizationMembershipId: params.organizationMembershipId,
1601
- permissionSlug: params.permissionSlug,
1602
- parentResourceExternalId: params.parentResourceExternalId,
1603
- parentResourceTypeSlug: params.parentResourceTypeSlug,
1604
- ...after ? { after } : {},
1605
- limit: 100,
1606
- order: "asc"
1607
- });
1608
- for (const resource of result.data ?? []) {
1609
- if (typeof resource?.externalId === "string") {
1610
- accessibleIds.add(resource.externalId);
1611
- }
1612
- }
1613
- after = result.listMetadata?.after ?? void 0;
1614
- } while (after);
1615
- return accessibleIds;
1616
- }
1617
- /**
1618
- * Map a WorkOS AuthorizationResource to Mastra's FGAResource type.
1619
- */
1620
- mapAuthorizationResource(resource) {
1621
- return {
1622
- id: resource.id,
1623
- externalId: resource.externalId,
1624
- name: resource.name,
1625
- description: resource.description,
1626
- resourceTypeSlug: resource.resourceTypeSlug,
1627
- organizationId: resource.organizationId,
1628
- parentResourceId: resource.parentResourceId
1629
- };
1630
- }
1372
+ workos;
1373
+ organizationId;
1374
+ resourceMapping;
1375
+ permissionMapping;
1376
+ requireForProtectedRoutes;
1377
+ auditProtectedRoutes;
1378
+ resolveRouteFGA;
1379
+ validatePermissions;
1380
+ constructor(options) {
1381
+ const apiKey = options.apiKey ?? process.env.WORKOS_API_KEY;
1382
+ const clientId = options.clientId ?? process.env.WORKOS_CLIENT_ID;
1383
+ if (!apiKey || !clientId) throw new Error("WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables.");
1384
+ this.workos = new WorkOS(apiKey, { clientId });
1385
+ this.organizationId = options.organizationId;
1386
+ this.resourceMapping = options.resourceMapping ?? {};
1387
+ this.permissionMapping = options.permissionMapping ?? {};
1388
+ this.requireForProtectedRoutes = options.requireForProtectedRoutes;
1389
+ this.auditProtectedRoutes = options.auditProtectedRoutes;
1390
+ this.resolveRouteFGA = options.resolveRouteFGA;
1391
+ this.validatePermissions = options.validatePermissions;
1392
+ }
1393
+ /**
1394
+ * Check if a user has permission on a resource.
1395
+ *
1396
+ * Resolves the user's organization membership ID, maps the permission
1397
+ * via `permissionMapping`, and delegates to `workos.authorization.check()`.
1398
+ *
1399
+ * When `params.permission` is an array, ANY-of semantics apply: returns true
1400
+ * if any single permission in the array authorizes the user.
1401
+ */
1402
+ async check(user, params) {
1403
+ const permissions = Array.isArray(params.permission) ? params.permission : [params.permission];
1404
+ if (permissions.length === 0) return false;
1405
+ for (const permission of permissions) {
1406
+ const checkOptions = this.buildCheckOptions(user, {
1407
+ ...params,
1408
+ permission
1409
+ });
1410
+ if (!checkOptions) continue;
1411
+ try {
1412
+ if ((await this.workos.authorization.check(checkOptions)).authorized) return true;
1413
+ } catch (error) {
1414
+ if (isWorkOSResourceNotFoundError(error)) continue;
1415
+ throw error;
1416
+ }
1417
+ }
1418
+ return false;
1419
+ }
1420
+ /**
1421
+ * Require that a user has permission, throwing FGADeniedError if not.
1422
+ *
1423
+ * When `params.permission` is an array, ANY-of semantics apply: passes if any
1424
+ * single permission authorizes the user; throws if none do.
1425
+ */
1426
+ async require(user, params) {
1427
+ const permissions = Array.isArray(params.permission) ? params.permission : [params.permission];
1428
+ if (permissions.length === 0) throw new FGADeniedError(user, params.resource, params.permission);
1429
+ let lastError;
1430
+ for (const permission of permissions) {
1431
+ const checkOptions = this.buildCheckOptions(user, {
1432
+ ...params,
1433
+ permission
1434
+ }, { strictMembershipResolution: true });
1435
+ if (!checkOptions) continue;
1436
+ try {
1437
+ if ((await this.workos.authorization.check(checkOptions)).authorized) return;
1438
+ } catch (error) {
1439
+ if (error instanceof FGADeniedError) throw error;
1440
+ if (isWorkOSResourceNotFoundError(error)) continue;
1441
+ lastError = error;
1442
+ }
1443
+ }
1444
+ if (lastError) throw lastError;
1445
+ throw new FGADeniedError(user, params.resource, params.permission);
1446
+ }
1447
+ /**
1448
+ * Filter resources to only those the user has permission to access.
1449
+ *
1450
+ * Uses WorkOS `listResourcesForMembership()` when the resource mapping can
1451
+ * resolve a parent resource from user context. This avoids one check per
1452
+ * resource for list endpoints like agents/workflows/tools.
1453
+ *
1454
+ * Falls back to per-resource `check()` calls when no parent resource can be
1455
+ * resolved from the configured mapping.
1456
+ */
1457
+ async filterAccessible(user, resources, resourceType, permission) {
1458
+ if (resources.length === 0) return [];
1459
+ const membershipId = this.resolveOrganizationMembershipId(user);
1460
+ if (!membershipId) return [];
1461
+ const permissionSlug = this.resolvePermission(permission);
1462
+ const parentResource = resourceType === "thread" ? void 0 : this.resolveParentResource(user, resourceType);
1463
+ if (parentResource) {
1464
+ const accessibleIds = await this.listAccessibleResourceExternalIds({
1465
+ organizationMembershipId: membershipId,
1466
+ permissionSlug,
1467
+ parentResourceExternalId: parentResource.externalId,
1468
+ parentResourceTypeSlug: parentResource.typeSlug
1469
+ });
1470
+ return resources.filter((resource) => {
1471
+ const mappedId = this.resolveResourceId(user, resourceType, resource.id, "resourceId" in resource && typeof resource.resourceId === "string" ? { resourceId: resource.resourceId } : void 0);
1472
+ return !!mappedId && accessibleIds.has(mappedId);
1473
+ });
1474
+ }
1475
+ const checks = [];
1476
+ for (let start = 0; start < resources.length; start += FILTER_ACCESSIBLE_CHECK_CONCURRENCY) {
1477
+ const batch = resources.slice(start, start + FILTER_ACCESSIBLE_CHECK_CONCURRENCY);
1478
+ const batchChecks = await Promise.all(batch.map(async (resource) => {
1479
+ return {
1480
+ resource,
1481
+ authorized: await this.check(user, {
1482
+ resource: {
1483
+ type: resourceType,
1484
+ id: resource.id
1485
+ },
1486
+ permission,
1487
+ context: "resourceId" in resource && typeof resource.resourceId === "string" ? { resourceId: resource.resourceId } : void 0
1488
+ })
1489
+ };
1490
+ }));
1491
+ checks.push(...batchChecks);
1492
+ }
1493
+ return checks.filter((c) => c.authorized).map((c) => c.resource);
1494
+ }
1495
+ /**
1496
+ * Create an authorization resource in WorkOS.
1497
+ */
1498
+ async createResource(params) {
1499
+ const options = {
1500
+ externalId: params.externalId,
1501
+ name: params.name,
1502
+ resourceTypeSlug: params.resourceTypeSlug,
1503
+ organizationId: params.organizationId
1504
+ };
1505
+ if (params.description !== void 0) options.description = params.description;
1506
+ if (params.parentResourceId) options.parentResourceId = params.parentResourceId;
1507
+ if (params.parentResourceExternalId) {
1508
+ options.parentResourceExternalId = params.parentResourceExternalId;
1509
+ options.parentResourceTypeSlug = params.parentResourceTypeSlug;
1510
+ }
1511
+ const result = await this.workos.authorization.createResource(options);
1512
+ return this.mapAuthorizationResource(result);
1513
+ }
1514
+ /**
1515
+ * Get an authorization resource by ID.
1516
+ */
1517
+ async getResource(resourceId) {
1518
+ const result = await this.workos.authorization.getResource(resourceId);
1519
+ return this.mapAuthorizationResource(result);
1520
+ }
1521
+ /**
1522
+ * List authorization resources with optional filters.
1523
+ */
1524
+ async listResources(options) {
1525
+ const listOptions = {};
1526
+ if (options?.organizationId) listOptions.organizationId = options.organizationId;
1527
+ if (options?.resourceTypeSlug) listOptions.resourceTypeSlug = options.resourceTypeSlug;
1528
+ if (options?.parentResourceId) listOptions.parentResourceId = options.parentResourceId;
1529
+ if (options?.search) listOptions.search = options.search;
1530
+ if (options?.limit) listOptions.limit = options.limit;
1531
+ if (options?.after) listOptions.after = options.after;
1532
+ return (await this.workos.authorization.listResources(listOptions)).data.map((r) => this.mapAuthorizationResource(r));
1533
+ }
1534
+ /**
1535
+ * Update an authorization resource.
1536
+ */
1537
+ async updateResource(params) {
1538
+ const options = { resourceId: params.resourceId };
1539
+ if (params.name !== void 0) options.name = params.name;
1540
+ if (params.description !== void 0) options.description = params.description;
1541
+ const result = await this.workos.authorization.updateResource(options);
1542
+ return this.mapAuthorizationResource(result);
1543
+ }
1544
+ /**
1545
+ * Delete an authorization resource.
1546
+ */
1547
+ async deleteResource(params) {
1548
+ if ("resourceId" in params && params.resourceId) await this.workos.authorization.deleteResource({ resourceId: params.resourceId });
1549
+ else if ("externalId" in params && params.externalId && params.resourceTypeSlug) await this.workos.authorization.deleteResourceByExternalId({
1550
+ externalId: params.externalId,
1551
+ resourceTypeSlug: params.resourceTypeSlug,
1552
+ organizationId: params.organizationId
1553
+ });
1554
+ }
1555
+ /**
1556
+ * Assign a role to an organization membership on a resource.
1557
+ */
1558
+ async assignRole(params) {
1559
+ const options = {
1560
+ organizationMembershipId: params.organizationMembershipId,
1561
+ roleSlug: params.roleSlug
1562
+ };
1563
+ if (params.resourceId) options.resourceId = params.resourceId;
1564
+ if (params.resourceExternalId) {
1565
+ options.resourceExternalId = params.resourceExternalId;
1566
+ options.resourceTypeSlug = params.resourceTypeSlug;
1567
+ }
1568
+ const result = await this.workos.authorization.assignRole(options);
1569
+ return {
1570
+ id: result.id,
1571
+ role: result.role,
1572
+ resource: {
1573
+ id: result.resource.id,
1574
+ externalId: result.resource.externalId,
1575
+ resourceTypeSlug: result.resource.resourceTypeSlug
1576
+ }
1577
+ };
1578
+ }
1579
+ /**
1580
+ * Remove a role assignment.
1581
+ */
1582
+ async removeRole(params) {
1583
+ const options = {
1584
+ organizationMembershipId: params.organizationMembershipId,
1585
+ roleSlug: params.roleSlug
1586
+ };
1587
+ if (params.resourceId) options.resourceId = params.resourceId;
1588
+ if (params.resourceExternalId) {
1589
+ options.resourceExternalId = params.resourceExternalId;
1590
+ options.resourceTypeSlug = params.resourceTypeSlug;
1591
+ }
1592
+ await this.workos.authorization.removeRole(options);
1593
+ }
1594
+ /**
1595
+ * List role assignments for an organization membership.
1596
+ */
1597
+ async listRoleAssignments(options) {
1598
+ return (await this.workos.authorization.listRoleAssignments({
1599
+ organizationMembershipId: options.organizationMembershipId,
1600
+ ...options.limit && { limit: options.limit },
1601
+ ...options.after && { after: options.after }
1602
+ })).data.map((ra) => ({
1603
+ id: ra.id,
1604
+ role: ra.role,
1605
+ resource: {
1606
+ id: ra.resource.id,
1607
+ externalId: ra.resource.externalId,
1608
+ resourceTypeSlug: ra.resource.resourceTypeSlug
1609
+ }
1610
+ }));
1611
+ }
1612
+ /**
1613
+ * Resolve the organization membership ID from a user object.
1614
+ * Looks for organizationMembershipId, then finds membership matching
1615
+ * configured organizationId, then falls back to first membership.
1616
+ *
1617
+ * Returns undefined if no membership can be resolved, which causes
1618
+ * authorization checks to deny access. Enable `fetchMemberships: true`
1619
+ * on MastraAuthWorkos to populate the memberships field.
1620
+ */
1621
+ resolveOrganizationMembershipId(user, options) {
1622
+ if (user?.organizationMembershipId) return user.organizationMembershipId;
1623
+ if (!user?.memberships?.length) {
1624
+ console.warn("[MastraFGAWorkos] Cannot resolve organization membership for user <redacted>. Ensure fetchMemberships is enabled on MastraAuthWorkos when using FGA.");
1625
+ if (options?.strictMembershipResolution) throw new WorkOSFGAMembershipResolutionError(user);
1626
+ return;
1627
+ }
1628
+ if (this.organizationId) {
1629
+ const match = user.memberships.find((m) => m.organizationId === this.organizationId);
1630
+ if (match) return match.id;
1631
+ console.warn("[MastraFGAWorkos] User <redacted> does not belong to configured organization <redacted>.");
1632
+ if (options?.strictMembershipResolution) throw new WorkOSFGAMembershipResolutionError(user);
1633
+ return;
1634
+ }
1635
+ return user.memberships[0].id;
1636
+ }
1637
+ /**
1638
+ * Map a Mastra permission string to a WorkOS permission slug via permissionMapping.
1639
+ * Falls back to the original permission if no mapping is found.
1640
+ */
1641
+ resolvePermission(permission) {
1642
+ return this.permissionMapping[permission] ?? permission;
1643
+ }
1644
+ /**
1645
+ * Resolve the parent resource context needed for WorkOS resource discovery.
1646
+ */
1647
+ resolveParentResource(user, resourceType) {
1648
+ const mapping = this.getResourceMapping(resourceType);
1649
+ const externalId = mapping?.deriveId?.({ user });
1650
+ const parentTypeSlug = mapping?.parentFgaResourceType ?? mapping?.parentResourceTypeSlug;
1651
+ if (!mapping?.fgaResourceType || !externalId || !parentTypeSlug || parentTypeSlug === mapping.fgaResourceType) return;
1652
+ return {
1653
+ externalId,
1654
+ typeSlug: parentTypeSlug
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Resolve the FGA resource ID using resourceMapping's deriveId function.
1659
+ * Falls back to the original resource ID if no mapping is found.
1660
+ */
1661
+ resolveResourceId(user, resourceType, resourceId, context) {
1662
+ return this.getResourceMapping(resourceType)?.deriveId?.({
1663
+ user,
1664
+ resourceId: context?.resourceId ?? resourceId,
1665
+ requestContext: context?.requestContext
1666
+ }) ?? resourceId;
1667
+ }
1668
+ buildCheckOptions(user, params, options) {
1669
+ const membershipId = this.resolveOrganizationMembershipId(user, options);
1670
+ if (!membershipId) return null;
1671
+ const permissionSlug = this.resolvePermission(params.permission);
1672
+ const resourceId = this.resolveResourceId(user, params.resource.type, params.resource.id, params.context);
1673
+ const checkOptions = {
1674
+ organizationMembershipId: membershipId,
1675
+ permissionSlug
1676
+ };
1677
+ if (!resourceId) return checkOptions;
1678
+ const mapping = this.getResourceMapping(params.resource.type);
1679
+ if (mapping) {
1680
+ checkOptions.resourceExternalId = resourceId;
1681
+ checkOptions.resourceTypeSlug = mapping.fgaResourceType;
1682
+ } else {
1683
+ checkOptions.resourceExternalId = params.resource.id;
1684
+ checkOptions.resourceTypeSlug = params.resource.type;
1685
+ }
1686
+ return checkOptions;
1687
+ }
1688
+ getResourceMapping(resourceType) {
1689
+ const aliases = resourceType === "agent" ? ["agent", "agents"] : resourceType === "workflow" ? ["workflow", "workflows"] : resourceType === "tool" ? ["tool", "tools"] : resourceType === "thread" ? [
1690
+ "thread",
1691
+ "threads",
1692
+ "memory"
1693
+ ] : [resourceType];
1694
+ for (const key of aliases) {
1695
+ const mapping = this.resourceMapping[key];
1696
+ if (mapping) return mapping;
1697
+ }
1698
+ }
1699
+ /**
1700
+ * List accessible child resources for a membership, following pagination.
1701
+ */
1702
+ async listAccessibleResourceExternalIds(params) {
1703
+ const accessibleIds = /* @__PURE__ */ new Set();
1704
+ let after;
1705
+ do {
1706
+ const result = await this.workos.authorization.listResourcesForMembership({
1707
+ organizationMembershipId: params.organizationMembershipId,
1708
+ permissionSlug: params.permissionSlug,
1709
+ parentResourceExternalId: params.parentResourceExternalId,
1710
+ parentResourceTypeSlug: params.parentResourceTypeSlug,
1711
+ ...after ? { after } : {},
1712
+ limit: 100,
1713
+ order: "asc"
1714
+ });
1715
+ for (const resource of result.data ?? []) if (typeof resource?.externalId === "string") accessibleIds.add(resource.externalId);
1716
+ after = result.listMetadata?.after ?? void 0;
1717
+ } while (after);
1718
+ return accessibleIds;
1719
+ }
1720
+ /**
1721
+ * Map a WorkOS AuthorizationResource to Mastra's FGAResource type.
1722
+ */
1723
+ mapAuthorizationResource(resource) {
1724
+ return {
1725
+ id: resource.id,
1726
+ externalId: resource.externalId,
1727
+ name: resource.name,
1728
+ description: resource.description,
1729
+ resourceTypeSlug: resource.resourceTypeSlug,
1730
+ organizationId: resource.organizationId,
1731
+ parentResourceId: resource.parentResourceId
1732
+ };
1733
+ }
1631
1734
  };
1632
-
1633
- // src/directory-sync.ts
1735
+ //#endregion
1736
+ //#region src/directory-sync.ts
1737
+ /**
1738
+ * WorkOSDirectorySync handles SCIM webhook events from WorkOS for automated
1739
+ * user provisioning and deprovisioning.
1740
+ *
1741
+ * @example
1742
+ * ```typescript
1743
+ * import { WorkOS } from '@workos-inc/node';
1744
+ * import { WorkOSDirectorySync } from '@mastra/auth-workos';
1745
+ *
1746
+ * const workos = new WorkOS(process.env.WORKOS_API_KEY);
1747
+ *
1748
+ * const directorySync = new WorkOSDirectorySync(workos, {
1749
+ * webhookSecret: process.env.WORKOS_WEBHOOK_SECRET,
1750
+ * handlers: {
1751
+ * onUserCreated: async (user) => {
1752
+ * await db.users.create({ email: user.emails[0]?.value });
1753
+ * },
1754
+ * onUserDeleted: async (user) => {
1755
+ * await db.users.delete({ id: user.id });
1756
+ * },
1757
+ * },
1758
+ * });
1759
+ *
1760
+ * // In your webhook endpoint:
1761
+ * app.post('/webhooks/workos', async (req, res) => {
1762
+ * const signature = req.headers['workos-signature'] as string;
1763
+ * await directorySync.handleWebhook(req.body, signature);
1764
+ * res.status(200).send('OK');
1765
+ * });
1766
+ * ```
1767
+ */
1634
1768
  var WorkOSDirectorySync = class {
1635
- workos;
1636
- webhookSecret;
1637
- handlers;
1638
- /**
1639
- * Creates a new WorkOSDirectorySync instance.
1640
- *
1641
- * @param workos - WorkOS client instance
1642
- * @param options - Configuration options including webhook secret and event handlers
1643
- * @throws Error if webhook secret is not provided
1644
- */
1645
- constructor(workos, options) {
1646
- this.workos = workos;
1647
- const webhookSecret = options.webhookSecret ?? process.env.WORKOS_WEBHOOK_SECRET;
1648
- if (!webhookSecret) {
1649
- throw new Error(
1650
- "WorkOS webhook secret is required. Provide it in options or set WORKOS_WEBHOOK_SECRET environment variable."
1651
- );
1652
- }
1653
- this.webhookSecret = webhookSecret;
1654
- this.handlers = options.handlers;
1655
- }
1656
- /**
1657
- * Handles incoming webhook events from WorkOS Directory Sync.
1658
- *
1659
- * This method verifies the webhook signature for security, parses the event,
1660
- * and routes it to the appropriate handler based on the event type.
1661
- *
1662
- * @param payload - Raw webhook payload (string or object)
1663
- * @param signature - WorkOS signature header for verification
1664
- * @throws Error if signature verification fails
1665
- */
1666
- async handleWebhook(payload, signature) {
1667
- const parsedPayload = typeof payload === "string" ? JSON.parse(payload) : payload;
1668
- const event = await this.workos.webhooks.constructEvent({
1669
- payload: parsedPayload,
1670
- sigHeader: signature,
1671
- secret: this.webhookSecret
1672
- });
1673
- try {
1674
- await this.routeEvent(event);
1675
- } catch (error) {
1676
- console.error(`[WorkOSDirectorySync] Error handling event ${event.event}:`, error);
1677
- }
1678
- }
1679
- /**
1680
- * Routes a directory sync event to the appropriate handler.
1681
- *
1682
- * @param event - The verified webhook event
1683
- */
1684
- async routeEvent(event) {
1685
- const { event: eventType, data } = event;
1686
- switch (eventType) {
1687
- case "dsync.user.created":
1688
- if (this.handlers.onUserCreated) {
1689
- await this.handlers.onUserCreated(this.mapUserData(data));
1690
- }
1691
- break;
1692
- case "dsync.user.updated":
1693
- if (this.handlers.onUserUpdated) {
1694
- await this.handlers.onUserUpdated(this.mapUserData(data));
1695
- }
1696
- break;
1697
- case "dsync.user.deleted":
1698
- if (this.handlers.onUserDeleted) {
1699
- await this.handlers.onUserDeleted(this.mapUserData(data));
1700
- }
1701
- break;
1702
- case "dsync.group.created":
1703
- if (this.handlers.onGroupCreated) {
1704
- await this.handlers.onGroupCreated(this.mapGroupData(data));
1705
- }
1706
- break;
1707
- case "dsync.group.updated":
1708
- if (this.handlers.onGroupUpdated) {
1709
- await this.handlers.onGroupUpdated(this.mapGroupData(data));
1710
- }
1711
- break;
1712
- case "dsync.group.deleted":
1713
- if (this.handlers.onGroupDeleted) {
1714
- await this.handlers.onGroupDeleted(this.mapGroupData(data));
1715
- }
1716
- break;
1717
- case "dsync.group.user_added":
1718
- if (this.handlers.onGroupUserAdded) {
1719
- await this.handlers.onGroupUserAdded({
1720
- group: this.mapGroupData(data.group),
1721
- user: this.mapUserData(data.user)
1722
- });
1723
- }
1724
- break;
1725
- case "dsync.group.user_removed":
1726
- if (this.handlers.onGroupUserRemoved) {
1727
- await this.handlers.onGroupUserRemoved({
1728
- group: this.mapGroupData(data.group),
1729
- user: this.mapUserData(data.user)
1730
- });
1731
- }
1732
- break;
1733
- default:
1734
- console.warn(`[WorkOSDirectorySync] Unknown event type: ${eventType}`);
1735
- }
1736
- }
1737
- /**
1738
- * Maps raw webhook user data to the DirectorySyncUserData type.
1739
- *
1740
- * @param data - Raw user data from webhook
1741
- * @returns Typed user data
1742
- */
1743
- mapUserData(data) {
1744
- return {
1745
- id: data.id,
1746
- directoryId: data.directory_id,
1747
- organizationId: data.organization_id,
1748
- idpId: data.idp_id,
1749
- firstName: data.first_name,
1750
- lastName: data.last_name,
1751
- jobTitle: data.job_title,
1752
- emails: data.emails ?? [],
1753
- username: data.username,
1754
- groups: data.groups ?? [],
1755
- state: data.state,
1756
- rawAttributes: data.raw_attributes ?? {},
1757
- customAttributes: data.custom_attributes ?? {},
1758
- createdAt: data.created_at,
1759
- updatedAt: data.updated_at
1760
- };
1761
- }
1762
- /**
1763
- * Maps raw webhook group data to the DirectorySyncGroupData type.
1764
- *
1765
- * @param data - Raw group data from webhook
1766
- * @returns Typed group data
1767
- */
1768
- mapGroupData(data) {
1769
- return {
1770
- id: data.id,
1771
- directoryId: data.directory_id,
1772
- organizationId: data.organization_id,
1773
- idpId: data.idp_id,
1774
- name: data.name,
1775
- createdAt: data.created_at,
1776
- updatedAt: data.updated_at,
1777
- rawAttributes: data.raw_attributes ?? {}
1778
- };
1779
- }
1780
- // ===========================================================================
1781
- // Helper Methods for Directory Sync Operations
1782
- // ===========================================================================
1783
- /**
1784
- * Lists all directories for an organization.
1785
- *
1786
- * @param organizationId - The WorkOS organization ID
1787
- * @returns Array of directories
1788
- *
1789
- * @example
1790
- * ```typescript
1791
- * const directories = await directorySync.listDirectories('org_123');
1792
- * for (const dir of directories) {
1793
- * console.log(`Directory: ${dir.name} (${dir.type})`);
1794
- * }
1795
- * ```
1796
- */
1797
- async listDirectories(organizationId) {
1798
- const response = await this.workos.directorySync.listDirectories({
1799
- organizationId
1800
- });
1801
- return response.data;
1802
- }
1803
- /**
1804
- * Lists all users in a directory.
1805
- *
1806
- * @param directoryId - The directory ID
1807
- * @returns Array of directory users
1808
- *
1809
- * @example
1810
- * ```typescript
1811
- * const users = await directorySync.listDirectoryUsers('directory_123');
1812
- * for (const user of users) {
1813
- * console.log(`User: ${user.firstName} ${user.lastName}`);
1814
- * }
1815
- * ```
1816
- */
1817
- async listDirectoryUsers(directoryId) {
1818
- const response = await this.workos.directorySync.listUsers({
1819
- directory: directoryId
1820
- });
1821
- return response.data;
1822
- }
1823
- /**
1824
- * Lists all groups in a directory.
1825
- *
1826
- * @param directoryId - The directory ID
1827
- * @returns Array of directory groups
1828
- *
1829
- * @example
1830
- * ```typescript
1831
- * const groups = await directorySync.listDirectoryGroups('directory_123');
1832
- * for (const group of groups) {
1833
- * console.log(`Group: ${group.name}`);
1834
- * }
1835
- * ```
1836
- */
1837
- async listDirectoryGroups(directoryId) {
1838
- const response = await this.workos.directorySync.listGroups({
1839
- directory: directoryId
1840
- });
1841
- return response.data;
1842
- }
1843
- };
1844
- var INTENT_MAP = {
1845
- sso: GeneratePortalLinkIntent.SSO,
1846
- dsync: GeneratePortalLinkIntent.DSync,
1847
- audit_logs: GeneratePortalLinkIntent.AuditLogs,
1848
- log_streams: GeneratePortalLinkIntent.LogStreams
1769
+ workos;
1770
+ webhookSecret;
1771
+ handlers;
1772
+ /**
1773
+ * Creates a new WorkOSDirectorySync instance.
1774
+ *
1775
+ * @param workos - WorkOS client instance
1776
+ * @param options - Configuration options including webhook secret and event handlers
1777
+ * @throws Error if webhook secret is not provided
1778
+ */
1779
+ constructor(workos, options) {
1780
+ this.workos = workos;
1781
+ const webhookSecret = options.webhookSecret ?? process.env.WORKOS_WEBHOOK_SECRET;
1782
+ if (!webhookSecret) throw new Error("WorkOS webhook secret is required. Provide it in options or set WORKOS_WEBHOOK_SECRET environment variable.");
1783
+ this.webhookSecret = webhookSecret;
1784
+ this.handlers = options.handlers;
1785
+ }
1786
+ /**
1787
+ * Handles incoming webhook events from WorkOS Directory Sync.
1788
+ *
1789
+ * This method verifies the webhook signature for security, parses the event,
1790
+ * and routes it to the appropriate handler based on the event type.
1791
+ *
1792
+ * @param payload - Raw webhook payload (string or object)
1793
+ * @param signature - WorkOS signature header for verification
1794
+ * @throws Error if signature verification fails
1795
+ */
1796
+ async handleWebhook(payload, signature) {
1797
+ const parsedPayload = typeof payload === "string" ? JSON.parse(payload) : payload;
1798
+ const event = await this.workos.webhooks.constructEvent({
1799
+ payload: parsedPayload,
1800
+ sigHeader: signature,
1801
+ secret: this.webhookSecret
1802
+ });
1803
+ try {
1804
+ await this.routeEvent(event);
1805
+ } catch (error) {
1806
+ console.error(`[WorkOSDirectorySync] Error handling event ${event.event}:`, error);
1807
+ }
1808
+ }
1809
+ /**
1810
+ * Routes a directory sync event to the appropriate handler.
1811
+ *
1812
+ * @param event - The verified webhook event
1813
+ */
1814
+ async routeEvent(event) {
1815
+ const { event: eventType, data } = event;
1816
+ switch (eventType) {
1817
+ case "dsync.user.created":
1818
+ if (this.handlers.onUserCreated) await this.handlers.onUserCreated(this.mapUserData(data));
1819
+ break;
1820
+ case "dsync.user.updated":
1821
+ if (this.handlers.onUserUpdated) await this.handlers.onUserUpdated(this.mapUserData(data));
1822
+ break;
1823
+ case "dsync.user.deleted":
1824
+ if (this.handlers.onUserDeleted) await this.handlers.onUserDeleted(this.mapUserData(data));
1825
+ break;
1826
+ case "dsync.group.created":
1827
+ if (this.handlers.onGroupCreated) await this.handlers.onGroupCreated(this.mapGroupData(data));
1828
+ break;
1829
+ case "dsync.group.updated":
1830
+ if (this.handlers.onGroupUpdated) await this.handlers.onGroupUpdated(this.mapGroupData(data));
1831
+ break;
1832
+ case "dsync.group.deleted":
1833
+ if (this.handlers.onGroupDeleted) await this.handlers.onGroupDeleted(this.mapGroupData(data));
1834
+ break;
1835
+ case "dsync.group.user_added":
1836
+ if (this.handlers.onGroupUserAdded) await this.handlers.onGroupUserAdded({
1837
+ group: this.mapGroupData(data.group),
1838
+ user: this.mapUserData(data.user)
1839
+ });
1840
+ break;
1841
+ case "dsync.group.user_removed":
1842
+ if (this.handlers.onGroupUserRemoved) await this.handlers.onGroupUserRemoved({
1843
+ group: this.mapGroupData(data.group),
1844
+ user: this.mapUserData(data.user)
1845
+ });
1846
+ break;
1847
+ default: console.warn(`[WorkOSDirectorySync] Unknown event type: ${eventType}`);
1848
+ }
1849
+ }
1850
+ /**
1851
+ * Maps raw webhook user data to the DirectorySyncUserData type.
1852
+ *
1853
+ * @param data - Raw user data from webhook
1854
+ * @returns Typed user data
1855
+ */
1856
+ mapUserData(data) {
1857
+ return {
1858
+ id: data.id,
1859
+ directoryId: data.directory_id,
1860
+ organizationId: data.organization_id,
1861
+ idpId: data.idp_id,
1862
+ firstName: data.first_name,
1863
+ lastName: data.last_name,
1864
+ jobTitle: data.job_title,
1865
+ emails: data.emails ?? [],
1866
+ username: data.username,
1867
+ groups: data.groups ?? [],
1868
+ state: data.state,
1869
+ rawAttributes: data.raw_attributes ?? {},
1870
+ customAttributes: data.custom_attributes ?? {},
1871
+ createdAt: data.created_at,
1872
+ updatedAt: data.updated_at
1873
+ };
1874
+ }
1875
+ /**
1876
+ * Maps raw webhook group data to the DirectorySyncGroupData type.
1877
+ *
1878
+ * @param data - Raw group data from webhook
1879
+ * @returns Typed group data
1880
+ */
1881
+ mapGroupData(data) {
1882
+ return {
1883
+ id: data.id,
1884
+ directoryId: data.directory_id,
1885
+ organizationId: data.organization_id,
1886
+ idpId: data.idp_id,
1887
+ name: data.name,
1888
+ createdAt: data.created_at,
1889
+ updatedAt: data.updated_at,
1890
+ rawAttributes: data.raw_attributes ?? {}
1891
+ };
1892
+ }
1893
+ /**
1894
+ * Lists all directories for an organization.
1895
+ *
1896
+ * @param organizationId - The WorkOS organization ID
1897
+ * @returns Array of directories
1898
+ *
1899
+ * @example
1900
+ * ```typescript
1901
+ * const directories = await directorySync.listDirectories('org_123');
1902
+ * for (const dir of directories) {
1903
+ * console.log(`Directory: ${dir.name} (${dir.type})`);
1904
+ * }
1905
+ * ```
1906
+ */
1907
+ async listDirectories(organizationId) {
1908
+ return (await this.workos.directorySync.listDirectories({ organizationId })).data;
1909
+ }
1910
+ /**
1911
+ * Lists all users in a directory.
1912
+ *
1913
+ * @param directoryId - The directory ID
1914
+ * @returns Array of directory users
1915
+ *
1916
+ * @example
1917
+ * ```typescript
1918
+ * const users = await directorySync.listDirectoryUsers('directory_123');
1919
+ * for (const user of users) {
1920
+ * console.log(`User: ${user.firstName} ${user.lastName}`);
1921
+ * }
1922
+ * ```
1923
+ */
1924
+ async listDirectoryUsers(directoryId) {
1925
+ return (await this.workos.directorySync.listUsers({ directory: directoryId })).data;
1926
+ }
1927
+ /**
1928
+ * Lists all groups in a directory.
1929
+ *
1930
+ * @param directoryId - The directory ID
1931
+ * @returns Array of directory groups
1932
+ *
1933
+ * @example
1934
+ * ```typescript
1935
+ * const groups = await directorySync.listDirectoryGroups('directory_123');
1936
+ * for (const group of groups) {
1937
+ * console.log(`Group: ${group.name}`);
1938
+ * }
1939
+ * ```
1940
+ */
1941
+ async listDirectoryGroups(directoryId) {
1942
+ return (await this.workos.directorySync.listGroups({ directory: directoryId })).data;
1943
+ }
1849
1944
  };
1850
- var WorkOSAdminPortal = class {
1851
- workos;
1852
- returnUrl;
1853
- /**
1854
- * Creates a new WorkOSAdminPortal instance.
1855
- *
1856
- * @param workos - The WorkOS client instance
1857
- * @param options - Configuration options for the Admin Portal
1858
- */
1859
- constructor(workos, options) {
1860
- this.workos = workos;
1861
- this.returnUrl = options?.returnUrl ?? "/";
1862
- }
1863
- /**
1864
- * Generates a link to the WorkOS Admin Portal for a specific organization.
1865
- *
1866
- * The generated link is a one-time use URL that expires after a short period.
1867
- * Users should be redirected to this link immediately after generation.
1868
- *
1869
- * @param organizationId - The WorkOS organization ID (e.g., 'org_01H...')
1870
- * @param intent - The portal section to open. Determines what the user can configure:
1871
- * - `'sso'`: Configure SSO connections (SAML, OIDC providers)
1872
- * - `'dsync'`: Configure Directory Sync (SCIM provisioning)
1873
- * - `'audit_logs'`: View and export audit logs
1874
- * - `'log_streams'`: Configure log streaming to external SIEM systems
1875
- * @returns A promise that resolves to the Admin Portal URL
1876
- *
1877
- * @example
1878
- * ```typescript
1879
- * // SSO configuration (default)
1880
- * const link = await adminPortal.getPortalLink('org_01H...');
1881
- *
1882
- * // Directory Sync configuration
1883
- * const link = await adminPortal.getPortalLink('org_01H...', 'dsync');
1884
- *
1885
- * // Audit logs viewing
1886
- * const link = await adminPortal.getPortalLink('org_01H...', 'audit_logs');
1887
- * ```
1888
- */
1889
- async getPortalLink(organizationId, intent) {
1890
- const result = await this.workos.portal.generateLink({
1891
- organization: organizationId,
1892
- intent: INTENT_MAP[intent ?? "sso"],
1893
- returnUrl: this.returnUrl
1894
- });
1895
- return result.link;
1896
- }
1897
- };
1898
- /**
1899
- * EE Authentication Interfaces
1900
- *
1901
- * Enterprise interfaces for RBAC, ACL, and advanced authorization.
1902
- *
1903
- * @license Mastra Enterprise License - see ee/LICENSE
1904
- * @packageDocumentation
1905
- */
1906
- /**
1907
- * FGA enforcement utility for checking fine-grained authorization.
1908
- *
1909
- * @license Mastra Enterprise License - see ee/LICENSE
1910
- */
1911
- /**
1912
- * RBAC provider implementations.
1913
- *
1914
- * @license Mastra Enterprise License - see ee/LICENSE
1915
- */
1945
+ //#endregion
1946
+ //#region src/admin-portal.ts
1916
1947
  /**
1917
- * Default implementations for EE authentication.
1918
- *
1919
- * @license Mastra Enterprise License - see ee/LICENSE
1920
- */
1948
+ * WorkOS Admin Portal integration for customer self-service configuration.
1949
+ *
1950
+ * The Admin Portal allows enterprise customers to configure their own:
1951
+ * - SSO connections (SAML, OIDC)
1952
+ * - Directory Sync (SCIM)
1953
+ * - Audit log viewing and export
1954
+ * - Log streaming to SIEM systems
1955
+ *
1956
+ * @module
1957
+ */
1921
1958
  /**
1922
- * @mastra/core/auth/ee
1923
- *
1924
- * Enterprise authentication capabilities for Mastra.
1925
- * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
1926
- *
1927
- * @license Mastra Enterprise License - see ee/LICENSE
1928
- * @packageDocumentation
1929
- */
1959
+ * Maps our AdminPortalIntent type to WorkOS GeneratePortalLinkIntent enum.
1960
+ */
1961
+ const INTENT_MAP = {
1962
+ sso: GeneratePortalLinkIntent.SSO,
1963
+ dsync: GeneratePortalLinkIntent.DSync,
1964
+ audit_logs: GeneratePortalLinkIntent.AuditLogs,
1965
+ log_streams: GeneratePortalLinkIntent.LogStreams
1966
+ };
1930
1967
  /**
1931
- * WorkOS FGA provider for Mastra.
1932
- *
1933
- * Integrates WorkOS Authorization API with Mastra's FGA interface
1934
- * for permission-based, resource-level authorization.
1935
- *
1936
- * @license Mastra Enterprise License - see ee/LICENSE
1937
- */
1938
-
1968
+ * Generates links to the WorkOS Admin Portal for customer self-service configuration.
1969
+ *
1970
+ * The Admin Portal provides a pre-built UI where enterprise customers can manage
1971
+ * their own identity configuration without developer intervention.
1972
+ *
1973
+ * @example
1974
+ * ```typescript
1975
+ * import { WorkOS } from '@workos-inc/node';
1976
+ * import { WorkOSAdminPortal } from '@mastra/workos';
1977
+ *
1978
+ * const workos = new WorkOS(process.env.WORKOS_API_KEY);
1979
+ * const adminPortal = new WorkOSAdminPortal(workos, {
1980
+ * returnUrl: 'https://app.example.com/settings',
1981
+ * });
1982
+ *
1983
+ * // Generate a link for SSO configuration
1984
+ * const ssoLink = await adminPortal.getPortalLink('org_01H...', 'sso');
1985
+ *
1986
+ * // Generate a link for Directory Sync configuration
1987
+ * const dsyncLink = await adminPortal.getPortalLink('org_01H...', 'dsync');
1988
+ *
1989
+ * // Redirect the user to the generated link
1990
+ * ```
1991
+ */
1992
+ var WorkOSAdminPortal = class {
1993
+ workos;
1994
+ returnUrl;
1995
+ /**
1996
+ * Creates a new WorkOSAdminPortal instance.
1997
+ *
1998
+ * @param workos - The WorkOS client instance
1999
+ * @param options - Configuration options for the Admin Portal
2000
+ */
2001
+ constructor(workos, options) {
2002
+ this.workos = workos;
2003
+ this.returnUrl = options?.returnUrl ?? "/";
2004
+ }
2005
+ /**
2006
+ * Generates a link to the WorkOS Admin Portal for a specific organization.
2007
+ *
2008
+ * The generated link is a one-time use URL that expires after a short period.
2009
+ * Users should be redirected to this link immediately after generation.
2010
+ *
2011
+ * @param organizationId - The WorkOS organization ID (e.g., 'org_01H...')
2012
+ * @param intent - The portal section to open. Determines what the user can configure:
2013
+ * - `'sso'`: Configure SSO connections (SAML, OIDC providers)
2014
+ * - `'dsync'`: Configure Directory Sync (SCIM provisioning)
2015
+ * - `'audit_logs'`: View and export audit logs
2016
+ * - `'log_streams'`: Configure log streaming to external SIEM systems
2017
+ * @returns A promise that resolves to the Admin Portal URL
2018
+ *
2019
+ * @example
2020
+ * ```typescript
2021
+ * // SSO configuration (default)
2022
+ * const link = await adminPortal.getPortalLink('org_01H...');
2023
+ *
2024
+ * // Directory Sync configuration
2025
+ * const link = await adminPortal.getPortalLink('org_01H...', 'dsync');
2026
+ *
2027
+ * // Audit logs viewing
2028
+ * const link = await adminPortal.getPortalLink('org_01H...', 'audit_logs');
2029
+ * ```
2030
+ */
2031
+ async getPortalLink(organizationId, intent) {
2032
+ return (await this.workos.portal.generateLink({
2033
+ organization: organizationId,
2034
+ intent: INTENT_MAP[intent ?? "sso"],
2035
+ returnUrl: this.returnUrl
2036
+ })).link;
2037
+ }
2038
+ };
2039
+ //#endregion
1939
2040
  export { MastraAuthWorkos, MastraFGAWorkos, MastraRBACWorkos, WebSessionStorage, WorkOSAdminPortal, WorkOSDirectorySync, WorkOSFGAMembershipResolutionError, WorkOSFGAResourceNotFoundError, mapWorkOSUserToEEUser };
1940
- //# sourceMappingURL=index.js.map
2041
+
1941
2042
  //# sourceMappingURL=index.js.map