{"record":{"id":"c8d8d38469cd16fa","repo":"mastra-ai/mastra","slug":"authentication-required","errorCode":null,"errorMessage":"Authentication required","messagePattern":"Authentication required","errorType":"http","errorClass":"HTTPException","httpStatus":401,"severity":"error","filePath":"packages/server/src/server/handlers/stored-agent-favorites.ts","lineNumber":50,"sourceCode":" */\nexport const FAVORITE_STORED_AGENT_ROUTE = createRoute({\n  method: 'PUT',\n  path: '/stored/agents/:storedAgentId/favorite',\n  responseType: 'json',\n  pathParamSchema: storedAgentIdPathParams,\n  responseSchema: favoriteToggleResponseSchema,\n  summary: 'Favorite a stored agent',\n  description: 'Marks the stored agent as favorited by the calling user. Idempotent.',\n  tags: ['Stored Agents'],\n  requiresAuth: true,\n  requiresPermission: 'stored-agents:read',\n  handler: async ({ mastra, requestContext, storedAgentId }) => {\n    try {\n      await requireBuilderFeature(mastra, 'favorites');\n\n      const callerId = getCallerAuthorId(requestContext);\n      if (!callerId) {\n        throw new HTTPException(401, { message: 'Authentication required' });\n      }\n\n      const { agentStore, favoritesStore } = await getFavoritesContext(mastra);\n\n      const agent = await agentStore.getById(storedAgentId);\n      if (!agent) {\n        throw new HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });\n      }\n      assertStoredResourceScope(agent, await getStoredResourceScope(mastra, requestContext));\n\n      // Throws 404 if the caller cannot read the agent (private + not owner/admin).\n      assertReadAccess({ requestContext, resource: 'stored-agents', resourceId: storedAgentId, record: agent });\n\n      const result = await favoritesStore.favorite({\n        userId: callerId,\n        entityType: 'agent',\n        entityId: storedAgentId,\n      });","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/server/src/server/handlers/stored-agent-favorites.ts#L32-L68","documentation":"The favorites toggle handler derives the caller's author id from requestContext via getCallerAuthorId. When the request carries no authenticated caller identity, the handler throws HTTPException 401 'Authentication required'. Favoriting is a per-user action, so an anonymous caller cannot be served.","triggerScenarios":"PUT /stored/agents/:storedAgentId/favorite (and other favorites routes) without an authenticated user in requestContext — missing/invalid auth token, expired session, or auth middleware not populating the caller identity.","commonSituations":"Calling the API from a script without attaching credentials; expired JWT/session cookie; auth middleware misconfigured or bypassed on the playground/server proxy; builder feature enabled but auth not wired up.","solutions":["Attach valid credentials (Authorization header or session cookie) to the request","Refresh or re-obtain the auth token if expired","Confirm auth middleware is registered and runs before the favorites route","Verify getCallerAuthorId's expected requestContext key is populated by your auth provider"],"exampleFix":"// before\nfetch('/api/stored-agents/123/favorite', { method: 'PUT' })\n// after\nfetch('/api/stored-agents/123/favorite', {\n  method: 'PUT',\n  headers: { Authorization: `Bearer ${token}` },\n  credentials: 'include',\n})","handlingStrategy":"try-catch","validationCode":"// Before calling the API\nconst token = getSessionToken();\nif (!token) redirectToLogin();","typeGuard":"function hasCallerIdentity(ctx: unknown): ctx is { callerAuthorId: string } {\n  return typeof ctx === 'object' && ctx !== null && typeof (ctx as any).callerAuthorId === 'string' && (ctx as any).callerAuthorId.length > 0;\n}","tryCatchPattern":"try {\n  await api.toggleFavorite(agentId);\n} catch (e) {\n  if (e.status === 401) { refreshToken(); redirectToLogin(); }\n  else throw e;\n}","preventionTips":["Attach Authorization headers/cookies in a shared API client wrapper","Proactively refresh tokens before expiry","Require auth middleware on all mutating routes"],"tags":["auth","http-401","unauthenticated"],"backgroundTag":"authentication-required","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}