@sourceregistry/sveltekit-oidc 1.1.1 → 1.3.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/README.md CHANGED
@@ -160,6 +160,127 @@ export async function load(event) {
160
160
  - periodic `invalidateAll()` revalidation so revoked server sessions are detected
161
161
  - a client context for nested auth-aware components through `useOIDC()` / `getOIDCContext()`
162
162
 
163
+ ## Typed Custom Claims
164
+
165
+ `createOIDC` infers a `TClaims` type from whatever `transformClaims` / `transformUser` / `transformSession` return, and threads it through the session, `event.locals.oidc`, `OIDCPublicSession`, and the client context — no casts needed.
166
+
167
+ ```ts
168
+ // src/lib/server/auth.ts
169
+ export const oidc = createOIDC({
170
+ issuer: 'https://your-idp.example.com',
171
+ clientId: process.env.OIDC_CLIENT_ID!,
172
+ cookieSecret: process.env.OIDC_COOKIE_SECRET!,
173
+ transformClaims: (claims) => ({
174
+ ...claims,
175
+ roles: (claims.roles as string[]) ?? [],
176
+ tenant: claims.tenant as string | undefined
177
+ })
178
+ });
179
+ ```
180
+
181
+ Extract the inferred type with `OIDCInferClaims` and apply it to `App.Locals` so `event.locals.oidc` is typed everywhere:
182
+
183
+ ```ts
184
+ // src/app.d.ts
185
+ import type { OIDCHandleLocals, OIDCInferClaims } from 'sveltekit-oidc/server';
186
+ import { oidc } from '$lib/server/auth';
187
+
188
+ export type AppClaims = OIDCInferClaims<typeof oidc>;
189
+
190
+ declare global {
191
+ namespace App {
192
+ interface Locals {
193
+ oidc?: OIDCHandleLocals<AppClaims>;
194
+ }
195
+ }
196
+ }
197
+
198
+ export {};
199
+ ```
200
+
201
+ Now `event.locals.oidc?.claims?.roles` is `string[]` and `?.tenant` is `string | undefined` in every hook, load function, and action.
202
+
203
+ `OIDCContext` is a generic component, but Svelte doesn't support passing explicit type arguments in markup — `TClaims` is inferred from the `session` prop instead. Since `data.session` comes from `oidc.getPublicSession(event)`, it's already typed `OIDCPublicSession<AppClaims> | null`, so the inference flows through automatically:
204
+
205
+ ```html
206
+ <!-- src/routes/+layout.svelte -->
207
+ <script lang="ts">
208
+ import { OIDCContext } from 'sveltekit-oidc';
209
+ let { data, children } = $props();
210
+ </script>
211
+
212
+ <OIDCContext session={data.session} config={data.sessionManagement}>
213
+ {@render children()}
214
+ </OIDCContext>
215
+ ```
216
+
217
+ ```html
218
+ <!-- src/lib/Account.svelte -->
219
+ <script lang="ts">
220
+ import { useOIDC } from 'sveltekit-oidc';
221
+ import type { AppClaims } from '../../app.d.ts';
222
+
223
+ const oidc = useOIDC<AppClaims>();
224
+ </script>
225
+
226
+ {#if oidc.isAuthenticated}
227
+ <p>Roles: {oidc.claims?.roles.join(', ')}</p>
228
+ {/if}
229
+ ```
230
+
231
+ If `transformClaims` (and friends) are omitted, `TClaims` defaults to `OIDCUserClaims` — existing setups keep working unchanged.
232
+
233
+ ## Typed Custom Session
234
+
235
+ Backend apps commonly stash application-specific data on the session itself (e.g. `tenantId`, `permissions`) — not just inside `claims`/`user`. A second generic, `TSession`, is inferred from `transformSession`'s return type and threads through the session store, cookies, `event.locals.oidc`, and `handleCallback`'s result — again with no casts:
236
+
237
+ ```ts
238
+ // src/lib/server/auth.ts
239
+ import { createOIDC, type OIDCSession } from 'sveltekit-oidc/server';
240
+
241
+ type AppSession = OIDCSession<AppClaims> & {
242
+ tenantId: string;
243
+ permissions: string[];
244
+ };
245
+
246
+ export const oidc = createOIDC({
247
+ issuer: 'https://your-idp.example.com',
248
+ clientId: process.env.OIDC_CLIENT_ID!,
249
+ cookieSecret: process.env.OIDC_COOKIE_SECRET!,
250
+ transformClaims: (claims) => ({ ...claims, tenant: claims.tenant as string | undefined }),
251
+ transformSession: (session): AppSession => ({
252
+ ...session,
253
+ tenantId: session.claims?.tenant ?? 'default',
254
+ permissions: session.user?.roles ?? []
255
+ })
256
+ });
257
+ ```
258
+
259
+ Extract the inferred type with `OIDCInferSession` and apply it alongside `OIDCInferClaims`:
260
+
261
+ ```ts
262
+ // src/app.d.ts
263
+ import type { OIDCHandleLocals, OIDCInferClaims, OIDCInferSession } from 'sveltekit-oidc/server';
264
+ import { oidc } from '$lib/server/auth';
265
+
266
+ export type AppClaims = OIDCInferClaims<typeof oidc>;
267
+ export type AppSession = OIDCInferSession<typeof oidc>;
268
+
269
+ declare global {
270
+ namespace App {
271
+ interface Locals {
272
+ oidc?: OIDCHandleLocals<AppClaims, AppSession>;
273
+ }
274
+ }
275
+ }
276
+
277
+ export {};
278
+ ```
279
+
280
+ Now `event.locals.oidc?.session?.tenantId` is `string` and `?.permissions` is `string[]` everywhere — and `oidc.requireAuth(event)` / `handleCallback`'s `onsuccess` resolve to `AppSession` directly.
281
+
282
+ If `transformSession` is omitted, `TSession` defaults to `OIDCSession<TClaims>` — existing setups keep working unchanged.
283
+
163
284
  ## Example App
164
285
 
165
286
  This repository now includes a runnable example under [src/routes](C:/Users/alexa/WebstormProjects/github.com/SourceRegistry/sveltekit-oidc/src/routes) and [src/hooks.server.ts](C:/Users/alexa/WebstormProjects/github.com/SourceRegistry/sveltekit-oidc/src/hooks.server.ts).
@@ -183,4 +304,4 @@ Set these environment variables to enable it:
183
304
  - Use `transformClaims`, `transformUser`, and `transformSession` to project provider-specific claims into your own session shape.
184
305
  - `check_session_iframe` monitoring only runs when the provider advertises that endpoint and the session includes `session_state`.
185
306
  - Refresh token handling is automatic when a valid refresh token is present.
186
- - `event.locals.oidc` is attached by the hook, but you should add your own `app.d.ts` augmentation in the consuming app for full typing.
307
+ - `event.locals.oidc` is attached by the hook and typed via `OIDCHandleLocals<TClaims>`; see [Typed Custom Claims](#typed-custom-claims) for wiring your own claim shapes through `app.d.ts`.
@@ -1,208 +1,214 @@
1
- <script lang="ts">
2
- import { goto, invalidateAll } from '$app/navigation';
3
- import type { Snippet } from 'svelte';
4
-
5
- import { setOIDCContext } from './context.js';
6
- import type { OIDCPublicSession, OIDCSessionManagementConfig } from '../server/index.js';
7
-
8
- type RedirectMode = 'login' | 'logout' | 'reload' | 'none';
9
-
10
- let {
11
- session = null,
12
- config,
13
- loginPath,
14
- logoutPath = '/auth/logout',
15
- checkSessionIntervalMs = 5000,
16
- revalidateIntervalMs = 30000,
17
- redirectOnExpired = 'login',
18
- redirectOnRevoked = 'login',
19
- redirectIfUnauthenticated = false,
20
- children
21
- }: {
22
- session?: OIDCPublicSession | null;
23
- config: OIDCSessionManagementConfig;
24
- loginPath?: string;
25
- logoutPath?: string;
26
- checkSessionIntervalMs?: number;
27
- revalidateIntervalMs?: number;
28
- redirectOnExpired?: RedirectMode;
29
- redirectOnRevoked?: RedirectMode;
30
- redirectIfUnauthenticated?: boolean;
31
- children?: Snippet;
32
- } = $props();
33
-
34
- let iframe = $state<HTMLIFrameElement | undefined>(undefined);
35
- let status = $state<'authenticated' | 'unauthenticated' | 'expired' | 'revoked'>('unauthenticated');
36
- let handledUnauthenticated = $state(false);
37
-
38
- const metadata = $derived(config.metadata);
39
- const resolvedLoginPath = $derived(loginPath ?? config.loginPath ?? '/auth/login');
40
- const iframeUrl = $derived(
41
- config.metadata.check_session_iframe ?? config.checkSessionIframe ?? undefined
42
- );
43
- const canMonitorIframe = $derived(
44
- Boolean(session?.isAuthenticated && session?.sessionState && iframeUrl)
45
- );
46
-
47
- const context = setOIDCContext({
48
- get isAuthenticated() {
49
- return Boolean(session?.isAuthenticated);
50
- },
51
- get session() {
52
- return session;
53
- },
54
- get user() {
55
- return session?.user;
56
- },
57
- get claims() {
58
- return session?.claims;
59
- },
60
- get groups() {
61
- return session?.groups ?? [];
62
- },
63
- get metadata() {
64
- return metadata;
65
- },
66
- get status() {
67
- return status;
68
- },
69
- login: (returnTo?: string) => login(returnTo),
70
- logout,
71
- revalidate
72
- });
73
-
74
- void context;
75
-
76
- function buildLoginUrl(returnTo = `${window.location.pathname}${window.location.search}`) {
77
- return `${resolvedLoginPath}?returnTo=${encodeURIComponent(returnTo)}`;
78
- }
79
-
80
- async function logout(clearSessionOnly = false) {
81
- const body = new URLSearchParams();
82
- if (clearSessionOnly) {
83
- body.set('clearSessionOnly', '1');
84
- }
85
-
86
- await fetch(logoutPath, {
87
- method: 'POST',
88
- headers: {
89
- 'content-type': 'application/x-www-form-urlencoded'
90
- },
91
- body
92
- });
93
- }
94
-
95
- function login(returnTo?: string) {
96
- void goto(buildLoginUrl(returnTo), { invalidateAll: false });
97
- }
98
-
99
- async function revalidate() {
100
- await invalidateAll();
101
- }
102
-
103
- async function handleRedirect(mode: RedirectMode) {
104
- if (mode === 'none') {
105
- return;
106
- }
107
- if (mode === 'reload') {
108
- window.location.reload();
109
- return;
110
- }
111
- if (mode === 'logout') {
112
- await logout(true);
113
- window.location.reload();
114
- return;
115
- }
116
-
117
- login();
118
- }
119
-
120
- $effect(() => {
121
- const isAuthenticated = Boolean(session?.isAuthenticated);
122
- status = isAuthenticated ? 'authenticated' : status === 'authenticated' ? 'unauthenticated' : status;
123
- });
124
-
125
- $effect(() => {
126
- if (!session?.isAuthenticated || !session.expiresAt) {
127
- return;
128
- }
129
-
130
- const timeoutMs = Math.max(0, session.expiresAt * 1000 - Date.now());
131
- const timer = window.setTimeout(() => {
132
- status = 'expired';
133
- void handleRedirect(redirectOnExpired);
134
- }, timeoutMs);
135
-
136
- return () => window.clearTimeout(timer);
137
- });
138
-
139
- $effect(() => {
140
- if (!session?.isAuthenticated || !revalidateIntervalMs) {
141
- return;
142
- }
143
-
144
- const timer = window.setInterval(() => {
145
- void revalidate();
146
- }, revalidateIntervalMs);
147
-
148
- return () => window.clearInterval(timer);
149
- });
150
-
151
- $effect(() => {
152
- if (session?.isAuthenticated) {
153
- handledUnauthenticated = false;
154
- return;
155
- }
156
- if (!redirectIfUnauthenticated || handledUnauthenticated) {
157
- return;
158
- }
159
-
160
- handledUnauthenticated = true;
161
- status = status === 'expired' || status === 'revoked' ? status : 'unauthenticated';
162
- void handleRedirect(status === 'revoked' ? redirectOnRevoked : redirectOnExpired);
163
- });
164
-
165
- $effect(() => {
166
- if (!canMonitorIframe || !iframeUrl || !iframe) {
167
- return;
168
- }
169
-
170
- const targetOrigin = new URL(iframeUrl).origin;
171
- const poll = window.setInterval(() => {
172
- if (!iframe?.contentWindow || !session?.sessionState) {
173
- return;
174
- }
175
-
176
- iframe.contentWindow.postMessage(`${config.clientId} ${session.sessionState}`, targetOrigin);
177
- }, checkSessionIntervalMs);
178
-
179
- const onMessage = (event: MessageEvent) => {
180
- if (event.origin !== targetOrigin || typeof event.data !== 'string') {
181
- return;
182
- }
183
- if (event.data === 'changed' || event.data === 'error') {
184
- status = 'revoked';
185
- void logout(true).then(() => handleRedirect(redirectOnRevoked));
186
- }
187
- };
188
-
189
- window.addEventListener('message', onMessage);
190
-
191
- return () => {
192
- window.clearInterval(poll);
193
- window.removeEventListener('message', onMessage);
194
- };
195
- });
1
+ <script lang="ts" module>
2
+ import type {
3
+ OIDCPublicSession,
4
+ OIDCSessionManagementConfig, OIDCUserClaims
5
+ } from '../server/index.js';
6
+ </script>
7
+
8
+ <script lang="ts" generics="TClaims extends OIDCUserClaims = OIDCUserClaims">
9
+ import {goto, invalidateAll} from '$app/navigation';
10
+ import type {Snippet} from 'svelte';
11
+
12
+ import {setOIDCContext} from './context.js';
13
+
14
+ type RedirectMode = 'login' | 'logout' | 'reload' | 'none';
15
+
16
+ let {
17
+ session = null,
18
+ config,
19
+ loginPath,
20
+ logoutPath = '/auth/logout',
21
+ checkSessionIntervalMs = 5000,
22
+ revalidateIntervalMs = 30000,
23
+ redirectOnExpired = 'login',
24
+ redirectOnRevoked = 'login',
25
+ redirectIfUnauthenticated = false,
26
+ children
27
+ }: {
28
+ session?: OIDCPublicSession<TClaims> | null;
29
+ config: OIDCSessionManagementConfig;
30
+ loginPath?: string;
31
+ logoutPath?: string;
32
+ checkSessionIntervalMs?: number;
33
+ revalidateIntervalMs?: number;
34
+ redirectOnExpired?: RedirectMode;
35
+ redirectOnRevoked?: RedirectMode;
36
+ redirectIfUnauthenticated?: boolean;
37
+ children?: Snippet;
38
+ } = $props();
39
+
40
+ let iframe = $state<HTMLIFrameElement | undefined>(undefined);
41
+ let status = $state<'authenticated' | 'unauthenticated' | 'expired' | 'revoked'>('unauthenticated');
42
+ let handledUnauthenticated = $state(false);
43
+
44
+ const metadata = $derived(config.metadata);
45
+ const resolvedLoginPath = $derived(loginPath ?? config.loginPath ?? '/auth/login');
46
+ const iframeUrl = $derived(
47
+ config.metadata.check_session_iframe ?? config.checkSessionIframe ?? undefined
48
+ );
49
+ const canMonitorIframe = $derived(
50
+ Boolean(session?.isAuthenticated && session?.sessionState && iframeUrl)
51
+ );
52
+
53
+ const context = setOIDCContext<TClaims>({
54
+ get isAuthenticated() {
55
+ return Boolean(session?.isAuthenticated);
56
+ },
57
+ get session() {
58
+ return session;
59
+ },
60
+ get user() {
61
+ return session?.user;
62
+ },
63
+ get claims() {
64
+ return session?.claims;
65
+ },
66
+ get groups() {
67
+ return session?.groups ?? [];
68
+ },
69
+ get metadata() {
70
+ return metadata;
71
+ },
72
+ get status() {
73
+ return status;
74
+ },
75
+ login: (returnTo?: string) => login(returnTo),
76
+ logout,
77
+ revalidate
78
+ });
79
+
80
+ void context;
81
+
82
+ function buildLoginUrl(returnTo = `${window.location.pathname}${window.location.search}`) {
83
+ return `${resolvedLoginPath}?returnTo=${encodeURIComponent(returnTo)}`;
84
+ }
85
+
86
+ async function logout(clearSessionOnly = false) {
87
+ const body = new URLSearchParams();
88
+ if (clearSessionOnly) {
89
+ body.set('clearSessionOnly', '1');
90
+ }
91
+
92
+ await fetch(logoutPath, {
93
+ method: 'POST',
94
+ headers: {
95
+ 'content-type': 'application/x-www-form-urlencoded'
96
+ },
97
+ body
98
+ });
99
+ }
100
+
101
+ function login(returnTo?: string) {
102
+ void goto(buildLoginUrl(returnTo), {invalidateAll: false});
103
+ }
104
+
105
+ async function revalidate() {
106
+ await invalidateAll();
107
+ }
108
+
109
+ async function handleRedirect(mode: RedirectMode) {
110
+ if (mode === 'none') {
111
+ return;
112
+ }
113
+ if (mode === 'reload') {
114
+ window.location.reload();
115
+ return;
116
+ }
117
+ if (mode === 'logout') {
118
+ await logout(true);
119
+ window.location.reload();
120
+ return;
121
+ }
122
+
123
+ login();
124
+ }
125
+
126
+ $effect(() => {
127
+ const isAuthenticated = Boolean(session?.isAuthenticated);
128
+ status = isAuthenticated ? 'authenticated' : status === 'authenticated' ? 'unauthenticated' : status;
129
+ });
130
+
131
+ $effect(() => {
132
+ if (!session?.isAuthenticated || !session.expiresAt) {
133
+ return;
134
+ }
135
+
136
+ const timeoutMs = Math.max(0, session.expiresAt * 1000 - Date.now());
137
+ const timer = window.setTimeout(() => {
138
+ status = 'expired';
139
+ void handleRedirect(redirectOnExpired);
140
+ }, timeoutMs);
141
+
142
+ return () => window.clearTimeout(timer);
143
+ });
144
+
145
+ $effect(() => {
146
+ if (!session?.isAuthenticated || !revalidateIntervalMs) {
147
+ return;
148
+ }
149
+
150
+ const timer = window.setInterval(() => {
151
+ void revalidate();
152
+ }, revalidateIntervalMs);
153
+
154
+ return () => window.clearInterval(timer);
155
+ });
156
+
157
+ $effect(() => {
158
+ if (session?.isAuthenticated) {
159
+ handledUnauthenticated = false;
160
+ return;
161
+ }
162
+ if (!redirectIfUnauthenticated || handledUnauthenticated) {
163
+ return;
164
+ }
165
+
166
+ handledUnauthenticated = true;
167
+ status = status === 'expired' || status === 'revoked' ? status : 'unauthenticated';
168
+ void handleRedirect(status === 'revoked' ? redirectOnRevoked : redirectOnExpired);
169
+ });
170
+
171
+ $effect(() => {
172
+ if (!canMonitorIframe || !iframeUrl || !iframe) {
173
+ return;
174
+ }
175
+
176
+ const targetOrigin = new URL(iframeUrl).origin;
177
+ const poll = window.setInterval(() => {
178
+ if (!iframe?.contentWindow || !session?.sessionState) {
179
+ return;
180
+ }
181
+
182
+ iframe.contentWindow.postMessage(`${config.clientId} ${session.sessionState}`, targetOrigin);
183
+ }, checkSessionIntervalMs);
184
+
185
+ const onMessage = (event: MessageEvent) => {
186
+ if (event.origin !== targetOrigin || typeof event.data !== 'string') {
187
+ return;
188
+ }
189
+ if (event.data === 'changed' || event.data === 'error') {
190
+ status = 'revoked';
191
+ void logout(true).then(() => handleRedirect(redirectOnRevoked));
192
+ }
193
+ };
194
+
195
+ window.addEventListener('message', onMessage);
196
+
197
+ return () => {
198
+ window.clearInterval(poll);
199
+ window.removeEventListener('message', onMessage);
200
+ };
201
+ });
196
202
  </script>
197
203
 
198
204
  {#if canMonitorIframe && iframeUrl}
199
- <iframe
200
- bind:this={iframe}
201
- title="OIDC session monitor"
202
- src={iframeUrl}
203
- hidden
204
- aria-hidden="true"
205
- ></iframe>
205
+ <iframe
206
+ bind:this={iframe}
207
+ title="OIDC session monitor"
208
+ src={iframeUrl}
209
+ hidden
210
+ aria-hidden="true"
211
+ ></iframe>
206
212
  {/if}
207
213
 
208
214
  {@render children?.()}
@@ -1,18 +1,37 @@
1
+ import type { OIDCPublicSession, OIDCSessionManagementConfig, OIDCUserClaims } from '../server/index.js';
1
2
  import type { Snippet } from 'svelte';
2
- import type { OIDCPublicSession, OIDCSessionManagementConfig } from '../server/index.js';
3
- type RedirectMode = 'login' | 'logout' | 'reload' | 'none';
4
- type $$ComponentProps = {
5
- session?: OIDCPublicSession | null;
6
- config: OIDCSessionManagementConfig;
7
- loginPath?: string;
8
- logoutPath?: string;
9
- checkSessionIntervalMs?: number;
10
- revalidateIntervalMs?: number;
11
- redirectOnExpired?: RedirectMode;
12
- redirectOnRevoked?: RedirectMode;
13
- redirectIfUnauthenticated?: boolean;
14
- children?: Snippet;
3
+ declare function $$render<TClaims extends OIDCUserClaims = OIDCUserClaims>(): {
4
+ props: {
5
+ session?: OIDCPublicSession<TClaims> | null;
6
+ config: OIDCSessionManagementConfig;
7
+ loginPath?: string;
8
+ logoutPath?: string;
9
+ checkSessionIntervalMs?: number;
10
+ revalidateIntervalMs?: number;
11
+ redirectOnExpired?: "none" | "login" | "logout" | "reload";
12
+ redirectOnRevoked?: "none" | "login" | "logout" | "reload";
13
+ redirectIfUnauthenticated?: boolean;
14
+ children?: Snippet;
15
+ };
16
+ exports: {};
17
+ bindings: "";
18
+ slots: {};
19
+ events: {};
15
20
  };
16
- declare const OIDCContext: import("svelte").Component<$$ComponentProps, {}, "">;
17
- type OIDCContext = ReturnType<typeof OIDCContext>;
21
+ declare class __sveltets_Render<TClaims extends OIDCUserClaims = OIDCUserClaims> {
22
+ props(): ReturnType<typeof $$render<TClaims>>['props'];
23
+ events(): ReturnType<typeof $$render<TClaims>>['events'];
24
+ slots(): ReturnType<typeof $$render<TClaims>>['slots'];
25
+ bindings(): "";
26
+ exports(): {};
27
+ }
28
+ interface $$IsomorphicComponent {
29
+ new <TClaims extends OIDCUserClaims = OIDCUserClaims>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<TClaims>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<TClaims>['props']>, ReturnType<__sveltets_Render<TClaims>['events']>, ReturnType<__sveltets_Render<TClaims>['slots']>> & {
30
+ $$bindings?: ReturnType<__sveltets_Render<TClaims>['bindings']>;
31
+ } & ReturnType<__sveltets_Render<TClaims>['exports']>;
32
+ <TClaims extends OIDCUserClaims = OIDCUserClaims>(internal: unknown, props: ReturnType<__sveltets_Render<TClaims>['props']> & {}): ReturnType<__sveltets_Render<TClaims>['exports']>;
33
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
34
+ }
35
+ declare const OIDCContext: $$IsomorphicComponent;
36
+ type OIDCContext<TClaims extends OIDCUserClaims = OIDCUserClaims> = InstanceType<typeof OIDCContext<TClaims>>;
18
37
  export default OIDCContext;
@@ -1,16 +1,16 @@
1
- import type { OIDCDiscoveryDocument, OIDCPublicSession } from '../server/index.js';
2
- export type OIDCClientContextValue = {
1
+ import type { OIDCDiscoveryDocument, OIDCPublicSession, OIDCUserClaims } from '../server/index.js';
2
+ export type OIDCClientContextValue<TClaims extends OIDCUserClaims = OIDCUserClaims> = {
3
3
  isAuthenticated: boolean;
4
- session: OIDCPublicSession | null;
5
- user: OIDCPublicSession['user'];
6
- claims: OIDCPublicSession['claims'];
7
- groups: OIDCPublicSession['groups'];
4
+ session: OIDCPublicSession<TClaims> | null;
5
+ user: OIDCPublicSession<TClaims>['user'];
6
+ claims: OIDCPublicSession<TClaims>['claims'];
7
+ groups: OIDCPublicSession<TClaims>['groups'];
8
8
  metadata?: Pick<OIDCDiscoveryDocument, 'issuer' | 'check_session_iframe' | 'end_session_endpoint' | 'backchannel_logout_supported' | 'backchannel_logout_session_supported'>;
9
9
  status: 'authenticated' | 'unauthenticated' | 'expired' | 'revoked';
10
10
  login: (returnTo?: string) => void;
11
11
  logout: (clearSessionOnly?: boolean) => Promise<void>;
12
12
  revalidate: () => Promise<void>;
13
13
  };
14
- export declare function setOIDCContext(value: OIDCClientContextValue): OIDCClientContextValue;
15
- export declare function getOIDCContext(): OIDCClientContextValue;
16
- export declare function useOIDC(): OIDCClientContextValue;
14
+ export declare function setOIDCContext<TClaims extends OIDCUserClaims = OIDCUserClaims>(value: OIDCClientContextValue<TClaims>): OIDCClientContextValue<TClaims>;
15
+ export declare function getOIDCContext<TClaims extends OIDCUserClaims = OIDCUserClaims>(): OIDCClientContextValue<TClaims>;
16
+ export declare function useOIDC<TClaims extends OIDCUserClaims = OIDCUserClaims>(): OIDCClientContextValue<TClaims>;
@@ -1,2 +1,2 @@
1
- import type { CookieOptions, OIDCCookies } from './types.js';
2
- export declare function createOIDCCookieStore(cookieSecret: string, sessionCookieName: string, stateCookieName: string, cookieOptions: CookieOptions): OIDCCookies;
1
+ import type { CookieOptions, OIDCCookies, OIDCSession, OIDCUserClaims } from './types.js';
2
+ export declare function createOIDCCookieStore<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>>(cookieSecret: string, sessionCookieName: string, stateCookieName: string, cookieOptions: CookieOptions): OIDCCookies<TClaims, TSession>;
@@ -1,5 +1,5 @@
1
- import type { OIDCOptions, OIDCInstance } from './types.js';
1
+ import type { OIDCOptions, OIDCInstance, OIDCSession, OIDCUserClaims } from './types.js';
2
2
  export type * from './types.js';
3
3
  export { createInMemoryBackChannelLogoutStore, createInMemorySessionStore } from './store.js';
4
- export declare function createOIDC(options: OIDCOptions): OIDCInstance;
4
+ export declare function createOIDC<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>>(options: OIDCOptions<TClaims, TSession>): OIDCInstance<TClaims, TSession>;
5
5
  export declare const OpenIDConnect: typeof createOIDC;
@@ -199,7 +199,9 @@ export function createOIDC(options) {
199
199
  algorithms: metadata.id_token_signing_alg_values_supported,
200
200
  clockSkew: clockSkewSeconds
201
201
  });
202
- const transformedClaims = options.transformClaims ? await options.transformClaims(claims) : claims;
202
+ const transformedClaims = options.transformClaims
203
+ ? await options.transformClaims(claims)
204
+ : claims;
203
205
  if (transformedClaims.nonce !== nonce) {
204
206
  throw error(401, { message: 'Invalid id_token nonce' });
205
207
  }
@@ -258,7 +260,9 @@ export function createOIDC(options) {
258
260
  ? await validateIdToken(tokenResponse.id_token, session.nonce)
259
261
  : session.claims;
260
262
  const rawUser = options.fetchUserInfo !== false ? await fetchUserInfo(tokenResponse.access_token) : session.user;
261
- const user = options.transformUser ? await options.transformUser(rawUser, { claims }) : rawUser;
263
+ const user = options.transformUser
264
+ ? await options.transformUser(rawUser, { claims })
265
+ : rawUser;
262
266
  const nextSession = {
263
267
  ...session,
264
268
  sub: claims?.sub ?? session.sub,
@@ -347,7 +351,9 @@ export function createOIDC(options) {
347
351
  const rawUser = options.fetchUserInfo === false
348
352
  ? undefined
349
353
  : await fetchUserInfo(tokenResponse.access_token).catch(() => undefined);
350
- const user = options.transformUser ? await options.transformUser(rawUser, { claims }) : rawUser;
354
+ const user = options.transformUser
355
+ ? await options.transformUser(rawUser, { claims })
356
+ : rawUser;
351
357
  const metadata = await getMetadata();
352
358
  const now = Math.floor(Date.now() / 1000);
353
359
  const session = {
@@ -1,3 +1,3 @@
1
- import type { OIDCSession, OIDCSessionTokens, OIDCTokenResponse } from './types.js';
1
+ import type { OIDCSession, OIDCSessionTokens, OIDCTokenResponse, OIDCUserClaims } from './types.js';
2
2
  export declare function normalizeTokens(tokenResponse: OIDCTokenResponse, defaultScope: string[], existing?: OIDCSessionTokens, now?: number): OIDCSessionTokens;
3
- export declare function shouldRefresh(session: OIDCSession, refreshToleranceSeconds: number, now?: number): boolean;
3
+ export declare function shouldRefresh<TClaims extends OIDCUserClaims = OIDCUserClaims>(session: OIDCSession<TClaims>, refreshToleranceSeconds: number, now?: number): boolean;
@@ -1,3 +1,3 @@
1
- import type { OIDCBackChannelLogoutStore, OIDCSessionStore } from './types.js';
2
- export declare function createInMemoryBackChannelLogoutStore(): OIDCBackChannelLogoutStore;
3
- export declare function createInMemorySessionStore(): OIDCSessionStore;
1
+ import type { OIDCBackChannelLogoutStore, OIDCSession, OIDCSessionStore, OIDCUserClaims } from './types.js';
2
+ export declare function createInMemoryBackChannelLogoutStore<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>>(): OIDCBackChannelLogoutStore<TClaims, TSession>;
3
+ export declare function createInMemorySessionStore<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>>(): OIDCSessionStore<TClaims, TSession>;
@@ -56,7 +56,7 @@ export type OIDCUserClaims = Record<string, unknown> & {
56
56
  nbf?: number;
57
57
  nonce?: string;
58
58
  };
59
- export type OIDCSession = {
59
+ export type OIDCSession<TClaims extends OIDCUserClaims = OIDCUserClaims> = {
60
60
  issuer: string;
61
61
  clientId: string;
62
62
  nonce?: string;
@@ -64,16 +64,16 @@ export type OIDCSession = {
64
64
  sid?: string;
65
65
  sessionState?: string;
66
66
  groups: string[];
67
- user?: OIDCUserClaims;
68
- claims?: OIDCUserClaims;
67
+ user?: TClaims;
68
+ claims?: TClaims;
69
69
  tokens: OIDCSessionTokens;
70
70
  createdAt: number;
71
71
  refreshedAt: number;
72
72
  };
73
- export type OIDCPublicSession = {
73
+ export type OIDCPublicSession<TClaims extends OIDCUserClaims = OIDCUserClaims> = {
74
74
  isAuthenticated: boolean;
75
- user?: OIDCUserClaims;
76
- claims?: OIDCUserClaims;
75
+ user?: TClaims;
76
+ claims?: TClaims;
77
77
  groups: string[];
78
78
  scope: string[];
79
79
  expiresAt?: number;
@@ -114,13 +114,13 @@ export type OIDCBackChannelLogoutRecord = {
114
114
  jti: string;
115
115
  iat: number;
116
116
  };
117
- export type OIDCBackChannelLogoutStore = {
117
+ export type OIDCBackChannelLogoutStore<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
118
118
  revoke(record: OIDCBackChannelLogoutRecord): MaybePromise<void>;
119
- isRevoked(session: OIDCSession): MaybePromise<boolean>;
119
+ isRevoked(session: TSession): MaybePromise<boolean>;
120
120
  };
121
- export type OIDCSessionStore = {
122
- get(sessionId: string): MaybePromise<OIDCSession | null>;
123
- set(sessionId: string, session: OIDCSession): MaybePromise<void>;
121
+ export type OIDCSessionStore<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
122
+ get(sessionId: string): MaybePromise<TSession | null>;
123
+ set(sessionId: string, session: TSession): MaybePromise<void>;
124
124
  delete(sessionId: string): MaybePromise<void>;
125
125
  };
126
126
  export type OIDCSessionManagementConfig = {
@@ -133,7 +133,7 @@ export type OIDCSessionManagementConfig = {
133
133
  backChannelLogoutSupported: boolean;
134
134
  backChannelLogoutSessionSupported: boolean;
135
135
  };
136
- export type OIDCOptions = {
136
+ export type OIDCOptions<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
137
137
  issuer?: string;
138
138
  discoveryUrl?: string;
139
139
  clientId: string;
@@ -155,19 +155,19 @@ export type OIDCOptions = {
155
155
  refreshToleranceSeconds?: number;
156
156
  defaultLoginRedirect?: string;
157
157
  defaultLogoutRedirect?: string;
158
- sessionStore?: OIDCSessionStore;
159
- backChannelLogoutStore?: OIDCBackChannelLogoutStore;
160
- transformClaims?: (claims: OIDCUserClaims) => MaybePromise<OIDCUserClaims>;
158
+ sessionStore?: OIDCSessionStore<TClaims, TSession>;
159
+ backChannelLogoutStore?: OIDCBackChannelLogoutStore<TClaims, TSession>;
160
+ transformClaims?: (claims: OIDCUserClaims) => MaybePromise<TClaims>;
161
161
  transformUser?: (user: OIDCUserClaims | undefined, context: {
162
- claims?: OIDCUserClaims;
163
- }) => MaybePromise<OIDCUserClaims | undefined>;
164
- transformSession?: (session: OIDCSession, context: {
162
+ claims?: TClaims;
163
+ }) => MaybePromise<TClaims | undefined>;
164
+ transformSession?: (session: OIDCSession<TClaims>, context: {
165
165
  event?: RequestEvent;
166
166
  tokenResponse?: OIDCTokenResponse;
167
- claims?: OIDCUserClaims;
168
- user?: OIDCUserClaims;
167
+ claims?: TClaims;
168
+ user?: TClaims;
169
169
  isRefresh: boolean;
170
- }) => MaybePromise<OIDCSession>;
170
+ }) => MaybePromise<TSession>;
171
171
  endpoints?: Partial<OIDCDiscoveryDocument>;
172
172
  };
173
173
  export type OIDCLoginOptions = {
@@ -181,16 +181,16 @@ export type OIDCLogoutOptions = {
181
181
  state?: string;
182
182
  clearSessionOnly?: boolean;
183
183
  };
184
- export type OIDCCallbackResult = {
185
- session: OIDCSession;
184
+ export type OIDCCallbackResult<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
185
+ session: TSession;
186
186
  returnTo: string;
187
187
  };
188
- export type OIDCHandleLocals = {
188
+ export type OIDCHandleLocals<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
189
189
  isAuthenticated: boolean;
190
- session: OIDCSession | null;
191
- user?: OIDCUserClaims;
192
- claims?: OIDCUserClaims;
193
- requireAuth: () => Promise<OIDCSession>;
190
+ session: TSession | null;
191
+ user?: TClaims;
192
+ claims?: TClaims;
193
+ requireAuth: () => Promise<TSession>;
194
194
  clearSession: () => Promise<void>;
195
195
  };
196
196
  export type OIDCStateCookie = {
@@ -200,8 +200,8 @@ export type OIDCStateCookie = {
200
200
  returnTo: string;
201
201
  createdAt: number;
202
202
  };
203
- export type OIDCCallbackHandlerOptions = {
204
- onsuccess?: (event: RequestEvent, result: OIDCCallbackResult) => MaybePromise<Response | void>;
203
+ export type OIDCCallbackHandlerOptions<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
204
+ onsuccess?: (event: RequestEvent, result: OIDCCallbackResult<TClaims, TSession>) => MaybePromise<Response | void>;
205
205
  onfailure?: (event: RequestEvent, err: unknown) => MaybePromise<Response | void>;
206
206
  redirectTo?: string;
207
207
  };
@@ -214,9 +214,9 @@ export type OIDCClientAssertionOptions = {
214
214
  clientId: string;
215
215
  clientSecret?: string;
216
216
  };
217
- export type OIDCCookies = {
218
- readSession(cookies: Cookies): OIDCSession | null;
219
- writeSession(cookies: Cookies, session: OIDCSession): void;
217
+ export type OIDCCookies<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
218
+ readSession(cookies: Cookies): TSession | null;
219
+ writeSession(cookies: Cookies, session: TSession): void;
220
220
  clearSession(cookies: Cookies): void;
221
221
  readSessionReference(cookies: Cookies): {
222
222
  id: string;
@@ -229,28 +229,30 @@ export type OIDCCookies = {
229
229
  writeState(cookies: Cookies, state: OIDCStateCookie): void;
230
230
  clearState(cookies: Cookies): void;
231
231
  };
232
- export type OIDCPersistedSession = {
232
+ export type OIDCPersistedSession<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
233
233
  id?: string;
234
- session: OIDCSession;
234
+ session: TSession;
235
235
  };
236
- export type OIDCInstance = {
236
+ export type OIDCInstance<TClaims extends OIDCUserClaims = OIDCUserClaims, TSession extends OIDCSession<TClaims> = OIDCSession<TClaims>> = {
237
237
  handle: Handle;
238
238
  getMetadata: () => Promise<OIDCDiscoveryDocument>;
239
- getSession: (event: RequestEvent) => Promise<OIDCSession | null>;
240
- getPublicSession: (event: RequestEvent) => Promise<OIDCPublicSession | null>;
239
+ getSession: (event: RequestEvent) => Promise<TSession | null>;
240
+ getPublicSession: (event: RequestEvent) => Promise<OIDCPublicSession<TClaims> | null>;
241
241
  getSessionManagementConfig: () => Promise<OIDCSessionManagementConfig>;
242
242
  login: (event: RequestEvent, loginOptions?: OIDCLoginOptions) => Promise<never>;
243
243
  logout: (event: RequestEvent, logoutOptions?: OIDCLogoutOptions) => Promise<never>;
244
- handleCallback: (event: RequestEvent) => Promise<OIDCCallbackResult>;
244
+ handleCallback: (event: RequestEvent) => Promise<OIDCCallbackResult<TClaims, TSession>>;
245
245
  handleBackChannelLogout: (event: RequestEvent) => Promise<Response>;
246
246
  loginHandler: (defaults?: OIDCLoginOptions) => RequestHandler;
247
- callbackHandler: (handlerOptions?: OIDCCallbackHandlerOptions) => RequestHandler;
247
+ callbackHandler: (handlerOptions?: OIDCCallbackHandlerOptions<TClaims, TSession>) => RequestHandler;
248
248
  logoutHandler: (defaults?: OIDCLogoutOptions) => RequestHandler;
249
249
  backChannelLogoutHandler: () => RequestHandler;
250
250
  createActions: (actionOptions?: OIDCActionOptions) => Readonly<{
251
251
  login: Action;
252
252
  logout: Action;
253
253
  }>;
254
- requireAuth: (event: RequestEvent, returnTo?: string) => Promise<OIDCSession>;
254
+ requireAuth: (event: RequestEvent, returnTo?: string) => Promise<TSession>;
255
255
  clearSession: (cookies: Cookies) => Promise<void>;
256
256
  };
257
+ export type OIDCInferClaims<T> = T extends OIDCInstance<infer TClaims> ? TClaims : OIDCUserClaims;
258
+ export type OIDCInferSession<T> = T extends OIDCInstance<infer _TClaims, infer TSession> ? TSession : OIDCSession<OIDCUserClaims>;
@@ -8,7 +8,7 @@ export declare function createPKCEPair(length?: number): {
8
8
  export declare function normalizeIssuer(issuer: string): string;
9
9
  export declare function normalizeScope(scope?: string[]): string[];
10
10
  export declare function normalizeStringArray(value: unknown): string[];
11
- export declare function collectGroups(...sources: Array<OIDCUserClaims | undefined>): string[];
11
+ export declare function collectGroups<TClaims extends OIDCUserClaims = OIDCUserClaims>(...sources: Array<TClaims | undefined>): string[];
12
12
  export declare function createSignedValue(value: string, secret: string): string;
13
13
  export declare function verifySignedValue(value: string, secret: string): string | null;
14
14
  export declare function serializeSignedCookie(payload: unknown, secret: string): string;
@@ -16,4 +16,4 @@ export declare function parseSignedCookie<T>(value: string | undefined, secret:
16
16
  export declare function buildCookieOptions(options?: Partial<CookieOptions>): CookieOptions;
17
17
  export declare function parseProviderError(event: RequestEvent): null;
18
18
  export declare function absoluteUrl(event: RequestEvent, pathOrUrl: string): string;
19
- export declare function toPublicSession(session: OIDCSession | null): OIDCPublicSession | null;
19
+ export declare function toPublicSession<TClaims extends OIDCUserClaims = OIDCUserClaims>(session: OIDCSession<TClaims> | null): OIDCPublicSession<TClaims> | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourceregistry/sveltekit-oidc",
3
- "version": "1.1.1",
3
+ "version": "1.3.0",
4
4
  "description": "OIDC authentication helpers for SvelteKit applications.",
5
5
  "license": "Apache-2.0",
6
6
  "scripts": {
@@ -57,22 +57,22 @@
57
57
  "svelte": "^5.0.0"
58
58
  },
59
59
  "devDependencies": {
60
- "@sveltejs/adapter-auto": "^7.0.0",
61
- "@sveltejs/kit": "^2.50.2",
62
- "@sveltejs/package": "^2.5.7",
63
- "@sveltejs/vite-plugin-svelte": "^6.2.4",
64
- "@types/node": "^25.5.2",
60
+ "@sveltejs/adapter-auto": "^7.0.1",
61
+ "@sveltejs/kit": "^2.63.1",
62
+ "@sveltejs/package": "^2.5.8",
63
+ "@sveltejs/vite-plugin-svelte": "^7.1.2",
64
+ "@types/node": "^25.9.2",
65
65
  "@semantic-release/changelog": "^6.0.3",
66
66
  "@semantic-release/git": "^10.0.1",
67
- "publint": "^0.3.17",
68
- "svelte": "^5.54.0",
69
- "svelte-check": "^4.4.2",
70
- "typescript": "^5.9.3",
71
- "vite": "^7.3.1",
72
- "@vitest/coverage-v8": "^4.1.2",
73
- "vitest": "^4.1.2",
74
- "@sourceregistry/semantic-release-jsr": "^1.0.1",
75
- "typedoc": "^0.28.18"
67
+ "publint": "^0.3.21",
68
+ "svelte": "^5.56.3",
69
+ "svelte-check": "^4.6.0",
70
+ "typescript": "^6.0.3",
71
+ "vite": "^8.0.16",
72
+ "@vitest/coverage-v8": "^4.1.8",
73
+ "vitest": "^4.1.8",
74
+ "@sourceregistry/semantic-release-jsr": "^1.1.1",
75
+ "typedoc": "^0.28.19"
76
76
  },
77
77
  "keywords": [
78
78
  "sveltekit",
@@ -83,7 +83,7 @@
83
83
  "oauth"
84
84
  ],
85
85
  "dependencies": {
86
- "@sourceregistry/node-jwt": "^1.5.9"
86
+ "@sourceregistry/node-jwt": "^1.5.10"
87
87
  },
88
88
  "release": {
89
89
  "branches": [