@snokam/auth 6.1.12 → 6.1.14

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,16 @@
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.14](https://github.com/snokam/components/compare/%40snokam%2Fauth%406.1.13...%40snokam%2Fauth%406.1.14) (2026-11-11)
7
+
8
+ ### Bug Fixes
9
+
10
+ - **auth:** a view-as session that ends reloads the page, and a missing task shows as missing ([#3560](https://github.com/snokam/components/issues/3560)) ([63d63ec](https://github.com/snokam/components/commit/63d63ecd28b51d3252f9d6d4d7cca6276a99ce93))
11
+
12
+ ## [6.1.13](https://github.com/snokam/components/compare/%40snokam%2Fauth%406.1.12...%40snokam%2Fauth%406.1.13) (2026-11-11)
13
+
14
+ **Note:** Version bump only for package @snokam/auth
15
+
6
16
  ## [6.1.12](https://github.com/snokam/components/compare/%40snokam%2Fauth%406.1.10...%40snokam%2Fauth%406.1.12) (2026-11-10)
7
17
 
8
18
  **Note:** Version bump only for package @snokam/auth
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@snokam/auth",
3
3
  "description": "Snøkam auth components",
4
- "version": "6.1.12",
4
+ "version": "6.1.14",
5
5
  "main": "src/index.ts",
6
6
  "sideEffects": false,
7
7
  "types": "src/index.ts",
@@ -26,11 +26,11 @@
26
26
  "@mui/material": "^9.5.0",
27
27
  "next-auth": "4.24.15",
28
28
  "path-to-regexp": "^9.0.0",
29
- "@snokam/page-content": "6.9.21",
29
+ "@snokam/identity": "1.1.1",
30
+ "@snokam/page-content": "6.9.22",
30
31
  "@snokam/react-query": "1.1.1",
31
32
  "@snokam/tenant": "4.5.7",
32
- "@snokam/ui": "7.6.4",
33
- "@snokam/identity": "1.1.1",
33
+ "@snokam/ui": "7.6.5",
34
34
  "@snokam/api-client": "1.0.0"
35
35
  },
36
36
  "peerDependencies": {
package/src/hooks.ts CHANGED
@@ -2,6 +2,8 @@ import { signIn, signOut } from "next-auth/react";
2
2
  import { useCallback, useMemo } from "react";
3
3
  import { readActiveCookie } from "./impersonation/cookies";
4
4
  import { useImpersonation } from "./impersonation/context";
5
+ import { pageIsReloading } from "./impersonation/checks";
6
+ import { leaveEndedSession } from "./impersonation/ended";
5
7
  import { useOwnIdentity } from "./identity/own";
6
8
  import { useSession } from "./session/useSession";
7
9
  import { isReusable, type CachedToken } from "./token/reuse";
@@ -13,6 +15,7 @@ import {
13
15
  import {
14
16
  ConsentRequiredError,
15
17
  failureOf,
18
+ ImpersonationEndedError,
16
19
  SignedOutError,
17
20
  TransientTokenError,
18
21
  } from "./token/failure";
@@ -78,6 +81,7 @@ async function fetchToken(kind: TokenKind, impKey: string): Promise<string> {
78
81
  }
79
82
 
80
83
  async function getFreshToken(kind: TokenKind): Promise<string> {
84
+ if (pageIsReloading()) return new Promise<string>(() => undefined);
81
85
  const impKey = kind === "own" ? "" : readImpersonationKey();
82
86
  const now = Date.now() / 1000;
83
87
  const cached = cachedTokens[kind];
@@ -118,6 +122,8 @@ function tokenOrLogin(kind: TokenKind): Promise<string> {
118
122
  return getFreshToken(kind).catch((error) => {
119
123
  console.error(error);
120
124
  if (error instanceof TransientTokenError) throw error;
125
+ if (error instanceof ImpersonationEndedError)
126
+ return leaveEndedSession(error);
121
127
  const onAuthPage = window.location.pathname.startsWith("/auth/");
122
128
  if (onAuthPage) return;
123
129
  if (error instanceof SignedOutError) return signInAgainIfSignedOut(error);
@@ -0,0 +1,34 @@
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+ import { registerSessionCheck } from "./checks";
5
+ import type { SessionWatch } from "./watch";
6
+
7
+ export function useSessionChecks(
8
+ watch: SessionWatch,
9
+ rereadCookie: () => void
10
+ ) {
11
+ useEffect(() => {
12
+ const unregister = registerSessionCheck(() => {
13
+ rereadCookie();
14
+ return watch.isReloading();
15
+ });
16
+ const onVisible = () => {
17
+ if (document.visibilityState === "visible") rereadCookie();
18
+ };
19
+ const onRestored = (event: PageTransitionEvent) => {
20
+ if (!event.persisted) return;
21
+ watch.resume();
22
+ rereadCookie();
23
+ };
24
+ window.addEventListener("focus", rereadCookie);
25
+ window.addEventListener("pageshow", onRestored);
26
+ document.addEventListener("visibilitychange", onVisible);
27
+ return () => {
28
+ unregister();
29
+ window.removeEventListener("focus", rereadCookie);
30
+ window.removeEventListener("pageshow", onRestored);
31
+ document.removeEventListener("visibilitychange", onVisible);
32
+ };
33
+ }, [watch, rereadCookie]);
34
+ }
@@ -0,0 +1,14 @@
1
+ type SessionCheck = () => boolean;
2
+
3
+ const checks = new Set<SessionCheck>();
4
+
5
+ export function registerSessionCheck(check: SessionCheck): () => void {
6
+ checks.add(check);
7
+ return () => {
8
+ checks.delete(check);
9
+ };
10
+ }
11
+
12
+ export function pageIsReloading(): boolean {
13
+ return [...checks].map((check) => check()).some(Boolean);
14
+ }
@@ -15,6 +15,9 @@ import { useSessionRenewal } from "./renewal";
15
15
  import { useOptionalConfig } from "@snokam/tenant";
16
16
  import { isAllowedRedirect, platformBaseDomain } from "./redirects";
17
17
  import { exitDestination } from "./exit";
18
+ import { browserPage } from "./page";
19
+ import { useSessionChecks } from "./checking";
20
+ import { watchSession } from "./watch";
18
21
 
19
22
  export interface StartImpersonationInput {
20
23
  targetEmail: string;
@@ -79,52 +82,63 @@ export function ImpersonationProvider({
79
82
  const [starting, setStarting] = useState(false);
80
83
  const [exiting, setExiting] = useState(false);
81
84
 
82
- const rereadCookie = useCallback(
83
- () =>
84
- setActive((current) =>
85
- keepIfUnchanged(current, readDocumentActiveCookie())
86
- ),
87
- []
85
+ const [watch] = useState(() =>
86
+ watchSession(initialActive?.tokenId ?? null, browserPage)
88
87
  );
89
88
 
89
+ const rereadCookie = useCallback(() => {
90
+ const next = readDocumentActiveCookie();
91
+ if (!watch.observe(next?.tokenId ?? null)) return;
92
+ setActive((current) => keepIfUnchanged(current, next));
93
+ }, [watch]);
94
+
90
95
  useEffect(() => {
91
96
  rereadCookie();
92
97
  }, [rereadCookie]);
93
98
 
99
+ useSessionChecks(watch, rereadCookie);
94
100
  useSessionRenewal(active, rereadCookie);
95
101
 
96
- const start = useCallback(async (input: StartImpersonationInput) => {
97
- setStarting(true);
98
- try {
99
- const { redirectTo, landingUrl } = input;
100
- const res = await fetch("/api/impersonation/start", {
101
- method: "POST",
102
- headers: { "Content-Type": "application/json" },
103
- credentials: "include",
104
- body: JSON.stringify(input),
105
- });
106
- if (!res.ok) {
107
- return {
108
- ok: false,
109
- error: (await res.text()) || `HTTP ${res.status}`,
102
+ const start = useCallback(
103
+ async (input: StartImpersonationInput) => {
104
+ setStarting(true);
105
+ watch.pause();
106
+ let leaving = false;
107
+ try {
108
+ const { redirectTo, landingUrl } = input;
109
+ const res = await fetch("/api/impersonation/start", {
110
+ method: "POST",
111
+ headers: { "Content-Type": "application/json" },
112
+ credentials: "include",
113
+ body: JSON.stringify(input),
114
+ });
115
+ if (!res.ok) {
116
+ return {
117
+ ok: false,
118
+ error: (await res.text()) || `HTTP ${res.status}`,
119
+ };
120
+ }
121
+ leaving = true;
122
+ clearAuthTokenCache();
123
+ const data = (await res.json().catch(() => ({}))) as {
124
+ adoptUrl?: string;
110
125
  };
126
+ if (data.adoptUrl) window.location.assign(data.adoptUrl);
127
+ else if (landingUrl) window.location.assign(landingUrl);
128
+ else if (redirectTo) window.location.assign(redirectTo);
129
+ else window.location.reload();
130
+ return { ok: true };
131
+ } finally {
132
+ if (!leaving) watch.resume();
133
+ setStarting(false);
111
134
  }
112
- clearAuthTokenCache();
113
- const data = (await res.json().catch(() => ({}))) as {
114
- adoptUrl?: string;
115
- };
116
- if (data.adoptUrl) window.location.assign(data.adoptUrl);
117
- else if (landingUrl) window.location.assign(landingUrl);
118
- else if (redirectTo) window.location.assign(redirectTo);
119
- else window.location.reload();
120
- return { ok: true };
121
- } finally {
122
- setStarting(false);
123
- }
124
- }, []);
135
+ },
136
+ [watch]
137
+ );
125
138
 
126
139
  const exit = useCallback(async () => {
127
140
  setExiting(true);
141
+ watch.pause();
128
142
  try {
129
143
  await fetch("/api/impersonation/end", {
130
144
  method: "POST",
@@ -148,7 +162,7 @@ export function ImpersonationProvider({
148
162
  } finally {
149
163
  setExiting(false);
150
164
  }
151
- }, [active, apiBaseUrl]);
165
+ }, [active, apiBaseUrl, watch]);
152
166
 
153
167
  const value = useMemo<ImpersonationContextValue>(
154
168
  () => ({ active, starting, exiting, start, exit }),
@@ -0,0 +1,10 @@
1
+ import { pageIsReloading } from "./checks";
2
+
3
+ export async function leaveEndedSession(error: Error): Promise<never> {
4
+ await fetch("/api/impersonation/end", {
5
+ method: "POST",
6
+ credentials: "include",
7
+ }).catch(() => undefined);
8
+ if (pageIsReloading()) return new Promise<never>(() => undefined);
9
+ throw error;
10
+ }
@@ -0,0 +1,21 @@
1
+ import type { CleanPage } from "./watch";
2
+
3
+ const LAST_RELOAD_KEY = "imp-clean-page";
4
+
5
+ export const browserPage: CleanPage = {
6
+ reload: () => window.location.reload(),
7
+ lastReload: () => {
8
+ try {
9
+ return sessionStorage.getItem(LAST_RELOAD_KEY);
10
+ } catch {
11
+ return null;
12
+ }
13
+ },
14
+ rememberReload: (change) => {
15
+ try {
16
+ sessionStorage.setItem(LAST_RELOAD_KEY, change);
17
+ } catch {
18
+ return;
19
+ }
20
+ },
21
+ };
@@ -24,7 +24,11 @@ export function useSessionRenewal(
24
24
  useEffect(() => {
25
25
  if (!tokenId || !expiresOn) return;
26
26
  return scheduleRenewal({ tokenId, expiresOn }, attempts, {
27
- renew: renewSession,
27
+ renew: async () => {
28
+ const renewed = await renewSession();
29
+ if (!renewed) rereadCookie();
30
+ return renewed;
31
+ },
28
32
  renewed: () => {
29
33
  clearAuthTokenCache();
30
34
  rereadCookie();
@@ -0,0 +1,74 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { IMPERSONATION_ENDED } from "../token/failure.ts";
4
+ import { personaTokenResponse } from "./standing.ts";
5
+
6
+ const NOW_MS = 1_800_000_000_000;
7
+ const LATER = NOW_MS / 1000 + 600;
8
+ const EARLIER = NOW_MS / 1000 - 1;
9
+
10
+ function cookie(name: string, value: object): string {
11
+ return `${name}=${encodeURIComponent(JSON.stringify(value))}`;
12
+ }
13
+
14
+ function session(tokenId: string, expiresOn: number): string {
15
+ return cookie("imp_session", { accessToken: "persona", expiresOn, tokenId });
16
+ }
17
+
18
+ function shown(tokenId: string, expiresOn: number): string {
19
+ return cookie("imp_active", {
20
+ targetEmail: "kari@snokam.no",
21
+ finance: false,
22
+ tokenId,
23
+ expiresOn,
24
+ });
25
+ }
26
+
27
+ function answer(...cookies: string[]): Response | null {
28
+ return personaTokenResponse(
29
+ ["next-auth.session-token=own", ...cookies].join("; "),
30
+ NOW_MS
31
+ );
32
+ }
33
+
34
+ async function refusal(response: Response | null) {
35
+ assert.equal(response?.status, 401);
36
+ assert.deepEqual(await response?.json(), { error: IMPERSONATION_ENDED });
37
+ }
38
+
39
+ describe("the token for a Vis som session", () => {
40
+ it("is the persona token while the session lasts", async () => {
41
+ const response = answer(session("imp-1", LATER), shown("imp-1", LATER));
42
+
43
+ assert.equal(response?.status, 200);
44
+ assert.deepEqual(await response?.json(), {
45
+ accessToken: "persona",
46
+ expiresOn: LATER,
47
+ });
48
+ });
49
+
50
+ it("leaves a request without impersonation cookies to the caller's own token", () => {
51
+ assert.equal(answer(), null);
52
+ assert.equal(personaTokenResponse(null, NOW_MS), null);
53
+ });
54
+
55
+ it("refuses instead of handing out the own token when the persona token has expired", async () => {
56
+ await refusal(answer(session("imp-1", EARLIER), shown("imp-1", EARLIER)));
57
+ await refusal(answer(session("imp-1", EARLIER), shown("imp-1", LATER)));
58
+ });
59
+
60
+ it("refuses when the page shows a persona but the persona token is gone", async () => {
61
+ await refusal(answer(shown("imp-1", LATER)));
62
+ });
63
+
64
+ it("refuses when the page shows another session than the token belongs to", async () => {
65
+ await refusal(answer(session("imp-2", LATER), shown("imp-1", LATER)));
66
+ });
67
+
68
+ it("still answers a persona token that has no readable companion cookie", async () => {
69
+ const response = answer(session("imp-1", LATER));
70
+
71
+ assert.equal(response?.status, 200);
72
+ assert.equal(answer(session("imp-1", EARLIER)), null);
73
+ });
74
+ });
@@ -0,0 +1,35 @@
1
+ import { IMPERSONATION_ENDED } from "../token/failure.ts";
2
+ import type { ImpersonationActive, ImpersonationSession } from "./cookies";
3
+ import {
4
+ IMP_ACTIVE_COOKIE,
5
+ IMP_SESSION_COOKIE,
6
+ parseCookieHeader,
7
+ } from "./jar.ts";
8
+
9
+ function readJson<T>(raw: string | undefined): T | null {
10
+ if (!raw) return null;
11
+ try {
12
+ return JSON.parse(raw) as T;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ export function personaTokenResponse(
19
+ cookieHeader: string | null,
20
+ nowMs: number = Date.now()
21
+ ): Response | null {
22
+ const jar = parseCookieHeader(cookieHeader);
23
+ const session = readJson<ImpersonationSession>(jar[IMP_SESSION_COOKIE]);
24
+ const shown = readJson<ImpersonationActive>(jar[IMP_ACTIVE_COOKIE]);
25
+ const persona = session && session.expiresOn * 1000 > nowMs ? session : null;
26
+
27
+ if (shown && persona?.tokenId !== shown.tokenId) {
28
+ return Response.json({ error: IMPERSONATION_ENDED }, { status: 401 });
29
+ }
30
+ if (!persona) return null;
31
+ return Response.json({
32
+ accessToken: persona.accessToken,
33
+ expiresOn: persona.expiresOn,
34
+ });
35
+ }
@@ -0,0 +1,123 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { watchSession, type CleanPage } from "./watch.ts";
4
+
5
+ function page(remembered: string | null = null) {
6
+ const state = { reloads: 0, remembered };
7
+ const clean: CleanPage = {
8
+ reload: () => {
9
+ state.reloads += 1;
10
+ },
11
+ lastReload: () => state.remembered,
12
+ rememberReload: (change) => {
13
+ state.remembered = change;
14
+ },
15
+ };
16
+ return { state, clean };
17
+ }
18
+
19
+ describe("a Vis som session that ends or changes under the page", () => {
20
+ it("reloads exactly once when the session ends", () => {
21
+ const { state, clean } = page();
22
+ const watch = watchSession("imp-1", clean);
23
+
24
+ assert.equal(watch.observe("imp-1"), true);
25
+ assert.equal(watch.observe(null), false);
26
+ assert.equal(watch.observe(null), false);
27
+ assert.equal(watch.observe("imp-1"), false);
28
+
29
+ assert.equal(state.reloads, 1);
30
+ assert.equal(watch.isReloading(), true);
31
+ });
32
+
33
+ it("reloads when the first read after a persona render finds no session", () => {
34
+ const { state, clean } = page();
35
+
36
+ assert.equal(watchSession("imp-1", clean).observe(null), false);
37
+ assert.equal(state.reloads, 1);
38
+ });
39
+
40
+ it("does not reload a page that never showed a persona", () => {
41
+ const { state, clean } = page();
42
+ const watch = watchSession(null, clean);
43
+
44
+ assert.equal(watch.observe(null), true);
45
+ assert.equal(watch.observe(null), true);
46
+
47
+ assert.equal(state.reloads, 0);
48
+ assert.equal(watch.isReloading(), false);
49
+ });
50
+
51
+ it("adopts the session the first read finds without reloading", () => {
52
+ const { state, clean } = page();
53
+ const watch = watchSession(null, clean);
54
+
55
+ assert.equal(watch.observe("imp-1"), true);
56
+ assert.equal(watch.observe("imp-1"), true);
57
+
58
+ assert.equal(state.reloads, 0);
59
+ });
60
+
61
+ it("reloads when another session replaces the one on the page", () => {
62
+ const { state, clean } = page();
63
+
64
+ assert.equal(watchSession("imp-1", clean).observe("imp-2"), false);
65
+ assert.equal(state.reloads, 1);
66
+ });
67
+
68
+ it("reloads when a session starts elsewhere after the page settled", () => {
69
+ const { state, clean } = page();
70
+ const watch = watchSession(null, clean);
71
+
72
+ watch.observe(null);
73
+
74
+ assert.equal(watch.observe("imp-1"), false);
75
+ assert.equal(state.reloads, 1);
76
+ });
77
+
78
+ it("keeps the session through a renewal, which keeps the token id", () => {
79
+ const { state, clean } = page();
80
+ const watch = watchSession("imp-1", clean);
81
+
82
+ for (let renewal = 0; renewal < 5; renewal += 1)
83
+ assert.equal(watch.observe("imp-1"), true);
84
+
85
+ assert.equal(state.reloads, 0);
86
+ });
87
+
88
+ it("leaves the navigation to an explicit start or exit", () => {
89
+ const { state, clean } = page();
90
+ const watch = watchSession("imp-1", clean);
91
+
92
+ watch.pause();
93
+
94
+ assert.equal(watch.observe(null), false);
95
+ assert.equal(watch.observe("imp-2"), false);
96
+ assert.equal(state.reloads, 0);
97
+ assert.equal(watch.isReloading(), false);
98
+ });
99
+
100
+ it("watches again when a start that was refused resumes", () => {
101
+ const { state, clean } = page();
102
+ const watch = watchSession("imp-1", clean);
103
+
104
+ watch.pause();
105
+ watch.resume();
106
+
107
+ assert.equal(watch.observe(null), false);
108
+ assert.equal(state.reloads, 1);
109
+ });
110
+
111
+ it("never reloads twice for the same change, so a reload cannot loop", () => {
112
+ const first = page();
113
+ watchSession("imp-1", first.clean).observe(null);
114
+ const afterReload = page(first.state.remembered);
115
+ const watch = watchSession("imp-1", afterReload.clean);
116
+
117
+ assert.equal(watch.observe(null), true);
118
+ assert.equal(watch.observe(null), true);
119
+
120
+ assert.equal(afterReload.state.reloads, 0);
121
+ assert.equal(watch.isReloading(), false);
122
+ });
123
+ });
@@ -0,0 +1,53 @@
1
+ export interface CleanPage {
2
+ reload: () => void;
3
+ lastReload: () => string | null;
4
+ rememberReload: (change: string) => void;
5
+ }
6
+
7
+ export interface SessionWatch {
8
+ observe: (tokenId: string | null) => boolean;
9
+ pause: () => void;
10
+ resume: () => void;
11
+ isReloading: () => boolean;
12
+ }
13
+
14
+ export function watchSession(
15
+ initialTokenId: string | null,
16
+ page: CleanPage
17
+ ): SessionWatch {
18
+ let known = initialTokenId;
19
+ let settled = initialTokenId !== null;
20
+ let paused = false;
21
+ let reloading = false;
22
+
23
+ const startClean = (next: string | null): boolean => {
24
+ const change = `${known ?? ""}>${next ?? ""}`;
25
+ known = next;
26
+ if (page.lastReload() === change) return true;
27
+ page.rememberReload(change);
28
+ reloading = true;
29
+ page.reload();
30
+ return false;
31
+ };
32
+
33
+ const observe = (tokenId: string | null): boolean => {
34
+ if (paused || reloading) return false;
35
+ const firstRead = !settled;
36
+ settled = true;
37
+ if (tokenId === known) return true;
38
+ if (!firstRead) return startClean(tokenId);
39
+ known = tokenId;
40
+ return true;
41
+ };
42
+
43
+ return {
44
+ observe,
45
+ pause: () => {
46
+ paused = true;
47
+ },
48
+ resume: () => {
49
+ paused = false;
50
+ },
51
+ isReloading: () => reloading,
52
+ };
53
+ }
@@ -6,7 +6,7 @@ import {
6
6
  import { Auth } from "../types";
7
7
  import { getAuthUrl, getSessionCookieSettings } from "../session";
8
8
  import { exchangePasswordToken } from "../password/api";
9
- import { readImpersonationSession } from "../impersonation/cookies";
9
+ import { personaTokenResponse } from "../impersonation/standing";
10
10
  import { exchangeSsoToken } from "../sso/exchange";
11
11
 
12
12
  export type TokenResult =
@@ -104,15 +104,10 @@ async function wantsOwnToken(request: Request): Promise<boolean> {
104
104
 
105
105
  export function createTokenHandler(authConfig: Auth.Config) {
106
106
  return async function POST(request: Request) {
107
- const impersonation = (await wantsOwnToken(request))
107
+ const persona = (await wantsOwnToken(request))
108
108
  ? null
109
- : readImpersonationSession(request);
110
- if (impersonation && impersonation.expiresOn * 1000 > Date.now()) {
111
- return Response.json({
112
- accessToken: impersonation.accessToken,
113
- expiresOn: impersonation.expiresOn,
114
- });
115
- }
109
+ : personaTokenResponse(request.headers.get("cookie"));
110
+ if (persona) return persona;
116
111
 
117
112
  const result = await resolveAccessToken(authConfig, request);
118
113
  if ("error" in result) {
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
3
3
  import {
4
4
  ConsentRequiredError,
5
5
  failureOf,
6
+ IMPERSONATION_ENDED,
7
+ ImpersonationEndedError,
6
8
  SignedOutError,
7
9
  TransientTokenError,
8
10
  } from "./failure.ts";
@@ -31,3 +33,10 @@ test("other refusals are neither transient nor a sign-out", () => {
31
33
  assert.ok(!(error instanceof TransientTokenError));
32
34
  assert.ok(!(error instanceof SignedOutError));
33
35
  });
36
+
37
+ test("an ended Vis som session is neither a sign-out nor a hiccup", () => {
38
+ const error = failureOf(401, { error: IMPERSONATION_ENDED });
39
+ assert.ok(error instanceof ImpersonationEndedError);
40
+ assert.ok(!(error instanceof SignedOutError));
41
+ assert.ok(!(error instanceof TransientTokenError));
42
+ });
@@ -2,14 +2,20 @@ export class ConsentRequiredError extends Error {}
2
2
 
3
3
  export class SignedOutError extends Error {}
4
4
 
5
+ export class ImpersonationEndedError extends Error {}
6
+
5
7
  export class TransientTokenError extends Error {}
6
8
 
9
+ export const IMPERSONATION_ENDED = "impersonation_ended";
10
+
7
11
  const TRANSIENT_STATUSES = new Set([408, 425, 429]);
8
12
 
9
13
  export function failureOf(status: number, body: unknown): Error {
10
14
  const error = (body as { error?: unknown } | null)?.error;
11
15
  if (status === 403 && error === "consent_required")
12
16
  return new ConsentRequiredError();
17
+ if (status === 401 && error === IMPERSONATION_ENDED)
18
+ return new ImpersonationEndedError("The Vis som session has ended");
13
19
  if (status === 401) return new SignedOutError("Not signed in");
14
20
  if (status >= 500 || TRANSIENT_STATUSES.has(status))
15
21
  return new TransientTokenError(`Token request failed with ${status}`);