@mastra/factory 0.2.2-alpha.0 → 0.2.2-alpha.1

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/auth.d.ts +2 -2
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +22 -2
  5. package/dist/auth.js.map +1 -1
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +411 -244
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.js +411 -244
  10. package/dist/index.js.map +1 -1
  11. package/dist/integrations/github/integration.js +85 -37
  12. package/dist/integrations/github/integration.js.map +1 -1
  13. package/dist/integrations/github/routes.d.ts.map +1 -1
  14. package/dist/integrations/github/routes.js +85 -37
  15. package/dist/integrations/github/routes.js.map +1 -1
  16. package/dist/integrations/github/sandbox.d.ts +2 -0
  17. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  18. package/dist/integrations/github/sandbox.js +28 -8
  19. package/dist/integrations/github/sandbox.js.map +1 -1
  20. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  21. package/dist/integrations/platform/github/integration.js +119 -39
  22. package/dist/integrations/platform/github/integration.js.map +1 -1
  23. package/dist/routes/config.d.ts.map +1 -1
  24. package/dist/routes/config.js +1 -4
  25. package/dist/routes/config.js.map +1 -1
  26. package/dist/routes/surface.js +1 -4
  27. package/dist/routes/surface.js.map +1 -1
  28. package/dist/routes/work-items.js.map +1 -1
  29. package/dist/rules/binding-context.js.map +1 -1
  30. package/dist/rules/dispatcher.d.ts.map +1 -1
  31. package/dist/rules/dispatcher.js +7 -1
  32. package/dist/rules/dispatcher.js.map +1 -1
  33. package/dist/rules/processor.js.map +1 -1
  34. package/dist/rules/tools.js.map +1 -1
  35. package/dist/spa-static.d.ts.map +1 -1
  36. package/dist/spa-static.js +1 -0
  37. package/dist/spa-static.js.map +1 -1
  38. package/dist/storage/domains/source-control/base.d.ts +9 -0
  39. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  40. package/dist/storage/domains/source-control/base.js +4 -0
  41. package/dist/storage/domains/source-control/base.js.map +1 -1
  42. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  43. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  44. package/dist/storage/domains/source-control/inmemory.js +4 -0
  45. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  46. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  47. package/dist/storage/domains/work-items/base.js +20 -4
  48. package/dist/storage/domains/work-items/base.js.map +1 -1
  49. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  50. package/dist/timing.d.ts +15 -0
  51. package/dist/timing.d.ts.map +1 -0
  52. package/dist/timing.js +27 -0
  53. package/dist/timing.js.map +1 -0
  54. package/dist/workspace.d.ts +2 -3
  55. package/dist/workspace.d.ts.map +1 -1
  56. package/dist/workspace.js +104 -65
  57. package/dist/workspace.js.map +1 -1
  58. package/factory-skills/factory-review/SKILL.md +9 -2
  59. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/rules/tools.ts","../../src/auth.ts","../../src/rules/binding-context.ts","../../src/rules/types.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { getFactorySessionAddress } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { FACTORY_RULE_STAGES } from './types.js';\nimport type { FactoryRuleBoard } from './types.js';\n\nconst transitionInputSchema = z\n .object({\n stage: z.enum(FACTORY_RULE_STAGES),\n expectedRevision: z.number().int().positive(),\n rationale: z.string().trim().min(1).max(1_000),\n })\n .strict();\n\nfunction boardForSource(type: string | undefined): FactoryRuleBoard {\n return type === 'pull-request' ? 'review' : 'work';\n}\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n}): Promise<IntegrationTools> {\n const address = getFactorySessionAddress(options.requestContext);\n if (!address) return {};\n const availableBinding = await options.storage.findActiveRunBinding(address);\n if (!availableBinding) return {};\n\n return {\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: transitionInputSchema,\n execute: async ({ stage, expectedRevision, rationale }, execution) => {\n const currentAddress = getFactorySessionAddress(execution.requestContext);\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n if (!binding || binding.id !== availableBinding.id) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n\n return options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board: boardForSource(item.externalSource?.type),\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n });\n },\n }),\n };\n}\n","import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\n\nimport type { RouteAuth } from './routes/route.js';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page and its `/assets/*`\n * bundle. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n organizationId?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n await ensureUserOrg(provider, user);\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/** Encode a validated returnTo path into the OAuth `state` parameter. */\nfunction encodeState(returnTo: string): string {\n return Buffer.from(JSON.stringify({ returnTo }), 'utf8').toString('base64url');\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n try {\n const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) as { returnTo?: string };\n return sanitizeReturnTo(parsed.returnTo);\n } catch {\n return '/';\n }\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const returnTo = decodeState(c.req.query('state'));\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // The SPA sign-in page and the static bundle it needs must be reachable\n // while signed out; no user is stashed, so `/api/*` stays protected.\n if (path === '/signin' || path.startsWith('/assets/')) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n\n if (user) {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n c.set(FACTORY_AUTH_USER_KEY, user);\n c.get('requestContext')?.set('user', user);\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n","import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { FactoryAuthUser } from '../auth.js';\nimport { getFactoryAuthOrgId } from '../auth.js';\nimport type { FactoryRunBindingAddress, FactoryRunBindingSessionAddress } from '../storage/domains/work-items/base.js';\n\ninterface FactorySessionState {\n factoryProjectId?: string;\n}\n\nexport function getFactorySessionCoordinates(\n requestContext: RequestContext | undefined,\n): FactoryRunBindingSessionAddress | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const context = requestContext.get('controller') as AgentControllerRequestContext<FactorySessionState> | undefined;\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context?.threadId || !context.resourceId || !factoryProjectId) return null;\n return {\n factoryProjectId,\n threadId: context.threadId,\n resourceId: context.resourceId,\n sessionId: context.resourceId,\n };\n}\n\nexport function getFactorySessionAddress(requestContext: RequestContext | undefined): FactoryRunBindingAddress | null {\n const coordinates = getFactorySessionCoordinates(requestContext);\n if (!coordinates || !requestContext || typeof requestContext.get !== 'function') return null;\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const orgId = getFactoryAuthOrgId(user);\n if (!orgId) return null;\n return { orgId, ...coordinates };\n}\n","export type WorkItemSource = 'github-issue' | 'github-pr' | 'linear-issue' | 'manual';\n\nexport const FACTORY_RULE_STAGES = ['intake', 'triage', 'planning', 'execute', 'review', 'done', 'canceled'] as const;\nexport type FactoryRuleStage = (typeof FACTORY_RULE_STAGES)[number];\n\nexport const FACTORY_RULE_BOARDS = ['work', 'review'] as const;\nexport type FactoryRuleBoard = (typeof FACTORY_RULE_BOARDS)[number];\n\nexport const FACTORY_RULE_SOURCES = ['issue', 'pullRequest', 'linearIssue', 'manual'] as const;\nexport type FactoryRuleSource = (typeof FACTORY_RULE_SOURCES)[number];\n\nexport const FACTORY_GITHUB_EVENTS = [\n 'issueOpened',\n 'pullRequestOpened',\n 'pullRequestUpdated',\n 'pullRequestReviewRequested',\n 'pullRequestMerged',\n] as const;\nexport type FactoryGithubEventName = (typeof FACTORY_GITHUB_EVENTS)[number];\n\nexport const FACTORY_LINEAR_EVENTS = ['issueObserved'] as const;\nexport type FactoryLinearEventName = (typeof FACTORY_LINEAR_EVENTS)[number];\n\nexport type FactoryRuleJsonValue =\n | null\n | boolean\n | number\n | string\n | FactoryRuleJsonValue[]\n | { [key: string]: FactoryRuleJsonValue };\n\nexport interface FactoryRuleItemContext {\n id: string;\n source: WorkItemSource;\n sourceKey: string | null;\n parentWorkItemId: string | null;\n title: string;\n url: string | null;\n stages: readonly string[];\n}\n\nexport type FactoryRuleActor =\n | { type: 'human'; id: string }\n | { type: 'agent'; bindingId: string; role: string }\n | { type: 'github'; login: string; trusted: boolean; factoryAuthored: boolean }\n | { type: 'system'; id: string };\n\nexport interface FactoryRuleIngressIdentity {\n type: 'human' | 'agent' | 'toolResult' | 'github' | 'linear' | 'rule';\n id: string;\n}\n\nexport interface FactoryRuleCausalEntry {\n ingressId: string;\n decisionType: FactoryCommitDecision['type'];\n}\n\nexport interface FactoryRuleContextBase {\n tenant: { orgId: string; projectId: string };\n actor: FactoryRuleActor;\n ingress: FactoryRuleIngressIdentity;\n cause: string;\n causalChain: readonly FactoryRuleCausalEntry[];\n ruleSetVersion: string;\n}\n\nexport interface FactoryBoundRuleContext extends FactoryRuleContextBase {\n item: FactoryRuleItemContext;\n board: FactoryRuleBoard;\n itemRevision: number;\n}\n\nexport interface FactoryStageRuleContext extends FactoryBoundRuleContext {\n source: FactoryRuleSource;\n stage: FactoryRuleStage;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n}\n\nexport interface FactoryToolResultRuleContext extends FactoryBoundRuleContext {\n toolName: string;\n threadId: string;\n assistantMessageId: string;\n toolCallId: string;\n result: {\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n };\n}\n\nexport interface FactoryGithubRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryGithubEventName;\n deliveryId: string;\n factory: { createdAt: string };\n repository: { id: number; fullName: string };\n issue?: { number: number; title: string; url: string; createdAt?: string };\n pullRequest?: {\n number: number;\n title: string;\n url: string;\n createdAt?: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n };\n}\n\nexport interface FactoryLinearRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryLinearEventName;\n issue: {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: readonly string[];\n createdAt: string;\n updatedAt: string;\n };\n}\n\nexport type FactoryRuleHandler<TContext> = (\n context: Readonly<TContext>,\n) => FactoryRuleDecision | void | Promise<FactoryRuleDecision | void>;\n\nexport interface FactoryBoardRuleLeaf {\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport interface FactoryToolRuleLeaf {\n onResult?: FactoryRuleHandler<FactoryToolResultRuleContext>;\n}\n\nexport interface FactoryGithubRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryGithubRuleContext>;\n}\n\nexport interface FactoryLinearRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryLinearRuleContext>;\n}\n\nexport type FactoryBoardRules = Partial<\n Record<FactoryRuleStage, Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>>>\n>;\n\nexport interface FactoryRules {\n version: string;\n work: FactoryBoardRules;\n review: FactoryBoardRules;\n tools: Record<string, FactoryToolRuleLeaf>;\n github: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport interface FactoryRulesOverrides {\n work?: FactoryBoardRules;\n review?: FactoryBoardRules;\n tools?: Record<string, FactoryToolRuleLeaf>;\n github?: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear?: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport type FactoryRuleRejectionCode =\n | 'forbidden'\n | 'invalid_transition'\n | 'missing_binding'\n | 'stale'\n | 'timeout'\n | 'rule_error'\n | 'causal_depth_exceeded'\n | 'repeated_transition';\n\nexport interface FactoryRuleRejectDecision {\n type: 'reject';\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\ninterface FactoryCommitDecisionBase {\n idempotencyKey: string;\n}\n\nexport interface FactoryTransitionDecision extends FactoryCommitDecisionBase {\n type: 'transition';\n board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n}\n\nexport interface FactoryUpsertLinkedWorkItemDecision extends FactoryCommitDecisionBase {\n type: 'upsertLinkedWorkItem';\n board: FactoryRuleBoard;\n source: WorkItemSource;\n sourceKey: string;\n title: string;\n url: string | null;\n stage: FactoryRuleStage;\n metadata?: Record<string, FactoryRuleJsonValue>;\n}\n\nexport interface FactoryInvokeSkillDecision extends FactoryCommitDecisionBase {\n type: 'invokeSkill';\n role: string;\n skillName: string;\n arguments?: string;\n precedingMessage?: string;\n}\n\nexport interface FactorySendMessageDecision extends FactoryCommitDecisionBase {\n type: 'sendMessage';\n role: string;\n message: string;\n priority?: 'medium' | 'high' | 'urgent';\n idleBehavior?: 'persist' | 'wake';\n prepareBinding?: boolean;\n}\n\nexport interface FactoryNotifyDecision extends FactoryCommitDecisionBase {\n type: 'notify';\n title: string;\n body?: string;\n level?: 'info' | 'warning' | 'error';\n}\n\nexport type FactoryCommitDecision =\n | FactoryTransitionDecision\n | FactoryUpsertLinkedWorkItemDecision\n | FactoryInvokeSkillDecision\n | FactorySendMessageDecision\n | FactoryNotifyDecision;\n\nexport type FactoryRuleDecision = FactoryRuleRejectDecision | FactoryCommitDecision;\n\nexport interface FactoryTransitionResultAccepted {\n status: 'accepted';\n transitionId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n decisions: FactoryCommitDecision[];\n}\n\nexport interface FactoryTransitionResultRejected {\n status: 'rejected';\n transitionId: string;\n itemId: string;\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\nexport type FactoryTransitionResult = FactoryTransitionResultAccepted | FactoryTransitionResultRejected;\n\nexport function factoryRuleSourceForWorkItem(source: WorkItemSource): FactoryRuleSource {\n switch (source) {\n case 'github-issue':\n return 'issue';\n case 'github-pr':\n return 'pullRequest';\n case 'lin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F;","names":[]}
