@mastra/auth-workos 1.6.4 → 1.6.5-alpha.0

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