@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/_types/@internal_auth/dist/_types/@internal_core/dist/base/index.d.ts +27 -27
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/index-Biaf3BmX.d.ts +319 -0
- package/dist/_types/@internal_auth/dist/ee/interfaces/fga.d.ts +11 -0
- package/dist/_types/@internal_auth/dist/ee/interfaces/permissions.generated.d.ts +225 -215
- package/dist/_types/@internal_auth/dist/types/index.d.ts +6 -2
- package/dist/admin-portal.d.ts.map +1 -1
- package/dist/auth-provider.d.ts.map +1 -1
- package/dist/directory-sync.d.ts.map +1 -1
- package/dist/fga-provider.d.ts.map +1 -1
- package/dist/index.cjs +2000 -1900
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1998 -1897
- package/dist/index.js.map +1 -1
- package/dist/rbac-provider.d.ts.map +1 -1
- package/dist/session-storage.d.ts.map +1 -1
- package/package.json +12 -12
- package/CHANGELOG.md +0 -756
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/logger/index.d.ts +0 -217
package/dist/index.cjs
CHANGED
|
@@ -1,1943 +1,2043 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
-
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region ../../packages/_internal-core/dist/base/index.js
|
|
122
241
|
var MastraBase = class {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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
|
-
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region ../../packages/_internals/auth/dist/provider/index.js
|
|
161
276
|
var MastraAuthProvider = class extends MastraBase {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
-
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/types.ts
|
|
333
|
+
/**
|
|
334
|
+
* Maps a WorkOS User to EEUser format.
|
|
335
|
+
*/
|
|
219
336
|
function mapWorkOSUserToEEUser(user) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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
|
-
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region src/auth-provider.ts
|
|
234
351
|
function getWebRequest(request) {
|
|
235
|
-
|
|
236
|
-
|
|
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
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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
|
-
|
|
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
|
-
|
|
255
|
-
|
|
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
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
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
|
-
|
|
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
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
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
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
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
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
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
|
-
|
|
999
|
-
|
|
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
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1311
|
+
return error?.status === 404 || error?.code === "entity_not_found";
|
|
1208
1312
|
}
|
|
1209
1313
|
var WorkOSFGAResourceNotFoundError = class extends Error {
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
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
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
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
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
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
|
-
|
|
1853
|
-
|
|
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
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
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
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
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
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
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
|
-
|
|
2050
|
+
|
|
1951
2051
|
//# sourceMappingURL=index.cjs.map
|