{"record":{"id":"873857f8625cabb0","repo":"different-ai/openwork","slug":"organization-context-required-error-http-500-unl","errorCode":null,"errorMessage":"organization_context_required (Error; HTTP 500 unless caught by route handler middleware)","messagePattern":"organization_context_required \\(Error; HTTP 500 unless caught by route handler middleware\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"ee/apps/den-api/src/routes/org/codemode-scripts.ts","lineNumber":159,"sourceCode":"      body: {\n        error: message,\n        message: \"Run the exact procedure successfully with execute_capability_script, then retry saving the Workflow without changing the code. The successful run must be less than 15 minutes old.\",\n      },\n    } as const\n  }\n  return { status: 400, body: { error: \"workflow_rejected\", message } } as const\n}\n\nexport const saveWorkflowOperationId = \"saveWorkflow\"\n\nexport function registerOrgWorkflowRoutes<T extends { Variables: OrgRouteVariables }>(app: Hono<T>) {\n  const contextFor = async (c: {\n    get(name: \"organizationContext\"): OrgRouteVariables[\"organizationContext\"]\n    get(name: \"session\"): OrgRouteVariables[\"session\"]\n    env: unknown\n  }) => {\n    const context = c.get(\"organizationContext\")\n    if (!context) throw new Error(\"organization_context_required\")\n    const teams = await listTeamsForMember({ organizationId: context.organization.id, memberId: context.currentMember.id })\n    const member = { orgMembershipId: context.currentMember.id, teamIds: teams.map((team) => team.id) }\n    const catalog = await getCatalog(app as unknown as Hono, c.env)\n    const principal = {\n      userId: context.currentMember.userId,\n      organizationId: context.organization.id,\n      scopes: new Set(DEN_MCP_REQUESTED_SCOPES),\n      payload: {},\n    }\n    const capabilityContext = createCapabilityRegistryContext({\n      app: app as unknown as Hono,\n      env: c.env,\n      catalog,\n      principal,\n      organizationId: context.organization.id,\n      member,\n      redirectUriBase: env.apiPublicUrl ?? \"http://127.0.0.1\",\n      generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,","sourceCodeStart":141,"sourceCodeEnd":177,"githubUrl":"https://github.com/different-ai/openwork/blob/2b7df46e8ae1517d64c896c7793d2d52ec845669/ee/apps/den-api/src/routes/org/codemode-scripts.ts#L141-L177","documentation":"The contextFor helper in codemode-scripts routes requires the Hono context to carry an organizationContext variable set by upstream org middleware. If it is missing, a plain Error(\"organization_context_required\") is thrown; per the message this surfaces as HTTP 500 unless the route handler middleware catches it. It is an internal invariant: the route was reached without the org middleware having resolved the organization/session.","triggerScenarios":"Any codemode script route handler calling contextFor when c.get(\"organizationContext\") is undefined — i.e. the organization-context middleware did not run, did not match the route, or failed silently before this handler.","commonSituations":"Registering the codemode-scripts routes outside the middleware chain that sets organizationContext; middleware short-circuiting on auth failure without halting; a route path added before the middleware's route matcher; tests invoking handlers directly without the middleware.","solutions":["Mount these routes inside the same middleware chain that sets organizationContext (org auth middleware) so the variable is always present.","Verify the middleware registration order: organization-context middleware must execute before codemode-scripts handlers.","Catch/convert the error in route middleware to return 401/403 instead of a 500 for unauthenticated access.","In tests, run requests through the full app with middleware rather than calling handlers directly."],"exampleFix":"// before\napp.route(\"/org/codemode-scripts\", codemodeScriptRoutes) // no org middleware\n// after\napp.use(\"/org/*\", organizationContextMiddleware)\napp.route(\"/org/codemode-scripts\", codemodeScriptRoutes)","handlingStrategy":"try-catch","validationCode":"// before calling routes or inside the handler\nconst organizationContext = c.get(\"organizationContext\")\nif (!organizationContext) {\n  return c.json({ error: \"organization_context_required\" }, 401)\n}","typeGuard":"function hasOrganizationContext(c: { get(name: \"organizationContext\"): unknown }): boolean {\n  return c.get(\"organizationContext\") !== undefined && c.get(\"organizationContext\") !== null\n}","tryCatchPattern":"try {\n  return await contextFor(c)\n} catch (e) {\n  if (e instanceof Error && e.message === \"organization_context_required\") {\n    return c.json({ error: \"organization_context_required\" }, 401)\n  }\n  throw e\n}","preventionTips":["Always mount org-scoped routes behind the middleware that sets organizationContext","Check middleware registration order — context middleware must precede route handlers","Return 401/403 (not 500) when the context is missing, via a top-level error handler","In tests, exercise the full app stack so middleware runs, instead of calling handlers directly"],"tags":["middleware","hono","routing","authorization"],"backgroundTag":"missing-request-context","analyzedSha":"2b7df46e8ae1517d64c896c7793d2d52ec845669","analyzedAt":"2026-09-01T07:59:23.713Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}