Merge pull request #99 from zitadel/instance-header

fix: postcss vulnerability, move utils for cookie and session handling to @zitadel/next package
This commit is contained in:
Max Peintner
2024-08-09 14:10:00 +02:00
committed by GitHub
39 changed files with 4452 additions and 5783 deletions

View File

@@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: add issue
uses: actions/add-to-project@v0.5.0
uses: actions/add-to-project@v1.0.1
if: ${{ github.event_name == 'issues' }}
with:
# You can target a repository in a different organization
@@ -28,14 +28,14 @@ jobs:
username: ${{ github.actor }}
GITHUB_TOKEN: ${{ secrets.ADD_TO_PROJECT_PAT }}
- name: add pr
uses: actions/add-to-project@v0.5.0
uses: actions/add-to-project@v1.0.1
if: ${{ github.event_name == 'pull_request_target' && github.actor != 'dependabot[bot]' && !contains(steps.checkUserMember.outputs.teams, 'engineers')}}
with:
# You can target a repository in a different organization
# to the issue
project-url: https://github.com/orgs/zitadel/projects/2
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
- uses: actions-ecosystem/action-add-labels@v1.1.0
- uses: actions-ecosystem/action-add-labels@v1.1.3
if: ${{ github.event_name == 'pull_request_target' && github.actor != 'dependabot[bot]' && !contains(steps.checkUserMember.outputs.teams, 'staff')}}
with:
github_token: ${{ secrets.ADD_TO_PROJECT_PAT }}

View File

@@ -40,6 +40,7 @@
"@zitadel/node": "workspace:*",
"@zitadel/proto": "workspace:*",
"@zitadel/react": "workspace:*",
"@zitadel/next": "workspace:*",
"clsx": "1.2.1",
"copy-to-clipboard": "^3.3.3",
"moment": "^2.29.4",
@@ -76,7 +77,7 @@
"lint-staged": "13.0.3",
"make-dir-cli": "3.0.0",
"nodemon": "^2.0.22",
"postcss": "8.4.21",
"postcss": "8.4.31",
"prettier-plugin-tailwindcss": "0.1.13",
"sass": "^1.77.1",
"start-server-and-test": "^2.0.0",

View File

@@ -1,5 +1,5 @@
import { getBrandingSettings, listSessions } from "@/lib/zitadel";
import { getAllSessionCookieIds } from "@/utils/cookies";
import { getAllSessionCookieIds } from "@zitadel/next";
import { UserPlusIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import SessionsList from "@/ui/SessionsList";

View File

@@ -51,16 +51,16 @@ export default async function Page({
organization={organization}
submit={submit}
allowRegister={!!loginSettings?.allowRegister}
/>
{legal && identityProviders && process.env.ZITADEL_API_URL && (
<SignInWithIDP
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization}
></SignInWithIDP>
)}
>
{legal && identityProviders && process.env.ZITADEL_API_URL && (
<SignInWithIDP
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization}
></SignInWithIDP>
)}
</UsernameForm>
</div>
</DynamicTheme>
);

View File

@@ -11,7 +11,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -29,10 +29,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
return listAuthenticationMethodTypes(
@@ -48,7 +48,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
return listAuthenticationMethodTypes(

View File

@@ -13,7 +13,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -31,10 +31,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
const userId = response.session.factors.user.id;
@@ -58,7 +58,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
const userId = response.session.factors.user.id;

View File

@@ -1,13 +1,9 @@
import {
getBrandingSettings,
getLoginSettings,
getSession,
} from "@/lib/zitadel";
import { getBrandingSettings, sessionService } from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import LoginOTP from "@/ui/LoginOTP";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -21,21 +17,13 @@ export default async function Page({
const { method } = params;
const { session, token } = await loadSession(loginName, organization);
const session = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
const branding = await getBrandingSettings(organization);
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };
});
}
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col items-center space-y-4">

View File

