@mastra/server 1.83.0-alpha.4 → 1.83.0-alpha.6
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/{agent-builder-73cAYGts.cjs → agent-builder-BP3doUBF.cjs} +2 -2
- package/dist/{agent-builder-73cAYGts.cjs.map → agent-builder-BP3doUBF.cjs.map} +1 -1
- package/dist/{agent-builder-pQaGXyFz.js → agent-builder-tQdzjW0P.js} +2 -2
- package/dist/{agent-builder-pQaGXyFz.js.map → agent-builder-tQdzjW0P.js.map} +1 -1
- package/dist/{api-schema-manifest-C4KWBHOE.cjs → api-schema-manifest-Bsbh_Rp6.cjs} +2 -2
- package/dist/{api-schema-manifest-C4KWBHOE.cjs.map → api-schema-manifest-Bsbh_Rp6.cjs.map} +1 -1
- package/dist/{api-schema-manifest-BNmKPj1d.js → api-schema-manifest-BuUPZy-0.js} +2 -2
- package/dist/{api-schema-manifest-BNmKPj1d.js.map → api-schema-manifest-BuUPZy-0.js.map} +1 -1
- package/dist/{dist-CXxA_Jnu.js → dist-C3cKdDos.js} +82 -21
- package/dist/{dist-CXxA_Jnu.js.map → dist-C3cKdDos.js.map} +1 -1
- package/dist/dist-CDQ0dDmK.js +1 -0
- package/dist/{dist-Dhi6UZwv.cjs → dist-DlH7rr5l.cjs} +1 -1
- package/dist/{dist-DIeKEdwH.cjs → dist-bVYV7beH.cjs} +82 -21
- package/dist/{dist-DIeKEdwH.cjs.map → dist-bVYV7beH.cjs.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/{helpers-B29a1nM3.js → helpers-C3dENOkQ.js} +183 -53
- package/dist/helpers-C3dENOkQ.js.map +1 -0
- package/dist/{helpers-CylvUIZm.cjs → helpers-D7d2R3LL.cjs} +188 -52
- package/dist/helpers-D7d2R3LL.cjs.map +1 -0
- package/dist/{memory-JzgWJevA.js → memory-B_qwCpu5.js} +89 -39
- package/dist/memory-B_qwCpu5.js.map +1 -0
- package/dist/{memory-DIos0BE-.cjs → memory-BfabRYCo.cjs} +89 -39
- package/dist/memory-BfabRYCo.cjs.map +1 -0
- package/dist/{probe-image-size-C2efNs3R.cjs → probe-image-size-0dhxcl8e.cjs} +2 -2
- package/dist/{probe-image-size-C2efNs3R.cjs.map → probe-image-size-0dhxcl8e.cjs.map} +1 -1
- package/dist/{probe-image-size-CO02-278.js → probe-image-size-fFwPOWWg.js} +2 -2
- package/dist/{probe-image-size-CO02-278.js.map → probe-image-size-fFwPOWWg.js.map} +1 -1
- package/dist/route-builder-BKEzjw_M.js.map +1 -1
- package/dist/route-builder-DHqDrSSy.cjs.map +1 -1
- package/dist/{routes-BtJyuAGq.cjs → routes-B0HqAMAk.cjs} +3 -3
- package/dist/{routes-BtJyuAGq.cjs.map → routes-B0HqAMAk.cjs.map} +1 -1
- package/dist/{routes-DgMuPPQr.js → routes-u0J9BsY1.js} +3 -3
- package/dist/{routes-DgMuPPQr.js.map → routes-u0J9BsY1.js.map} +1 -1
- package/dist/server/auth/custom-route-matcher.d.ts +54 -0
- package/dist/server/auth/custom-route-matcher.d.ts.map +1 -0
- package/dist/server/auth/helpers.d.ts +14 -5
- package/dist/server/auth/helpers.d.ts.map +1 -1
- package/dist/server/auth/index.cjs +1 -1
- package/dist/server/auth/index.js +1 -1
- package/dist/server/auth/path-pattern.d.ts.map +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/auth.cjs +1 -1
- package/dist/server/handlers/auth.js +1 -1
- package/dist/server/handlers/datasets.cjs +22 -3
- package/dist/server/handlers/datasets.cjs.map +1 -1
- package/dist/server/handlers/datasets.d.ts +8 -2
- package/dist/server/handlers/datasets.d.ts.map +1 -1
- package/dist/server/handlers/datasets.js +22 -3
- package/dist/server/handlers/datasets.js.map +1 -1
- package/dist/server/handlers/memory.cjs +1 -1
- package/dist/server/handlers/memory.d.ts.map +1 -1
- package/dist/server/handlers/memory.js +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers.cjs +2 -2
- package/dist/server/handlers.js +2 -2
- package/dist/server/server-adapter/api-schema-manifest.d.ts +1 -1
- package/dist/server/server-adapter/index.cjs +68 -4
- package/dist/server/server-adapter/index.cjs.map +1 -1
- package/dist/server/server-adapter/index.d.ts +34 -0
- package/dist/server/server-adapter/index.d.ts.map +1 -1
- package/dist/server/server-adapter/index.js +68 -4
- package/dist/server/server-adapter/index.js.map +1 -1
- package/dist/server/server-adapter/openapi-utils.d.ts +1 -1
- package/dist/server/server-adapter/routes/datasets.d.ts +8 -2
- package/dist/server/server-adapter/routes/datasets.d.ts.map +1 -1
- package/dist/server/server-adapter/routes/workspace.d.ts +23 -23
- package/package.json +4 -4
- package/dist/dist-CQGBYe6U.js +0 -1
- package/dist/helpers-B29a1nM3.js.map +0 -1
- package/dist/helpers-CylvUIZm.cjs.map +0 -1
- package/dist/memory-DIos0BE-.cjs.map +0 -1
- package/dist/memory-JzgWJevA.js.map +0 -1
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/_types/@internal_ai-sdk-v4@0.0.95/dist/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/_types/@internal_ai-sdk-v5@0.0.95/dist/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/_types/@internal_ai-v6@0.0.95/dist/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/_types/@standard-schema_spec@1.1.0/dist/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/_types/@types_json-schema@7.0.15/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/index.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/null-to-undefined.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/anthropic.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/deepseek.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/google.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/meta.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/openai-reasoning.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/provider-compats/openai.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/schema-compatibility-v3.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/schema-compatibility-v4.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/schema-compatibility.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/schema.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/schema.types.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/standard-schema/standard-schema.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/standard-schema/standard-schema.types.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/standard-schema-compat.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/types.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/utils.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/dist/zod-to-json.d.ts +0 -0
- /package/dist/_types/{@mastra_schema-compat@1.3.17 → @mastra_schema-compat@1.3.18-alpha.0}/package.json +0 -0
|
@@ -1,6 +1,104 @@
|
|
|
1
1
|
const require_constants = require("./constants-DMg8hUOR.cjs");
|
|
2
2
|
const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
|
|
3
3
|
let _mastra_core_server = require("@mastra/core/server");
|
|
4
|
+
let hono = require("hono");
|
|
5
|
+
let hono_request = require("hono/request");
|
|
6
|
+
// src/server/auth/custom-route-matcher.ts
|
|
7
|
+
const noopMiddleware = () => void 0;
|
|
8
|
+
const paramRequest = new Request("http://localhost/");
|
|
9
|
+
/**
|
|
10
|
+
* Answers "which custom route will run for this request?" using the same Hono router
|
|
11
|
+
* the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in
|
|
12
|
+
* the same order with the same paths and methods. Auth decisions use this instead
|
|
13
|
+
* of a separate pattern matcher, so they can't disagree with dispatch on precedence,
|
|
14
|
+
* case, trailing slashes, percent-decoding or HEAD handling.
|
|
15
|
+
*/
|
|
16
|
+
var CustomRouteMatcher = class {
|
|
17
|
+
#app = new hono.Hono();
|
|
18
|
+
#indexByHandler = /* @__PURE__ */ new Map();
|
|
19
|
+
#entries;
|
|
20
|
+
constructor(entries) {
|
|
21
|
+
this.#entries = entries;
|
|
22
|
+
this.#app.use("*", noopMiddleware);
|
|
23
|
+
entries.forEach((entry, index) => {
|
|
24
|
+
const marker = () => void 0;
|
|
25
|
+
this.#indexByHandler.set(marker, index);
|
|
26
|
+
const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker);
|
|
27
|
+
if (entry.method === "ALL") this.#app.all(entry.path, handlers[0], ...handlers.slice(1));
|
|
28
|
+
else this.#app.on(entry.method, entry.path, handlers[0], ...handlers.slice(1));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Match a path the way Hono dispatches it, i.e. `path` is already in the form
|
|
33
|
+
* `getPath()` returns (no query string, percent-decoded once).
|
|
34
|
+
* Throws if Hono can't build a router for the registered paths.
|
|
35
|
+
*/
|
|
36
|
+
matchPath(path, method) {
|
|
37
|
+
const upper = method.toUpperCase();
|
|
38
|
+
const dispatchMethod = upper === "HEAD" ? "GET" : upper;
|
|
39
|
+
const result = this.#app.router.match(dispatchMethod, path);
|
|
40
|
+
const handlers = result[0];
|
|
41
|
+
for (let i = 0; i < handlers.length; i++) {
|
|
42
|
+
const index = this.#indexByHandler.get(handlers[i][0][0]);
|
|
43
|
+
if (index === void 0) continue;
|
|
44
|
+
const request = new hono_request.HonoRequest(paramRequest, path, result);
|
|
45
|
+
request.routeIndex = i;
|
|
46
|
+
return {
|
|
47
|
+
entry: this.#entries[index],
|
|
48
|
+
index,
|
|
49
|
+
params: request.param()
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Match the full URL handed to the custom-route app. Parses it the same way
|
|
55
|
+
* (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters
|
|
56
|
+
* and the query string are handled exactly as dispatch handles them.
|
|
57
|
+
* Throws if the URL can't be parsed.
|
|
58
|
+
*/
|
|
59
|
+
matchUrl(url, method) {
|
|
60
|
+
const path = this.#app.getPath(new Request(url));
|
|
61
|
+
return this.matchPath(path, method);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to
|
|
65
|
+
* the path Hono would dispatch when the bridge forwards it. Throws on an
|
|
66
|
+
* unparseable path.
|
|
67
|
+
*/
|
|
68
|
+
dispatchPathForRawPath(rawPath) {
|
|
69
|
+
return this.#app.getPath(new Request(`http://localhost${rawPath}`));
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const MAX_CACHED_MATCHERS = 32;
|
|
73
|
+
const matcherCache = /* @__PURE__ */ new Map();
|
|
74
|
+
/**
|
|
75
|
+
* Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are
|
|
76
|
+
* `METHOD:path` in registration order, which is the order the server registers
|
|
77
|
+
* custom routes with the custom-route app.
|
|
78
|
+
*/
|
|
79
|
+
function getCustomRouteAuthConfigMatcher(keys) {
|
|
80
|
+
const signature = JSON.stringify(keys);
|
|
81
|
+
const cached = matcherCache.get(signature);
|
|
82
|
+
if (cached) {
|
|
83
|
+
matcherCache.delete(signature);
|
|
84
|
+
matcherCache.set(signature, cached);
|
|
85
|
+
return cached;
|
|
86
|
+
}
|
|
87
|
+
const entries = [];
|
|
88
|
+
for (const key of keys) {
|
|
89
|
+
const colonIndex = key.indexOf(":");
|
|
90
|
+
if (colonIndex === -1) continue;
|
|
91
|
+
entries.push({
|
|
92
|
+
key,
|
|
93
|
+
method: key.substring(0, colonIndex).toUpperCase(),
|
|
94
|
+
path: key.substring(colonIndex + 1)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const matcher = new CustomRouteMatcher(entries);
|
|
98
|
+
matcherCache.set(signature, matcher);
|
|
99
|
+
if (matcherCache.size > MAX_CACHED_MATCHERS) matcherCache.delete(matcherCache.keys().next().value);
|
|
100
|
+
return matcher;
|
|
101
|
+
}
|
|
4
102
|
// src/server/auth/defaults.ts
|
|
5
103
|
const defaultAuthConfig = {
|
|
6
104
|
protected: ["/api/*"],
|
|
@@ -49,7 +147,7 @@ function parse(input, loose) {
|
|
|
49
147
|
keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));
|
|
50
148
|
pattern += !!~o && !~ext ? "(?:/([^/]+?))?" : "/([^/]+?)";
|
|
51
149
|
if (~ext) pattern += (~o ? "?" : "") + "\\" + tmp.substring(ext);
|
|
52
|
-
} else pattern += "/" + tmp;
|
|
150
|
+
} else pattern += "/" + tmp.replace(/([.+*?^${}()|[\]\\])/g, "\\$1");
|
|
53
151
|
}
|
|
54
152
|
return {
|
|
55
153
|
keys,
|
|
@@ -58,45 +156,87 @@ function parse(input, loose) {
|
|
|
58
156
|
}
|
|
59
157
|
// src/server/auth/helpers.ts
|
|
60
158
|
/**
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
159
|
+
* Decide auth for a request from the custom route the custom-route app will dispatch
|
|
160
|
+
* it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.
|
|
161
|
+
*
|
|
162
|
+
* Fails closed:
|
|
163
|
+
* - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a
|
|
164
|
+
* path registered as protected is never served without auth;
|
|
165
|
+
* - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already
|
|
166
|
+
* decoded, so it's resolved both ways and is only public if every reading lands on
|
|
167
|
+
* a public route, and protected if any reading lands on a protected one;
|
|
168
|
+
* - if the routes or the path can't be parsed, the request is treated as protected.
|
|
64
169
|
*/
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
if (customRouteAuthConfig.
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
170
|
+
const resolveCustomRouteAuth = (path, method, customRouteAuthConfig) => {
|
|
171
|
+
const upperMethod = method.toUpperCase();
|
|
172
|
+
const methods = upperMethod === "HEAD" ? ["HEAD", "GET"] : [upperMethod];
|
|
173
|
+
for (const m of methods) if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) return "protected";
|
|
174
|
+
const keys = [...customRouteAuthConfig.keys()];
|
|
175
|
+
const lastKey = keys[keys.length - 1];
|
|
176
|
+
const pinnedKey = lastKey !== void 0 && methods.some((m) => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`) ? lastKey : void 0;
|
|
177
|
+
let matcher;
|
|
178
|
+
const candidates = /* @__PURE__ */ new Set([path]);
|
|
179
|
+
try {
|
|
180
|
+
matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);
|
|
181
|
+
candidates.add(matcher.dispatchPathForRawPath(path));
|
|
182
|
+
} catch {
|
|
183
|
+
return "protected";
|
|
78
184
|
}
|
|
79
|
-
|
|
185
|
+
let matchedPublic = false;
|
|
186
|
+
let unmatched = false;
|
|
187
|
+
for (const candidate of candidates) {
|
|
188
|
+
let key;
|
|
189
|
+
try {
|
|
190
|
+
key = matcher.matchPath(candidate, upperMethod)?.entry.key;
|
|
191
|
+
} catch {
|
|
192
|
+
return "protected";
|
|
193
|
+
}
|
|
194
|
+
if (key === void 0 && pinnedKey && candidate === path) key = pinnedKey;
|
|
195
|
+
if (key === void 0) {
|
|
196
|
+
unmatched = true;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (customRouteAuthConfig.get(key) !== false) return "protected";
|
|
200
|
+
matchedPublic = true;
|
|
201
|
+
}
|
|
202
|
+
return matchedPublic && !unmatched ? "public" : "none";
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* Check if a request will be handled by a registered custom route that requires
|
|
206
|
+
* authentication. The route that decides is the one the custom-route app dispatches
|
|
207
|
+
* to (first registered match), using Hono's own matching. Returns false when no
|
|
208
|
+
* custom route handles the request.
|
|
209
|
+
*/
|
|
210
|
+
const isProtectedCustomRoute = (path, method, customRouteAuthConfig) => {
|
|
211
|
+
if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) return false;
|
|
212
|
+
return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === "protected";
|
|
80
213
|
};
|
|
214
|
+
const apiRouteMatchers = /* @__PURE__ */ new WeakMap();
|
|
81
215
|
/**
|
|
82
|
-
* Find
|
|
83
|
-
*
|
|
216
|
+
* Find the custom API route Hono dispatches `path` to, with its decoded path params.
|
|
217
|
+
* `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).
|
|
218
|
+
* Matching follows Hono: first registered match wins, case-sensitive, strict
|
|
219
|
+
* trailing slash, and HEAD is served by GET routes.
|
|
84
220
|
*/
|
|
85
221
|
const findMatchingCustomRoute = (path, method, apiRoutes) => {
|
|
86
|
-
if (!apiRoutes) return void 0;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (keys && keys.length > 0) {
|
|
94
|
-
for (let i = 0; i < keys.length; i++) if (match[i + 1] !== void 0) params[keys[i]] = match[i + 1];
|
|
95
|
-
}
|
|
96
|
-
return {
|
|
97
|
-
route,
|
|
98
|
-
params
|
|
222
|
+
if (!apiRoutes || apiRoutes.length === 0) return void 0;
|
|
223
|
+
const signature = JSON.stringify(apiRoutes.map((route) => `${route.method}:${route.path}`));
|
|
224
|
+
let cached = apiRouteMatchers.get(apiRoutes);
|
|
225
|
+
if (!cached || cached.signature !== signature) {
|
|
226
|
+
cached = {
|
|
227
|
+
signature,
|
|
228
|
+
matcher: new CustomRouteMatcher(apiRoutes)
|
|
99
229
|
};
|
|
230
|
+
apiRouteMatchers.set(apiRoutes, cached);
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const match = cached.matcher.matchPath(path, method);
|
|
234
|
+
return match ? {
|
|
235
|
+
route: match.entry,
|
|
236
|
+
params: match.params
|
|
237
|
+
} : void 0;
|
|
238
|
+
} catch {
|
|
239
|
+
return;
|
|
100
240
|
}
|
|
101
241
|
};
|
|
102
242
|
/**
|
|
@@ -108,25 +248,15 @@ const isDevPlaygroundRequest = (path, method, getHeader, authConfig, customRoute
|
|
|
108
248
|
const protectedAccess = [...defaultAuthConfig.protected || [], ...authConfig.protected || []];
|
|
109
249
|
return process.env.MASTRA_DEV === "true" && (!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig) || getHeader("x-mastra-dev-playground") === "true");
|
|
110
250
|
};
|
|
251
|
+
/**
|
|
252
|
+
* Check if a request will be handled by a custom route registered as public
|
|
253
|
+
* (`requiresAuth: false`). Uses the same dispatch-order resolution as
|
|
254
|
+
* `isProtectedCustomRoute`, and returns false (not public) when no custom route
|
|
255
|
+
* handles the request or the answer is ambiguous.
|
|
256
|
+
*/
|
|
111
257
|
const isCustomRoutePublic = (path, method, customRouteAuthConfig) => {
|
|
112
|
-
if (!customRouteAuthConfig) return false;
|
|
113
|
-
|
|
114
|
-
if (customRouteAuthConfig.has(exactRouteKey)) return !customRouteAuthConfig.get(exactRouteKey);
|
|
115
|
-
const allRouteKey = `ALL:${path}`;
|
|
116
|
-
if (customRouteAuthConfig.has(allRouteKey)) return !customRouteAuthConfig.get(allRouteKey);
|
|
117
|
-
let matchedPublic = false;
|
|
118
|
-
for (const [routeKey, requiresAuth] of customRouteAuthConfig.entries()) {
|
|
119
|
-
const colonIndex = routeKey.indexOf(":");
|
|
120
|
-
if (colonIndex === -1) continue;
|
|
121
|
-
const routeMethod = routeKey.substring(0, colonIndex);
|
|
122
|
-
const routePattern = routeKey.substring(colonIndex + 1);
|
|
123
|
-
if (routeMethod !== method && routeMethod !== "ALL") continue;
|
|
124
|
-
if (pathMatchesPattern(path, routePattern)) {
|
|
125
|
-
if (requiresAuth) return false;
|
|
126
|
-
matchedPublic = true;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return matchedPublic;
|
|
258
|
+
if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) return false;
|
|
259
|
+
return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === "public";
|
|
130
260
|
};
|
|
131
261
|
const isProtectedPath = (path, method, authConfig, customRouteAuthConfig) => {
|
|
132
262
|
const protectedAccess = [...defaultAuthConfig.protected || [], ...authConfig.protected || []];
|
|
@@ -438,6 +568,12 @@ const checkRules = async (rules, path, method, user) => {
|
|
|
438
568
|
}
|
|
439
569
|
return false;
|
|
440
570
|
};
|
|
571
|
+
Object.defineProperty(exports, "CustomRouteMatcher", {
|
|
572
|
+
enumerable: true,
|
|
573
|
+
get: function() {
|
|
574
|
+
return CustomRouteMatcher;
|
|
575
|
+
}
|
|
576
|
+
});
|
|
441
577
|
Object.defineProperty(exports, "authorizeAuthenticatedUser", {
|
|
442
578
|
enumerable: true,
|
|
443
579
|
get: function() {
|
|
@@ -529,4 +665,4 @@ Object.defineProperty(exports, "supportsSessionRefresh", {
|
|
|
529
665
|
}
|
|
530
666
|
});
|
|
531
667
|
|
|
532
|
-
//# sourceMappingURL=helpers-
|
|
668
|
+
//# sourceMappingURL=helpers-D7d2R3LL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers-D7d2R3LL.cjs","names":["Hono","HonoRequest","HTTPException","MASTRA_USER_KEY","MASTRA_AUTH_TOKEN_KEY","CompositeAuth","MASTRA_RESOURCE_ID_KEY","MASTRA_AUTH_MODE_KEY","MASTRA_USER_PERMISSIONS_KEY","MASTRA_USER_ROLES_KEY"],"sources":["../src/server/auth/custom-route-matcher.ts","../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { HonoRequest } from 'hono/request';\n\n/** A custom route as the internal custom-route Hono app registers it. */\nexport interface CustomRouteMatcherEntry {\n method: string;\n path: string;\n /**\n * How many handlers (route middleware + handler) the route registers. Hono stores\n * each one as its own router entry, so mirror the count to build the same router.\n */\n handlerCount?: number;\n}\n\nexport interface CustomRouteMatch<T> {\n entry: T;\n index: number;\n params: Record<string, string>;\n}\n\ntype Marker = (...args: unknown[]) => undefined;\n\nconst noopMiddleware: Marker = () => undefined;\nconst paramRequest = new Request('http://localhost/');\n\n/**\n * Answers \"which custom route will run for this request?\" using the same Hono router\n * the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in\n * the same order with the same paths and methods. Auth decisions use this instead\n * of a separate pattern matcher, so they can't disagree with dispatch on precedence,\n * case, trailing slashes, percent-decoding or HEAD handling.\n */\nexport class CustomRouteMatcher<T extends CustomRouteMatcherEntry> {\n readonly #app = new Hono();\n readonly #indexByHandler = new Map<unknown, number>();\n readonly #entries: readonly T[];\n\n constructor(entries: readonly T[]) {\n this.#entries = entries;\n // Same global middleware as the custom-route app, so the router sees the same table.\n this.#app.use('*', noopMiddleware as never);\n entries.forEach((entry, index) => {\n const marker: Marker = () => undefined;\n this.#indexByHandler.set(marker, index);\n const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker as never);\n if (entry.method === 'ALL') {\n this.#app.all(entry.path, handlers[0]!, ...handlers.slice(1));\n } else {\n this.#app.on(entry.method, entry.path, handlers[0]!, ...handlers.slice(1));\n }\n });\n }\n\n /**\n * Match a path the way Hono dispatches it, i.e. `path` is already in the form\n * `getPath()` returns (no query string, percent-decoded once).\n * Throws if Hono can't build a router for the registered paths.\n */\n matchPath(path: string, method: string): CustomRouteMatch<T> | undefined {\n const upper = method.toUpperCase();\n // Hono serves HEAD with the GET handler.\n const dispatchMethod = upper === 'HEAD' ? 'GET' : upper;\n const result = this.#app.router.match(dispatchMethod, path);\n const handlers = result[0];\n for (let i = 0; i < handlers.length; i++) {\n const index = this.#indexByHandler.get(handlers[i]![0][0]);\n if (index === undefined) continue; // the global middleware\n const request = new HonoRequest(paramRequest, path, result as never);\n request.routeIndex = i;\n return { entry: this.#entries[index]!, index, params: request.param() as Record<string, string> };\n }\n return undefined;\n }\n\n /**\n * Match the full URL handed to the custom-route app. Parses it the same way\n * (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters\n * and the query string are handled exactly as dispatch handles them.\n * Throws if the URL can't be parsed.\n */\n matchUrl(url: string, method: string): CustomRouteMatch<T> | undefined {\n const path = this.#app.getPath(new Request(url));\n return this.matchPath(path, method);\n }\n\n /**\n * Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to\n * the path Hono would dispatch when the bridge forwards it. Throws on an\n * unparseable path.\n */\n dispatchPathForRawPath(rawPath: string): string {\n return this.#app.getPath(new Request(`http://localhost${rawPath}`));\n }\n}\n\nconst MAX_CACHED_MATCHERS = 32;\nconst matcherCache = new Map<string, CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }>>();\n\n/**\n * Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are\n * `METHOD:path` in registration order, which is the order the server registers\n * custom routes with the custom-route app.\n */\nexport function getCustomRouteAuthConfigMatcher(\n keys: readonly string[],\n): CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }> {\n const signature = JSON.stringify(keys);\n const cached = matcherCache.get(signature);\n if (cached) {\n matcherCache.delete(signature);\n matcherCache.set(signature, cached);\n return cached;\n }\n\n const entries: Array<CustomRouteMatcherEntry & { key: string }> = [];\n for (const key of keys) {\n const colonIndex = key.indexOf(':');\n if (colonIndex === -1) continue; // malformed key\n entries.push({ key, method: key.substring(0, colonIndex).toUpperCase(), path: key.substring(colonIndex + 1) });\n }\n\n const matcher = new CustomRouteMatcher(entries);\n matcherCache.set(signature, matcher);\n if (matcherCache.size > MAX_CACHED_MATCHERS) {\n matcherCache.delete(matcherCache.keys().next().value!);\n }\n return matcher;\n}\n","import type { MastraAuthConfig } from '@mastra/core/server';\n\n// Default configuration that can be extended by clients\nexport const defaultAuthConfig: MastraAuthConfig = {\n protected: ['/api/*'],\n public: ['/api', '/api/auth/*'],\n // Simple rule system\n rules: [\n // Admin users can do anything\n {\n condition: user => {\n if (typeof user === 'object' && user !== null) {\n if ('isAdmin' in user) {\n return !!user.isAdmin;\n }\n\n if ('role' in user) {\n return user.role === 'admin';\n }\n }\n return false;\n },\n allow: true,\n },\n ],\n};\n","/**\n * Path pattern matching utility\n * Inlined from regexparam v3.0.0 (MIT License)\n * https://github.com/lukeed/regexparam\n *\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface ParsedPattern {\n keys: string[] | false;\n pattern: RegExp;\n}\n\n/**\n * Parse a route pattern into a RegExp\n * Supports:\n * - Named parameters: /users/:id\n * - Optional parameters: /users/:id?\n * - Wildcards: /files/*\n * - Mixed patterns: /api/:version/users/:id\n */\nexport function parse(input: string | RegExp, loose?: boolean): ParsedPattern {\n if (input instanceof RegExp) return { keys: false, pattern: input };\n\n let c: string;\n let o: number;\n let tmp: string | undefined;\n let ext: number;\n const keys: string[] = [];\n let pattern = '';\n const arr = input.split('/');\n\n arr[0] || arr.shift();\n\n while ((tmp = arr.shift())) {\n c = tmp[0]!;\n if (c === '*') {\n keys.push(c);\n pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';\n } else if (c === ':') {\n o = tmp.indexOf('?', 1);\n ext = tmp.indexOf('.', 1);\n keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));\n pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n if (~ext) pattern += (~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n } else {\n // Escape regex metacharacters so static segments stay literal. Without this,\n // a public route like '/a.b' would also match '/axb' and could skip auth for\n // a later protected route the framework dispatches instead.\n pattern += '/' + tmp.replace(/([.+*?^${}()|[\\]\\\\])/g, '\\\\$1');\n }\n }\n\n return {\n keys: keys,\n pattern: new RegExp('^' + pattern + (loose ? '(?=$|/)' : '/?$'), 'i'),\n };\n}\n\n/**\n * Test if a path matches a pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean {\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n}\n","import type { ISessionProvider } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth } from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, MastraAuthConfig, MastraAuthRequest } from '@mastra/core/server';\n\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_AUTH_MODE_KEY,\n} from '../constants';\nimport { HTTPException } from '../http-exception';\nimport { CustomRouteMatcher, getCustomRouteAuthConfigMatcher } from './custom-route-matcher';\nimport { defaultAuthConfig } from './defaults';\nimport { parse } from './path-pattern';\n\n// Re-export request-context key constants so custom middleware can read namespaced\n// auth state without importing internal paths.\nexport { MASTRA_USER_KEY, MASTRA_USER_PERMISSIONS_KEY, MASTRA_USER_ROLES_KEY } from '../constants';\n\ntype CustomRouteAuthDecision = 'protected' | 'public' | 'none';\n\n/**\n * Decide auth for a request from the custom route the custom-route app will dispatch\n * it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.\n *\n * Fails closed:\n * - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a\n * path registered as protected is never served without auth;\n * - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already\n * decoded, so it's resolved both ways and is only public if every reading lands on\n * a public route, and protected if any reading lands on a protected one;\n * - if the routes or the path can't be parsed, the request is treated as protected.\n */\nconst resolveCustomRouteAuth = (\n path: string,\n method: string,\n customRouteAuthConfig: Map<string, boolean>,\n): CustomRouteAuthDecision => {\n const upperMethod = method.toUpperCase();\n const methods = upperMethod === 'HEAD' ? ['HEAD', 'GET'] : [upperMethod];\n for (const m of methods) {\n if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) {\n return 'protected';\n }\n }\n\n // Adapters pin the current request by appending `METHOD:path` to a copy of the map.\n // As the last entry it only decides when no earlier route matches, so resolve the\n // rest with a cached matcher and fall back to it, instead of building a new router\n // for every request path.\n const keys = [...customRouteAuthConfig.keys()];\n const lastKey = keys[keys.length - 1];\n const pinnedKey =\n lastKey !== undefined && methods.some(m => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`)\n ? lastKey\n : undefined;\n\n let matcher: ReturnType<typeof getCustomRouteAuthConfigMatcher>;\n const candidates = new Set<string>([path]);\n try {\n matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);\n candidates.add(matcher.dispatchPathForRawPath(path));\n } catch {\n return 'protected';\n }\n\n let matchedPublic = false;\n let unmatched = false;\n for (const candidate of candidates) {\n let key: string | undefined;\n try {\n key = matcher.matchPath(candidate, upperMethod)?.entry.key;\n } catch {\n return 'protected';\n }\n if (key === undefined && pinnedKey && candidate === path) {\n key = pinnedKey;\n }\n if (key === undefined) {\n unmatched = true;\n continue;\n }\n if (customRouteAuthConfig.get(key) !== false) {\n return 'protected';\n }\n matchedPublic = true;\n }\n\n return matchedPublic && !unmatched ? 'public' : 'none';\n};\n\n/**\n * Check if a request will be handled by a registered custom route that requires\n * authentication. The route that decides is the one the custom-route app dispatches\n * to (first registered match), using Hono's own matching. Returns false when no\n * custom route handles the request.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'protected';\n};\n\nconst apiRouteMatchers = new WeakMap<\n readonly ApiRoute[],\n { signature: string; matcher: CustomRouteMatcher<ApiRoute> }\n>();\n\n/**\n * Find the custom API route Hono dispatches `path` to, with its decoded path params.\n * `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).\n * Matching follows Hono: first registered match wins, case-sensitive, strict\n * trailing slash, and HEAD is served by GET routes.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes || apiRoutes.length === 0) return undefined;\n\n const signature = JSON.stringify(apiRoutes.map(route => `${route.method}:${route.path}`));\n let cached = apiRouteMatchers.get(apiRoutes);\n if (!cached || cached.signature !== signature) {\n cached = { signature, matcher: new CustomRouteMatcher(apiRoutes) };\n apiRouteMatchers.set(apiRoutes, cached);\n }\n\n try {\n const match = cached.matcher.matchPath(path, method);\n return match ? { route: match.entry, params: match.params } : undefined;\n } catch {\n // Hono can't route these paths either, so no custom route handles the request.\n return undefined;\n }\n};\n\n/**\n * Check if request is from dev playground\n * @param getHeader - Function to get header value from request\n * @param customRouteAuthConfig - Map of custom route auth configurations\n */\nexport const isDevPlaygroundRequest = (\n path: string,\n method: string,\n getHeader: (name: string) => string | undefined,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return (\n process.env.MASTRA_DEV === 'true' &&\n // Allow if path doesn't match protected patterns AND is not a protected custom route\n ((!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig)) ||\n // Or if has playground header\n getHeader('x-mastra-dev-playground') === 'true')\n );\n};\n\n/**\n * Check if a request will be handled by a custom route registered as public\n * (`requiresAuth: false`). Uses the same dispatch-order resolution as\n * `isProtectedCustomRoute`, and returns false (not public) when no custom route\n * handles the request or the answer is ambiguous.\n */\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'public';\n};\n\n// NOTE: This uses isProtectedCustomRoute (default-allow for unknown paths) rather than\n// !isCustomRoutePublic (default-deny). This is intentional — all registered server and\n// custom routes are auth-checked via registerRoute/checkRouteAuth regardless of this\n// function. The '/api/*' protected pattern exists as a user-facing override mechanism.\n// The old default-deny logic incorrectly blocked non-API paths (e.g. '/', '/agents')\n// which prevented the studio login page from loading in production.\nexport const isProtectedPath = (\n path: string,\n method: string,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return isAnyMatch(path, method, protectedAccess) || isProtectedCustomRoute(path, method, customRouteAuthConfig);\n};\n\nexport const canAccessPublicly = (path: string, method: string, authConfig: MastraAuthConfig): boolean => {\n // Check if this path+method combination is publicly accessible\n const publicAccess = [...(defaultAuthConfig.public || []), ...(authConfig.public || [])];\n\n return isAnyMatch(path, method, publicAccess);\n};\n\nconst isAnyMatch = (\n path: string,\n method: string,\n patterns: MastraAuthConfig['protected'] | MastraAuthConfig['public'],\n): boolean => {\n if (!patterns) {\n return false;\n }\n\n for (const patternPathOrMethod of patterns) {\n if (patternPathOrMethod instanceof RegExp) {\n if (patternPathOrMethod.test(path)) {\n return true;\n }\n }\n\n if (typeof patternPathOrMethod === 'string' && pathMatchesPattern(path, patternPathOrMethod)) {\n return true;\n }\n\n if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {\n const [pattern, methodOrMethods] = patternPathOrMethod;\n if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\nexport const pathMatchesPattern = (path: string, pattern: string): boolean => {\n // Use regexparam for battle-tested path matching\n // Supports:\n // - Exact paths: '/api/users'\n // - Wildcards: '/api/agents/*' matches '/api/agents/123'\n // - Path parameters: '/users/:id' matches '/users/123'\n // - Optional parameters: '/users/:id?' matches '/users' and '/users/123'\n // - Mixed patterns: '/api/:version/users/:id/profile'\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n};\n\nexport const pathMatchesRule = (path: string, rulePath: string | RegExp | string[] | undefined): boolean => {\n if (!rulePath) return true; // No path specified means all paths\n\n if (typeof rulePath === 'string') {\n return pathMatchesPattern(path, rulePath);\n }\n\n if (rulePath instanceof RegExp) {\n return rulePath.test(path);\n }\n\n if (Array.isArray(rulePath)) {\n return rulePath.some(p => pathMatchesPattern(path, p));\n }\n\n return false;\n};\n\nexport const matchesOrIncludes = (values: string | string[], value: string): boolean => {\n if (typeof values === 'string') {\n return values === value;\n }\n\n if (Array.isArray(values)) {\n return values.includes(value);\n }\n\n return false;\n};\n\n// ── Core auth middleware ──\n// Framework-agnostic auth logic extracted from adapter middlewares.\n// Each adapter builds an AuthMiddlewareContext and delegates to coreAuthMiddleware.\n\nexport interface AuthMiddlewareContext {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: { get: (key: string) => unknown; set: (key: string, value: unknown) => void };\n rawRequest: MastraAuthRequest;\n token: string | null;\n buildAuthorizeContext: () => unknown;\n /** When true, force authentication even if the path matches a public pattern. */\n requiresAuth?: boolean;\n}\n\nexport type AuthResult =\n | { action: 'next'; headers?: Record<string, string> }\n | { action: 'error'; status: number; body: Record<string, unknown>; headers?: Record<string, string> };\n\nconst pass: AuthResult = { action: 'next' };\n\n/**\n * Lets an app's `authorize(path, method, user, context)` read `context.get('requestContext')` and\n * `context.get('mastra')` on every adapter, as it can on Hono, so per-caller values (the Knowledge scope) bind\n * the same way everywhere. Hono and NestJS contexts already answer `get`; Express, Fastify and Koa pass a web\n * Request, Elysia its own context, and adapters with no builder pass nothing.\n */\nconst withAuthorizeVariables = (\n base: unknown,\n ctx: Pick<AuthMiddlewareContext, 'mastra' | 'requestContext' | 'customRouteAuthConfig' | 'rawRequest'>,\n): unknown => {\n const variables: Record<string, unknown> = {\n mastra: ctx.mastra,\n requestContext: ctx.requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n };\n const get = (key: string) => variables[key];\n if (base === null || base === undefined) {\n return { get, req: ctx.rawRequest };\n }\n if (typeof base === 'object' && typeof (base as { get?: unknown }).get !== 'function') {\n Object.defineProperty(base, 'get', { value: get, configurable: true });\n }\n return base;\n};\n\nconst adaptToMastraAuthRequest = (request: MastraAuthRequest): MastraAuthRequest => {\n if (!(request instanceof Request)) {\n return request;\n }\n\n return {\n raw: request,\n headers: request.headers,\n header: name => request.headers.get(name) ?? undefined,\n };\n};\n\nexport interface GetAuthenticatedUserOptions {\n mastra: Mastra;\n token: string;\n request: MastraAuthRequest;\n}\n\nexport const getAuthenticatedUser = async <TUser = unknown>({\n mastra,\n token,\n request,\n}: GetAuthenticatedUserOptions): Promise<TUser | null> => {\n const normalizedToken = token.replace(/^Bearer\\s+/i, '').trim();\n if (!normalizedToken) {\n return null;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig || typeof authConfig.authenticateToken !== 'function') {\n return null;\n }\n\n return (await authConfig.authenticateToken(normalizedToken, request)) as TUser | null;\n};\n\n/**\n * Check if an auth config object supports transparent session refresh.\n * Returns true if the auth provider implements the necessary ISessionProvider methods.\n */\nexport function supportsSessionRefresh(\n authConfig: MastraAuthConfig | IMastraAuthProvider,\n): authConfig is (MastraAuthConfig | IMastraAuthProvider) &\n Pick<ISessionProvider, 'refreshSession' | 'getSessionIdFromRequest' | 'getSessionHeaders'> {\n return (\n typeof (authConfig as any).getSessionIdFromRequest === 'function' &&\n typeof (authConfig as any).refreshSession === 'function' &&\n typeof (authConfig as any).getSessionHeaders === 'function'\n );\n}\n\n/**\n * Single auth middleware: authenticate → authorize.\n * Skip checks (dev playground, unprotected path, public path) are evaluated once.\n */\nexport const coreAuthMiddleware = async (ctx: AuthMiddlewareContext): Promise<AuthResult> => {\n const {\n path,\n method,\n getHeader,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n token,\n requiresAuth,\n } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\n // Only bypass auth for dev playground when no real auth provider is configured.\n // When auth IS configured (has authenticateToken), we need the full auth flow\n // so user/roles/permissions are set in requestContext.\n const hasAuthProvider = typeof authConfig.authenticateToken === 'function';\n if (!hasAuthProvider && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n // When a route explicitly requires auth (requiresAuth: true), skip the\n // public-path bypass so the user is still authenticated and permissions\n // are injected into the request context.\n if (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n ) {\n return pass;\n }\n\n // ── Authentication ──\n\n let user: unknown;\n let refreshHeaders: Record<string, string> | undefined;\n const authRequest = adaptToMastraAuthRequest(rawRequest);\n\n type ConsumePendingResponseHeadersFn = (request: typeof authRequest) => Record<string, string> | undefined;\n const mergePendingProviderHeaders = (request: typeof authRequest = authRequest) => {\n const consume = (authConfig as { consumePendingResponseHeaders?: ConsumePendingResponseHeadersFn })\n .consumePendingResponseHeaders;\n if (typeof consume !== 'function') return;\n let pending: Record<string, string> | undefined;\n try {\n pending = consume.call(authConfig, request);\n } catch {\n // Forwarding a rotated cookie is best-effort; never fail auth over it.\n return;\n }\n if (!pending) return;\n refreshHeaders = { ...(refreshHeaders ?? {}), ...pending };\n };\n\n try {\n if (typeof authConfig.authenticateToken === 'function') {\n user = await authConfig.authenticateToken(token ?? '', authRequest);\n mergePendingProviderHeaders();\n } else {\n throw new Error('No token verification method configured');\n }\n\n // If authentication failed, attempt transparent session refresh before returning 401.\n // This handles expired access tokens without requiring client-side refresh logic.\n if (!user && supportsSessionRefresh(authConfig) && rawRequest instanceof Request) {\n let retryHttpError: HTTPException | undefined;\n try {\n const sessionId = authConfig.getSessionIdFromRequest(rawRequest);\n if (sessionId) {\n const newSession = await authConfig.refreshSession(sessionId);\n if (newSession) {\n // Refresh succeeded — build updated session headers and re-authenticate.\n // We create a synthetic request with the new session cookie so\n // authenticateToken (which reads cookies from the request) picks up\n // the refreshed session instead of the expired one.\n refreshHeaders = authConfig.getSessionHeaders(newSession);\n const refreshedCookie = Object.entries(refreshHeaders)\n .filter(([k]) => k.toLowerCase() === 'set-cookie')\n .map(([, v]) => v.split(';')[0]) // Extract name=value before attributes\n .join('; ');\n if (refreshedCookie) {\n const refreshedRequest = new Request(rawRequest.url, {\n method: rawRequest.method,\n headers: new Headers(rawRequest.headers),\n });\n refreshedRequest.headers.set('Cookie', refreshedCookie);\n // Pass the refreshed cookie value as the token so authenticateToken\n // picks up the new session instead of the stale original.\n // Auth providers typically read cookies from the request object, but\n // some may also inspect the token parameter directly.\n const cookieValue = refreshedCookie.includes('=')\n ? refreshedCookie.split('=').slice(1).join('=')\n : refreshedCookie;\n try {\n const retryAuthRequest = adaptToMastraAuthRequest(refreshedRequest);\n user = await authConfig.authenticateToken(cookieValue, retryAuthRequest);\n mergePendingProviderHeaders(retryAuthRequest);\n } catch (retryErr) {\n retryHttpError = retryErr instanceof HTTPException ? retryErr : undefined;\n throw retryErr;\n }\n }\n if (!user) {\n refreshHeaders = undefined;\n }\n }\n }\n } catch (refreshErr) {\n refreshHeaders = undefined;\n // An explicit HTTP error from the retried authenticateToken goes to the outer handler.\n if (retryHttpError === refreshErr) throw refreshErr;\n mastra.getLogger()?.debug('Session refresh failed, falling back to 401', {\n error: refreshErr instanceof Error ? { message: refreshErr.message } : refreshErr,\n });\n }\n }\n\n if (!user) {\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n requestContext.set(MASTRA_USER_KEY, user);\n // Backward-compat: also write the legacy `'user'` key so existing\n // middleware and integrations that read `requestContext.get('user')`\n // (including built-in FGA route enforcement, memory handlers, and the\n // documented public surface) keep working. New code should prefer\n // `MASTRA_USER_KEY` to avoid collisions with caller-supplied keys.\n requestContext.set('user', user);\n\n // Store the raw auth token so downstream code (e.g., editor MCP client\n // resolution) can forward it when connecting to auth-protected MCP servers.\n // The token may arrive via Authorization header, apiKey query param, or\n // cookie (SimpleAuth sets `mastra-token`). Check all sources so the\n // forwarded value is available regardless of how the user authenticated.\n let effectiveToken = token;\n if (!effectiveToken && rawRequest instanceof Request) {\n const cookieHeader = rawRequest.headers.get('cookie');\n if (cookieHeader) {\n const match = cookieHeader.match(/mastra-token=([^;]+)/);\n if (match?.[1]) effectiveToken = match[1];\n }\n }\n if (effectiveToken) {\n requestContext.set(MASTRA_AUTH_TOKEN_KEY, effectiveToken);\n }\n\n if (typeof authConfig.mapUserToResourceId === 'function') {\n try {\n const resourceId = authConfig.mapUserToResourceId(user);\n // CompositeAuth validates the authenticating provider's mapper. It can\n // return undefined when that provider never configured a mapper.\n if (resourceId !== undefined || !(authConfig instanceof CompositeAuth)) {\n if (typeof resourceId !== 'string' || !resourceId.trim()) {\n throw new Error('mapUserToResourceId must return a non-empty string for the authenticated user');\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, resourceId);\n }\n } catch (mapError) {\n mastra.getLogger()?.error('mapUserToResourceId failed', {\n error: mapError instanceof Error ? { message: mapError.message, stack: mapError.stack } : mapError,\n });\n return {\n action: 'error',\n status: 500,\n body: { error: 'Failed to map authenticated user to a resource ID' },\n headers: refreshHeaders,\n };\n }\n }\n\n try {\n // Determine which RBAC provider to use based on auth mode\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n const serverConfig = mastra.getServer();\n const studioConfig = mastra.getStudio?.();\n // Use studio RBAC if this is a studio request, otherwise use server RBAC\n const rbacProvider = (authMode === 'studio' ? (studioConfig?.rbac ?? serverConfig?.rbac) : serverConfig?.rbac) as\n | IRBACProvider<EEUser>\n | undefined;\n\n if (rbacProvider) {\n if (!user || typeof user !== 'object' || !('id' in user)) {\n mastra.getLogger()?.warn('RBAC: authenticated user missing required \"id\" field, skipping permission loading');\n } else {\n const permissions = await rbacProvider.getPermissions(user as EEUser);\n requestContext.set(MASTRA_USER_PERMISSIONS_KEY, permissions);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userPermissions', permissions);\n\n const roles = await rbacProvider.getRoles(user as EEUser);\n requestContext.set(MASTRA_USER_ROLES_KEY, roles);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userRoles', roles);\n }\n }\n } catch (rbacError) {\n mastra.getLogger()?.error('RBAC: failed to load user permissions/roles', {\n error: rbacError instanceof Error ? { message: rbacError.message, stack: rbacError.stack } : rbacError,\n });\n }\n } catch (err) {\n mastra.getLogger()?.error('Authentication error', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n // Explicit HTTP errors from auth callbacks keep their status/message; anything else is redacted.\n // The HTTPException message is sent to the client, so callers must keep it safe (no internal details).\n if (err instanceof HTTPException && err.status >= 400 && err.status <= 599) {\n return { action: 'error', status: err.status, body: { error: err.message }, headers: refreshHeaders };\n }\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n // ── Authorization ──\n\n const authorizationError = await authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n buildAuthorizeContext: ctx.buildAuthorizeContext,\n });\n if (authorizationError) {\n return { action: 'error', ...authorizationError, headers: refreshHeaders };\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\n};\n\nexport interface AuthorizeAuthenticatedUserContext {\n path: string;\n method: string;\n user: unknown;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: AuthMiddlewareContext['requestContext'];\n rawRequest: MastraAuthRequest;\n buildAuthorizeContext: () => unknown;\n}\n\n/**\n * The authorization step of server auth for an already authenticated user:\n * `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.\n * Returns null when the user may access `method path`.\n */\nexport const authorizeAuthenticatedUser = async (\n ctx: AuthorizeAuthenticatedUserContext,\n): Promise<{ status: number; body: Record<string, unknown> } | null> => {\n const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;\n const denied = { status: 403, body: { error: 'Access denied' } };\n\n if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest));\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorizeUser', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {\n mastra,\n requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n rawRequest,\n });\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorize', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n path,\n method,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n return (await checkRules(authConfig.rules, path, method, user)) ? null : denied;\n }\n\n // No explicit authorization configured (authorizeUser, authorize, or rules)\n // Check if RBAC is configured - if not, allow authenticated users through\n // (auth-only mode = authenticated users get full access)\n const rbacProvider =\n requestContext.get(MASTRA_AUTH_MODE_KEY) === 'studio'\n ? (mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac)\n : mastra.getServer()?.rbac;\n if (rbacProvider) {\n if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {\n return (await checkRules(defaultAuthConfig.rules, path, method, user)) ? null : denied;\n }\n return denied;\n }\n\n return null;\n};\n\n// Check authorization rules\nexport const checkRules = async (\n rules: MastraAuthConfig['rules'],\n path: string,\n method: string,\n user: unknown,\n): Promise<boolean> => {\n // Go through rules in order (first match wins)\n for (const i in rules || []) {\n const rule = rules?.[i]!;\n // Check if rule applies to this path\n if (!pathMatchesRule(path, rule.path)) {\n continue;\n }\n\n // Check if rule applies to this method\n if (rule.methods && !matchesOrIncludes(rule.methods, method)) {\n continue;\n }\n\n // Rule matches, check conditions\n const condition = rule.condition;\n if (typeof condition === 'function') {\n const allowed = await Promise.resolve()\n .then(() => condition(user))\n .catch(() => false);\n\n if (allowed) {\n return true;\n }\n } else if (rule.allow) {\n return true;\n }\n }\n\n // No matching rules, deny by default\n return false;\n};\n"],"mappings":";;;;;;AAsBA,MAAM,uBAA+B,KAAA;AACrC,MAAM,eAAe,IAAI,QAAQ,mBAAmB;;;;;;;;AASpD,IAAa,qBAAb,MAAmE;CACjE,OAAgB,IAAIA,KAAAA,KAAK;CACzB,kCAA2B,IAAI,IAAqB;CACpD;CAEA,YAAY,SAAuB;EACjC,KAAK,WAAW;EAEhB,KAAK,KAAK,IAAI,KAAK,cAAuB;EAC1C,QAAQ,SAAS,OAAO,UAAU;GAChC,MAAM,eAAuB,KAAA;GAC7B,KAAK,gBAAgB,IAAI,QAAQ,KAAK;GACtC,MAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAA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,QAAQ,CAAC,CACpC,WAAW,UAAU,IAAI,CAAC,CAAC,CAC3B,YAAY,KAAK,GAGlB,OAAO;EAAA,OAEJ,IAAI,KAAK,OACd,OAAO;CAEX;CAGA,OAAO;AACT"}
|
|
@@ -38,6 +38,23 @@ var memory_exports = /* @__PURE__ */ __exportAll({
|
|
|
38
38
|
UPDATE_WORKING_MEMORY_ROUTE: () => UPDATE_WORKING_MEMORY_ROUTE,
|
|
39
39
|
getTextContent: () => getTextContent
|
|
40
40
|
});
|
|
41
|
+
/**
|
|
42
|
+
* Enforces thread access on a gateway thread before its observational memory is read.
|
|
43
|
+
* Returns false when the thread doesn't exist: the gateway only serves OM through thread paths, so a
|
|
44
|
+
* record behind a missing thread (new chat, or mid-deletion) has no owner to check against. Unlike
|
|
45
|
+
* local storage there is no resource-only lookup to fall back to, even for the deprecated resource scope.
|
|
46
|
+
*/
|
|
47
|
+
async function enforceGatewayThreadAccess({ gwClient, mastra, requestContext, threadId, effectiveResourceId }) {
|
|
48
|
+
const result = await gwClient.getThread(threadId);
|
|
49
|
+
await enforceThreadAccess({
|
|
50
|
+
mastra,
|
|
51
|
+
requestContext,
|
|
52
|
+
threadId,
|
|
53
|
+
thread: result ? toLocalThread(result.thread) : null,
|
|
54
|
+
effectiveResourceId
|
|
55
|
+
});
|
|
56
|
+
return !!result;
|
|
57
|
+
}
|
|
41
58
|
function hasFGAUser(requestContext) {
|
|
42
59
|
const user = requestContext?.get("user");
|
|
43
60
|
return !!user && typeof user === "object";
|
|
@@ -253,6 +270,8 @@ const GET_MEMORY_STATUS_ROUTE = createRoute({
|
|
|
253
270
|
requiresAuth: true,
|
|
254
271
|
handler: async ({ mastra, agentId, resourceId, threadId, requestContext }) => {
|
|
255
272
|
try {
|
|
273
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
274
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
256
275
|
const agent = await getAgentFromContext({
|
|
257
276
|
mastra,
|
|
258
277
|
agentId,
|
|
@@ -263,26 +282,44 @@ const GET_MEMORY_STATUS_ROUTE = createRoute({
|
|
|
263
282
|
const gwClient = getGatewayClient();
|
|
264
283
|
if (gwClient) {
|
|
265
284
|
let omStatus;
|
|
266
|
-
if (
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
285
|
+
if (effectiveResourceId && effectiveThreadId) {
|
|
286
|
+
let threadResult;
|
|
287
|
+
try {
|
|
288
|
+
threadResult = await gwClient.getThread(effectiveThreadId);
|
|
289
|
+
} catch {
|
|
290
|
+
omStatus = { enabled: true };
|
|
291
|
+
}
|
|
292
|
+
if (threadResult !== void 0) await enforceThreadAccess({
|
|
293
|
+
mastra,
|
|
294
|
+
requestContext,
|
|
295
|
+
threadId: effectiveThreadId,
|
|
296
|
+
thread: threadResult ? toLocalThread(threadResult.thread) : null,
|
|
297
|
+
effectiveResourceId
|
|
298
|
+
});
|
|
299
|
+
if (threadResult === null) omStatus = {
|
|
279
300
|
enabled: true,
|
|
280
301
|
hasRecord: false
|
|
281
302
|
};
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
303
|
+
else if (threadResult) try {
|
|
304
|
+
const { record } = await gwClient.getObservationRecord(effectiveThreadId, effectiveResourceId);
|
|
305
|
+
if (record) omStatus = {
|
|
306
|
+
enabled: true,
|
|
307
|
+
hasRecord: true,
|
|
308
|
+
originType: record.originType,
|
|
309
|
+
lastObservedAt: record.lastObservedAt ? new Date(record.lastObservedAt) : void 0,
|
|
310
|
+
tokenCount: record.totalTokensObserved,
|
|
311
|
+
observationTokenCount: record.observationTokenCount,
|
|
312
|
+
isObserving: record.isObserving,
|
|
313
|
+
isReflecting: record.isReflecting
|
|
314
|
+
};
|
|
315
|
+
else omStatus = {
|
|
316
|
+
enabled: true,
|
|
317
|
+
hasRecord: false
|
|
318
|
+
};
|
|
319
|
+
} catch {
|
|
320
|
+
omStatus = { enabled: true };
|
|
321
|
+
}
|
|
322
|
+
} else omStatus = { enabled: true };
|
|
286
323
|
return {
|
|
287
324
|
result: true,
|
|
288
325
|
memoryType: "gateway",
|
|
@@ -300,14 +337,13 @@ const GET_MEMORY_STATUS_ROUTE = createRoute({
|
|
|
300
337
|
let omStatus;
|
|
301
338
|
if (agent) {
|
|
302
339
|
const omConfig = await getOMConfigFromAgent(agent, requestContext);
|
|
303
|
-
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
304
340
|
let threadMissing = false;
|
|
305
|
-
if (omConfig?.enabled && effectiveResourceId &&
|
|
306
|
-
const thread = await memory.getThreadById({ threadId });
|
|
341
|
+
if (omConfig?.enabled && effectiveResourceId && effectiveThreadId) {
|
|
342
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
307
343
|
await enforceThreadAccess({
|
|
308
344
|
mastra,
|
|
309
345
|
requestContext,
|
|
310
|
-
threadId,
|
|
346
|
+
threadId: effectiveThreadId,
|
|
311
347
|
thread,
|
|
312
348
|
effectiveResourceId
|
|
313
349
|
});
|
|
@@ -318,7 +354,7 @@ const GET_MEMORY_STATUS_ROUTE = createRoute({
|
|
|
318
354
|
hasRecord: false
|
|
319
355
|
};
|
|
320
356
|
else if (omConfig?.enabled && effectiveResourceId) {
|
|
321
|
-
const omThreadId = omConfig.scope === "resource" ? void 0 :
|
|
357
|
+
const omThreadId = omConfig.scope === "resource" ? void 0 : effectiveThreadId;
|
|
322
358
|
try {
|
|
323
359
|
const memoryStore = await memory.storage.getStore("memory");
|
|
324
360
|
if (memoryStore) {
|
|
@@ -409,6 +445,8 @@ const GET_OBSERVATIONAL_MEMORY_ROUTE = createRoute({
|
|
|
409
445
|
requiresAuth: true,
|
|
410
446
|
handler: async ({ mastra, agentId, resourceId, threadId, from, to, offset, limit, requestContext }) => {
|
|
411
447
|
try {
|
|
448
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
449
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
412
450
|
const agent = await getAgentFromContext({
|
|
413
451
|
mastra,
|
|
414
452
|
agentId,
|
|
@@ -423,9 +461,15 @@ const GET_OBSERVATIONAL_MEMORY_ROUTE = createRoute({
|
|
|
423
461
|
};
|
|
424
462
|
const gwClient = await isGatewayAgentAsync(agent) ? getGatewayClient() : null;
|
|
425
463
|
if (gwClient) {
|
|
426
|
-
if (
|
|
427
|
-
|
|
428
|
-
|
|
464
|
+
if (effectiveResourceId && effectiveThreadId && await enforceGatewayThreadAccess({
|
|
465
|
+
gwClient,
|
|
466
|
+
mastra,
|
|
467
|
+
requestContext,
|
|
468
|
+
threadId: effectiveThreadId,
|
|
469
|
+
effectiveResourceId
|
|
470
|
+
})) {
|
|
471
|
+
const [recordResult, historyResult] = await Promise.all([gwClient.getObservationRecord(effectiveThreadId, effectiveResourceId), gwClient.getObservationHistory(effectiveThreadId, {
|
|
472
|
+
resourceId: effectiveResourceId,
|
|
429
473
|
limit: historyLimit,
|
|
430
474
|
from,
|
|
431
475
|
to,
|
|
@@ -456,14 +500,13 @@ const GET_OBSERVATIONAL_MEMORY_ROUTE = createRoute({
|
|
|
456
500
|
throw new HTTPException(400, { message: "Memory storage is not initialized" });
|
|
457
501
|
}
|
|
458
502
|
if (!memoryStore) throw new HTTPException(400, { message: "Memory storage is not initialized" });
|
|
459
|
-
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
460
503
|
if (!effectiveResourceId) throw new HTTPException(400, { message: "resourceId is required for observational memory lookup" });
|
|
461
|
-
if (
|
|
462
|
-
const thread = await memory.getThreadById({ threadId });
|
|
504
|
+
if (effectiveThreadId) {
|
|
505
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
463
506
|
await enforceThreadAccess({
|
|
464
507
|
mastra,
|
|
465
508
|
requestContext,
|
|
466
|
-
threadId,
|
|
509
|
+
threadId: effectiveThreadId,
|
|
467
510
|
thread,
|
|
468
511
|
effectiveResourceId
|
|
469
512
|
});
|
|
@@ -472,7 +515,7 @@ const GET_OBSERVATIONAL_MEMORY_ROUTE = createRoute({
|
|
|
472
515
|
history: void 0
|
|
473
516
|
};
|
|
474
517
|
}
|
|
475
|
-
const omThreadId = omConfig.scope === "resource" ? null :
|
|
518
|
+
const omThreadId = omConfig.scope === "resource" ? null : effectiveThreadId ?? null;
|
|
476
519
|
const record = await memoryStore.getObservationalMemory(omThreadId, effectiveResourceId);
|
|
477
520
|
const history = await memoryStore.getObservationalMemoryHistory(omThreadId, effectiveResourceId, historyLimit, historyOptions);
|
|
478
521
|
return {
|
|
@@ -496,6 +539,8 @@ const AWAIT_BUFFER_STATUS_ROUTE = createRoute({
|
|
|
496
539
|
requiresAuth: true,
|
|
497
540
|
handler: async ({ mastra, agentId, resourceId, threadId, requestContext }) => {
|
|
498
541
|
try {
|
|
542
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
543
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
499
544
|
const agent = await getAgentFromContext({
|
|
500
545
|
mastra,
|
|
501
546
|
agentId,
|
|
@@ -504,13 +549,19 @@ const AWAIT_BUFFER_STATUS_ROUTE = createRoute({
|
|
|
504
549
|
if (!agent) throw new HTTPException(404, { message: "Agent not found" });
|
|
505
550
|
const gwClient = await isGatewayAgentAsync(agent) ? getGatewayClient() : null;
|
|
506
551
|
if (gwClient) {
|
|
507
|
-
if (
|
|
552
|
+
if (effectiveResourceId && effectiveThreadId && await enforceGatewayThreadAccess({
|
|
553
|
+
gwClient,
|
|
554
|
+
mastra,
|
|
555
|
+
requestContext,
|
|
556
|
+
threadId: effectiveThreadId,
|
|
557
|
+
effectiveResourceId
|
|
558
|
+
})) {
|
|
508
559
|
const maxWaitMs = 3e4;
|
|
509
560
|
const pollIntervalMs = 1e3;
|
|
510
561
|
const deadline = Date.now() + maxWaitMs;
|
|
511
562
|
let record = null;
|
|
512
563
|
while (Date.now() < deadline) {
|
|
513
|
-
const result = await gwClient.getObservationRecord(
|
|
564
|
+
const result = await gwClient.getObservationRecord(effectiveThreadId, effectiveResourceId);
|
|
514
565
|
record = result.record ? toLocalOMRecord(result.record) : null;
|
|
515
566
|
if (!record || !record.isBufferingObservation && !record.isBufferingReflection) break;
|
|
516
567
|
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
@@ -536,21 +587,20 @@ const AWAIT_BUFFER_STATUS_ROUTE = createRoute({
|
|
|
536
587
|
throw new HTTPException(400, { message: "Memory storage is not initialized" });
|
|
537
588
|
}
|
|
538
589
|
if (!memoryStore) throw new HTTPException(400, { message: "Memory storage is not initialized" });
|
|
539
|
-
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
540
590
|
if (!effectiveResourceId) throw new HTTPException(400, { message: "resourceId is required" });
|
|
541
|
-
if (
|
|
542
|
-
const thread = await memory.getThreadById({ threadId });
|
|
591
|
+
if (effectiveThreadId) {
|
|
592
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
543
593
|
await enforceThreadAccess({
|
|
544
594
|
mastra,
|
|
545
595
|
requestContext,
|
|
546
|
-
threadId,
|
|
596
|
+
threadId: effectiveThreadId,
|
|
547
597
|
thread,
|
|
548
598
|
effectiveResourceId
|
|
549
599
|
});
|
|
550
600
|
if (!thread && omConfig.scope !== "resource") return { record: null };
|
|
551
601
|
}
|
|
552
|
-
await omProcessor.waitForBuffering(
|
|
553
|
-
const omThreadId = omConfig.scope === "resource" ? null :
|
|
602
|
+
await omProcessor.waitForBuffering(effectiveThreadId, effectiveResourceId);
|
|
603
|
+
const omThreadId = omConfig.scope === "resource" ? null : effectiveThreadId ?? null;
|
|
554
604
|
return { record: await memoryStore.getObservationalMemory(omThreadId, effectiveResourceId) ?? null };
|
|
555
605
|
} catch (error) {
|
|
556
606
|
console.error("Error awaiting buffer status", error);
|
|
@@ -1776,4 +1826,4 @@ const DELETE_MESSAGES_NETWORK_ROUTE = createRoute({
|
|
|
1776
1826
|
});
|
|
1777
1827
|
export { TRANSFER_THREAD_ROUTE as C, getTextContent as D, UPDATE_WORKING_MEMORY_ROUTE as E, memory_exports as O, SEARCH_MEMORY_ROUTE as S, UPDATE_THREAD_ROUTE as T, LIST_MESSAGES_ROUTE as _, DELETE_MESSAGES_NETWORK_ROUTE as a, SAVE_MESSAGES_NETWORK_ROUTE as b, DELETE_THREAD_ROUTE as c, GET_MEMORY_STATUS_ROUTE as d, GET_OBSERVATIONAL_MEMORY_ROUTE as f, LIST_MESSAGES_NETWORK_ROUTE as g, GET_WORKING_MEMORY_ROUTE as h, CREATE_THREAD_ROUTE as i, GET_MEMORY_CONFIG_ROUTE as l, GET_THREAD_BY_ID_ROUTE as m, CLONE_THREAD_ROUTE as n, DELETE_MESSAGES_ROUTE as o, GET_THREAD_BY_ID_NETWORK_ROUTE as p, CREATE_THREAD_NETWORK_ROUTE as r, DELETE_THREAD_NETWORK_ROUTE as s, AWAIT_BUFFER_STATUS_ROUTE as t, GET_MEMORY_STATUS_NETWORK_ROUTE as u, LIST_THREADS_NETWORK_ROUTE as v, UPDATE_THREAD_NETWORK_ROUTE as w, SAVE_MESSAGES_ROUTE as x, LIST_THREADS_ROUTE as y };
|
|
1778
1828
|
|
|
1779
|
-
//# sourceMappingURL=memory-
|
|
1829
|
+
//# sourceMappingURL=memory-B_qwCpu5.js.map
|