The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
made saml work
Steven Tey777c2e33fe9b
diff --git a/app/app/(auth)/auth/saml/form.tsx b/app/app/(auth)/auth/saml/form.tsxnew file mode 100644index 0000000000..40c7b40f6a--- /dev/null+++ b/app/app/(auth)/auth/saml/form.tsx@@ -0,0 +1,21 @@+"use client";++import { signIn } from "next-auth/react";+import { useSearchParams } from "next/navigation";+import { useEffect } from "react";++// To handle the IdP initiated login flow callback+export default function SAMLForm() {+ const searchParams = useSearchParams();++ useEffect(() => {+ const code = searchParams?.get("code");++ signIn("idp-saml", {+ callbackUrl: "/",+ code,+ });+ }, []);++ return null;+}diff --git a/app/app/(auth)/auth/saml/page.tsx b/app/app/(auth)/auth/saml/page.tsxnew file mode 100644index 0000000000..e49e439188--- /dev/null+++ b/app/app/(auth)/auth/saml/page.tsx@@ -0,0 +1,18 @@+import { LoadingSpinner } from "#/ui/icons";+import SAMLIDPForm from "./form";++export default function SAMLPage() {+ return (+ <div>+ <SAMLIDPForm />+ <div className="flex h-screen flex-col items-center justify-center space-y-6 text-center">+ <h1 className="font-display text-4xl font-bold">Authenticating</h1>+ <p className="text-lg text-gray-600">+ Dub is verifying your identity.+ <br /> Please wait...+ </p>+ <LoadingSpinner className="h-7 w-7" />+ </div>+ </div>+ );+}diff --git a/app/app/(auth)/login/form.tsx b/app/app/(auth)/login/form.tsxindex b6d08484ae..5d92a56a28 100644--- a/app/app/(auth)/login/form.tsx+++ b/app/app/(auth)/login/form.tsx@@ -129,7 +129,7 @@ export default function LoginForm() {}await signIn("boxyhq-saml", undefined, {tenant: data.projectId,- product: "dub",+ product: "Dub",});});}}diff --git a/components/app/modals/remove-saml-modal.tsx b/components/app/modals/remove-saml-modal.tsxnew file mode 100644index 0000000000..603c588e4b--- /dev/null+++ b/components/app/modals/remove-saml-modal.tsx@@ -0,0 +1,120 @@+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import BlurImage from "#/ui/blur-image";+import Modal from "#/ui/modal";+import useProject from "#/lib/swr/use-project";+import { toast } from "sonner";+import Button from "#/ui/button";+import { Logo } from "#/ui/icons";+import useSAML from "#/lib/swr/use-saml";++function RemoveSAMLModal({+ showRemoveSAMLModal,+ setShowRemoveSAMLModal,+}: {+ showRemoveSAMLModal: boolean;+ setShowRemoveSAMLModal: Dispatch<SetStateAction<boolean>>;+}) {+ const [removing, setRemoving] = useState(false);+ const { slug, logo } = useProject();+ const { saml, mutate } = useSAML();++ return (+ <Modal+ showModal={showRemoveSAMLModal}+ setShowModal={setShowRemoveSAMLModal}+ >+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">+ {logo ? (+ <BlurImage+ src={logo}+ alt="Project logo"+ className="h-10 w-10 rounded-full"+ width={20}+ height={20}+ />+ ) : (+ <Logo />+ )}+ <h3 className="text-lg font-medium">Remove SAML</h3>+ <p className="text-center text-sm text-gray-500">+ This will remove SAML from your project. Are you sure you want to+ continue?+ </p>+ </div>++ <div className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-16">+ <div className="flex items-center space-x-3 rounded-md border border-gray-300 bg-white p-3">+ <BlurImage+ src="/_static/icons/okta.svg"+ alt="Okta logo"+ width={40}+ height={40}+ className="overflow-hidden rounded-full border border-gray-200"+ />+ <div className="flex flex-col">+ <h3 className="text-sm font-medium">Okta SAML</h3>+ <p className="text-xs text-gray-500">Okta SAML is configured</p>+ </div>+ </div>+ <Button+ text="Confirm remove"+ variant="danger"+ loading={removing}+ onClick={() => {+ setRemoving(true);+ if (!saml?.connections[0]) {+ toast.error("No SAML connection found");+ return;+ }+ const { clientID, clientSecret } = saml.connections[0];+ const params = new URLSearchParams({+ clientID,+ clientSecret,+ });++ fetch(`/api/projects/${slug}/saml?${params}`, {+ method: "DELETE",+ }).then(async (res) => {+ if (res.ok) {+ toast.success("SAML removed successfully");+ mutate();+ setRemoving(false);+ setShowRemoveSAMLModal(false);+ } else {+ toast.error("Error removing SAML");+ setRemoving(false);+ }+ });+ }}+ />+ </div>+ </Modal>+ );+}++export function useRemoveSAMLModal() {+ const [showRemoveSAMLModal, setShowRemoveSAMLModal] = useState(false);++ const RemoveSAMLModalCallback = useCallback(() => {+ return (+ <RemoveSAMLModal+ showRemoveSAMLModal={showRemoveSAMLModal}+ setShowRemoveSAMLModal={setShowRemoveSAMLModal}+ />+ );+ }, [showRemoveSAMLModal, setShowRemoveSAMLModal]);++ return useMemo(+ () => ({+ setShowRemoveSAMLModal,+ RemoveSAMLModal: RemoveSAMLModalCallback,+ }),+ [setShowRemoveSAMLModal, RemoveSAMLModalCallback],+ );+}diff --git a/components/app/modals/saml-modal.tsx b/components/app/modals/saml-modal.tsxindex 452458f2b9..ef3ad947dd 100644--- a/components/app/modals/saml-modal.tsx+++ b/components/app/modals/saml-modal.tsx@@ -13,6 +13,7 @@ import { Logo } from "#/ui/icons";import useProject from "#/lib/swr/use-project";import { InfoTooltip, SimpleTooltipContent } from "#/ui/tooltip";import { HOME_DOMAIN } from "#/lib/constants";+import useSAML from "#/lib/swr/use-saml";function SAMLModal({showSAMLModal,@@ -23,6 +24,7 @@ function SAMLModal({}) {const { slug } = useProject();const [submitting, setSubmitting] = useState(false);+ const { mutate } = useSAML();return (<Modal showModal={showSAMLModal} setShowModal={setShowSAMLModal}>@@ -57,6 +59,7 @@ function SAMLModal({}),}).then((res) => {if (res.ok) {+ mutate();toast.success("Successfully configured SAML");setShowSAMLModal(false);} else {diff --git a/lib/constants/index.ts b/lib/constants/index.tsindex 1b8693b9b4..857c14b412 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -49,6 +49,7 @@ export const APP_HOSTNAMES = new Set(["app.dub.sh","app.localhost:3000","app.localhost",+ "localhost:8888","preview.dub.sh",]);@@ -57,7 +58,7 @@ export const APP_DOMAIN =? "https://app.dub.sh": process.env.NEXT_PUBLIC_VERCEL_ENV === "preview"? "https://preview.dub.sh"- : "http://app.localhost:3000";+ : "http://localhost:8888";export const DEFAULT_REDIRECTS = {home: "https://dub.sh",@@ -99,6 +100,7 @@ export const SHOW_BACKGROUND_SEGMENTS = new Set(["(blog-post)","login","register",+ "auth",]);export { default as COUNTRIES } from "./countries";diff --git a/lib/jackson.ts b/lib/jackson.tsindex 016c207896..5c025717d6 100644--- a/lib/jackson.ts+++ b/lib/jackson.ts@@ -6,8 +6,8 @@ import type {ISPSAMLConfig,} from "@boxyhq/saml-jackson";+const samlPath = "/api/oauth/saml";const samlAudience = "https://saml.dub.sh";-const samlPath = "/api/auth/saml/acs";const opts: JacksonOption = {externalUrl: process.env.NEXTAUTH_URL as string,diff --git a/lib/middleware/app.ts b/lib/middleware/app.tsindex 1328d1446d..854823c8de 100644--- a/lib/middleware/app.ts+++ b/lib/middleware/app.ts@@ -14,7 +14,12 @@ export default async function AppMiddleware(req: NextRequest) {user?: UserProps;};// if there's no session and the path isn't /login or /register, redirect to /login- if (!session?.email && path !== "/login" && path !== "/register") {+ if (+ !session?.email &&+ path !== "/login" &&+ path !== "/register" &&+ path !== "/auth/saml"+ ) {return NextResponse.redirect(new URL(`/login${path !== "/" ? `?next=${encodeURIComponent(path)}` : ""}`,diff --git a/lib/swr/use-saml.ts b/lib/swr/use-saml.tsnew file mode 100644index 0000000000..37fa476264--- /dev/null+++ b/lib/swr/use-saml.ts@@ -0,0 +1,26 @@+import { useRouter } from "next/router";+import useSWR from "swr";+import type { SAMLSSORecord } from "@boxyhq/saml-jackson";+import { fetcher } from "#/lib/utils";++export default function useSAML() {+ const router = useRouter();+ const { slug } = router.query as {+ slug: string;+ };++ const {+ data: saml,+ isLoading,+ mutate,+ } = useSWR<{ connections: SAMLSSORecord[] }>(+ slug && `/api/projects/${slug}/saml`,+ fetcher,+ );++ return {+ saml,+ isLoading,+ mutate,+ };+}diff --git a/package.json b/package.jsonindex 7316d9b78d..4aacbb6996 100644--- a/package.json+++ b/package.json@@ -2,7 +2,7 @@"private": true,"license": "AGPL-3.0-or-later","scripts": {- "dev": "concurrently --kill-others \"next dev\" \"prisma studio --browser none\" \"email dev --port 3333\"",+ "dev": "concurrently --kill-others \"next dev --port 8888\" \"prisma studio --browser none\" \"email dev --port 3333\"","build": "prisma generate & next build","format:write": "prettier --write \"**/*.{css,js,json,jsx,ts,tsx}\"","format": "prettier \"**/*.{css,js,json,jsx,ts,tsx}\"",diff --git a/pages/api/auth/[...nextauth].tsx b/pages/api/auth/[...nextauth].tsxindex ac48e262e9..ba916c4a3d 100644--- a/pages/api/auth/[...nextauth].tsx+++ b/pages/api/auth/[...nextauth].tsx@@ -1,12 +1,14 @@import EmailProvider from "next-auth/providers/email";import GoogleProvider from "next-auth/providers/google";import BoxyHQSAMLProvider from "next-auth/providers/boxyhq-saml";+import CredentialsProvider from "next-auth/providers/credentials";import { PrismaAdapter } from "@next-auth/prisma-adapter";import { sendEmail } from "emails";import LoginLink from "emails/login-link";import WelcomeEmail from "emails/welcome-email";import NextAuth, { type NextAuthOptions } from "next-auth";import prisma from "#/lib/prisma";+import jackson from "#/lib/jackson";import { isBlacklistedEmail } from "#/lib/edge-config";const VERCEL_DEPLOYMENT = !!process.env.VERCEL_URL;@@ -36,12 +38,61 @@ export const authOptions: NextAuthOptions = {authorization: { params: { scope: "" } },issuer: process.env.NEXTAUTH_URL,clientId: "dummy",- clientSecret: "dummy",+ clientSecret: process.env.NEXTAUTH_SECRET as string,allowDangerousEmailAccountLinking: true,httpOptions: {timeout: 30000,},}),+ CredentialsProvider({+ id: "idp-saml",+ name: "IdP Login",+ credentials: {+ code: {},+ },+ async authorize(credentials) {+ if (!credentials) {+ return null;+ }++ const { code } = credentials;++ if (!code) {+ return null;+ }++ const { oauthController } = await jackson();++ // Fetch access token+ const { access_token } = await oauthController.token({+ code,+ grant_type: "authorization_code",+ redirect_uri: process.env.NEXTAUTH_URL as string,+ client_id: "dummy",+ client_secret: process.env.NEXTAUTH_SECRET as string,+ });++ if (!access_token) {+ return null;+ }++ // Fetch user info+ const userInfo = await oauthController.userInfo(access_token);++ if (!userInfo) {+ return null;+ }++ const { id, firstName, lastName, email } = userInfo;++ return {+ id,+ email,+ name: `${firstName} ${lastName}`.trim(),+ email_verified: true,+ };+ },+ }),],adapter: PrismaAdapter(prisma),session: { strategy: "jwt" },diff --git a/pages/api/auth/saml/authorize.ts b/pages/api/auth/saml/authorize.tsdeleted file mode 100644index 83be8515d5..0000000000--- a/pages/api/auth/saml/authorize.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";-import type { OAuthReq } from "@boxyhq/saml-jackson";--import jackson from "#/lib/jackson";--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- const { oauthController } = await jackson();-- const { redirect_url } = await oauthController.authorize(- req.query as unknown as OAuthReq,- );-- return res.redirect(302, redirect_url as string);-}diff --git a/pages/api/auth/saml/acs.ts b/pages/api/auth/sso/acs.tssimilarity index 100%rename from pages/api/auth/saml/acs.tsrename to pages/api/auth/sso/acs.tsdiff --git a/pages/api/auth/sso/verify.tsx b/pages/api/auth/sso/verify.tsxindex a5da578166..2adac8fbd6 100644--- a/pages/api/auth/sso/verify.tsx+++ b/pages/api/auth/sso/verify.tsx@@ -26,7 +26,7 @@ export default async function handler(const connections = await apiController.getConnections({tenant: project.id,- product: "dub",+ product: "Dub",});if (!connections || connections.length === 0) {@@ -35,8 +35,6 @@ export default async function handler(.json({ error: "No SSO connections found for this project." });}- console.log({ connections });-const data = {projectId: project.id,};diff --git a/pages/api/oauth/authorize.ts b/pages/api/oauth/authorize.tsindex a284675188..afff735580 100644--- a/pages/api/oauth/authorize.ts+++ b/pages/api/oauth/authorize.ts@@ -5,39 +5,25 @@ export default async function handler(req: NextApiRequest,res: NextApiResponse,) {- const { method } = req;+ if (req.method === "GET" || req.method === "POST") {+ const { oauthController } = await jackson();- try {- switch (method) {- case "GET":- case "POST":- await handleAuthorize(req, res);- break;- default:- res.setHeader("Allow", "GET, POST");- res.status(405).json({- error: { message: `Method ${method} Not Allowed` },- });- }- } catch (err: any) {- res.status(500).json({ error: { message: err.message } });- }-}--const handleAuthorize = async (req: NextApiRequest, res: NextApiResponse) => {- const { oauthController } = await jackson();+ const requestParams = req.method === "GET" ? req.query : req.body;- const requestParams = req.method === "GET" ? req.query : req.body;+ const { redirect_url, authorize_form } = await oauthController.authorize(+ requestParams,+ );- const { redirect_url, authorize_form } = await oauthController.authorize(- requestParams,- );- console.log(JSON.stringify({ redirect_url, authorize_form }, null, 2));-- if (redirect_url) {- res.redirect(302, redirect_url);+ if (redirect_url) {+ res.redirect(302, redirect_url);+ } else {+ res.setHeader("Content-Type", "text/html; charset=utf-8");+ res.send(authorize_form);+ }} else {- res.setHeader("Content-Type", "text/html; charset=utf-8");- res.send(authorize_form);+ res.setHeader("Allow", "GET, POST");+ res.status(405).json({+ error: { message: `Method ${req.method} Not Allowed` },+ });}-};+}diff --git a/pages/api/auth/saml/callback.ts b/pages/api/oauth/saml.tssimilarity index 100%rename from pages/api/auth/saml/callback.tsrename to pages/api/oauth/saml.tsdiff --git a/pages/api/auth/saml/token.ts b/pages/api/oauth/token.tssimilarity index 100%rename from pages/api/auth/saml/token.tsrename to pages/api/oauth/token.tsdiff --git a/pages/api/auth/saml/userinfo.ts b/pages/api/oauth/userinfo.tssimilarity index 95%rename from pages/api/auth/saml/userinfo.tsrename to pages/api/oauth/userinfo.tsindex 81a9a068ac..e5971479dd 100644--- a/pages/api/auth/saml/userinfo.ts+++ b/pages/api/oauth/userinfo.ts@@ -17,7 +17,6 @@ export default async function handler(const token = authHeader.split(" ")[1];const user = await oauthController.userInfo(token);- console.log(user);return res.json(user);}diff --git a/pages/api/projects/[slug]/saml.ts b/pages/api/projects/[slug]/saml.tsindex a2fc5439fd..46fca80f98 100644--- a/pages/api/projects/[slug]/saml.ts+++ b/pages/api/projects/[slug]/saml.ts@@ -8,13 +8,13 @@ export default withProjectAuth(async (req, res, project) => {const connections = await apiController.getConnections({tenant: project.id,- product: "dub",+ product: "Dub",});const response = {connections,issuer: "https://saml.dub.sh",- acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,+ acs: `${process.env.NEXTAUTH_URL}/api/oauth/saml`,};return res.status(200).json(response);@@ -28,15 +28,31 @@ export default withProjectAuth(async (req, res, project) => {const data = await apiController.createSAMLConnection({encodedRawMetadata: "",metadataUrl,- defaultRedirectUrl: process.env.NEXTAUTH_URL as string,+ defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,redirectUrl: process.env.NEXTAUTH_URL as string,tenant: project.id,- product: "dub",+ product: "Dub",});return res.status(200).json(data);++ // DELETE /api/projects/[slug]/saml – delete all SAML connections+ } else if (req.method === "DELETE") {+ const { clientID, clientSecret } = req.query as {+ clientID: string;+ clientSecret: string;+ };++ const { apiController } = await jackson();++ const response = await apiController.deleteConnections({+ clientID,+ clientSecret,+ });++ return res.status(200).json(response);} else {- res.setHeader("Allow", ["GET", "POST"]);+ res.setHeader("Allow", ["GET", "POST", "DELETE"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}});diff --git a/pages/app/[slug]/settings/security.tsx b/pages/app/[slug]/settings/security.tsxindex 6c04e87440..c8c020789e 100644--- a/pages/app/[slug]/settings/security.tsx+++ b/pages/app/[slug]/settings/security.tsx@@ -1,42 +1,45 @@import Button from "#/ui/button";import { useSAMLModal } from "@/components/app/modals/saml-modal";+import { useRemoveSAMLModal } from "@/components/app/modals/remove-saml-modal";import SettingsLayout from "@/components/layout/app/settings-layout";-import { Lock } from "lucide-react";+import { Lock, ShieldOff } from "lucide-react";import useProject from "#/lib/swr/use-project";-import useSWR from "swr";-import type { SAMLSSORecord } from "@boxyhq/saml-jackson";-import { fetcher } from "#/lib/utils";-import { useMemo } from "react";+import { useMemo, useState } from "react";+import { ThreeDots } from "@/components/shared/icons";+import Popover from "#/ui/popover";+import IconMenu from "@/components/shared/icon-menu";+import useSAML from "#/lib/swr/use-saml";export default function ProjectSecurity() {const { SAMLModal, setShowSAMLModal } = useSAMLModal();+ const { RemoveSAMLModal, setShowRemoveSAMLModal } = useRemoveSAMLModal();const { slug } = useProject();- const { data: sso, isLoading } = useSWR<{ connections: SAMLSSORecord[] }>(- slug && `/api/projects/${slug}/saml`,- fetcher,- );+ const { saml, isLoading } = useSAML();const data = useMemo(() => {if (!slug || isLoading) {return {+ status: "loading",logo: null,title: null,description: null,};- } else if (sso && sso.connections.length > 0) {+ } else if (saml && saml.connections.length > 0) {return {+ status: "configured",logo: (<imgsrc="/_static/icons/okta.svg"- alt={sso.connections[0].idpMetadata.friendlyProviderName + " logo"}+ alt={saml.connections[0].idpMetadata.friendlyProviderName + " logo"}className="h-8 w-8"/>),- title: sso.connections[0].idpMetadata.friendlyProviderName,+ title: `${saml.connections[0].idpMetadata.friendlyProviderName} SAML`,description: "SAML SSO is configured for your project.",};} elsereturn {+ status: "unconfigured",logo: (<div className="rounded-full border border-gray-200 p-2"><Lock className="h-4 w-4 text-gray-600" />@@ -45,11 +48,14 @@ export default function ProjectSecurity() {title: "SAML",description: "Choose an identity provider to get started.",};- }, [isLoading, sso]);+ }, [isLoading, saml]);++ const [openPopover, setOpenPopover] = useState(false);return (<SettingsLayout>- <SAMLModal />+ {data.status === "unconfigured" && <SAMLModal />}+ {data.status === "configured" && <RemoveSAMLModal />}<div className="rounded-lg border border-gray-200 bg-white"><div className="relative flex flex-col space-y-6 p-5 sm:p-10"><div className="flex flex-col space-y-3">@@ -81,7 +87,48 @@ export default function ProjectSecurity() {</div></div><div>- <Button text="Configure" onClick={() => setShowSAMLModal(true)} />+ {data.status === "loading" ? (+ <div className="h-9 w-24 animate-pulse rounded-md bg-gray-100" />+ ) : data.status === "configured" ? (+ <Popover+ content={+ <div className="grid w-full gap-1 p-2 sm:w-48">+ <button+ onClick={() => {+ setShowRemoveSAMLModal(true);+ setOpenPopover(false);+ }}+ className="rounded-md p-2 text-left text-sm font-medium text-red-600 transition-all duration-75 hover:bg-red-600 hover:text-white"+ >+ <IconMenu+ text="Remove"+ icon={<ShieldOff className="h-4 w-4" />}+ />+ </button>+ </div>+ }+ align="end"+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ >+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setOpenPopover(!openPopover);+ }}+ className="rounded-md px-1 py-2 transition-all duration-75 hover:bg-gray-100 active:bg-gray-200"+ >+ <span className="sr-only">Edit</span>+ <ThreeDots className="h-5 w-5 text-gray-500" />+ </button>+ </Popover>+ ) : (+ <Button+ text="Configure"+ onClick={() => setShowSAMLModal(true)}+ />+ )}</div></div></div>