1
+ {"version":3,"sources":["../../src/rules/tools.ts","../../src/auth.ts","../../src/rules/binding-context.ts","../../src/rules/types.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { getFactorySessionAddress } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { FACTORY_RULE_STAGES } from './types.js';\nimport type { FactoryRuleBoard } from './types.js';\n\nconst transitionInputSchema = z\n .object({\n stage: z.enum(FACTORY_RULE_STAGES),\n expectedRevision: z.number().int().positive(),\n rationale: z.string().trim().min(1).max(1_000),\n })\n .strict();\n\nfunction boardForSource(type: string | undefined): FactoryRuleBoard {\n return type === 'pull-request' ? 'review' : 'work';\n}\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n}): Promise<IntegrationTools> {\n const address = getFactorySessionAddress(options.requestContext);\n if (!address) return {};\n const availableBinding = await options.storage.findActiveRunBinding(address);\n if (!availableBinding) return {};\n\n return {\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: transitionInputSchema,\n execute: async ({ stage, expectedRevision, rationale }, execution) => {\n const currentAddress = getFactorySessionAddress(execution.requestContext);\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n if (!binding || binding.id !== availableBinding.id) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n\n return options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board: boardForSource(item.externalSource?.type),\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n });\n },\n }),\n };\n}\n","import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\n\nimport type { RouteAuth } from './routes/route.js';\nimport { timedAboveThreshold } from './timing.js';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page, its `/assets/*` bundle,\n * and the SPA manifest metadata. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n organizationId?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n await ensureUserOrg(provider, user);\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/** Encode a validated returnTo path into the OAuth `state` parameter. */\nfunction encodeState(returnTo: string): string {\n return Buffer.from(JSON.stringify({ returnTo }), 'utf8').toString('base64url');\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n try {\n const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) as { returnTo?: string };\n return sanitizeReturnTo(parsed.returnTo);\n } catch {\n return '/';\n }\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const returnTo = decodeState(c.req.query('state'));\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // The SPA sign-in page, its static bundle, and browser-fetched metadata\n // must be reachable while signed out; no user is stashed, so `/api/*`\n // stays protected.\n if (\n path === '/signin' ||\n path.startsWith('/assets/') ||\n path === '/manifest.webmanifest' ||\n path === '/mastra.svg'\n ) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n // A slow verification here delays EVERY protected request — surface\n // outliers so auth-backend latency is attributable from server logs.\n const user = await timedAboveThreshold('auth.gate.authenticate', 1_000, () =>\n authenticateRequest(provider, token, c.req.raw),\n );\n\n if (user) {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n c.set(FACTORY_AUTH_USER_KEY, user);\n c.get('requestContext')?.set('user', user);\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n","import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { FactoryAuthUser } from '../auth.js';\nimport { getFactoryAuthOrgId } from '../auth.js';\nimport type { FactoryRunBindingAddress, FactoryRunBindingSessionAddress } from '../storage/domains/work-items/base.js';\n\ninterface FactorySessionState {\n factoryProjectId?: string;\n}\n\nexport function getFactorySessionCoordinates(\n requestContext: RequestContext | undefined,\n): FactoryRunBindingSessionAddress | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const context = requestContext.get('controller') as AgentControllerRequestContext<FactorySessionState> | undefined;\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context?.threadId || !context.resourceId || !factoryProjectId) return null;\n return {\n factoryProjectId,\n threadId: context.threadId,\n resourceId: context.resourceId,\n sessionId: context.resourceId,\n };\n}\n\nexport function getFactorySessionAddress(requestContext: RequestContext | undefined): FactoryRunBindingAddress | null {\n const coordinates = getFactorySessionCoordinates(requestContext);\n if (!coordinates || !requestContext || typeof requestContext.get !== 'function') return null;\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const orgId = getFactoryAuthOrgId(user);\n if (!orgId) return null;\n return { orgId, ...coordinates };\n}\n","export type WorkItemSource = 'github-issue' | 'github-pr' | 'linear-issue' | 'manual';\n\nexport const FACTORY_RULE_STAGES = ['intake', 'triage', 'planning', 'execute', 'review', 'done', 'canceled'] as const;\nexport type FactoryRuleStage = (typeof FACTORY_RULE_STAGES)[number];\n\nexport const FACTORY_RULE_BOARDS = ['work', 'review'] as const;\nexport type FactoryRuleBoard = (typeof FACTORY_RULE_BOARDS)[number];\n\nexport const FACTORY_RULE_SOURCES = ['issue', 'pullRequest', 'linearIssue', 'manual'] as const;\nexport type FactoryRuleSource = (typeof FACTORY_RULE_SOURCES)[number];\n\nexport const FACTORY_GITHUB_EVENTS = [\n 'issueOpened',\n 'pullRequestOpened',\n 'pullRequestUpdated',\n 'pullRequestReviewRequested',\n 'pullRequestMerged',\n] as const;\nexport type FactoryGithubEventName = (typeof FACTORY_GITHUB_EVENTS)[number];\n\nexport const FACTORY_LINEAR_EVENTS = ['issueObserved'] as const;\nexport type FactoryLinearEventName = (typeof FACTORY_LINEAR_EVENTS)[number];\n\nexport type FactoryRuleJsonValue =\n | null\n | boolean\n | number\n | string\n | FactoryRuleJsonValue[]\n | { [key: string]: FactoryRuleJsonValue };\n\nexport interface FactoryRuleItemContext {\n id: string;\n source: WorkItemSource;\n sourceKey: string | null;\n parentWorkItemId: string | null;\n title: string;\n url: string | null;\n stages: readonly string[];\n}\n\nexport type FactoryRuleActor =\n | { type: 'human'; id: string }\n | { type: 'agent'; bindingId: string; role: string }\n | { type: 'github'; login: string; trusted: boolean; factoryAuthored: boolean }\n | { type: 'system'; id: string };\n\nexport interface FactoryRuleIngressIdentity {\n type: 'human' | 'agent' | 'toolResult' | 'github' | 'linear' | 'rule';\n id: string;\n}\n\nexport interface FactoryRuleCausalEntry {\n ingressId: string;\n decisionType: FactoryCommitDecision['type'];\n}\n\nexport interface FactoryRuleContextBase {\n tenant: { orgId: string; projectId: string };\n actor: FactoryRuleActor;\n ingress: FactoryRuleIngressIdentity;\n cause: string;\n causalChain: readonly FactoryRuleCausalEntry[];\n ruleSetVersion: string;\n}\n\nexport interface FactoryBoundRuleContext extends FactoryRuleContextBase {\n item: FactoryRuleItemContext;\n board: FactoryRuleBoard;\n itemRevision: number;\n}\n\nexport interface FactoryStageRuleContext extends FactoryBoundRuleContext {\n source: FactoryRuleSource;\n stage: FactoryRuleStage;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n}\n\nexport interface FactoryToolResultRuleContext extends FactoryBoundRuleContext {\n toolName: string;\n threadId: string;\n assistantMessageId: string;\n toolCallId: string;\n result: {\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n };\n}\n\nexport interface FactoryGithubRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryGithubEventName;\n deliveryId: string;\n factory: { createdAt: string };\n repository: { id: number; fullName: string };\n issue?: { number: number; title: string; url: string; createdAt?: string };\n pullRequest?: {\n number: number;\n title: string;\n url: string;\n createdAt?: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n };\n}\n\nexport interface FactoryLinearRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryLinearEventName;\n issue: {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: readonly string[];\n createdAt: string;\n updatedAt: string;\n };\n}\n\nexport type FactoryRuleHandler<TContext> = (\n context: Readonly<TContext>,\n) => FactoryRuleDecision | void | Promise<FactoryRuleDecision | void>;\n\nexport interface FactoryBoardRuleLeaf {\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport interface FactoryToolRuleLeaf {\n onResult?: FactoryRuleHandler<FactoryToolResultRuleContext>;\n}\n\nexport interface FactoryGithubRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryGithubRuleContext>;\n}\n\nexport interface FactoryLinearRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryLinearRuleContext>;\n}\n\nexport type FactoryBoardRules = Partial<\n Record<FactoryRuleStage, Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>>>\n>;\n\nexport interface FactoryRules {\n version: string;\n work: FactoryBoardRules;\n review: FactoryBoardRules;\n tools: Record<string, FactoryToolRuleLeaf>;\n github: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport interface FactoryRulesOverrides {\n work?: FactoryBoardRules;\n review?: FactoryBoardRules;\n tools?: Record<string, FactoryToolRuleLeaf>;\n github?: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear?: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport type FactoryRuleRejectionCode =\n | 'forbidden'\n | 'invalid_transition'\n | 'missing_binding'\n | 'stale'\n | 'timeout'\n | 'rule_error'\n | 'causal_depth_exceeded'\n | 'repeated_transition';\n\nexport interface FactoryRuleRejectDecision {\n type: 'reject';\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\ninterface FactoryCommitDecisionBase {\n idempotencyKey: string;\n}\n\nexport interface FactoryTransitionDecision extends FactoryCommitDecisionBase {\n type: 'transition';\n board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n}\n\nexport interface FactoryUpsertLinkedWorkItemDecision extends FactoryCommitDecisionBase {\n type: 'upsertLinkedWorkItem';\n board: FactoryRuleBoard;\n source: WorkItemSource;\n sourceKey: string;\n title: string;\n url: string | null;\n stage: FactoryRuleStage;\n metadata?: Record<string, FactoryRuleJsonValue>;\n}\n\nexport interface FactoryInvokeSkillDecision extends FactoryCommitDecisionBase {\n type: 'invokeSkill';\n role: string;\n skillName: string;\n arguments?: string;\n precedingMessage?: string;\n}\n\nexport interface FactorySendMessageDecision extends FactoryCommitDecisionBase {\n type: 'sendMessage';\n role: string;\n message: string;\n priority?: 'medium' | 'high' | 'urgent';\n idleBehavior?: 'persist' | 'wake';\n prepareBinding?: boolean;\n}\n\nexport interface FactoryNotifyDecision extends FactoryCommitDecisionBase {\n type: 'notify';\n title: string;\n body?: string;\n level?: 'info' | 'warning' | 'error';\n}\n\nexport type FactoryCommitDecision =\n | FactoryTransitionDecision\n | FactoryUpsertLinkedWorkItemDecision\n | FactoryInvokeSkillDecision\n | FactorySendMessageDecision\n | FactoryNotifyDecision;\n\nexport type FactoryRuleDecision = FactoryRuleRejectDecision | FactoryCommitDecision;\n\nexport interface FactoryTransitionResultAccepted {\n status: 'accepted';\n transitionId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n decisions: FactoryCommitDecision[];\n}\n\nexport interface FactoryTransitionResultRejected {\n status: 'rejected';\n transitionId: string;\n itemId: string;\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\nexport type FactoryTransitionResult = FactoryTransitionResultAccepted | FactoryTransitionResultRejected;\n\nexport function factoryRuleSourceForWorkItem(source: WorkItemSource): FactoryRuleSource {\n switch (source) {\n case 'github-issue':\n return 'issue';\n case 'github-pr':\n return 'pullRequest';\n case 'linear-issue':\n return 'linearIssue';\n case 'manual':\n return 'manual';\n }\n}\n"],"mappings":";AACA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;;;ACFlB,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgHA,SAAS,oBAAoB,MAAuD;AACzF,SAAO,MAAM;AACf;;;AC/GO,SAAS,6BACd,gBACwC;AACxC,MAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,WAAY,QAAO;AACxE,QAAM,UAAU,eAAe,IAAI,YAAY;AAC/C,QAAM,mBAAmB,SAAS,SAAS,EAAE;AAC7C,MAAI,CAAC,SAAS,YAAY,CAAC,QAAQ,cAAc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"","sources":["../src/spa-static.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA2BpC;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAarD;AAmBD;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,IACxC,GAAG,OAAO,EAAE,MAAM,MAAM,OAAO,CAAC,IAAI,CAAC,KAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAuB/E"}
@@ -9,6 +9,7 @@ var MIME = {
9
9
  ".mjs": "text/javascript; charset=utf-8",
10
10
  ".css": "text/css; charset=utf-8",
11
11
  ".json": "application/json",
12
+ ".webmanifest": "application/manifest+json",
12
13
  ".map": "application/json",
13
14
  ".svg": "image/svg+xml",
14
15
  ".png": "image/png",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/spa-static.ts"],"sourcesContent":["/**\n * Same-origin SPA serving for production.\n *\n * In dev the SPA is served by Vite (:5173) which proxies API paths to the\n * server (:4111) — this module is effectively idle there. In production the\n * built SPA (vite output) is served by the API server itself at `/`, so the\n * app is a single origin and no CORS / separate static host is required.\n *\n * The middleware is mounted via the Mastra entry's `server.middleware`, which\n * the deployer applies before routes: real file hits and SPA navigations are\n * answered here, everything else falls through to the API routes.\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, normalize, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Context } from 'hono';\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json',\n '.map': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.txt': 'text/plain; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.wasm': 'application/wasm',\n};\n\n/** Server-owned path prefixes the SPA middleware must never answer for. */\nconst SERVER_PREFIXES = ['/api', '/web', '/auth'];\n\n/**\n * Locate the built SPA (a dir containing `index.html`). Checked in order:\n * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.\n * 2. `factory/` under cwd — both `mastra dev` (cwd is the Mastra public dir)\n * and `mastra start` (cwd is `.mastra/output`) expose assets this way.\n * 3. `factory/` next to the bundled server module.\n * 4. Source-layout fallbacks under `MASTRA_PROJECT_ROOT` or cwd.\n * Returns `undefined` when no build is found (e.g. plain `mastra dev` without\n * a prior vite build), in which case the middleware is simply not mounted.\n */\nexport function resolveUiDistDir(): string | undefined {\n const projectRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n const candidates = [\n process.env.MASTRACODE_UI_DIST,\n resolve(process.cwd(), 'factory'),\n join(dirname(fileURLToPath(import.meta.url)), 'factory'),\n projectRoot && resolve(projectRoot, 'src/mastra/public/factory'),\n resolve(process.cwd(), 'src/mastra/public/factory'),\n ];\n for (const candidate of candidates) {\n if (candidate && existsSync(join(candidate, 'index.html'))) return resolve(candidate);\n }\n return undefined;\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nasync function serveFile(c: Context, filePath: string, immutable: boolean): Promise<Response> {\n const data = await readFile(filePath);\n c.header('Content-Type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream');\n // Vite emits content-hashed filenames under assets/ — cache those forever;\n // index.html (and anything unhashed) must revalidate so deploys roll out.\n c.header('Cache-Control', immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return c.body(new Uint8Array(data));\n}\n\n/**\n * Hono middleware serving the built SPA from `uiDist`:\n * - exact file hits (js/css/assets) are served directly,\n * - GET navigations to non-server paths fall back to `index.html` (SPA\n * client-side routing),\n * - `/api`, `/web`, `/auth` and non-GET requests always pass through.\n */\nexport function createSpaStaticMiddleware(uiDist: string) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();\n const path = c.req.path;\n if (SERVER_PREFIXES.some(prefix => path === prefix || path.startsWith(`${prefix}/`))) return next();\n\n // Resolve the request path inside uiDist, rejecting traversal escapes.\n const relative = normalize(decodeURIComponent(path)).replace(/^[/\\\\]+/, '');\n const filePath = resolve(uiDist, relative);\n // Use a trailing separator so a sibling like \"ui.key\" can't slip past the\n // prefix check (same pattern as fs-routes.ts isWithinRoot).\n const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;\n if (filePath.startsWith(uiDistPrefix) && relative !== '' && (await isFile(filePath))) {\n return serveFile(c, filePath, relative.startsWith('assets/'));\n }\n\n // SPA fallback: serve index.html for root and html navigations.\n const accept = c.req.header('Accept') ?? '';\n if (path === '/' || accept.includes('text/html')) {\n return serveFile(c, join(uiDist, 'index.html'), false);\n }\n\n return next();\n };\n}\n"],"mappings":";AAaA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,YAAY;AAC/B,SAAS,SAAS,SAAS,MAAM,WAAW,SAAS,WAAW;AAChE,SAAS,qBAAqB;AAI9B,IAAM,OAA+B;AAAA,EACnC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,SAAS;AACX;AAGA,IAAM,kBAAkB,CAAC,QAAQ,QAAQ,O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,GAAG,IAAI,SAAS,SAAS;AAC9D,QAAI,SAAS,WAAW,YAAY,KAAK,aAAa,MAAO,MAAM,OAAO,QAAQ,GAAI;AACpF,aAAO,UAAU,GAAG,UAAU,SAAS,WAAW,SAAS,CAAC;AAAA,IAC9D;AAGA,UAAM,SAAS,EAAE,IAAI,OAAO,QAAQ,KAAK;AACzC,QAAI,SAAS,OAAO,OAAO,SAAS,WAAW,GAAG;AAChD,aAAO,UAAU,GAAG,KAAK,QAAQ,YAAY,GAAG,KAAK;AAAA,IACvD;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/spa-static.ts"],"sourcesContent":["/**\n * Same-origin SPA serving for production.\n *\n * In dev the SPA is served by Vite (:5173) which proxies API paths to the\n * server (:4111) — this module is effectively idle there. In production the\n * built SPA (vite output) is served by the API server itself at `/`, so the\n * app is a single origin and no CORS / separate static host is required.\n *\n * The middleware is mounted via the Mastra entry's `server.middleware`, which\n * the deployer applies before routes: real file hits and SPA navigations are\n * answered here, everything else falls through to the API routes.\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, normalize, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Context } from 'hono';\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json',\n '.webmanifest': 'application/manifest+json',\n '.map': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.txt': 'text/plain; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.wasm': 'application/wasm',\n};\n\n/** Server-owned path prefixes the SPA middleware must never answer for. */\nconst SERVER_PREFIXES = ['/api', '/web', '/auth'];\n\n/**\n * Locate the built SPA (a dir containing `index.html`). Checked in order:\n * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.\n * 2. `factory/` under cwd — both `mastra dev` (cwd is the Mastra public dir)\n * and `mastra start` (cwd is `.mastra/output`) expose assets this way.\n * 3. `factory/` next to the bundled server module.\n * 4. Source-layout fallbacks under `MASTRA_PROJECT_ROOT` or cwd.\n * Returns `undefined` when no build is found (e.g. plain `mastra dev` without\n * a prior vite build), in which case the middleware is simply not mounted.\n */\nexport function resolveUiDistDir(): string | undefined {\n const projectRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n const candidates = [\n process.env.MASTRACODE_UI_DIST,\n resolve(process.cwd(), 'factory'),\n join(dirname(fileURLToPath(import.meta.url)), 'factory'),\n projectRoot && resolve(projectRoot, 'src/mastra/public/factory'),\n resolve(process.cwd(), 'src/mastra/public/factory'),\n ];\n for (const candidate of candidates) {\n if (candidate && existsSync(join(candidate, 'index.html'))) return resolve(candidate);\n }\n return undefined;\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nasync function serveFile(c: Context, filePath: string, immutable: boolean): Promise<Response> {\n const data = await readFile(filePath);\n c.header('Content-Type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream');\n // Vite emits content-hashed filenames under assets/ — cache those forever;\n // index.html (and anything unhashed) must revalidate so deploys roll out.\n c.header('Cache-Control', immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return c.body(new Uint8Array(data));\n}\n\n/**\n * Hono middleware serving the built SPA from `uiDist`:\n * - exact file hits (js/css/assets) are served directly,\n * - GET navigations to non-server paths fall back to `index.html` (SPA\n * client-side routing),\n * - `/api`, `/web`, `/auth` and non-GET requests always pass through.\n */\nexport function createSpaStaticMiddleware(uiDist: string) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();\n const path = c.req.path;\n if (SERVER_PREFIXES.some(prefix => path === prefix || path.startsWith(`${prefix}/`))) return next();\n\n // Resolve the request path inside uiDist, rejecting traversal escapes.\n const relative = normalize(decodeURIComponent(path)).replace(/^[/\\\\]+/, '');\n const filePath = resolve(uiDist, relative);\n // Use a trailing separator so a sibling like \"ui.key\" can't slip past the\n // prefix check (same pattern as fs-routes.ts isWithinRoot).\n const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;\n if (filePath.startsWith(uiDistPrefix) && relative !== '' && (await isFile(filePath))) {\n return serveFile(c, filePath, relative.startsWith('assets/'));\n }\n\n // SPA fallback: serve index.html for root and html navigations.\n const accept = c.req.header('Accept') ?? '';\n if (path === '/' || accept.includes('text/html')) {\n return serveFile(c, join(uiDist, 'index.html'), false);\n }\n\n return next();\n };\n}\n"],"mappings":";AAaA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,YAAY;AAC/B,SAAS,SAAS,SAAS,MAAM,WAAW,SAAS,WAAW;AAChE,SAAS,qBAAqB;AAI9B,IAAM,OAA+B;AAAA,EACnC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,SAAS;AACX;AAGA,IAAM,kBAAkB,CAAC,QAAQ,QAAQ,OAAO;AAYzC,SAAS,mBAAuC;AACrD,QAAM,cAAc,QAAQ,IAAI,qBAAqB,KAAK;AAC1D,QAAM,aAAa;AAAA,IACjB,QAAQ,IAAI;AAAA,IACZ,QAAQ,QAAQ,IAAI,GAAG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AAAA,IAC9D;AAGA,UAAM,SAAS,EAAE,IAAI,OAAO,QAAQ,KAAK;AACzC,QAAI,SAAS,OAAO,OAAO,SAAS,WAAW,GAAG;AAChD,aAAO,UAAU,GAAG,KAAK,QAAQ,YAAY,GAAG,KAAK;AAAA,IACvD;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":[]}
@@ -222,6 +222,15 @@ export interface SourceControlStorageHandle {
222
222
  getById(args: {
223
223
  id: string;
224
224
  }): Promise<ProjectRepositorySandbox | null>;
225
+ /**
226
+ * Point the binding at a new workdir and clear `materializedAt` — a moved
227
+ * workdir means the checkout must be re-cloned. Used to heal bindings whose
228
+ * inherited workdir went stale (e.g. the sandbox provider changed).
229
+ */
230
+ setWorkdir(args: {
231
+ id: string;
232
+ sandboxWorkdir: string;
233
+ }): Promise<void>;
225
234
  setSandboxId(args: {
226
235
  id: string;
227
236
  sandboxId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/source-control/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,sBAAsB,CAAC;AAWhF,eAAO,MAAM,sBAAsB,EAAE,gBAAgB,EA4JpD,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEpE,MAAM,WAAW,yBAAyB;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,EAAE,6BAA6B,CAAC;IAChD,SAAS,EAAE,IAAI,CAAC;C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AI,OAAO,CAAC,IAAI,CAAC;IAU1C,cAAc,CAAC,aAAa,EAAE,MAAM,GAAG,0BAA0B;CAydlE"}
@@ -581,6 +581,10 @@ var SourceControlStorage = class extends FactoryStorageDomain {
581
581
  }
582
582
  },
583
583
  getById: ({ id }) => getSandbox(id),
584
+ setWorkdir: async ({ id, sandboxWorkdir }) => {
585
+ await requireSandbox(id);
586
+ await db().updateMany(SANDBOXES, { id }, { sandbox_workdir: sandboxWorkdir, materialized_at: null });
587
+ },
584
588
  setSandboxId: async ({ id, sandboxId }) => {
585
589
  await requireSandbox(id);
586
590
  await db().updateMany(SANDBOXES, { id }, { sandbox_id: sandboxId });