mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
7 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c0d3bfdc43 |
feat: pass the authenticated user to DynamicArgument callbacks (#28612)
Dynamic agent config callbacks now get the authenticated end user as an
optional `user` argument, so you can personalize an agent without
digging auth keys out of `requestContext` yourself. It works in any
`DynamicArgument` callback: instructions, model, tools, memory,
workspace, processors, scorers, and so on.
```ts
import { Agent } from '@mastra/core/agent';
const supportAgent = new Agent({
id: 'support-agent',
instructions: ({ user }) =>
user ? `You are helping ${user.name ?? user.id}.` : 'You are a helpful assistant.',
model: ({ user }) => (user?.role === 'admin' ? 'openai/gpt-5' : 'openai/gpt-5-mini'),
tools: ({ user }) => (user ? { accountTool, ...(user.role === 'admin' ? { adminTool } : {}) } : {}),
memory: ({ user }) => (user ? userMemory : undefined),
});
```
`user` always has the same `MastraUser` shape, no matter which auth
provider you use, and it's `undefined` for unauthenticated requests:
```ts
import type { MastraUser } from '@mastra/core/types';
// { id: string; name?: string; email?: string; avatarUrl?: string; role?: string }
```
The server auth middleware builds it through a new overridable
`toMastraUser()` on `MastraAuthProvider`. The default handles common
shapes (`id`/`sub`/`userId`, `name`, `email`, `avatarUrl`/`picture`,
`role`), and JWT, Cloud, Supabase, Neon and Better Auth ship overrides
for their user objects. Custom providers can map their own shape:
```ts
import { MastraAuthProvider } from '@mastra/core/server';
import type { MastraUser } from '@mastra/core/types';
class MyAuth extends MastraAuthProvider<MyUser> {
async authenticateToken(token: string) { /* ... */ }
async authorizeUser(user: MyUser) { return true; }
toMastraUser(user: MyUser): MastraUser {
return { id: user.accountId, name: user.profile.displayName, role: user.permissions.primaryRole };
}
}
```
Inline auth configs can pass `toMastraUser` too. If the provider user
has no role and an RBAC provider is configured, the primary RBAC role
fills it in, so `user.role` also works with WorkOS, Okta, Google and
Neon. The raw provider user is still available when you need
provider-specific fields, and the new context key is reserved, so
clients can't spoof it through the request body:
```ts
instructions: ({ requestContext }) => {
const rawUser = requestContext.get('mastra__user'); // provider-specific object, unchanged
// ...
},
```
Dynamic `vectorStore` resolvers on RAG tools get `user` as well:
```ts
createVectorQueryTool({
indexName: 'docs',
model: embedder,
vectorStore: ({ user }) => (user ? tenantStores.get(user.id)! : sharedStore),
});
```
Inside core, every place that invoked a `DynamicArgument` callback
inline now goes through a single `resolveDynamicArgument` helper, which
reads the user from `requestContext` at call time. This is non-breaking:
callbacks get an extra optional field, providers get a method with a
working default. Requests served through an `MCPServer` don't get `user`
yet, since MCP builds its own request context; that's documented.
Tested with unit tests for the helper, normalization and each provider
override, middleware tests (inline config, provider role, RBAC role,
CompositeAuth ordering, unauthenticated), regression tests for the
migrated call sites, and an end-to-end test where an agent behind a fake
auth provider gets personalized instructions. Core, server, rag and the
touched auth packages typecheck clean, and their suites pass.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
When a signed-in user makes a request, configuration callbacks can now
use a standard set of details about that user. When a workflow resumes,
it uses the new request’s user details instead of restoring them from
the earlier run.
## Summary
- Added optional `user` data to `DynamicArgument` callbacks and RAG
vector-store resolvers. Callbacks can also use `getRequestUser()` to
read the normalized user from request context.
- Added the `MastraUser` type and `toMastraUser()` normalization hooks
for auth providers and inline auth configs. The server stores the
normalized user in a reserved request-context key and uses the primary
RBAC role when the user has no role.
- Updated core dynamic configuration paths to use the shared resolver.
Added user support to agent scopes and migrated A2A memory resolution.
- Added `withoutLiveRequestKeys()` to remove live authentication and
authorization data from saved context during workflow resume, restart,
and time travel. Saved non-authentication context, such as tenant data,
remains available.
- Added documentation and changesets. Raised relevant `@mastra/core`
peer dependency minimums to 1.81.0. MCPServer requests do not receive
the normalized `user`.
## Validation
The author reports passing typechecks and test suites across core,
server, RAG, and several auth packages. The author also reports three
failing Inngest tests and earlier failures in evented workflow and
scheduler tests, which reportedly fail the same way on comparison
sources. These results are author-reported and have not been
independently verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
ac05f2d7fc |
refactor(auth): adopt Web Crypto without async API breaks (#24583) | ||
|
|
8a4a4af313 |
fix(auth): harden getRequestHeader for Express requests (#21261)
Co-authored-by: Lawrence Millard <l@millard.ink> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
95d0264eff |
fix(auth-cloud): prevent PKCE cross-wiring in concurrent SSO logins (#20233)
Co-authored-by: Mastra Code <noreply@mastra.ai> |
||
|
|
5c0df776c4 |
refactor(auth): extract shared auth internals (#17142)
Moves shared auth interfaces, providers, sessions, and EE auth helpers
into @internal/auth so auth provider packages no longer depend on
@mastra/core. The existing @mastra/core auth imports still work through
re-export stubs.
Before:
```ts
import { MastraAuthProvider } from '@mastra/core/server';
```
After, internal auth providers use:
```ts
import { MastraAuthProvider } from '@internal/auth/provider';
```
Verified with focused auth builds, lint, typecheck, and tests.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
This PR moves the shared “auth code” (providers, sessions, and
enterprise features) out of `@mastra/core` into a new `@internal/auth`
package so all auth providers can reuse the same implementation.
`@mastra/core` keeps re-export stubs for compatibility, and new
lint/build rules help ensure providers stop importing from
`@mastra/core` directly.
## What changed
- Extracted shared auth internals into `@internal/auth`:
- Auth provider base classes and shared options (`MastraAuthProvider`,
`CompositeAuth`, `SimpleAuth`)
- Session types/providers (`Session`, `MemorySessionProvider`,
`CookieSessionProvider`)
- SSO/credentials/user auth types
- Enterprise Edition auth helpers:
- License validation + caching
- Telemetry bridge + EE capability detection
- RBAC/ACL/FGA interfaces and utilities (including `StaticRBACProvider`,
`FGADeniedError`, and `buildCapabilities`)
- Updated auth provider packages to import shared interfaces/helpers
from `@internal/auth` instead of `@mastra/core`.
- Added `no-restricted-imports` ESLint rules across auth packages to
prevent importing `@mastra/core` (including subpaths), with guidance to
use `@internal/auth`.
- Updated manifests and build configs so auth packages depend on
`@internal/auth` and generate types from the new entrypoints (narrowing
`generateTypes` scope to `@internal/auth`).
- Added new internal package entrypoints:
- `@internal/auth`
- `@internal/auth/provider`
- `@internal/auth/session`
- `@internal/auth/ee`
- `@internal/auth/ee/capabilities`
- Kept backward compatibility by converting many `@mastra/core` auth
exports into re-export stubs that delegate to `@internal/auth`.
## Notable internal auth additions
- New provider system:
- `MastraAuthProvider`
- `CompositeAuth`
- `SimpleAuth`
- New session providers:
- `MemorySessionProvider`
- `CookieSessionProvider`
- New EE helpers:
- License validation client and helpers
- Telemetry bridge
- RBAC/ACL/FGA interfaces and utilities
- Default roles + permission matching
- `buildCapabilities` and `FGADeniedError`
## Follow-up: narrower EE symbol exposure
- Updated core re-export entrypoints to reduce unintended EE symbol
leakage from broad `@internal/auth/ee` re-exports (using the dedicated
`@internal/auth/ee/capabilities` entrypoint and more targeted
FGA-related re-exports).
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
|
||
|
|
552285e5af |
fix(core): remove hono runtime dependency (#17410)
Moves Hono and hono-openapi out of @mastra/core runtime dependencies while keeping their public types bundled in core declarations. This should avoid duplicate Hono type instances for consumers without requiring them to install Hono directly. Before: ```ts // Installing @mastra/core also installed Hono at runtime. ``` After: ```ts // @mastra/core still exposes the same route and middleware types, // but Hono is no longer installed as a runtime dependency. ``` Fixes #17405 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## ELI5 This PR stops bundling the Hono web framework inside `@mastra/core` and related packages so projects only use one Hono installation provided by the app, avoiding TypeScript type conflicts; `@mastra/core` still exposes Hono-shaped types so existing code keeps working. ## Overview - Moves Hono from runtime dependencies to dev/peer/dev-only entries so `@mastra/core` no longer installs Hono at runtime but still includes Hono types in generated declarations. - Adds framework-agnostic request abstractions and helpers so auth providers and server code accept both native Web Request and Hono-shaped requests without requiring Hono at runtime. - Reworks MCP and server modules to avoid leaking Hono runtime types (e.g., Context) across package boundaries while preserving Hono-compatible public types. - Cleans up auth package manifests and implementations to remove runtime Hono dependency and adopt the shared MastraAuthRequest surface. ## Key changes - package metadata - packages/core/package.json: removed hono and hono-openapi from runtime deps; moved them to development/type-generation usage. - Several auth packages (better-auth, cloud, okta, studio, workos): removed hono from deps/devDeps/peerDeps where applicable. - Build config - packages/core/tsup.config.ts: added 'hono' and 'hono-openapi' to the type-generation allowlist so their public types are emitted. - New/shared request types & helpers - packages/core/src/server/request-types.ts: introduces HonoRequestLike, MastraAuthRequest (Request | HonoRequestLike), AuthenticateTokenFn, AuthorizeUserFn, getRequestHeader, and getWebRequest. - packages/core/src/server/index.ts: re-exports these types/helpers for consumers. - Auth API typing surface - packages/core/src/server/auth.ts, types.ts, simple-auth.ts, composite-auth.ts, and related tests: updated to use MastraAuthRequest and the new callback types; tests updated to use real Web Request-based mocks where appropriate. - Auth provider implementations (auth/better-auth, auth/cloud, auth/okta, auth/studio, auth/workos): updated to accept MastraAuthRequest and use getRequestHeader/getWebRequest for header/session access. - MCP & server internals - packages/core/src/mcp/types.ts: replaces Hono Context usage with a HonoContextLike interface capturing only used shape. - packages/mcp/src/server/server.ts and packages/deployer/src/server/index.ts, plus server adapter code: added local casting/adapters to keep runtime behavior while avoiding exported Hono runtime types. - packages/server/src/server/auth/helpers.ts and server-adapter: adapt incoming requests to MastraAuthRequest and ensure middleware always receives a normalized request. - Types & tests - Added type-test suite ensuring HonoRequest is assignable to the new MastraAuthRequest-based provider types. - Updated many tests to construct real Request objects and MastraAuthRequest wrappers instead of Hono-specific mocks. - Changeset - .changeset/dull-papers-buy.md: documents removal of Hono runtime deps and migration to framework-agnostic request types; triggers patch releases. ## Impact - Fixes `#17405` by preventing duplicate Hono instances and TypeScript incompatibilities (e.g., conflicting Handler types). - Consumers that use Hono should install it directly (peer dependency semantics); consumers who do not use Hono are unaffected. - Public type compatibility retained: Hono-shaped types remain available through `@mastra/core`’s emitted declarations while runtime coupling to Hono is removed. Fixes `#17405` <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/mastra-ai/mastra/pull/17410?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai> |
||
|
|
6dbeeb94a8 |
feat: auth core, server RBAC, and adapter permission enforcement (#13163)
## Summary
PR 1 of 3 from the `auth-rbac-cms` branch split. This PR adds all
backend plumbing for auth/RBAC. PRs 2 (auth providers) and 3 (playground
UI) depend on this and can land in parallel once this merges.
- **New `@mastra/core/auth` export** — interfaces for RBAC, sessions,
SSO, credentials, ACL, and user management, plus default implementations
(static RBAC provider, cookie/memory session providers, built-in roles)
- **Server auth handlers** — login, signup, logout, session management,
and SSO flows with Zod-validated schemas
- **Route-level permission enforcement** — `requiresPermission` on route
configs with convention-based derivation from path/method (e.g. `GET
/agents/:id` → `agents:read`)
- **Server adapter RBAC middleware** (Hono, Express, Fastify, Koa) —
resolves user permissions via RBAC provider, cookie auth fallthrough for
session-based auth
- **Authorization policy fix** — `isProtectedPath` now uses
`isProtectedCustomRoute` instead of `!isCustomRoutePublic`, fixing a bug
where studio UI couldn't load in production
- **Deployer updates** — `MASTRA_PACKAGES_FILE` env var injection,
dynamic CORS origin when auth configured
- **Client SDK** — `getFullUrl` helper, `AuthCapabilities` type export
### Key behavioral changes
| Change | Risk | Mitigation |
|---|---|---|
| `SimpleAuth<TUser>` → `SimpleAuth<TUser extends EEUser>` | Medium —
requires `id` + `email` fields | Intentional; compile-time catch |
| `isProtectedPath` logic change | Medium — authorization policy | New
tests cover this; required for studio login in prod |
| Cookie fallthrough in Hono auth middleware | Low | Falls back to 401
if no user found |
| No RBAC → authenticated users get full access | Low — intentional |
Auth-only mode preserved |
| CORS dynamic origin when auth configured | Low | Only activates with
auth config; user can override |
### Deviation from plan
`deployers/cloud/package.json` — the plan called for adding
`@mastra/auth-cloud` dependency, but that package is created in PR 2.
Omitted here to avoid workspace resolution failure; PR 2 will add it.
### Fixed pre-existing test bug
All 4 adapter RBAC tests had a failing test ("should derive permissions
from route path/method when not explicitly set") that registered an API
handler at `/agents/test` with no prefix. That's a frontend/SPA path —
real API handlers are always under `/api/*`. Fixed the test to use
`prefix: '/api'` so the route is at `/api/agents/test`, matching how
routes are actually registered. Verified the bug exists on
`auth-rbac-cms` with clean install + build.
## Test plan
- [x] `pnpm build:packages` — 35/35 tasks pass
- [x] Core auth tests (cookie.test.ts) — 16/16 pass
- [x] Server tests (permissions, helpers, system) — 177/177 pass
- [x] Hono RBAC tests — 21/21 pass
- [x] Express RBAC tests — 15/15 pass
- [x] Fastify RBAC tests — 15/15 pass
- [x] Koa RBAC tests — 15/15 pass
- [x] Client SDK tests (base.test.ts) — 5/5 pass
- [ ] Verify no auth configured → all existing behavior identical (no
403s, no auth prompts)
- [ ] Verify pre-commit hooks pass (eslint + prettier)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* Enterprise auth: SSO and credentials sign-in/sign-up, login/logout,
cookie and in-memory sessions, auth capabilities and current-user
endpoints.
* RBAC: default roles, static RBAC provider, route-level permission
enforcement and middleware across adapters.
* Client: full-URL helper; system responses include isDev.
* Deploy/build: bundling emits package metadata; deployers set runtime
packages file and adjust CORS when auth is enabled.
* **Bug Fixes**
* Studio UI loads correctly in production.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Shane Thomas <shane@codekarate.com>
Co-authored-by: Mastra Code (anthropic/claude-opus-4-6) <noreply@mastra.ai>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
|