@snokam/auth 6.0.10 → 6.1.0

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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,27 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [6.1.0](https://github.com/snokam/components/compare/%40snokam%2Fauth%406.0.9...%40snokam%2Fauth%406.1.0) (2026-11-09)
7
+
8
+ ### Bug Fixes
9
+
10
+ - **deps:** close all open npm Dependabot alerts and bump deps within major ([#3364](https://github.com/snokam/components/issues/3364)) ([1372dbb](https://github.com/snokam/components/commit/1372dbbed19d6d6c93c357f3543f4c8db01bfb43))
11
+ - one resource-group lookup for secrets, Salg deep link without waterfall, theme choice before profile load wins ([#3300](https://github.com/snokam/components/issues/3300)) ([441675e](https://github.com/snokam/components/commit/441675ecfd4e12f1e93a70b1687e6ad2b2f35e3d))
12
+ - persona audit appends never 500, no login loop, /ai and settings without failing calls ([#3302](https://github.com/snokam/components/issues/3302)) ([580fdaf](https://github.com/snokam/components/commit/580fdaf2e8a1521bbeb24ef2ea29a3981e00555c))
13
+
14
+ ### Features
15
+
16
+ - **platform:** sign apps in as a chosen test persona when persona mode is on ([#3276](https://github.com/snokam/components/issues/3276)) ([7c6147c](https://github.com/snokam/components/commit/7c6147cf26600260ad0bc40d6e4a1571ca4453ac))
17
+
18
+ ### Performance Improvements
19
+
20
+ - **web:** cache public pages per host and speed up every app (Lighthouse round 2) ([#3279](https://github.com/snokam/components/issues/3279)) ([4ab508b](https://github.com/snokam/components/commit/4ab508ba90289a5d1bd28e7b843f9069dae5cc44))
21
+ - **web:** faster and more accessible public pages (Lighthouse) ([#3273](https://github.com/snokam/components/issues/3273)) ([0501fea](https://github.com/snokam/components/commit/0501feaeb803dec1c0a2993726a65f10a986f803)), closes [#1976d2](https://github.com/snokam/components/issues/1976d2) [#1565c0](https://github.com/snokam/components/issues/1565c0)
22
+ - **web:** halve the JavaScript on the signed-in apps ([#3281](https://github.com/snokam/components/issues/3281)) ([c248da6](https://github.com/snokam/components/commit/c248da646f6a9b457278042890b92976b07a8d16))
23
+ - **web:** min side portrait from the session, prompts after load ([#3311](https://github.com/snokam/components/issues/3311)) ([08533fe](https://github.com/snokam/components/commit/08533fee974742d73d2b6ba7af935208de4e147f))
24
+ - **web:** Min side sections load independently; signed-in Lighthouse tooling ([#3299](https://github.com/snokam/components/issues/3299)) ([15f83bc](https://github.com/snokam/components/commit/15f83bc90a469eb76b703e67c2ec72cf92672179))
25
+ - **web:** ship only the JavaScript a public visitor needs (Lighthouse round 4) ([#3285](https://github.com/snokam/components/issues/3285)) ([88bcf84](https://github.com/snokam/components/commit/88bcf8482ebbb7aa14109e0c99b91cda8dbfb4d5))
26
+
6
27
  ## [6.0.10](https://github.com/snokam/components/compare/@snokam/auth@6.0.9...@snokam/auth@6.0.10) (2026-11-07)
7
28
 
8
29
  **Note:** Version bump only for package @snokam/auth
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@snokam/auth",
3
3
  "description": "Snøkam auth components",
4
- "version": "6.0.10",
4
+ "version": "6.1.0",
5
5
  "main": "src/index.ts",
6
+ "sideEffects": false,
6
7
  "types": "src/index.ts",
7
8
  "files": [
8
9
  "src",
@@ -18,28 +19,28 @@
18
19
  "access": "public"
19
20
  },
20
21
  "dependencies": {
21
- "@azure/msal-node": "^5.4.2",
22
+ "@azure/msal-node": "^7.2.1",
22
23
  "@emotion/react": "^11.14.0",
23
24
  "@emotion/styled": "^11.14.1",
24
- "@mui/icons-material": "^9.2.0",
25
- "@mui/material": "^9.2.0",
25
+ "@mui/icons-material": "^9.5.0",
26
+ "@mui/material": "^9.5.0",
26
27
  "next-auth": "4.24.15",
27
- "path-to-regexp": "^8.4.2",
28
+ "path-to-regexp": "^9.0.0",
28
29
  "@snokam/api-client": "1.0.0",
29
- "@snokam/identity": "1.1.0",
30
- "@snokam/page-content": "6.9.8",
31
- "@snokam/react-query": "1.1.0",
32
- "@snokam/tenant": "4.5.4",
33
- "@snokam/ui": "7.2.2"
30
+ "@snokam/identity": "1.1.1",
31
+ "@snokam/page-content": "6.9.9",
32
+ "@snokam/react-query": "1.1.1",
33
+ "@snokam/tenant": "4.5.5",
34
+ "@snokam/ui": "7.3.0"
34
35
  },
35
36
  "peerDependencies": {
36
- "next": "16.3.8",
37
- "react": "19.2.8",
38
- "react-dom": "19.2.8"
37
+ "next": "16.4.5",
38
+ "react": "19.3.1",
39
+ "react-dom": "19.3.1"
39
40
  },
40
41
  "devDependencies": {
41
- "@types/react": "^19.2.17",
42
- "@types/react-dom": "^19.2.3"
42
+ "@types/react": "^19.3.0",
43
+ "@types/react-dom": "^19.3.0"
43
44
  },
44
45
  "exports": {
45
46
  ".": "./src/index.ts",
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
- import { memo, ReactNode, Suspense, useEffect } from "react";
4
- import { useSearchParams } from "next/navigation";
3
+ import { memo, ReactNode, useEffect } from "react";
4
+ import { useLoadedSearchParams } from "@snokam/ui/framework";
5
5
  import { Auth } from "../../../types";
6
6
  import { Authenticate } from "../../../components/Authenticate";
7
7
  import { SessionProvider } from "next-auth/react";
@@ -9,6 +9,7 @@ import { useAuth } from "../../../hooks";
9
9
  import { EmployeeThemeSync } from "../../../theme/employee-theme-sync";
10
10
  import { ServerSessionContext } from "../../../session/useSession";
11
11
  import { ConfirmedSessionProvider } from "../../../session/confirmed";
12
+ import { SessionHintSync } from "../../../session/hint";
12
13
 
13
14
  export const Provider = memo((props: Auth.Provider.Props) => {
14
15
  const { session, children } = props;
@@ -18,9 +19,8 @@ export const Provider = memo((props: Auth.Provider.Props) => {
18
19
  <SessionProvider session={session ?? undefined}>
19
20
  <ConfirmedSessionProvider>
20
21
  <EmployeeThemeSync />
21
- <Suspense fallback={<>{children}</>}>
22
- <ProviderInner {...props}>{children}</ProviderInner>
23
- </Suspense>
22
+ <SessionHintSync />
23
+ <ProviderInner {...props}>{children}</ProviderInner>
24
24
  </ConfirmedSessionProvider>
25
25
  </SessionProvider>
26
26
  </ServerSessionContext.Provider>
@@ -29,7 +29,7 @@ export const Provider = memo((props: Auth.Provider.Props) => {
29
29
 
30
30
  const ProviderInner = (props: Auth.Provider.Props) => {
31
31
  const { children, enforceLogin } = props;
32
- const searchParams = useSearchParams();
32
+ const searchParams = useLoadedSearchParams();
33
33
  const enforceLoginParam = searchParams?.get("enforceLogin");
34
34
 
35
35
  if (enforceLoginParam || enforceLogin) {
@@ -45,7 +45,7 @@ const ProviderInner = (props: Auth.Provider.Props) => {
45
45
 
46
46
  const Wrapper = ({ children }: { children: ReactNode }) => {
47
47
  const { signOut } = useAuth();
48
- const searchParams = useSearchParams();
48
+ const searchParams = useLoadedSearchParams();
49
49
 
50
50
  useEffect(() => {
51
51
  if (searchParams?.get("logout") === "true") {
@@ -10,6 +10,7 @@ import { EmployeeGate } from "../components/EmployeeGate";
10
10
 
11
11
  export { Unauthenticated } from "../components/Unauthenticated";
12
12
  export { Authenticated } from "../components/Authenticated";
13
+ export { SessionSwitch } from "../components/SessionSwitch";
13
14
  export { useAuth } from "../hooks";
14
15
  export { useSession } from "../session/useSession";
15
16
  export { useIsHydrating } from "../hydration/useIsHydrating";
@@ -13,6 +13,8 @@ export interface ConsentClaims extends AuthorizationParams {
13
13
  state: string;
14
14
  clientName: string;
15
15
  businessName: string;
16
+ businessId: string;
17
+ personaRequired: boolean;
16
18
  issuer: string;
17
19
  email: string;
18
20
  nonce: string;
@@ -114,6 +114,12 @@ function clientRedirect(
114
114
  });
115
115
  }
116
116
 
117
+ function backToConsent(request: Request, ticket: string): Response {
118
+ const consent = new URL("/oauth/consent", requestOrigin(request));
119
+ consent.searchParams.set("ticket", ticket);
120
+ return Response.redirect(consent.toString(), 303);
121
+ }
122
+
117
123
  export function createAppSignInAuthorizeHandler(authConfig: Auth.Config) {
118
124
  return async function GET(request: Request) {
119
125
  const query = new URL(request.url).searchParams;
@@ -139,6 +145,8 @@ export function createAppSignInAuthorizeHandler(authConfig: Auth.Config) {
139
145
  ...params,
140
146
  clientName: preview.value.clientName ?? "",
141
147
  businessName: preview.value.businessName ?? "",
148
+ businessId: preview.value.businessId ?? "",
149
+ personaRequired: preview.value.personaRequired ?? false,
142
150
  issuer: preview.value.issuer ?? "",
143
151
  business: new URL(params.resource).hostname,
144
152
  state: query.get("state") ?? "",
@@ -184,7 +192,16 @@ export function createAppSignInApproveHandler(authConfig: Auth.Config) {
184
192
  return clientRedirect(request, consent, { error: ACCESS_DENIED });
185
193
  }
186
194
 
187
- const approved = await approveAuthorization(consent, signer.accessToken);
195
+ const persona = String(form.get("persona") ?? "");
196
+ if (consent.personaRequired && !persona) {
197
+ return backToConsent(request, String(form.get("ticket")));
198
+ }
199
+
200
+ const approved = await approveAuthorization(
201
+ consent,
202
+ signer.accessToken,
203
+ consent.personaRequired ? persona : undefined
204
+ );
188
205
  return clientRedirect(
189
206
  request,
190
207
  consent,
@@ -28,24 +28,45 @@ async function asLoginSite<T>(
28
28
  }
29
29
  }
30
30
 
31
+ function authorizationRequest(
32
+ params: AuthorizationParams,
33
+ userToken: string,
34
+ personaEmail?: string
35
+ ) {
36
+ return {
37
+ clientId: params.clientId,
38
+ redirectUri: params.redirectUri,
39
+ codeChallenge: params.codeChallenge,
40
+ codeChallengeMethod: params.codeChallengeMethod,
41
+ resource: params.resource,
42
+ userToken,
43
+ personaEmail,
44
+ };
45
+ }
46
+
31
47
  export function previewAuthorization(
32
48
  params: AuthorizationParams,
33
49
  userToken: string
34
50
  ): Promise<Outcome<AuthorizationPreview>> {
35
51
  return asLoginSite((client) =>
36
52
  client.previewOAuthAuthorization({
37
- authorizationRequest: { ...params, userToken },
53
+ authorizationRequest: authorizationRequest(params, userToken),
38
54
  })
39
55
  );
40
56
  }
41
57
 
42
58
  export function approveAuthorization(
43
59
  params: AuthorizationParams,
44
- userToken: string
60
+ userToken: string,
61
+ personaEmail?: string
45
62
  ): Promise<Outcome<IssuedAuthorizationCode>> {
46
63
  return asLoginSite((client) =>
47
64
  client.approveOAuthAuthorization({
48
- authorizationRequest: { ...params, userToken },
65
+ authorizationRequest: authorizationRequest(
66
+ params,
67
+ userToken,
68
+ personaEmail
69
+ ),
49
70
  })
50
71
  );
51
72
  }
@@ -45,7 +45,7 @@ export const EmployeeGate = ({
45
45
  return <>{children}</>;
46
46
  }
47
47
 
48
- if (inProgress || (isAuthenticated && isLoading)) {
48
+ if ((inProgress && !allowAnonymous) || (isAuthenticated && isLoading)) {
49
49
  return <PageLoader />;
50
50
  }
51
51
 
@@ -0,0 +1,26 @@
1
+ "use client";
2
+
3
+ import { ReactNode } from "react";
4
+ import { useSession } from "../../session/useSession";
5
+ import { AnonymousHinted, SignedInHinted } from "./styles";
6
+
7
+ interface Props {
8
+ signedIn?: ReactNode;
9
+ anonymous?: ReactNode;
10
+ }
11
+
12
+ export const SessionSwitch = ({ signedIn, anonymous }: Props) => {
13
+ const { status } = useSession();
14
+
15
+ if (status === "authenticated") return <>{signedIn}</>;
16
+ if (status === "unauthenticated") return <>{anonymous}</>;
17
+
18
+ return (
19
+ <>
20
+ <SignedInHinted>{signedIn}</SignedInHinted>
21
+ <AnonymousHinted>{anonymous}</AnonymousHinted>
22
+ </>
23
+ );
24
+ };
25
+
26
+ export default SessionSwitch;
@@ -0,0 +1,20 @@
1
+ import styled from "@emotion/styled";
2
+ import { SESSION_HINT_ATTRIBUTE, SIGNED_IN_HINT } from "@snokam/ui/theme";
3
+
4
+ const signedInHint = `[${SESSION_HINT_ATTRIBUTE}="${SIGNED_IN_HINT}"]`;
5
+
6
+ export const SignedInHinted = styled.span`
7
+ display: contents;
8
+
9
+ html:not(${signedInHint}) & {
10
+ display: none;
11
+ }
12
+ `;
13
+
14
+ export const AnonymousHinted = styled.span`
15
+ display: contents;
16
+
17
+ html${signedInHint} & {
18
+ display: none;
19
+ }
20
+ `;
@@ -3,3 +3,4 @@ export { Authenticated } from "./Authenticated";
3
3
  export { Unauthenticated } from "./Unauthenticated";
4
4
  export { Consent } from "./Consent";
5
5
  export { Error } from "./Error";
6
+ export { SessionSwitch } from "./SessionSwitch";
@@ -1,4 +1,5 @@
1
1
  import { getToken } from "next-auth/jwt";
2
+ import { withSessionHint } from "../session/hintCookie";
2
3
  import {
3
4
  getSessionCookieSettings,
4
5
  getAuthUrl,
@@ -146,7 +147,7 @@ export function createHandoffLogoutHandler(config?: HandoffConfig) {
146
147
  for (const cookieName of [name, `${name}.0`, `${name}.1`]) {
147
148
  headers.append("Set-Cookie", expireCookie(cookieName, domain, secure));
148
149
  }
149
- return new Response(null, { status: 302, headers });
150
+ return withSessionHint(new Response(null, { status: 302, headers }), name);
150
151
  };
151
152
  }
152
153
 
@@ -0,0 +1,64 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import {
4
+ carriesImpersonationCookies,
5
+ clearImpersonationCookies,
6
+ clearRequestImpersonation,
7
+ } from "./clear.ts";
8
+
9
+ const expiredNames = (cookies: string[]) =>
10
+ cookies.map((cookie) => cookie.split("=")[0]);
11
+
12
+ describe("clearing stale Vis som cookies", () => {
13
+ it("expires every Vis som cookie both on the shared cookie domain and on the host itself", () => {
14
+ process.env.NEXT_PUBLIC_PLATFORM_DOMAIN = "";
15
+ const cookies = clearImpersonationCookies("minside.test.snokam.no");
16
+
17
+ for (const name of ["imp_session", "imp_active", "imp_pass"]) {
18
+ const forName = cookies.filter((cookie) => cookie.startsWith(`${name}=`));
19
+ assert.equal(forName.length, 2, name);
20
+ assert.ok(
21
+ forName.some((cookie) => cookie.includes("Domain=.test.snokam.no"))
22
+ );
23
+ assert.ok(forName.some((cookie) => !cookie.includes("Domain=")));
24
+ assert.ok(forName.every((cookie) => cookie.includes("Max-Age=0")));
25
+ }
26
+ });
27
+
28
+ it("does not repeat itself on hosts without a shared cookie domain", () => {
29
+ const cookies = clearImpersonationCookies("localhost:3120");
30
+
31
+ assert.deepEqual(expiredNames(cookies), [
32
+ "imp_session",
33
+ "imp_active",
34
+ "imp_pass",
35
+ ]);
36
+ });
37
+
38
+ it("clears for the host the browser asked for, behind a proxy too", () => {
39
+ process.env.NEXT_PUBLIC_PLATFORM_DOMAIN = "test.snosky.no";
40
+ const request = new Request("http://internal:8080/auth/login", {
41
+ headers: {
42
+ host: "internal:8080",
43
+ "x-forwarded-host": "snokam.test.snosky.no",
44
+ },
45
+ });
46
+
47
+ const cookies = clearRequestImpersonation(request);
48
+
49
+ assert.ok(cookies.every((cookie) => cookie.includes("Secure")));
50
+ assert.ok(cookies.every((cookie) => !cookie.includes("Domain=")));
51
+ });
52
+ });
53
+
54
+ describe("noticing Vis som cookies on a request", () => {
55
+ it("sees any one of them", () => {
56
+ assert.equal(carriesImpersonationCookies("a=1; imp_active=%7B%7D"), true);
57
+ assert.equal(carriesImpersonationCookies("imp_pass=x"), true);
58
+ });
59
+
60
+ it("ignores requests without them", () => {
61
+ assert.equal(carriesImpersonationCookies("a=1; imp_activex=2"), false);
62
+ assert.equal(carriesImpersonationCookies(null), false);
63
+ });
64
+ });
@@ -0,0 +1,60 @@
1
+ import { resolveCookieDomain } from "../session/cookies.ts";
2
+ import {
3
+ IMP_ACTIVE_COOKIE,
4
+ IMP_PASS_COOKIE,
5
+ IMP_SESSION_COOKIE,
6
+ parseCookieHeader,
7
+ } from "./jar.ts";
8
+
9
+ interface CookieOptions {
10
+ host?: string | null;
11
+ httpOnly: boolean;
12
+ maxAge: number;
13
+ hostOnly?: boolean;
14
+ }
15
+
16
+ const IMPERSONATION_COOKIES = [
17
+ { name: IMP_SESSION_COOKIE, httpOnly: true },
18
+ { name: IMP_ACTIVE_COOKIE, httpOnly: false },
19
+ { name: IMP_PASS_COOKIE, httpOnly: true },
20
+ ];
21
+
22
+ export function serialize(
23
+ name: string,
24
+ value: string,
25
+ { host, httpOnly, maxAge, hostOnly = false }: CookieOptions
26
+ ): string {
27
+ const domain = hostOnly ? undefined : resolveCookieDomain(host ?? undefined);
28
+ const secure = host ? !host.includes("localhost") : true;
29
+ const parts = [
30
+ `${name}=${encodeURIComponent(value)}`,
31
+ "Path=/",
32
+ "SameSite=Lax",
33
+ `Max-Age=${maxAge}`,
34
+ ];
35
+ if (domain) parts.push(`Domain=${domain}`);
36
+ if (httpOnly) parts.push("HttpOnly");
37
+ if (secure) parts.push("Secure");
38
+ return parts.join("; ");
39
+ }
40
+
41
+ export function clearImpersonationCookies(host: string | null): string[] {
42
+ const expired = IMPERSONATION_COOKIES.flatMap(({ name, httpOnly }) => [
43
+ serialize(name, "", { host, httpOnly, maxAge: 0 }),
44
+ serialize(name, "", { host, httpOnly, maxAge: 0, hostOnly: true }),
45
+ ]);
46
+ return [...new Set(expired)];
47
+ }
48
+
49
+ export function clearRequestImpersonation(request: Request): string[] {
50
+ return clearImpersonationCookies(
51
+ request.headers.get("x-forwarded-host") ?? request.headers.get("host")
52
+ );
53
+ }
54
+
55
+ export function carriesImpersonationCookies(
56
+ cookieHeader: string | null
57
+ ): boolean {
58
+ const jar = parseCookieHeader(cookieHeader);
59
+ return IMPERSONATION_COOKIES.some(({ name }) => name in jar);
60
+ }
@@ -20,6 +20,7 @@ export interface StartImpersonationInput {
20
20
  targetEmail: string;
21
21
  targetName?: string;
22
22
  targetImage?: string;
23
+ targetPortrait?: string;
23
24
  reason: string;
24
25
  businessId?: string;
25
26
  redirectTo?: string;
@@ -1,12 +1,17 @@
1
- import { resolveCookieDomain } from "../session";
2
1
  import { tokenClaims } from "./claims";
2
+ import { serialize } from "./clear";
3
3
  import {
4
4
  IMP_ACTIVE_COOKIE,
5
- IMP_PASS_COOKIE,
6
5
  IMP_SESSION_COOKIE,
7
6
  parseCookieHeader,
8
7
  } from "./jar";
9
8
 
9
+ export {
10
+ carriesImpersonationCookies,
11
+ clearImpersonationCookies,
12
+ serialize,
13
+ } from "./clear";
14
+
10
15
  export {
11
16
  IMP_ACTIVE_COOKIE,
12
17
  IMP_PASS_COOKIE,
@@ -26,6 +31,7 @@ export interface ImpersonationActive {
26
31
  targetEmail: string;
27
32
  targetName?: string | null;
28
33
  targetImage?: string | null;
34
+ targetPortrait?: string | null;
29
35
  finance: boolean;
30
36
  tokenId: string;
31
37
  expiresOn: number;
@@ -41,6 +47,7 @@ interface MintedToken {
41
47
  targetEmail: string;
42
48
  targetName?: string | null;
43
49
  targetImage?: string | null;
50
+ targetPortrait?: string | null;
44
51
  finance: boolean;
45
52
  returnTo?: string;
46
53
  origins?: string[];
@@ -68,29 +75,6 @@ export function readImpersonationActive(
68
75
  return readCookieJson<ImpersonationActive>(request, IMP_ACTIVE_COOKIE);
69
76
  }
70
77
 
71
- export function serialize(
72
- name: string,
73
- value: string,
74
- {
75
- host,
76
- httpOnly,
77
- maxAge,
78
- }: { host?: string | null; httpOnly: boolean; maxAge: number }
79
- ): string {
80
- const domain = resolveCookieDomain(host ?? undefined);
81
- const secure = host ? !host.includes("localhost") : true;
82
- const parts = [
83
- `${name}=${encodeURIComponent(value)}`,
84
- "Path=/",
85
- "SameSite=Lax",
86
- `Max-Age=${maxAge}`,
87
- ];
88
- if (domain) parts.push(`Domain=${domain}`);
89
- if (httpOnly) parts.push("HttpOnly");
90
- if (secure) parts.push("Secure");
91
- return parts.join("; ");
92
- }
93
-
94
78
  export function buildImpersonationCookies(
95
79
  minted: MintedToken,
96
80
  host: string | null
@@ -107,6 +91,7 @@ export function buildImpersonationCookies(
107
91
  targetEmail: minted.targetEmail,
108
92
  targetName: minted.targetName,
109
93
  targetImage: minted.targetImage,
94
+ targetPortrait: minted.targetPortrait,
110
95
  finance: minted.finance,
111
96
  tokenId: minted.tokenId,
112
97
  expiresOn: minted.expiresOn,
@@ -126,11 +111,3 @@ export function buildImpersonationCookies(
126
111
  }),
127
112
  ];
128
113
  }
129
-
130
- export function clearImpersonationCookies(host: string | null): string[] {
131
- return [
132
- serialize(IMP_SESSION_COOKIE, "", { host, httpOnly: true, maxAge: 0 }),
133
- serialize(IMP_ACTIVE_COOKIE, "", { host, httpOnly: false, maxAge: 0 }),
134
- serialize(IMP_PASS_COOKIE, "", { host, httpOnly: true, maxAge: 0 }),
135
- ];
136
- }
@@ -21,6 +21,7 @@ interface StartBody {
21
21
  targetEmail?: string;
22
22
  targetName?: string;
23
23
  targetImage?: string;
24
+ targetPortrait?: string;
24
25
  reason?: string;
25
26
  businessId?: string;
26
27
  redirectTo?: string;
@@ -97,6 +98,7 @@ export function createImpersonationStartHandler(authConfig: Auth.Config) {
97
98
  targetEmail: minted.value.targetEmail ?? body.targetEmail ?? "",
98
99
  targetName: minted.value.targetName,
99
100
  targetImage: body.targetImage ?? null,
101
+ targetPortrait: body.targetPortrait ?? null,
100
102
  finance: minted.value.finance ?? false,
101
103
  };
102
104
  const summary = {
@@ -6,6 +6,8 @@ export interface ImpersonationTicket {
6
6
  tokenId: string;
7
7
  targetEmail: string;
8
8
  targetName?: string | null;
9
+ targetImage?: string | null;
10
+ targetPortrait?: string | null;
9
11
  finance: boolean;
10
12
  business: string;
11
13
  returnTo?: string;
@@ -7,9 +7,22 @@ import { getSessionCookieSettings, getAuthUrl } from "./session";
7
7
  import { addCorsHeaders } from "./cors";
8
8
  import { allowsCrossOrigin } from "./cors-paths";
9
9
  import { hasImpersonationPass } from "./impersonation/pass-cookie";
10
+ import {
11
+ carriesImpersonationCookies,
12
+ clearRequestImpersonation,
13
+ } from "./impersonation/clear";
10
14
 
11
15
  const TEST_ENVIRONMENT = "t";
12
16
 
17
+ function withoutImpersonation(
18
+ response: NextResponse,
19
+ request: Request
20
+ ): NextResponse {
21
+ for (const cookie of clearRequestImpersonation(request))
22
+ response.headers.append("Set-Cookie", cookie);
23
+ return response;
24
+ }
25
+
13
26
  const LOGIN_FLOW_PATHS = [
14
27
  "/auth/",
15
28
  "/handoff/",
@@ -95,9 +108,14 @@ export function buildAuthMiddleware({
95
108
 
96
109
  const authMiddleware = async (req: NextRequestWithAuth) => {
97
110
  const { pathname, search, origin, basePath } = req.nextUrl;
111
+ const onSignInPage = pathname === signInPage;
112
+ const impersonating = carriesImpersonationCookies(
113
+ req.headers.get("cookie")
114
+ );
98
115
 
99
116
  if (
100
- [signInPage, errorPage].includes(pathname) ||
117
+ (onSignInPage && !impersonating) ||
118
+ pathname === errorPage ||
101
119
  publicPaths.some((p) => pathname.startsWith(p))
102
120
  ) {
103
121
  return;
@@ -105,6 +123,7 @@ export function buildAuthMiddleware({
105
123
 
106
124
  const secret =
107
125
  rest.secret ?? process.env.NEXTAUTH_SECRET ?? process.env.AUTH_SECRET;
126
+ if (!secret && onSignInPage) return;
108
127
  if (!secret) {
109
128
  console.error("[next-auth][error][NO_SECRET]");
110
129
  const errorUrl = new URL(`${basePath}${errorPage}`, origin);
@@ -119,9 +138,17 @@ export function buildAuthMiddleware({
119
138
  secret,
120
139
  });
121
140
 
141
+ const hasPass = hasImpersonationPass(req, secret);
142
+ const staleImpersonation = impersonating && !token && !hasPass;
143
+
144
+ if (onSignInPage) {
145
+ if (!staleImpersonation) return;
146
+ const sameLoginPage = new URL(`${basePath}${pathname}${search}`, origin);
147
+ return withoutImpersonation(NextResponse.redirect(sameLoginPage), req);
148
+ }
149
+
122
150
  const isAuthorized =
123
- ((await authorized({ req, token })) ?? !!token) ||
124
- hasImpersonationPass(req, secret);
151
+ ((await authorized({ req, token })) ?? !!token) || hasPass;
125
152
  if (isAuthorized) {
126
153
  req.nextauth = { token };
127
154
  return;
@@ -132,7 +159,8 @@ export function buildAuthMiddleware({
132
159
  "callbackUrl",
133
160
  `${basePath}${pathname}${search}`
134
161
  );
135
- return NextResponse.redirect(signInUrl);
162
+ const toSignIn = NextResponse.redirect(signInUrl);
163
+ return staleImpersonation ? withoutImpersonation(toSignIn, req) : toSignIn;
136
164
  };
137
165
 
138
166
  const corsEnabled = cors.enabled !== false;
@@ -36,6 +36,7 @@ export function callbacks(config: Auth.Config): NextAuthOptions["callbacks"] {
36
36
  );
37
37
  if (employee.colorScheme) token.colorScheme = employee.colorScheme;
38
38
  token.picture = employee.imageUrl ?? null;
39
+ token.portraitUrl = employee.portraitUrl ?? null;
39
40
  token.profileCheckedAt = Date.now();
40
41
  }
41
42
 
@@ -53,6 +54,7 @@ export function callbacks(config: Auth.Config): NextAuthOptions["callbacks"] {
53
54
  );
54
55
  if (employee.colorScheme) token.colorScheme = employee.colorScheme;
55
56
  if (employee.imageUrl) token.picture = employee.imageUrl;
57
+ if (employee.portraitUrl) token.portraitUrl = employee.portraitUrl;
56
58
  token.profileCheckedAt = Date.now();
57
59
  }
58
60
 
@@ -74,6 +76,7 @@ export function callbacks(config: Auth.Config): NextAuthOptions["callbacks"] {
74
76
  token.authMethod as string | undefined
75
77
  );
76
78
  if (employee.imageUrl) token.picture = employee.imageUrl;
79
+ if (employee.portraitUrl) token.portraitUrl = employee.portraitUrl;
77
80
  token.profileCheckedAt = Date.now();
78
81
  }
79
82
 
@@ -86,12 +89,14 @@ export function callbacks(config: Auth.Config): NextAuthOptions["callbacks"] {
86
89
  oid?: string;
87
90
  tid?: string;
88
91
  authMethod?: string;
92
+ portraitUrl?: string | null;
89
93
  };
90
94
  const target = session as {
91
95
  colorScheme?: ColorScheme;
92
96
  oid?: string;
93
97
  tid?: string;
94
98
  authMethod?: string;
99
+ portraitUrl?: string | null;
95
100
  };
96
101
 
97
102
  if (isColorScheme(claims.colorScheme))
@@ -99,6 +104,7 @@ export function callbacks(config: Auth.Config): NextAuthOptions["callbacks"] {
99
104
  target.oid = claims.oid;
100
105
  target.tid = claims.tid;
101
106
  if (claims.authMethod) target.authMethod = claims.authMethod;
107
+ if (claims.portraitUrl) target.portraitUrl = claims.portraitUrl;
102
108
 
103
109
  return session;
104
110
  },
@@ -26,6 +26,7 @@ export function isColorScheme(value: unknown): value is ColorScheme {
26
26
  interface EmployeeProfile {
27
27
  colorScheme?: ColorScheme;
28
28
  imageUrl?: string;
29
+ portraitUrl?: string;
29
30
  }
30
31
 
31
32
  export async function fetchEmployeeProfile(
@@ -70,6 +71,7 @@ export async function fetchEmployeeProfile(
70
71
  colorScheme: isColorScheme(me.settings?.colorScheme)
71
72
  ? me.settings.colorScheme
72
73
  : undefined,
74
+ portraitUrl: me.image?.asset?.url,
73
75
  imageUrl: getSanityImageUrl(me.image?.asset?.url, {
74
76
  width: 128,
75
77
  height: 128,
@@ -1,6 +1,7 @@
1
1
  import NextAuth from "next-auth";
2
2
  import type { NextAuthOptions } from "next-auth";
3
3
  import { resolveCookieDomain } from "../session";
4
+ import { withSessionHint } from "../session/hintCookie";
4
5
 
5
6
  type AuthOptionsFor = NextAuthOptions | ((req: Request) => NextAuthOptions);
6
7
 
@@ -27,12 +28,15 @@ export function createAuthHandler(options: AuthOptionsFor) {
27
28
  }
28
29
  : authOptions;
29
30
 
30
- return (
31
+ const response = await (
31
32
  NextAuth(perRequest) as unknown as (
32
33
  req: Request,
33
34
  ctx: unknown
34
35
  ) => Promise<Response>
35
36
  )(req, ctx);
37
+ return sessionToken
38
+ ? withSessionHint(response, sessionToken.name)
39
+ : response;
36
40
  };
37
41
  }
38
42
 
@@ -0,0 +1,16 @@
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+ import { markSignedIn } from "@snokam/ui/theme/session-hint";
5
+ import { useSession } from "./useSession";
6
+
7
+ export function SessionHintSync() {
8
+ const { status } = useSession();
9
+
10
+ useEffect(() => {
11
+ if (status === "loading") return;
12
+ markSignedIn(status === "authenticated");
13
+ }, [status]);
14
+
15
+ return null;
16
+ }
@@ -0,0 +1,52 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { sessionHintCookie } from "./hintCookie.ts";
4
+
5
+ const NAME = "__Secure-next-auth.snosky-no.session-token";
6
+
7
+ test("the hint copies the session cookie's scope and lifetime", () => {
8
+ const hint = sessionHintCookie(
9
+ [
10
+ `${NAME}=abc; Path=/; Expires=Wed, 01 Jan 2099 00:00:00 GMT; HttpOnly; Secure; SameSite=Lax`,
11
+ ],
12
+ NAME
13
+ );
14
+ assert.equal(
15
+ hint,
16
+ "snokam.session=signed-in; Path=/; Expires=Wed, 01 Jan 2099 00:00:00 GMT; Secure; SameSite=Lax"
17
+ );
18
+ });
19
+
20
+ test("a session cookie shared across a zone gives the hint the same domain", () => {
21
+ const hint = sessionHintCookie(
22
+ [`${NAME}=abc; Path=/; Domain=.snokam.no; HttpOnly; Max-Age=3600`],
23
+ NAME
24
+ );
25
+ assert.equal(
26
+ hint,
27
+ "snokam.session=signed-in; Path=/; Domain=.snokam.no; Max-Age=3600"
28
+ );
29
+ });
30
+
31
+ test("clearing the session clears the hint", () => {
32
+ const hint = sessionHintCookie(
33
+ [`${NAME}=; Path=/; Max-Age=0; HttpOnly`],
34
+ NAME
35
+ );
36
+ assert.equal(hint, "snokam.session=; Path=/; Max-Age=0");
37
+ });
38
+
39
+ test("a chunked session counts as signed in even when the plain cookie is removed", () => {
40
+ const hint = sessionHintCookie(
41
+ [
42
+ `${NAME}=; Path=/; Max-Age=0; HttpOnly`,
43
+ `${NAME}.0=part; Path=/; Max-Age=3600; HttpOnly`,
44
+ ],
45
+ NAME
46
+ );
47
+ assert.equal(hint, "snokam.session=signed-in; Path=/; Max-Age=3600");
48
+ });
49
+
50
+ test("responses that do not touch the session leave the hint alone", () => {
51
+ assert.equal(sessionHintCookie(["other=1; Path=/"], NAME), undefined);
52
+ });
@@ -0,0 +1,69 @@
1
+ import {
2
+ SESSION_HINT_COOKIE,
3
+ SIGNED_IN_HINT,
4
+ } from "@snokam/ui/theme/session-hint";
5
+
6
+ const DROPPED_ATTRIBUTES = new Set(["httponly"]);
7
+
8
+ function cookieName(setCookie: string): string {
9
+ return setCookie.split("=", 1)[0].trim();
10
+ }
11
+
12
+ function attributesOf(setCookie: string): string[] {
13
+ return setCookie
14
+ .split(";")
15
+ .slice(1)
16
+ .map((attribute) => attribute.trim())
17
+ .filter(Boolean);
18
+ }
19
+
20
+ function isExpired(attribute: string): boolean {
21
+ const [key, value = ""] = attribute.split("=");
22
+ if (key.toLowerCase() === "max-age") return Number(value) <= 0;
23
+ if (key.toLowerCase() === "expires") return Date.parse(value) <= Date.now();
24
+ return false;
25
+ }
26
+
27
+ function isCleared(setCookie: string): boolean {
28
+ const pair = setCookie.split(";", 1)[0];
29
+ const value = pair.slice(pair.indexOf("=") + 1).trim();
30
+ return value === "" || attributesOf(setCookie).some(isExpired);
31
+ }
32
+
33
+ function belongsToSession(setCookie: string, sessionName: string): boolean {
34
+ const name = cookieName(setCookie);
35
+ return name === sessionName || name.startsWith(`${sessionName}.`);
36
+ }
37
+
38
+ export function sessionHintCookie(
39
+ setCookies: string[],
40
+ sessionName: string
41
+ ): string | undefined {
42
+ const session = setCookies.filter((cookie) =>
43
+ belongsToSession(cookie, sessionName)
44
+ );
45
+ if (session.length === 0) return undefined;
46
+ const live = session.find((cookie) => !isCleared(cookie));
47
+ const source = live ?? session[0];
48
+ const attributes = attributesOf(source).filter(
49
+ (attribute) =>
50
+ !DROPPED_ATTRIBUTES.has(attribute.split("=")[0].toLowerCase())
51
+ );
52
+ const value = live ? SIGNED_IN_HINT : "";
53
+ return [`${SESSION_HINT_COOKIE}=${value}`, ...attributes].join("; ");
54
+ }
55
+
56
+ export function withSessionHint(
57
+ response: Response,
58
+ sessionName: string
59
+ ): Response {
60
+ const hint = sessionHintCookie(response.headers.getSetCookie(), sessionName);
61
+ if (!hint) return response;
62
+ const headers = new Headers(response.headers);
63
+ headers.append("Set-Cookie", hint);
64
+ return new Response(response.body, {
65
+ status: response.status,
66
+ statusText: response.statusText,
67
+ headers,
68
+ });
69
+ }
@@ -1,56 +1,17 @@
1
1
  "use client";
2
2
 
3
- import { useEffect, useMemo, useRef } from "react";
4
- import { Configuration, EmployeesClient } from "@snokam/api-client/employees";
5
- import { apiBaseUrl, useOptionalConfig } from "@snokam/tenant";
6
- import { useClientQuery } from "@snokam/react-query";
7
- import { useAdminTheme } from "@snokam/ui/theme/admin";
8
- import type { ColorSchemeMode } from "@snokam/ui/theme/admin";
3
+ import { lazy, Suspense } from "react";
9
4
  import { useAuth } from "../hooks";
10
- import { retryUnlessMissing } from "../employee-query/retry";
11
5
 
12
- const MODES: ColorSchemeMode[] = ["system", "light", "dark"];
13
-
14
- function isMode(value: unknown): value is ColorSchemeMode {
15
- return MODES.includes(value as ColorSchemeMode);
16
- }
6
+ const SavedThemeSync = lazy(() => import("./saved-theme-sync"));
17
7
 
18
8
  export function EmployeeThemeSync() {
19
- const { isAuthenticated, getToken } = useAuth();
20
- const { setMode } = useAdminTheme();
21
- const config = useOptionalConfig();
22
- const seeded = useRef(false);
23
-
24
- const basePath = config ? apiBaseUrl(config) : undefined;
25
- const client = useMemo(
26
- () =>
27
- new EmployeesClient(
28
- new Configuration({
29
- basePath,
30
- ...(isAuthenticated && { accessToken: () => getToken() }),
31
- })
32
- ),
33
- [basePath, isAuthenticated, getToken]
34
- );
9
+ const { isAuthenticated } = useAuth();
10
+ if (!isAuthenticated) return null;
35
11
 
36
- const { data } = useClientQuery({
37
- name: "Employees",
38
- client,
39
- }).useGetMeProtectedQuery(
40
- {},
41
- {
42
- enabled: isAuthenticated && !!basePath,
43
- retry: retryUnlessMissing,
44
- }
12
+ return (
13
+ <Suspense fallback={null}>
14
+ <SavedThemeSync />
15
+ </Suspense>
45
16
  );
46
-
47
- const saved = data?.settings?.colorScheme;
48
-
49
- useEffect(() => {
50
- if (seeded.current || !isMode(saved)) return;
51
- seeded.current = true;
52
- setMode(saved);
53
- }, [saved, setMode]);
54
-
55
- return null;
56
17
  }
@@ -0,0 +1,53 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo } from "react";
4
+ import { Configuration, EmployeesClient } from "@snokam/api-client/employees";
5
+ import { apiBaseUrl, useOptionalConfig } from "@snokam/tenant";
6
+ import { useClientQuery } from "@snokam/react-query";
7
+ import { useAdminTheme } from "@snokam/ui/theme/admin";
8
+ import type { ColorSchemeMode } from "@snokam/ui/theme/admin";
9
+ import { useAuth } from "../hooks";
10
+ import { retryUnlessMissing } from "../employee-query/retry";
11
+
12
+ const MODES: ColorSchemeMode[] = ["system", "light", "dark"];
13
+
14
+ function isMode(value: unknown): value is ColorSchemeMode {
15
+ return MODES.includes(value as ColorSchemeMode);
16
+ }
17
+
18
+ export default function SavedThemeSync() {
19
+ const { isAuthenticated, getToken } = useAuth();
20
+ const { seedMode } = useAdminTheme();
21
+ const config = useOptionalConfig();
22
+
23
+ const basePath = config ? apiBaseUrl(config) : undefined;
24
+ const client = useMemo(
25
+ () =>
26
+ new EmployeesClient(
27
+ new Configuration({
28
+ basePath,
29
+ ...(isAuthenticated && { accessToken: () => getToken() }),
30
+ })
31
+ ),
32
+ [basePath, isAuthenticated, getToken]
33
+ );
34
+
35
+ const { data } = useClientQuery({
36
+ name: "Employees",
37
+ client,
38
+ }).useGetMeProtectedQuery(
39
+ {},
40
+ {
41
+ enabled: isAuthenticated && !!basePath,
42
+ retry: retryUnlessMissing,
43
+ }
44
+ );
45
+
46
+ const saved = data?.settings?.colorScheme;
47
+
48
+ useEffect(() => {
49
+ if (isMode(saved)) seedMode(saved);
50
+ }, [saved, seedMode]);
51
+
52
+ return null;
53
+ }