'use strict';

var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunkK52BGIHQ_cjs = require('./chunk-K52BGIHQ.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var auth = require('@mastra/core/auth');
var zod = require('zod');

var ssoConfigSchema = zod.z.object({
  provider: zod.z.string(),
  text: zod.z.string(),
  icon: zod.z.string().optional(),
  url: zod.z.string()
});
var loginConfigSchema = zod.z.object({
  type: zod.z.enum(["sso", "credentials", "both"]),
  sso: ssoConfigSchema.optional()
}).nullable();
var publicCapabilitiesSchema = zod.z.object({
  enabled: zod.z.boolean(),
  login: loginConfigSchema
});
var authenticatedUserSchema = zod.z.object({
  id: zod.z.string(),
  email: zod.z.string().optional(),
  name: zod.z.string().optional(),
  avatarUrl: zod.z.string().optional()
});
var capabilityFlagsSchema = zod.z.object({
  user: zod.z.boolean(),
  session: zod.z.boolean(),
  sso: zod.z.boolean(),
  rbac: zod.z.boolean(),
  acl: zod.z.boolean()
});
var userAccessSchema = zod.z.object({
  roles: zod.z.array(zod.z.string()),
  permissions: zod.z.array(zod.z.string())
}).nullable();
var authenticatedCapabilitiesSchema = publicCapabilitiesSchema.extend({
  user: authenticatedUserSchema,
  capabilities: capabilityFlagsSchema,
  access: userAccessSchema
});
var capabilitiesResponseSchema = zod.z.union([publicCapabilitiesSchema, authenticatedCapabilitiesSchema]);
var ssoLoginQuerySchema = zod.z.object({
  redirect_uri: zod.z.string().optional()
});
var ssoCallbackQuerySchema = zod.z.object({
  code: zod.z.string(),
  state: zod.z.string().optional()
});
zod.z.object({
  url: zod.z.string()
});
zod.z.object({
  success: zod.z.boolean(),
  user: authenticatedUserSchema.optional(),
  redirectTo: zod.z.string().optional()
});
zod.z.object({
  success: zod.z.boolean(),
  redirectTo: zod.z.string().optional()
});
var currentUserResponseSchema = zod.z.object({
  id: zod.z.string(),
  email: zod.z.string().optional(),
  name: zod.z.string().optional(),
  avatarUrl: zod.z.string().optional(),
  roles: zod.z.array(zod.z.string()).optional(),
  permissions: zod.z.array(zod.z.string()).optional()
}).nullable();
var credentialsSignInBodySchema = zod.z.object({
  email: zod.z.string().email(),
  password: zod.z.string().min(1)
});
var credentialsSignUpBodySchema = zod.z.object({
  email: zod.z.string().email(),
  password: zod.z.string().min(1),
  name: zod.z.string().optional()
});
zod.z.object({
  user: authenticatedUserSchema,
  token: zod.z.string().optional()
});

// src/server/handlers/auth.ts
function getAuthProvider(mastra) {
  const serverConfig = mastra.getServer?.();
  if (!serverConfig?.auth) return null;
  if (typeof serverConfig.auth.authenticateToken === "function") {
    return serverConfig.auth;
  }
  return null;
}
function getPublicOrigin(request) {
  const forwardedHost = request.headers.get("x-forwarded-host");
  if (forwardedHost) {
    return `https://${forwardedHost}`;
  }
  return new URL(request.url).origin;
}
function getRBACProvider(mastra) {
  const serverConfig = mastra.getServer?.();
  return serverConfig?.rbac;
}
function implementsInterface(auth, method) {
  return auth !== null && typeof auth === "object" && method in auth;
}
var GET_AUTH_CAPABILITIES_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "GET",
  path: "/auth/capabilities",
  responseType: "json",
  responseSchema: capabilitiesResponseSchema,
  summary: "Get auth capabilities",
  description: "Returns authentication capabilities and current user info. Used by Studio to determine available features and user state.",
  tags: ["Auth"],
  handler: async (ctx) => {
    try {
      const { mastra, request } = ctx;
      const auth$1 = getAuthProvider(mastra);
      const rbac = getRBACProvider(mastra);
      const capabilities = await auth.buildCapabilities(auth$1, request, { rbac });
      return capabilities;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting auth capabilities");
    }
  }
});
var GET_CURRENT_USER_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "GET",
  path: "/auth/me",
  responseType: "json",
  responseSchema: currentUserResponseSchema,
  summary: "Get current user",
  description: "Returns the currently authenticated user, or null if not authenticated.",
  tags: ["Auth"],
  handler: async (ctx) => {
    try {
      const { mastra, request } = ctx;
      const auth = getAuthProvider(mastra);
      const rbac = getRBACProvider(mastra);
      if (!auth || !implementsInterface(auth, "getCurrentUser")) {
        return null;
      }
      const user = await auth.getCurrentUser(request);
      if (!user) return null;
      let roles;
      let permissions;
      if (rbac) {
        try {
          roles = await rbac.getRoles(user);
          permissions = await rbac.getPermissions(user);
        } catch {
        }
      }
      return {
        id: user.id,
        email: user.email,
        name: user.name,
        avatarUrl: user.avatarUrl,
        roles,
        permissions
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting current user");
    }
  }
});
var GET_SSO_LOGIN_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "GET",
  path: "/auth/sso/login",
  responseType: "datastream-response",
  queryParamSchema: ssoLoginQuerySchema,
  summary: "Initiate SSO login",
  description: "Returns the SSO login URL and sets PKCE cookies if needed.",
  tags: ["Auth"],
  handler: async (ctx) => {
    try {
      const { mastra, redirect_uri, request } = ctx;
      const auth = getAuthProvider(mastra);
      if (!auth || !implementsInterface(auth, "getLoginUrl")) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "SSO not configured" });
      }
      const origin = getPublicOrigin(request);
      const oauthCallbackUri = `${origin}/api/auth/sso/callback`;
      const stateId = crypto.randomUUID();
      const postLoginRedirect = redirect_uri || "/";
      const state = `${stateId}|${encodeURIComponent(postLoginRedirect)}`;
      const loginUrl = auth.getLoginUrl(oauthCallbackUri, state);
      const headers = new Headers({ "Content-Type": "application/json" });
      if (implementsInterface(auth, "getLoginCookies") && auth.getLoginCookies) {
        const cookies = auth.getLoginCookies(oauthCallbackUri, state);
        if (cookies?.length) {
          console.log("[auth-handler] setting PKCE cookies", cookies.map((c) => c.split("=")[0]));
          for (const cookie of cookies) {
            headers.append("Set-Cookie", cookie);
          }
        }
      }
      return new Response(JSON.stringify({ url: loginUrl }), { status: 200, headers });
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error initiating SSO login");
    }
  }
});
var GET_SSO_CALLBACK_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "GET",
  path: "/auth/sso/callback",
  responseType: "datastream-response",
  queryParamSchema: ssoCallbackQuerySchema,
  summary: "Handle SSO callback",
  description: "Handles the OAuth callback, exchanges code for session, and redirects to the app.",
  tags: ["Auth"],
  handler: async (ctx) => {
    const { mastra, code, state, request } = ctx;
    const baseUrl = getPublicOrigin(request);
    let redirectTo = "/";
    let stateId = state || "";
    if (state && state.includes("|")) {
      const [id, encodedRedirect] = state.split("|", 2);
      stateId = id;
      try {
        redirectTo = decodeURIComponent(encodedRedirect);
      } catch {
        redirectTo = "/";
      }
    }
    const absoluteRedirect = redirectTo.startsWith("http") ? redirectTo : `${baseUrl}${redirectTo}`;
    try {
      const auth = getAuthProvider(mastra);
      if (!auth || !implementsInterface(auth, "handleCallback")) {
        return Response.redirect(`${absoluteRedirect}?error=sso_not_configured`, 302);
      }
      const reqCookieHeader = request.headers.get("cookie");
      console.log("[auth-handler] callback received", { hasCode: !!code, stateId, hasCookie: !!reqCookieHeader });
      if (typeof auth.setCallbackCookieHeader === "function") {
        console.log("[auth-handler] setting callback cookie header");
        auth.setCallbackCookieHeader(reqCookieHeader);
      }
      const result = await auth.handleCallback(code, stateId);
      console.log("[auth-handler] handleCallback result", { userId: result.user?.id, cookieCount: result.cookies?.length });
      const user = result.user;
      const headers = new Headers();
      headers.set("Location", absoluteRedirect);
      if (result.cookies?.length) {
        console.log("[auth-handler] setting cookies", result.cookies.map((c) => c.split("=")[0]));
        for (const cookie of result.cookies) {
          headers.append("Set-Cookie", cookie);
        }
      } else if (implementsInterface(auth, "createSession") && result.tokens) {
        const session = await auth.createSession(user.id, {
          accessToken: result.tokens.accessToken,
          refreshToken: result.tokens.refreshToken,
          expiresAt: result.tokens.expiresAt,
          organizationId: user.organizationId
        });
        const sessionHeaders = auth.getSessionHeaders(session);
        for (const [key, value] of Object.entries(sessionHeaders)) {
          headers.append(key, value);
        }
      }
      return new Response(null, {
        status: 302,
        headers
      });
    } catch (error) {
      const errorMessage = encodeURIComponent(error instanceof Error ? error.message : "Unknown error");
      return Response.redirect(`${absoluteRedirect}?error=${errorMessage}`, 302);
    }
  }
});
var POST_LOGOUT_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "POST",
  path: "/auth/logout",
  responseType: "datastream-response",
  summary: "Logout",
  description: "Destroys the current session and returns logout redirect URL if available.",
  tags: ["Auth"],
  handler: async (ctx) => {
    const { mastra, request } = ctx;
    try {
      const auth = getAuthProvider(mastra);
      if (!auth) {
        return new Response(JSON.stringify({ success: true }), {
          status: 200,
          headers: { "Content-Type": "application/json" }
        });
      }
      if (implementsInterface(auth, "getSessionIdFromRequest")) {
        const sessionId = auth.getSessionIdFromRequest(request);
        if (sessionId && implementsInterface(auth, "destroySession")) {
          await auth.destroySession(sessionId);
        }
      }
      let redirectTo;
      if (implementsInterface(auth, "getLogoutUrl") && auth.getLogoutUrl) {
        const origin = getPublicOrigin(request);
        const logoutUrl = await auth.getLogoutUrl(origin, request);
        redirectTo = logoutUrl ?? void 0;
      }
      const headers = new Headers({ "Content-Type": "application/json" });
      if (implementsInterface(auth, "getClearSessionHeaders")) {
        const clearHeaders = auth.getClearSessionHeaders();
        for (const [key, value] of Object.entries(clearHeaders)) {
          headers.append(key, value);
        }
      }
      return new Response(JSON.stringify({ success: true, redirectTo }), {
        status: 200,
        headers
      });
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error logging out");
    }
  }
});
var POST_CREDENTIALS_SIGN_IN_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "POST",
  path: "/auth/credentials/sign-in",
  responseType: "datastream-response",
  bodySchema: credentialsSignInBodySchema,
  summary: "Sign in with credentials",
  description: "Authenticates a user with email and password.",
  tags: ["Auth"],
  handler: async (ctx) => {
    const { mastra, request, email, password } = ctx;
    try {
      const auth = getAuthProvider(mastra);
      if (!auth || !implementsInterface(auth, "signIn")) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Credentials authentication not configured" });
      }
      const result = await auth.signIn(email, password, request);
      const user = result.user;
      const responseBody = JSON.stringify({
        user: {
          id: user.id,
          email: user.email,
          name: user.name,
          avatarUrl: user.avatarUrl
        },
        token: result.token
      });
      const headers = new Headers({
        "Content-Type": "application/json"
      });
      if (result.cookies?.length) {
        for (const cookie of result.cookies) {
          headers.append("Set-Cookie", cookie);
        }
      }
      return new Response(responseBody, { status: 200, headers });
    } catch (error) {
      if (error instanceof chunk64ITUOXI_cjs.HTTPException) throw error;
      throw new chunk64ITUOXI_cjs.HTTPException(401, { message: "Invalid email or password" });
    }
  }
});
var POST_CREDENTIALS_SIGN_UP_ROUTE = chunkK52BGIHQ_cjs.createPublicRoute({
  method: "POST",
  path: "/auth/credentials/sign-up",
  responseType: "datastream-response",
  bodySchema: credentialsSignUpBodySchema,
  summary: "Sign up with credentials",
  description: "Creates a new user account with email and password.",
  tags: ["Auth"],
  handler: async (ctx) => {
    const { mastra, request, email, password, name } = ctx;
    try {
      const auth = getAuthProvider(mastra);
      if (!auth || !implementsInterface(auth, "signUp")) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Credentials authentication not configured" });
      }
      const result = await auth.signUp(email, password, name, request);
      const user = result.user;
      const responseBody = JSON.stringify({
        user: {
          id: user.id,
          email: user.email,
          name: user.name,
          avatarUrl: user.avatarUrl
        },
        token: result.token
      });
      const headers = new Headers({
        "Content-Type": "application/json"
      });
      if (result.cookies?.length) {
        for (const cookie of result.cookies) {
          headers.append("Set-Cookie", cookie);
        }
      }
      return new Response(responseBody, { status: 200, headers });
    } catch (error) {
      if (error instanceof chunk64ITUOXI_cjs.HTTPException) throw error;
      const errorMessage = error instanceof Error ? error.message : "Failed to create account";
      throw new chunk64ITUOXI_cjs.HTTPException(400, { message: errorMessage });
    }
  }
});
var AUTH_ROUTES = [
  GET_AUTH_CAPABILITIES_ROUTE,
  GET_CURRENT_USER_ROUTE,
  GET_SSO_LOGIN_ROUTE,
  GET_SSO_CALLBACK_ROUTE,
  POST_LOGOUT_ROUTE,
  POST_CREDENTIALS_SIGN_IN_ROUTE,
  POST_CREDENTIALS_SIGN_UP_ROUTE
];

exports.AUTH_ROUTES = AUTH_ROUTES;
exports.GET_AUTH_CAPABILITIES_ROUTE = GET_AUTH_CAPABILITIES_ROUTE;
exports.GET_CURRENT_USER_ROUTE = GET_CURRENT_USER_ROUTE;
exports.GET_SSO_CALLBACK_ROUTE = GET_SSO_CALLBACK_ROUTE;
exports.GET_SSO_LOGIN_ROUTE = GET_SSO_LOGIN_ROUTE;
exports.POST_CREDENTIALS_SIGN_IN_ROUTE = POST_CREDENTIALS_SIGN_IN_ROUTE;
exports.POST_CREDENTIALS_SIGN_UP_ROUTE = POST_CREDENTIALS_SIGN_UP_ROUTE;
exports.POST_LOGOUT_ROUTE = POST_LOGOUT_ROUTE;
//# sourceMappingURL=chunk-FWRZAKZK.cjs.map
//# sourceMappingURL=chunk-FWRZAKZK.cjs.map