@@ -2,19 +2,18 @@ import {
addOTPEmail,
addOTPSMS,
getBrandingSettings,
getSession,
registerTOTP,
sessionService,
} from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import BackButton from "@/ui/BackButton";
import { Button, ButtonVariants } from "@/ui/Button";
import DynamicTheme from "@/ui/DynamicTheme";
import { Spinner } from "@/ui/Spinner";
import TOTPRegister from "@/ui/TOTPRegister";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import Link from "next/link";
import { RegisterTOTPResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -28,7 +27,10 @@ export default async function Page({
const { method } = params;
const branding = await getBrandingSettings(organization);
const { session, token } = await loadSession(loginName, organization);
const session = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
let totpResponse: RegisterTOTPResponse | undefined,
totpError: Error | undefined;
@@ -56,17 +58,6 @@ export default async function Page({
throw new Error("No session found");
}
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };
});
}
const paramsToContinue = new URLSearchParams({});
let urlToContinue = "/accounts";

View File

@@ -1,9 +1,9 @@
import { getBrandingSettings, getSession } from "@/lib/zitadel";
import { getBrandingSettings, getSession, sessionService } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import RegisterPasskey from "@/ui/RegisterPasskey";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -13,19 +13,11 @@ export default async function Page({
const { loginName, promptPasswordless, organization, authRequestId } =
searchParams;
const sessionFactors = await loadSession(loginName);
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
async function loadSession(loginName?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const title = !!promptPasswordless
? "Authenticate with a passkey"
: "Use your passkey to confirm it's really you";

View File

@@ -6,7 +6,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
const title = "Authenticate with a passkey";
const description =
@@ -28,10 +28,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
@@ -40,7 +40,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;

View File

@@ -2,12 +2,13 @@ import {
getBrandingSettings,
getLoginSettings,
getSession,
sessionService,
} from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import PasswordForm from "@/ui/PasswordForm";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -16,20 +17,11 @@ export default async function Page({
}) {
const { loginName, organization, promptPasswordless, authRequestId, alt } =
searchParams;
const sessionFactors = await loadSession(loginName, organization);
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
const branding = await getBrandingSettings(organization);
const loginSettings = await getLoginSettings(organization);

View File

@@ -1,11 +1,11 @@
import { createCallback, getBrandingSettings, getSession } from "@/lib/zitadel";
import DynamicTheme from "@/ui/DynamicTheme";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { redirect } from "next/navigation";
async function loadSession(loginName: string, authRequestId?: string) {
const recent = await getMostRecentCookieWithLoginname(`${loginName}`);
const recent = await getMostRecentCookieWithLoginname({ loginName });
if (authRequestId) {
return createCallback({

View File

@@ -10,7 +10,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -31,10 +31,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
@@ -43,7 +43,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;

View File

@@ -1,10 +1,11 @@
import { getBrandingSettings, getSession } from "@/lib/zitadel";
import { getBrandingSettings, getSession, sessionService } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import RegisterPasskey from "@/ui/RegisterPasskey";
import RegisterU2F from "@/ui/RegisterU2F";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -13,19 +14,11 @@ export default async function Page({
}) {
const { loginName, organization, authRequestId } = searchParams;
const sessionFactors = await loadSession(loginName);
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
async function loadSession(loginName?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const title = "Use your passkey to confirm it's really you";
const description =
"Your device will ask for your fingerprint, face, or screen lock";

View File

@@ -1,9 +1,8 @@
import {
SessionCookie,
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
} from "@/utils/cookies";
} from "@zitadel/next";
import { setSessionAndUpdateCookie } from "@/utils/session";
import { NextRequest, NextResponse, userAgent } from "next/server";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
@@ -16,12 +15,12 @@ export async function POST(request: NextRequest) {
const { loginName, sessionId, organization, authRequestId, code, method } =
body;
const recentPromise: Promise<SessionCookie> = sessionId
? getSessionCookieById(sessionId).catch((error) => {
const recentPromise = sessionId
? getSessionCookieById({ sessionId }).catch((error) => {
return Promise.reject(error);
})
: loginName
? getSessionCookieByLoginName(loginName, organization).catch(
? getSessionCookieByLoginName({ loginName, organization }).catch(
(error) => {
return Promise.reject(error);
},

View File

@@ -3,7 +3,7 @@ import {
getSession,
registerPasskey,
} from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
@@ -11,7 +11,7 @@ export async function POST(request: NextRequest) {
if (body) {
const { sessionId } = body;
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -1,5 +1,5 @@
import { getSession, verifyPasskeyRegistration } from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse, userAgent } from "next/server";
export async function POST(request: NextRequest) {
@@ -13,7 +13,7 @@ export async function POST(request: NextRequest) {
device.vendor || device.model ? ", " : ""
}${os.name}${os.name ? ", " : ""}${browser.name}`;
}
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -5,12 +5,11 @@ import {
listAuthenticationMethodTypes,
} from "@/lib/zitadel";
import {
SessionCookie,
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
removeSessionFromCookie,
} from "@/utils/cookies";
} from "@zitadel/next";
import {
createSessionAndUpdateCookie,
createSessionForIdpAndUpdateCookie,
@@ -76,12 +75,12 @@ export async function PUT(request: NextRequest) {
challenges,
} = body;
const recentPromise: Promise<SessionCookie> = sessionId
const recentPromise = sessionId
? getSessionCookieById(sessionId).catch((error) => {
return Promise.reject(error);
})
: loginName
? getSessionCookieByLoginName(loginName, organization).catch(
? getSessionCookieByLoginName({ loginName, organization }).catch(
(error) => {
return Promise.reject(error);
},
@@ -166,9 +165,9 @@ export async function PUT(request: NextRequest) {
*/
export async function DELETE(request: NextRequest) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (id) {
const session = await getSessionCookieById(id);
const sessionId = searchParams.get("id");
if (sessionId) {
const session = await getSessionCookieById({ sessionId });
return deleteSession(session.id, session.token)
.then(() => {

View File

@@ -4,7 +4,7 @@ import {
registerPasskey,
registerU2F,
} from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
@@ -12,7 +12,7 @@ export async function POST(request: NextRequest) {
if (body) {
const { sessionId } = body;
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -1,5 +1,5 @@
import { getSession, verifyU2FRegistration } from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse, userAgent } from "next/server";
import { VerifyU2FRegistrationRequest } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { PlainMessage } from "@zitadel/client";
@@ -15,7 +15,7 @@ export async function POST(request: NextRequest) {
device.vendor || device.model ? ", " : ""
}${os.name}${os.name ? ", " : ""}${browser.name}`;
}
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -6,7 +6,7 @@ import {
listSessions,
startIdentityProviderFlow,
} from "@/lib/zitadel";
import { SessionCookie, getAllSessions } from "@/utils/cookies";
import { getAllSessions } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import {
@@ -52,7 +52,7 @@ export async function GET(request: NextRequest) {
const authRequestId = searchParams.get("authRequest");
const sessionId = searchParams.get("sessionId");
const sessionCookies: SessionCookie[] = await getAllSessions();
const sessionCookies = await getAllSessions();
const ids = sessionCookies.map((s) => s.id);
let sessions: Session[] = [];
if (ids && ids.length) {

View File

@@ -1,5 +1,5 @@
import { listSessions } from "@/lib/zitadel";
import { SessionCookie, getAllSessions } from "@/utils/cookies";
import { getAllSessions } from "@zitadel/next";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { NextRequest, NextResponse } from "next/server";
@@ -12,7 +12,7 @@ async function loadSessions(ids: string[]): Promise<Session[]> {
}
export async function GET(request: NextRequest) {
const sessionCookies: SessionCookie[] = await getAllSessions();
const sessionCookies = await getAllSessions();
const ids = sessionCookies.map((s) => s.id);
let sessions: Session[] = [];
if (ids && ids.length) {

View File

@@ -1,6 +1,6 @@
"use server";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { getSession, verifyTOTPRegistration } from "./zitadel";
export async function verifyTOTP(
@@ -8,7 +8,7 @@ export async function verifyTOTP(
loginName?: string,
organization?: string,
) {
return getMostRecentCookieWithLoginname(loginName, organization)
return getMostRecentCookieWithLoginname({ loginName, organization })
.then((recent) => {
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };

View File

@@ -19,6 +19,10 @@ export function middleware(request: NextRequest) {
// this is a workaround for the next.js server not forwarding the host header
requestHeaders.set("x-zitadel-forwarded", `host="${request.nextUrl.host}"`);
// requestHeaders.set("x-zitadel-public-host", `${request.nextUrl.host}`);
// this is a workaround for the next.js server not forwarding the host header
// requestHeaders.set("x-zitadel-instance-host", `${INSTANCE}`);
const responseHeaders = new Headers();
responseHeaders.set("Access-Control-Allow-Origin", "*");

View File

@@ -149,10 +149,6 @@ export function SignInWithIDP({
<Alert>{error}</Alert>
</div>
)}
<div className="mt-8 flex w-full flex-row items-center pt-4">
<BackButton />
<span className="flex-grow"></span>
</div>
</div>
);
}

View File

@@ -11,6 +11,7 @@ import {
LoginSettings,
PasskeysType,
} from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import BackButton from "./BackButton";
type Inputs = {
loginName: string;
@@ -23,6 +24,7 @@ type Props = {
organization?: string;
submit: boolean;
allowRegister: boolean;
children?: React.ReactNode;
};
export default function UsernameForm({
@@ -32,6 +34,7 @@ export default function UsernameForm({
organization,
submit,
allowRegister,
children,
}: Props) {
const { register, handleSubmit, formState } = useForm<Inputs>({
mode: "onBlur",
@@ -220,6 +223,16 @@ export default function UsernameForm({
{...register("loginName", { required: "This field is required" })}
label="Loginname"
/>
{allowRegister && (
<button
className="transition-all text-sm hover:text-primary-light-500 dark:hover:text-primary-dark-500"
onClick={() => router.push("/register")}
type="button"
disabled={loading}
>
Register new user
</button>
)}
</div>
{error && (
@@ -228,17 +241,10 @@ export default function UsernameForm({
</div>
)}
<div className="mt-8 flex w-full flex-row items-center">
{allowRegister && (
<Button
type="button"
className="self-end"
variant={ButtonVariants.Secondary}
onClick={() => router.push("/register")}
>
register
</Button>
)}
<div className="pt-6 pb-4">{children}</div>
<div className="mt-4 flex w-full flex-row items-center">
<BackButton />
<span className="flex-grow"></span>
<Button
type="submit"

View File

@@ -6,11 +6,7 @@ import {
getSession,
setSession,
} from "@/lib/zitadel";
import {
SessionCookie,
addSessionToCookie,
updateSessionCookie,
} from "./cookies";
import { addSessionToCookie, updateSessionCookie } from "@zitadel/next";
import {
Challenges,
RequestChallenges,
@@ -19,6 +15,17 @@ import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { PlainMessage } from "@zitadel/client";
type CustomCookieData = {
id: string;
token: string;
loginName: string;
organization?: string;
creationDate: string;
expirationDate: string;
changeDate: string;
authRequestId?: string; // if its linked to an OIDC flow
};
export async function createSessionAndUpdateCookie(
loginName: string,
password: string | undefined,
@@ -43,7 +50,7 @@ export async function createSessionAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -61,7 +68,7 @@ export async function createSessionAndUpdateCookie(
sessionCookie.organization = organization;
}
return addSessionToCookie(sessionCookie).then(() => {
return addSessionToCookie<CustomCookieData>(sessionCookie).then(() => {
return response.session as Session;
});
} else {
@@ -96,7 +103,7 @@ export async function createSessionForUserIdAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -146,7 +153,7 @@ export async function createSessionForIdpAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -181,7 +188,7 @@ export type SessionWithChallenges = Session & {
};
export async function setSessionAndUpdateCookie(
recentCookie: SessionCookie,
recentCookie: CustomCookieData,
checks: PlainMessage<Checks>,
challenges: RequestChallenges | undefined,
authRequestId: string | undefined,
@@ -193,7 +200,7 @@ export async function setSessionAndUpdateCookie(
checks,
).then((updatedSession) => {
if (updatedSession) {
const sessionCookie: SessionCookie = {
const sessionCookie: CustomCookieData = {
id: recentCookie.id,
token: updatedSession.sessionToken,
creationDate: recentCookie.creationDate,
@@ -211,7 +218,7 @@ export async function setSessionAndUpdateCookie(
(response) => {
if (response?.session && response.session.factors?.user?.loginName) {
const { session } = response;
const newCookie: SessionCookie = {
const newCookie: CustomCookieData = {
id: sessionCookie.id,
token: updatedSession.sessionToken,
creationDate: sessionCookie.creationDate,

View File

@@ -9,28 +9,32 @@
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:integration": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:unit": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:watch": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
}
}

View File

@@ -26,7 +26,7 @@
"devDependencies": {
"@changesets/cli": "^2.22.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint": "8.57.0",
"eslint-config-zitadel": "workspace:*",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^4.0.0",

View File

@@ -6,6 +6,7 @@
"types": "./dist/index.d.ts",
"sideEffects": false,
"license": "MIT",
"type": "module",
"files": [
"dist/**"
],
@@ -25,6 +26,8 @@
"peerDependencies": {
"@zitadel/node": "workspace:*",
"@zitadel/react": "workspace:*",
"@zitadel/client": "workspace:*",
"@zitadel/proto": "workspace:*",
"next": "^14.2.3",
"react": "18.2.0"
},
@@ -35,7 +38,7 @@
"@types/react": "^17.0.80",
"@zitadel/tsconfig": "workspace:*",
"eslint-config-zitadel": "workspace:*",
"postcss": "8.4.21",
"postcss": "8.4.31",
"tailwindcss": "3.2.4",
"zitadel-tailwind-config": "workspace:*"
}

View File

@@ -1,6 +1,5 @@
import "./styles.css";
// import "./styles.css";
export {
ZitadelNextProvider,
type ZitadelNextProps,
} from "./components/ZitadelNextProvider";
export { ZitadelNextProvider, type ZitadelNextProps } from "./components/ZitadelNextProvider";
export * from "./utils/cookies";
export { loadMostRecentSession } from "./utils/session";

View File

@@ -2,7 +2,7 @@
import { cookies } from "next/headers";
export type SessionCookie = {
export type Cookie = {
id: string;
token: string;
loginName: string;
@@ -13,7 +13,9 @@ export type SessionCookie = {
authRequestId?: string; // if its linked to an OIDC flow
};
function setSessionHttpOnlyCookie(sessions: SessionCookie[]) {
type SessionCookie<T> = Cookie & T;
function setSessionHttpOnlyCookie<T>(sessions: SessionCookie<T>[]) {
const cookiesList = cookies();
// @ts-ignore
return cookiesList.set({
@@ -24,20 +26,13 @@ function setSessionHttpOnlyCookie(sessions: SessionCookie[]) {
});
}
export async function addSessionToCookie(
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function addSessionToCookie<T>(session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
let currentSessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [];
let currentSessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [];
const index = currentSessions.findIndex(
(s) => s.loginName === session.loginName,
);
const index = currentSessions.findIndex((s) => s.loginName === session.loginName);
if (index > -1) {
currentSessions[index] = session;
@@ -56,17 +51,11 @@ export async function addSessionToCookie(
}
}
export async function updateSessionCookie(
id: string,
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function updateSessionCookie<T>(id: string, session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const sessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [session];
const foundIndex = sessions.findIndex((session) => session.id === id);
@@ -82,20 +71,15 @@ export async function updateSessionCookie(
return setSessionHttpOnlyCookie(sessions);
}
} else {
throw "updateSessionCookie: session id now found";
throw "updateSessionCookie<T>: session id now found";
}
}
export async function removeSessionFromCookie(
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function removeSessionFromCookie<T>(session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const sessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [session];
const reducedSessions = sessions.filter((s) => s.id !== session.id);
if (cleanup) {
@@ -109,18 +93,15 @@ export async function removeSessionFromCookie(
}
}
export async function getMostRecentSessionCookie(): Promise<any> {
export async function getMostRecentSessionCookie<T>(): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const latest = sessions.reduce((prev, current) => {
return new Date(prev.changeDate).getTime() >
new Date(current.changeDate).getTime()
? prev
: current;
return new Date(prev.changeDate).getTime() > new Date(current.changeDate).getTime() ? prev : current;
});
return latest;
@@ -129,20 +110,21 @@ export async function getMostRecentSessionCookie(): Promise<any> {
}
}
export async function getSessionCookieById(
id: string,
organization?: string,
): Promise<SessionCookie> {
export async function getSessionCookieById<T>({
sessionId,
organization,
}: {
sessionId: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.id === id
: s.id === id,
organization ? s.organization === organization && s.id === sessionId : s.id === sessionId,
);
if (found) {
return found;
@@ -154,19 +136,20 @@ export async function getSessionCookieById(
}
}
export async function getSessionCookieByLoginName(
loginName: string,
organization?: string,
): Promise<SessionCookie> {
export async function getSessionCookieByLoginName<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.loginName === loginName
: s.loginName === loginName,
organization ? s.organization === organization && s.loginName === loginName : s.loginName === loginName,
);
if (found) {
return found;
@@ -183,23 +166,17 @@ export async function getSessionCookieByLoginName(
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessionCookieIds(
cleanup: boolean = false,
): Promise<any> {
export async function getAllSessionCookieIds<T>(cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions
.filter((session) =>
session.expirationDate
? new Date(session.expirationDate) > now
: true,
)
.filter((session) => (session.expirationDate ? new Date(session.expirationDate) > now : true))
.map((session) => session.id);
} else {
return sessions.map((session) => session.id);
@@ -214,20 +191,16 @@ export async function getAllSessionCookieIds(
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessions(
cleanup: boolean = false,
): Promise<SessionCookie[]> {
export async function getAllSessions<T>(cleanup: boolean = false): Promise<SessionCookie<T>[]> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions.filter((session) =>
session.expirationDate ? new Date(session.expirationDate) > now : true,
);
return sessions.filter((session) => (session.expirationDate ? new Date(session.expirationDate) > now : true));
} else {
return sessions;
}
@@ -238,18 +211,22 @@ export async function getAllSessions(
/**
* Returns most recent session filtered by optinal loginName
* @param loginName
* @param loginName optional loginName to filter cookies, if non provided, returns most recent session
* @param organization optional organization to filter cookies
* @returns most recent session
*/
export async function getMostRecentCookieWithLoginname(
loginName?: string,
organization?: string,
): Promise<any> {
export async function getMostRecentCookieWithLoginname<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
let filtered = sessions.filter((cookie) => {
return !!loginName ? cookie.loginName === loginName : true;
});
@@ -263,10 +240,7 @@ export async function getMostRecentCookieWithLoginname(
const latest =
filtered && filtered.length
? filtered.reduce((prev, current) => {
return new Date(prev.changeDate).getTime() >
new Date(current.changeDate).getTime()
? prev
: current;
return new Date(prev.changeDate).getTime() > new Date(current.changeDate).getTime() ? prev : current;
})
: undefined;
@@ -280,5 +254,3 @@ export async function getMostRecentCookieWithLoginname(
return Promise.reject("Could not read session cookie");
}
}
export async function clearSessions() {}

View File

@@ -0,0 +1,16 @@
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { GetSessionResponse } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { getMostRecentCookieWithLoginname } from "./cookies";
export async function loadMostRecentSession(
sessionService: any, // TODO: SessionServiceClient,
sessionParams: { loginName?: string; organization?: string },
): Promise<Session | undefined> {
const recent = await getMostRecentCookieWithLoginname({
loginName: sessionParams.loginName,
organization: sessionParams.organization,
});
return sessionService
.getSession({ sessionId: recent.id, sessionToken: recent.token }, {})
.then((resp: GetSessionResponse) => resp.session);
}

View File

@@ -1,20 +1,9 @@
{
"extends": [
"//"
],
"extends": ["//"],
"tasks": {
"dev": {
"dependsOn": [
"@zitadel/react#build"
]
},
"build": {
"outputs": [
"dist/**"
],
"dependsOn": [
"@zitadel/react#build"
]
"outputs": ["dist/**"],
"dependsOn": ["@zitadel/client#build", "@zitadel/react#build"]
}
}
}

View File

@@ -3,7 +3,7 @@
"tasks": {
"generate": {
"outputs": ["zitadel/**"],
"cache": false
"cache": true
}
}
}

View File

@@ -40,7 +40,7 @@
"autoprefixer": "10.4.13",
"eslint-config-zitadel": "workspace:*",
"jsdom": "^24.0.0",
"postcss": "8.4.21",
"postcss": "8.4.31",
"sass": "^1.77.1",
"tailwindcss": "3.2.4",
"zitadel-tailwind-config": "workspace:*"

9752
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff