@oxog/authkeeper 1.4.0 → 1.5.1
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 +18 -0
- package/README.md +72 -0
- package/dist/{auth-source-BaZ_-Fu7.d.cts → auth-source-CXqrhLDO.d.ts} +15 -2
- package/dist/{auth-source-Cm0R6C6I.d.ts → auth-source-rjMWiP1Q.d.cts} +15 -2
- package/dist/{chunk-KE7V52DI.js → chunk-7B77NZGY.js} +18 -8
- package/dist/chunk-7B77NZGY.js.map +1 -0
- package/dist/{chunk-CYCWWUCJ.js → chunk-DLCD3SBV.js} +2 -2
- package/dist/chunk-DLCD3SBV.js.map +1 -0
- package/dist/{chunk-KLT44YR2.cjs → chunk-LGZGECYE.cjs} +35 -8
- package/dist/chunk-LGZGECYE.cjs.map +1 -0
- package/dist/{chunk-SUGFPZ6O.js → chunk-UUQDRHGF.js} +33 -9
- package/dist/chunk-UUQDRHGF.js.map +1 -0
- package/dist/{chunk-EXV2RG6T.cjs → chunk-VVSZPARR.cjs} +28 -18
- package/dist/chunk-VVSZPARR.cjs.map +1 -0
- package/dist/{chunk-62XK5QLP.cjs → chunk-XGKVBZSF.cjs} +2 -2
- package/dist/chunk-XGKVBZSF.cjs.map +1 -0
- package/dist/{index-CuvfPscu.d.cts → index-C4pGS-TI.d.cts} +1 -1
- package/dist/{index-BF4j_buH.d.ts → index-CQwGO-Wk.d.ts} +1 -1
- package/dist/index.cjs +51 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -11
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -15
- package/dist/plugins/index.d.cts +2 -2
- package/dist/plugins/index.d.ts +2 -2
- package/dist/plugins/index.js +2 -2
- package/dist/react/index.cjs +92 -8
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +98 -4
- package/dist/react/index.d.ts +98 -4
- package/dist/react/index.js +87 -7
- package/dist/react/index.js.map +1 -1
- package/dist/svelte/index.cjs +25 -9
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.d.cts +40 -9
- package/dist/svelte/index.d.ts +40 -9
- package/dist/svelte/index.js +24 -10
- package/dist/svelte/index.js.map +1 -1
- package/dist/{types-Bmo8S8O4.d.cts → types-DMPBl-Ym.d.cts} +1 -1
- package/dist/{types-Bmo8S8O4.d.ts → types-DMPBl-Ym.d.ts} +1 -1
- package/dist/vue/index.cjs +36 -7
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +51 -3
- package/dist/vue/index.d.ts +51 -3
- package/dist/vue/index.js +35 -8
- package/dist/vue/index.js.map +1 -1
- package/package.json +8 -4
- package/dist/chunk-62XK5QLP.cjs.map +0 -1
- package/dist/chunk-CYCWWUCJ.js.map +0 -1
- package/dist/chunk-EXV2RG6T.cjs.map +0 -1
- package/dist/chunk-KE7V52DI.js.map +0 -1
- package/dist/chunk-KLT44YR2.cjs.map +0 -1
- package/dist/chunk-SUGFPZ6O.js.map +0 -1
package/dist/vue/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkXGKVBZSF_cjs = require('../chunk-XGKVBZSF.cjs');
|
|
4
|
+
var chunkLGZGECYE_cjs = require('../chunk-LGZGECYE.cjs');
|
|
5
5
|
var vue = require('vue');
|
|
6
6
|
|
|
7
7
|
var AUTH_KEY = /* @__PURE__ */ Symbol("authkeeper");
|
|
@@ -11,7 +11,10 @@ function provideAuth(auth) {
|
|
|
11
11
|
function injectAuth() {
|
|
12
12
|
const auth = vue.inject(AUTH_KEY, null);
|
|
13
13
|
if (!auth) {
|
|
14
|
-
throw new
|
|
14
|
+
throw new chunkXGKVBZSF_cjs.AuthError(
|
|
15
|
+
"CONFIG_ERROR",
|
|
16
|
+
"No AuthKeeper provided: call provideAuth(auth) in an ancestor"
|
|
17
|
+
);
|
|
15
18
|
}
|
|
16
19
|
return auth;
|
|
17
20
|
}
|
|
@@ -22,14 +25,18 @@ function authKeeperPlugin(auth) {
|
|
|
22
25
|
}
|
|
23
26
|
};
|
|
24
27
|
}
|
|
25
|
-
function
|
|
28
|
+
function useSnapshot(auth, read) {
|
|
26
29
|
const instance = auth ?? injectAuth();
|
|
27
|
-
const source =
|
|
28
|
-
const state = vue.shallowRef(source
|
|
30
|
+
const source = chunkLGZGECYE_cjs.createAuthSource(instance);
|
|
31
|
+
const state = vue.shallowRef(read(source));
|
|
29
32
|
const stop = source.subscribe(() => {
|
|
30
|
-
state.value = source
|
|
33
|
+
state.value = read(source);
|
|
31
34
|
});
|
|
32
35
|
if (vue.getCurrentScope()) vue.onScopeDispose(stop);
|
|
36
|
+
return { instance, state, stop };
|
|
37
|
+
}
|
|
38
|
+
function useAuth(auth) {
|
|
39
|
+
const { instance, state, stop } = useSnapshot(auth, (source) => source.getState());
|
|
33
40
|
return {
|
|
34
41
|
isAuthenticated: vue.computed(() => state.value.isAuthenticated),
|
|
35
42
|
accessToken: vue.computed(() => state.value.accessToken),
|
|
@@ -42,10 +49,32 @@ function useAuth(auth) {
|
|
|
42
49
|
stop
|
|
43
50
|
};
|
|
44
51
|
}
|
|
52
|
+
function useToken(auth) {
|
|
53
|
+
const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState());
|
|
54
|
+
return {
|
|
55
|
+
accessToken: vue.computed(() => state.value.accessToken),
|
|
56
|
+
refreshToken: vue.computed(() => state.value.refreshToken),
|
|
57
|
+
isExpired: vue.computed(() => state.value.isExpired),
|
|
58
|
+
expiresAt: vue.computed(() => state.value.expiresAt),
|
|
59
|
+
authFetch: instance.createFetch(),
|
|
60
|
+
stop
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function useUser(auth) {
|
|
64
|
+
const { state, stop } = useSnapshot(auth, (source) => source.getState().user);
|
|
65
|
+
return {
|
|
66
|
+
user: vue.computed(() => state.value),
|
|
67
|
+
claims: vue.computed(() => state.value ?? chunkLGZGECYE_cjs.NO_CLAIMS),
|
|
68
|
+
getClaim: (key) => chunkLGZGECYE_cjs.readClaim(state.value, key),
|
|
69
|
+
stop
|
|
70
|
+
};
|
|
71
|
+
}
|
|
45
72
|
|
|
46
73
|
exports.authKeeperPlugin = authKeeperPlugin;
|
|
47
74
|
exports.injectAuth = injectAuth;
|
|
48
75
|
exports.provideAuth = provideAuth;
|
|
49
76
|
exports.useAuth = useAuth;
|
|
77
|
+
exports.useToken = useToken;
|
|
78
|
+
exports.useUser = useUser;
|
|
50
79
|
//# sourceMappingURL=index.cjs.map
|
|
51
80
|
//# sourceMappingURL=index.cjs.map
|
package/dist/vue/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/vue/use-auth.ts"],"names":["provide","inject","AuthError","createAuthSource","shallowRef","getCurrentScope","onScopeDispose","computed"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/vue/use-auth.ts","../../src/adapters/vue/use-token.ts"],"names":["provide","inject","AuthError","createAuthSource","shallowRef","getCurrentScope","onScopeDispose","computed","NO_CLAIMS","readClaim"],"mappings":"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","file":"index.cjs","sourcesContent":["/**\n * Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable\n */\n\nimport {\n computed,\n getCurrentScope,\n inject,\n onScopeDispose,\n provide,\n shallowRef,\n type App,\n type ComputedRef,\n type InjectionKey,\n type ShallowRef,\n} from 'vue'\nimport {\n AuthError,\n type AuthKeeper,\n type LogoutOptions,\n type TokenPayload,\n type TokenSet,\n} from '../../types'\nimport { createAuthSource, type AuthSource } from '../auth-source'\n\nconst AUTH_KEY: InjectionKey<AuthKeeper> = Symbol('authkeeper')\n\n/**\n * Provide an AuthKeeper instance to the component's descendants\n * (call in `setup()`; for the whole app use `app.use(authKeeperPlugin(auth))`)\n */\nexport function provideAuth(auth: AuthKeeper): void {\n provide(AUTH_KEY, auth)\n}\n\n/**\n * The provided AuthKeeper instance (call in `setup()`)\n * @throws {AuthError} CONFIG_ERROR when none was provided\n */\nexport function injectAuth(): AuthKeeper {\n const auth = inject(AUTH_KEY, null)\n if (!auth) {\n throw new AuthError(\n 'CONFIG_ERROR',\n 'No AuthKeeper provided: call provideAuth(auth) in an ancestor',\n )\n }\n return auth\n}\n\n/**\n * Vue plugin: `app.use(authKeeperPlugin(auth))` provides the instance app-wide\n */\nexport function authKeeperPlugin(auth: AuthKeeper): { install(app: App): void } {\n return {\n install(app: App) {\n app.provide(AUTH_KEY, auth)\n },\n }\n}\n\n/**\n * A shallow ref of `read(source)`, updated while the calling component (or\n * effect scope) lives. It only triggers when the snapshot changes.\n * @internal\n */\nexport function useSnapshot<T>(\n auth: AuthKeeper | undefined,\n read: (source: AuthSource) => T,\n): { instance: AuthKeeper; state: Readonly<ShallowRef<T>>; stop: () => void } {\n const instance = auth ?? injectAuth()\n const source = createAuthSource(instance)\n const state = shallowRef(read(source))\n const stop = source.subscribe(() => {\n state.value = read(source)\n })\n if (getCurrentScope()) onScopeDispose(stop)\n return { instance, state, stop }\n}\n\n/**\n * useAuth() return value: read-only refs plus actions\n */\nexport interface UseAuthReturn {\n isAuthenticated: ComputedRef<boolean>\n accessToken: ComputedRef<string | null>\n user: ComputedRef<TokenPayload | null>\n expiresAt: ComputedRef<Date | null>\n error: ComputedRef<AuthError | null>\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive auth state. Updates after login, logout, refresh and error events\n * and when the access token expires; stops when the calling component (or\n * effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useAuth(auth?: AuthKeeper): UseAuthReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getState())\n return {\n isAuthenticated: computed(() => state.value.isAuthenticated),\n accessToken: computed(() => state.value.accessToken),\n user: computed(() => state.value.user),\n expiresAt: computed(() => state.value.expiresAt),\n error: computed(() => state.value.error),\n setTokens: (tokens) => instance.setTokens(tokens),\n logout: (options) => instance.logout(options),\n refresh: () => instance.refresh(),\n stop,\n }\n}\n","/**\n * Vue 3 bindings: the useToken() and useUser() composables\n */\n\nimport { computed, type ComputedRef } from 'vue'\nimport type { AuthFetch, AuthKeeper, TokenPayload } from '../../types'\nimport { NO_CLAIMS, readClaim } from '../auth-source'\nimport { useSnapshot } from './use-auth'\n\n/**\n * useToken() return value: read-only refs plus an authenticated fetch\n */\nexport interface UseTokenReturn {\n accessToken: ComputedRef<string | null>\n /** Null when none is stored (e.g. an httpOnly cookie) */\n refreshToken: ComputedRef<string | null>\n /** An access token is set but has expired */\n isExpired: ComputedRef<boolean>\n expiresAt: ComputedRef<Date | null>\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive tokens. Update when a token or the expiry changes (login, refresh,\n * logout, expiry); stop when the calling component (or effect scope) is\n * disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useToken(auth?: AuthKeeper): UseTokenReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState())\n return {\n accessToken: computed(() => state.value.accessToken),\n refreshToken: computed(() => state.value.refreshToken),\n isExpired: computed(() => state.value.isExpired),\n expiresAt: computed(() => state.value.expiresAt),\n authFetch: instance.createFetch(),\n stop,\n }\n}\n\n/**\n * useUser() return value\n */\nexport interface UseUserReturn {\n /** Decoded access token payload (null when signed out or for opaque tokens) */\n user: ComputedRef<TokenPayload | null>\n /** The payload's claims (empty when there is no user) */\n claims: ComputedRef<TokenPayload>\n /** One claim of the current payload (reactive inside computed / templates) */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive decoded access token payload. Updates when the access token\n * changes; stops when the calling component (or effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useUser(auth?: AuthKeeper): UseUserReturn {\n const { state, stop } = useSnapshot(auth, (source) => source.getState().user)\n return {\n user: computed(() => state.value),\n claims: computed(() => state.value ?? NO_CLAIMS),\n getClaim: (key) => readClaim(state.value, key),\n stop,\n }\n}\n"]}
|
package/dist/vue/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ComputedRef, App } from 'vue';
|
|
2
|
-
import { a as TokenPayload,
|
|
3
|
-
export { A as AuthState } from '../auth-source-
|
|
2
|
+
import { a as TokenPayload, c as AuthError, T as TokenSet, L as LogoutOptions, b as AuthKeeper, A as AuthFetch } from '../types-DMPBl-Ym.cjs';
|
|
3
|
+
export { A as AuthState } from '../auth-source-rjMWiP1Q.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable
|
|
@@ -46,4 +46,52 @@ interface UseAuthReturn {
|
|
|
46
46
|
*/
|
|
47
47
|
declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Vue 3 bindings: the useToken() and useUser() composables
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* useToken() return value: read-only refs plus an authenticated fetch
|
|
55
|
+
*/
|
|
56
|
+
interface UseTokenReturn {
|
|
57
|
+
accessToken: ComputedRef<string | null>;
|
|
58
|
+
/** Null when none is stored (e.g. an httpOnly cookie) */
|
|
59
|
+
refreshToken: ComputedRef<string | null>;
|
|
60
|
+
/** An access token is set but has expired */
|
|
61
|
+
isExpired: ComputedRef<boolean>;
|
|
62
|
+
expiresAt: ComputedRef<Date | null>;
|
|
63
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
64
|
+
authFetch: AuthFetch;
|
|
65
|
+
/** Stop updating (done automatically when the component / effect scope is disposed) */
|
|
66
|
+
stop: () => void;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reactive tokens. Update when a token or the expiry changes (login, refresh,
|
|
70
|
+
* logout, expiry); stop when the calling component (or effect scope) is
|
|
71
|
+
* disposed.
|
|
72
|
+
*
|
|
73
|
+
* @param auth - Instance to use (default: the provided one)
|
|
74
|
+
*/
|
|
75
|
+
declare function useToken(auth?: AuthKeeper): UseTokenReturn;
|
|
76
|
+
/**
|
|
77
|
+
* useUser() return value
|
|
78
|
+
*/
|
|
79
|
+
interface UseUserReturn {
|
|
80
|
+
/** Decoded access token payload (null when signed out or for opaque tokens) */
|
|
81
|
+
user: ComputedRef<TokenPayload | null>;
|
|
82
|
+
/** The payload's claims (empty when there is no user) */
|
|
83
|
+
claims: ComputedRef<TokenPayload>;
|
|
84
|
+
/** One claim of the current payload (reactive inside computed / templates) */
|
|
85
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
86
|
+
/** Stop updating (done automatically when the component / effect scope is disposed) */
|
|
87
|
+
stop: () => void;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Reactive decoded access token payload. Updates when the access token
|
|
91
|
+
* changes; stops when the calling component (or effect scope) is disposed.
|
|
92
|
+
*
|
|
93
|
+
* @param auth - Instance to use (default: the provided one)
|
|
94
|
+
*/
|
|
95
|
+
declare function useUser(auth?: AuthKeeper): UseUserReturn;
|
|
96
|
+
|
|
97
|
+
export { type UseAuthReturn, type UseTokenReturn, type UseUserReturn, authKeeperPlugin, injectAuth, provideAuth, useAuth, useToken, useUser };
|
package/dist/vue/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ComputedRef, App } from 'vue';
|
|
2
|
-
import { a as TokenPayload,
|
|
3
|
-
export { A as AuthState } from '../auth-source-
|
|
2
|
+
import { a as TokenPayload, c as AuthError, T as TokenSet, L as LogoutOptions, b as AuthKeeper, A as AuthFetch } from '../types-DMPBl-Ym.js';
|
|
3
|
+
export { A as AuthState } from '../auth-source-CXqrhLDO.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable
|
|
@@ -46,4 +46,52 @@ interface UseAuthReturn {
|
|
|
46
46
|
*/
|
|
47
47
|
declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Vue 3 bindings: the useToken() and useUser() composables
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* useToken() return value: read-only refs plus an authenticated fetch
|
|
55
|
+
*/
|
|
56
|
+
interface UseTokenReturn {
|
|
57
|
+
accessToken: ComputedRef<string | null>;
|
|
58
|
+
/** Null when none is stored (e.g. an httpOnly cookie) */
|
|
59
|
+
refreshToken: ComputedRef<string | null>;
|
|
60
|
+
/** An access token is set but has expired */
|
|
61
|
+
isExpired: ComputedRef<boolean>;
|
|
62
|
+
expiresAt: ComputedRef<Date | null>;
|
|
63
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
64
|
+
authFetch: AuthFetch;
|
|
65
|
+
/** Stop updating (done automatically when the component / effect scope is disposed) */
|
|
66
|
+
stop: () => void;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reactive tokens. Update when a token or the expiry changes (login, refresh,
|
|
70
|
+
* logout, expiry); stop when the calling component (or effect scope) is
|
|
71
|
+
* disposed.
|
|
72
|
+
*
|
|
73
|
+
* @param auth - Instance to use (default: the provided one)
|
|
74
|
+
*/
|
|
75
|
+
declare function useToken(auth?: AuthKeeper): UseTokenReturn;
|
|
76
|
+
/**
|
|
77
|
+
* useUser() return value
|
|
78
|
+
*/
|
|
79
|
+
interface UseUserReturn {
|
|
80
|
+
/** Decoded access token payload (null when signed out or for opaque tokens) */
|
|
81
|
+
user: ComputedRef<TokenPayload | null>;
|
|
82
|
+
/** The payload's claims (empty when there is no user) */
|
|
83
|
+
claims: ComputedRef<TokenPayload>;
|
|
84
|
+
/** One claim of the current payload (reactive inside computed / templates) */
|
|
85
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
86
|
+
/** Stop updating (done automatically when the component / effect scope is disposed) */
|
|
87
|
+
stop: () => void;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Reactive decoded access token payload. Updates when the access token
|
|
91
|
+
* changes; stops when the calling component (or effect scope) is disposed.
|
|
92
|
+
*
|
|
93
|
+
* @param auth - Instance to use (default: the provided one)
|
|
94
|
+
*/
|
|
95
|
+
declare function useUser(auth?: AuthKeeper): UseUserReturn;
|
|
96
|
+
|
|
97
|
+
export { type UseAuthReturn, type UseTokenReturn, type UseUserReturn, authKeeperPlugin, injectAuth, provideAuth, useAuth, useToken, useUser };
|
package/dist/vue/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { AuthError } from '../chunk-
|
|
2
|
-
import { createAuthSource } from '../chunk-
|
|
3
|
-
import { provide, inject, shallowRef, getCurrentScope, onScopeDispose
|
|
1
|
+
import { AuthError } from '../chunk-DLCD3SBV.js';
|
|
2
|
+
import { readClaim, NO_CLAIMS, createAuthSource } from '../chunk-UUQDRHGF.js';
|
|
3
|
+
import { provide, inject, computed, shallowRef, getCurrentScope, onScopeDispose } from 'vue';
|
|
4
4
|
|
|
5
5
|
var AUTH_KEY = /* @__PURE__ */ Symbol("authkeeper");
|
|
6
6
|
function provideAuth(auth) {
|
|
@@ -9,7 +9,10 @@ function provideAuth(auth) {
|
|
|
9
9
|
function injectAuth() {
|
|
10
10
|
const auth = inject(AUTH_KEY, null);
|
|
11
11
|
if (!auth) {
|
|
12
|
-
throw new AuthError(
|
|
12
|
+
throw new AuthError(
|
|
13
|
+
"CONFIG_ERROR",
|
|
14
|
+
"No AuthKeeper provided: call provideAuth(auth) in an ancestor"
|
|
15
|
+
);
|
|
13
16
|
}
|
|
14
17
|
return auth;
|
|
15
18
|
}
|
|
@@ -20,14 +23,18 @@ function authKeeperPlugin(auth) {
|
|
|
20
23
|
}
|
|
21
24
|
};
|
|
22
25
|
}
|
|
23
|
-
function
|
|
26
|
+
function useSnapshot(auth, read) {
|
|
24
27
|
const instance = auth ?? injectAuth();
|
|
25
28
|
const source = createAuthSource(instance);
|
|
26
|
-
const state = shallowRef(source
|
|
29
|
+
const state = shallowRef(read(source));
|
|
27
30
|
const stop = source.subscribe(() => {
|
|
28
|
-
state.value = source
|
|
31
|
+
state.value = read(source);
|
|
29
32
|
});
|
|
30
33
|
if (getCurrentScope()) onScopeDispose(stop);
|
|
34
|
+
return { instance, state, stop };
|
|
35
|
+
}
|
|
36
|
+
function useAuth(auth) {
|
|
37
|
+
const { instance, state, stop } = useSnapshot(auth, (source) => source.getState());
|
|
31
38
|
return {
|
|
32
39
|
isAuthenticated: computed(() => state.value.isAuthenticated),
|
|
33
40
|
accessToken: computed(() => state.value.accessToken),
|
|
@@ -40,7 +47,27 @@ function useAuth(auth) {
|
|
|
40
47
|
stop
|
|
41
48
|
};
|
|
42
49
|
}
|
|
50
|
+
function useToken(auth) {
|
|
51
|
+
const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState());
|
|
52
|
+
return {
|
|
53
|
+
accessToken: computed(() => state.value.accessToken),
|
|
54
|
+
refreshToken: computed(() => state.value.refreshToken),
|
|
55
|
+
isExpired: computed(() => state.value.isExpired),
|
|
56
|
+
expiresAt: computed(() => state.value.expiresAt),
|
|
57
|
+
authFetch: instance.createFetch(),
|
|
58
|
+
stop
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function useUser(auth) {
|
|
62
|
+
const { state, stop } = useSnapshot(auth, (source) => source.getState().user);
|
|
63
|
+
return {
|
|
64
|
+
user: computed(() => state.value),
|
|
65
|
+
claims: computed(() => state.value ?? NO_CLAIMS),
|
|
66
|
+
getClaim: (key) => readClaim(state.value, key),
|
|
67
|
+
stop
|
|
68
|
+
};
|
|
69
|
+
}
|
|
43
70
|
|
|
44
|
-
export { authKeeperPlugin, injectAuth, provideAuth, useAuth };
|
|
71
|
+
export { authKeeperPlugin, injectAuth, provideAuth, useAuth, useToken, useUser };
|
|
45
72
|
//# sourceMappingURL=index.js.map
|
|
46
73
|
//# sourceMappingURL=index.js.map
|
package/dist/vue/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/vue/use-auth.ts"],"names":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/vue/use-auth.ts","../../src/adapters/vue/use-token.ts"],"names":["computed"],"mappings":"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","file":"index.js","sourcesContent":["/**\n * Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable\n */\n\nimport {\n computed,\n getCurrentScope,\n inject,\n onScopeDispose,\n provide,\n shallowRef,\n type App,\n type ComputedRef,\n type InjectionKey,\n type ShallowRef,\n} from 'vue'\nimport {\n AuthError,\n type AuthKeeper,\n type LogoutOptions,\n type TokenPayload,\n type TokenSet,\n} from '../../types'\nimport { createAuthSource, type AuthSource } from '../auth-source'\n\nconst AUTH_KEY: InjectionKey<AuthKeeper> = Symbol('authkeeper')\n\n/**\n * Provide an AuthKeeper instance to the component's descendants\n * (call in `setup()`; for the whole app use `app.use(authKeeperPlugin(auth))`)\n */\nexport function provideAuth(auth: AuthKeeper): void {\n provide(AUTH_KEY, auth)\n}\n\n/**\n * The provided AuthKeeper instance (call in `setup()`)\n * @throws {AuthError} CONFIG_ERROR when none was provided\n */\nexport function injectAuth(): AuthKeeper {\n const auth = inject(AUTH_KEY, null)\n if (!auth) {\n throw new AuthError(\n 'CONFIG_ERROR',\n 'No AuthKeeper provided: call provideAuth(auth) in an ancestor',\n )\n }\n return auth\n}\n\n/**\n * Vue plugin: `app.use(authKeeperPlugin(auth))` provides the instance app-wide\n */\nexport function authKeeperPlugin(auth: AuthKeeper): { install(app: App): void } {\n return {\n install(app: App) {\n app.provide(AUTH_KEY, auth)\n },\n }\n}\n\n/**\n * A shallow ref of `read(source)`, updated while the calling component (or\n * effect scope) lives. It only triggers when the snapshot changes.\n * @internal\n */\nexport function useSnapshot<T>(\n auth: AuthKeeper | undefined,\n read: (source: AuthSource) => T,\n): { instance: AuthKeeper; state: Readonly<ShallowRef<T>>; stop: () => void } {\n const instance = auth ?? injectAuth()\n const source = createAuthSource(instance)\n const state = shallowRef(read(source))\n const stop = source.subscribe(() => {\n state.value = read(source)\n })\n if (getCurrentScope()) onScopeDispose(stop)\n return { instance, state, stop }\n}\n\n/**\n * useAuth() return value: read-only refs plus actions\n */\nexport interface UseAuthReturn {\n isAuthenticated: ComputedRef<boolean>\n accessToken: ComputedRef<string | null>\n user: ComputedRef<TokenPayload | null>\n expiresAt: ComputedRef<Date | null>\n error: ComputedRef<AuthError | null>\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive auth state. Updates after login, logout, refresh and error events\n * and when the access token expires; stops when the calling component (or\n * effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useAuth(auth?: AuthKeeper): UseAuthReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getState())\n return {\n isAuthenticated: computed(() => state.value.isAuthenticated),\n accessToken: computed(() => state.value.accessToken),\n user: computed(() => state.value.user),\n expiresAt: computed(() => state.value.expiresAt),\n error: computed(() => state.value.error),\n setTokens: (tokens) => instance.setTokens(tokens),\n logout: (options) => instance.logout(options),\n refresh: () => instance.refresh(),\n stop,\n }\n}\n","/**\n * Vue 3 bindings: the useToken() and useUser() composables\n */\n\nimport { computed, type ComputedRef } from 'vue'\nimport type { AuthFetch, AuthKeeper, TokenPayload } from '../../types'\nimport { NO_CLAIMS, readClaim } from '../auth-source'\nimport { useSnapshot } from './use-auth'\n\n/**\n * useToken() return value: read-only refs plus an authenticated fetch\n */\nexport interface UseTokenReturn {\n accessToken: ComputedRef<string | null>\n /** Null when none is stored (e.g. an httpOnly cookie) */\n refreshToken: ComputedRef<string | null>\n /** An access token is set but has expired */\n isExpired: ComputedRef<boolean>\n expiresAt: ComputedRef<Date | null>\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive tokens. Update when a token or the expiry changes (login, refresh,\n * logout, expiry); stop when the calling component (or effect scope) is\n * disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useToken(auth?: AuthKeeper): UseTokenReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState())\n return {\n accessToken: computed(() => state.value.accessToken),\n refreshToken: computed(() => state.value.refreshToken),\n isExpired: computed(() => state.value.isExpired),\n expiresAt: computed(() => state.value.expiresAt),\n authFetch: instance.createFetch(),\n stop,\n }\n}\n\n/**\n * useUser() return value\n */\nexport interface UseUserReturn {\n /** Decoded access token payload (null when signed out or for opaque tokens) */\n user: ComputedRef<TokenPayload | null>\n /** The payload's claims (empty when there is no user) */\n claims: ComputedRef<TokenPayload>\n /** One claim of the current payload (reactive inside computed / templates) */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive decoded access token payload. Updates when the access token\n * changes; stops when the calling component (or effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useUser(auth?: AuthKeeper): UseUserReturn {\n const { state, stop } = useSnapshot(auth, (source) => source.getState().user)\n return {\n user: computed(() => state.value),\n claims: computed(() => state.value ?? NO_CLAIMS),\n getClaim: (key) => readClaim(state.value, key),\n stop,\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxog/authkeeper",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.1",
|
|
4
4
|
"description": "Zero-dependency token & auth management toolkit with micro-kernel plugin architecture",
|
|
5
5
|
"author": "Ersin KOÇ",
|
|
6
6
|
"license": "MIT",
|
|
@@ -114,9 +114,11 @@
|
|
|
114
114
|
"test:package": "node scripts/check-package.mjs",
|
|
115
115
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
116
116
|
"lint": "eslint src tests --max-warnings=0",
|
|
117
|
-
"format": "prettier --write
|
|
118
|
-
"check": "npm run lint && npm run typecheck && npm run test:coverage",
|
|
119
|
-
"prepublishOnly": "npm run check && npm run build && npm run test:package"
|
|
117
|
+
"format": "prettier --write .",
|
|
118
|
+
"check": "npm run format:check && npm run lint && npm run typecheck && npm run test:coverage",
|
|
119
|
+
"prepublishOnly": "npm run check && npm run build && npm run test:package",
|
|
120
|
+
"format:check": "prettier --check .",
|
|
121
|
+
"test:browser": "vitest run --config vitest.config.browser.mts"
|
|
120
122
|
},
|
|
121
123
|
"devDependencies": {
|
|
122
124
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
@@ -126,12 +128,14 @@
|
|
|
126
128
|
"@types/node": "^20.10.6",
|
|
127
129
|
"@types/react": "^18.2.46",
|
|
128
130
|
"@vitejs/plugin-react": "^4.7.0",
|
|
131
|
+
"@vitest/browser-playwright": "^4.1.12",
|
|
129
132
|
"@vitest/coverage-v8": "^4.1.12",
|
|
130
133
|
"@vitest/ui": "^4.1.12",
|
|
131
134
|
"@vue/test-utils": "^2.4.3",
|
|
132
135
|
"eslint": "^10.0.0",
|
|
133
136
|
"globals": "^17.0.0",
|
|
134
137
|
"happy-dom": "^21.0.4",
|
|
138
|
+
"playwright": "^1.65.2",
|
|
135
139
|
"prettier": "^3.1.1",
|
|
136
140
|
"publint": "^0.3.25",
|
|
137
141
|
"tsup": "^8.5.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";;;AAmJO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,IAAA,EAAqB,OAAA,EAAiB,OAAA,EAA4B;AAC5E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AACxB,IAAA,IAAA,CAAK,QAAQ,OAAA,EAAS,KAAA;AAGtB,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,UAAS,CAAA;AAAA,IACzC;AAAA,EACF;AACF","file":"chunk-62XK5QLP.cjs","sourcesContent":["/**\n * AuthKeeper Type Definitions\n *\n * Complete type system for the AuthKeeper library.\n * All interfaces and types are exported for use by consumers.\n */\n\n// ============================================================================\n// Token Types\n// ============================================================================\n\n/**\n * Token set returned from authentication/refresh operations\n */\nexport interface TokenSet {\n /** JWT access token */\n accessToken: string\n /** Optional refresh token for obtaining new access tokens */\n refreshToken?: string\n /** Token expiration in seconds from now */\n expiresIn?: number\n /** Token expiration as Unix timestamp (seconds) */\n expiresAt?: number\n /** Token type (default: 'Bearer') */\n tokenType?: string\n}\n\n/**\n * Standard JWT payload with common claims\n */\nexport interface TokenPayload {\n // Standard JWT claims (RFC 7519)\n /** Subject - usually the user ID */\n sub?: string\n /** Issuer - who created the token */\n iss?: string\n /** Audience - who the token is intended for */\n aud?: string | string[]\n /** Expiration time (Unix timestamp in seconds) */\n exp?: number\n /** Not before time (Unix timestamp in seconds) */\n nbf?: number\n /** Issued at time (Unix timestamp in seconds) */\n iat?: number\n /** JWT ID - unique identifier */\n jti?: string\n\n // Common custom claims\n /** User email address */\n email?: string\n /** User display name */\n name?: string\n /** User roles */\n roles?: string[]\n /** User permissions */\n permissions?: string[]\n /** OAuth2 scope */\n scope?: string\n\n // Allow any additional custom claims\n [key: string]: unknown\n}\n\n/**\n * JWT header information\n */\nexport interface TokenHeader {\n /** Algorithm used to sign the token */\n alg: string\n /** Token type (usually 'JWT') */\n typ?: string\n /** Key ID used to sign the token */\n kid?: string\n [key: string]: unknown\n}\n\n/**\n * Complete token information including decoded parts\n */\nexport interface TokenInfo {\n /** Raw JWT string */\n raw: string\n /** Decoded payload */\n payload: TokenPayload\n /** Decoded header */\n header: TokenHeader\n /** When the token expires (null if no expiry) */\n expiresAt: Date | null\n /** Whether the token is expired */\n isExpired: boolean\n /** Time until expiry in milliseconds (null if no expiry) */\n expiresIn: number | null\n}\n\n/**\n * Stored token data with metadata\n */\nexport interface StoredTokens {\n /** Access token */\n accessToken: string\n /** Refresh token (null if not available) */\n refreshToken: string | null\n /** Token type (e.g., 'Bearer') */\n tokenType: string\n /** Expiration timestamp in milliseconds (null if no expiry) */\n expiresAt: number | null\n /** When tokens were set (timestamp in milliseconds) */\n setAt: number\n /** Number of times tokens have been refreshed */\n refreshCount: number\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error codes for authentication errors\n */\nexport type AuthErrorCode =\n | 'TOKEN_EXPIRED'\n | 'TOKEN_INVALID'\n | 'TOKEN_DECODE_FAILED'\n | 'REFRESH_FAILED'\n | 'REFRESH_TOKEN_MISSING'\n | 'STORAGE_ERROR'\n | 'NETWORK_ERROR'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'OAUTH_ERROR'\n | 'PKCE_ERROR'\n | 'CALLBACK_ERROR'\n | 'CONFIG_ERROR'\n\n/**\n * Options for creating an AuthError\n */\nexport interface AuthErrorOptions {\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n}\n\n/**\n * Custom error class for authentication errors\n */\nexport class AuthError extends Error {\n /** Error code identifying the type of error */\n code: AuthErrorCode\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n\n constructor(code: AuthErrorCode, message: string, options?: AuthErrorOptions) {\n super(message)\n this.name = 'AuthError'\n this.code = code\n this.context = options?.context\n this.cause = options?.cause\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AuthError)\n }\n }\n}\n\n// ============================================================================\n// Event Types\n// ============================================================================\n\n/**\n * All possible event types\n */\nexport type EventType =\n | 'login'\n | 'logout'\n | 'refresh'\n | 'expired'\n | 'error'\n | 'storage-change'\n | 'tab-sync'\n\n/**\n * Login event - fired when user logs in\n */\nexport interface LoginEvent {\n type: 'login'\n tokens: TokenSet\n timestamp: number\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n}\n\n/**\n * Refresh event - fired when tokens are refreshed\n */\nexport interface RefreshEvent {\n type: 'refresh'\n tokens: TokenSet\n previousExpiresAt: Date | null\n newExpiresAt: Date | null\n timestamp: number\n}\n\n/**\n * Expired event - fired when token expires\n */\nexport interface ExpiredEvent {\n type: 'expired'\n expiredAt: Date\n timestamp: number\n}\n\n/**\n * Error event - fired when an error occurs\n */\nexport interface ErrorEvent {\n type: 'error'\n error: AuthError\n context: 'refresh' | 'storage' | 'decode' | 'network' | 'plugin'\n timestamp: number\n}\n\n/**\n * Storage change event - fired when storage changes\n */\nexport interface StorageChangeEvent {\n type: 'storage-change'\n key: string\n oldValue: string | null\n newValue: string | null\n timestamp: number\n}\n\n/**\n * Tab sync event - fired when syncing across tabs\n */\nexport interface TabSyncEvent {\n type: 'tab-sync'\n action: 'login' | 'logout' | 'refresh'\n sourceTabId: string\n timestamp: number\n}\n\n/**\n * Union of all event types\n */\nexport type AuthEvent =\n | LoginEvent\n | LogoutEvent\n | RefreshEvent\n | ExpiredEvent\n | ErrorEvent\n | StorageChangeEvent\n | TabSyncEvent\n\n/**\n * Event handler function type\n */\nexport type EventHandler<E extends EventType> = (\n event: Extract<AuthEvent, { type: E }>\n) => void\n\n/**\n * Unsubscribe function returned from event handlers\n */\nexport type Unsubscribe = () => void\n\n// ============================================================================\n// Storage Types\n// ============================================================================\n\n/**\n * Storage adapter interface for token persistence\n */\nexport interface StorageAdapter {\n /** Get value by key */\n get(key: string): string | null\n /** Set value by key */\n set(key: string, value: string): void\n /** Remove value by key */\n remove(key: string): void\n /** Clear all values */\n clear(): void\n}\n\n/**\n * Built-in storage types\n */\nexport type StorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'cookie'\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n/**\n * Plugin interface for extending AuthKeeper\n */\nexport interface Plugin {\n /** Unique plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Plugin type */\n type: 'core' | 'optional'\n\n /** Install plugin and return API */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kept (not `unknown`) so existing plugin APIs stay usable without casts\n install(kernel: AuthKeeper): any\n /** Uninstall plugin and cleanup */\n uninstall?(): void | Promise<void>\n\n /** Reserved lifecycle hooks; not invoked by the kernel yet */\n hooks?: {\n /** Called before tokens are set */\n beforeSetTokens?: (tokens: TokenSet) => TokenSet | false\n /** Called after tokens are set */\n afterSetTokens?: (tokens: TokenSet) => void\n /** Called before refresh */\n beforeRefresh?: () => boolean\n /** Called after refresh */\n afterRefresh?: (tokens: TokenSet) => void\n /** Called before logout */\n beforeLogout?: () => boolean\n /** Called after logout */\n afterLogout?: () => void\n /** Called when token expires */\n onExpired?: () => void\n /** Called on error */\n onError?: (error: AuthError) => void\n /** Called before request */\n beforeRequest?: (request: Request) => Request\n /** Called after response */\n afterResponse?: (response: Response) => Response\n }\n\n /** Plugin API exposed to consumers */\n api?: Record<string, unknown>\n}\n\n/**\n * Plugin information\n */\nexport interface PluginInfo {\n name: string\n version: string\n type: 'core' | 'optional'\n enabled: boolean\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Refresh token function type\n */\nexport type RefreshTokenFn = (refreshToken: string) => Promise<TokenSet>\n\n/**\n * Kernel configuration options\n */\nexport interface KernelOptions {\n /**\n * Where tokens are persisted (default: 'memory', i.e. not persisted).\n * 'localStorage' / 'sessionStorage' / 'cookie' fall back to memory where\n * unavailable. Persistent storage is readable by any script on the page.\n */\n storage?: StorageType | StorageAdapter\n /** Function to refresh tokens */\n refreshToken: RefreshTokenFn\n /** Enable automatic token refresh (default: true) */\n autoRefresh?: boolean\n /** Seconds before expiry to refresh (default: 60) */\n refreshThreshold?: number\n /**\n * Reserved for multi-tab sync; not implemented yet (currently a no-op).\n * `getOptions().syncTabs` always reports `false`.\n */\n syncTabs?: boolean\n /** Error handler */\n onError?: (error: AuthError) => void\n /** Additional plugins to install */\n plugins?: Plugin[]\n}\n\n/**\n * Logout options\n */\nexport interface LogoutOptions {\n /** Reserved for multi-tab logout; not implemented yet (currently a no-op) */\n allTabs?: boolean\n /** Redirect URL after logout */\n redirect?: string\n}\n\n// ============================================================================\n// Fetch Interceptor Types\n// ============================================================================\n\n/**\n * Authenticated fetch function\n */\nexport type AuthFetch = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>\n\n/**\n * Fetch interceptor options\n */\nexport interface FetchInterceptorOptions {\n /** Header name for auth token (default: 'Authorization') */\n headerName?: string\n /** Header prefix (default: 'Bearer ') */\n headerPrefix?: string\n /** Only include auth header for these URLs */\n includeUrls?: (string | RegExp)[]\n /** Exclude auth header for these URLs */\n excludeUrls?: (string | RegExp)[]\n /** Callback on 401 response */\n onUnauthorized?: (response: Response) => void\n /** Retry on 401 after refresh (default: true) */\n retry401?: boolean\n /** Max retries (default: 1) */\n maxRetries?: number\n}\n\n// ============================================================================\n// OAuth2 Types\n// ============================================================================\n\n/**\n * OAuth2 login options\n */\nexport interface LoginOptions {\n /** OAuth2 scope */\n scope?: string\n /** OAuth2 state parameter */\n state?: string\n /** OAuth2 prompt parameter */\n prompt?: 'none' | 'login' | 'consent' | 'select_account'\n /** Login hint (email, etc.) */\n loginHint?: string\n /** Additional OAuth2 parameters */\n extraParams?: Record<string, string>\n}\n\n/**\n * User info from OIDC userinfo endpoint\n */\nexport interface UserInfo {\n sub: string\n email?: string\n name?: string\n picture?: string\n [key: string]: unknown\n}\n\n// ============================================================================\n// Main AuthKeeper Interface\n// ============================================================================\n\n/**\n * Main AuthKeeper interface - the kernel\n */\nexport interface AuthKeeper {\n // Token Management\n /** Set authentication tokens */\n setTokens(tokens: TokenSet): void\n /** Get access token */\n getAccessToken(): string | null\n /** Get refresh token */\n getRefreshToken(): string | null\n /** Clear all tokens */\n clearTokens(): void\n\n // Auth State\n /** Check if user is authenticated */\n isAuthenticated(): boolean\n /** Check if token is expired */\n isExpired(): boolean\n /** Get token expiration date */\n getExpiresAt(): Date | null\n /** Get time until expiry in milliseconds */\n getTimeUntilExpiry(): number | null\n\n // Token Decoding\n /** Decode token payload */\n decode<T = TokenPayload>(): T | null\n /** Get specific claim from token */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined\n /** Get multiple claims from token */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>\n\n // Refresh\n /** Manually refresh tokens */\n refresh(): Promise<TokenSet>\n /** Schedule automatic refresh */\n scheduleRefresh(): void\n /** Cancel scheduled refresh */\n cancelScheduledRefresh(): void\n\n // Logout\n /** Logout user */\n logout(options?: LogoutOptions): void\n\n // Interceptors\n /** Create authenticated fetch function */\n createFetch(options?: FetchInterceptorOptions): AuthFetch\n /** Wrap global fetch with auth */\n wrapFetch(fetch: typeof globalThis.fetch): void\n\n // Plugin Management\n /**\n * Register and install a plugin. Rejects if installation fails; the failure\n * is also emitted as an 'error' event with context 'plugin'.\n */\n register(plugin: Plugin): Promise<void>\n /** Unregister a plugin */\n unregister(pluginName: string): Promise<void>\n /** Get plugin by name */\n getPlugin<P extends Plugin>(name: string): P | undefined\n /** List all plugins */\n listPlugins(): PluginInfo[]\n\n // Event System\n /** Emit an event */\n emit(event: AuthEvent): void\n /** Subscribe to events */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe\n /** Unsubscribe from events */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void\n\n // Lifecycle\n /** Initialize kernel */\n init(): Promise<void>\n /** Destroy kernel and cleanup */\n destroy(): void\n\n // Configuration\n /** Update configuration */\n configure(options: Partial<KernelOptions>): void\n /** Get current configuration */\n getOptions(): KernelOptions\n}\n\n// ============================================================================\n// Export all types\n// ============================================================================\n\nexport type {\n // Re-export for convenience\n AuthKeeper as default,\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";AAmJO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,IAAA,EAAqB,OAAA,EAAiB,OAAA,EAA4B;AAC5E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AACxB,IAAA,IAAA,CAAK,QAAQ,OAAA,EAAS,KAAA;AAGtB,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,UAAS,CAAA;AAAA,IACzC;AAAA,EACF;AACF","file":"chunk-CYCWWUCJ.js","sourcesContent":["/**\n * AuthKeeper Type Definitions\n *\n * Complete type system for the AuthKeeper library.\n * All interfaces and types are exported for use by consumers.\n */\n\n// ============================================================================\n// Token Types\n// ============================================================================\n\n/**\n * Token set returned from authentication/refresh operations\n */\nexport interface TokenSet {\n /** JWT access token */\n accessToken: string\n /** Optional refresh token for obtaining new access tokens */\n refreshToken?: string\n /** Token expiration in seconds from now */\n expiresIn?: number\n /** Token expiration as Unix timestamp (seconds) */\n expiresAt?: number\n /** Token type (default: 'Bearer') */\n tokenType?: string\n}\n\n/**\n * Standard JWT payload with common claims\n */\nexport interface TokenPayload {\n // Standard JWT claims (RFC 7519)\n /** Subject - usually the user ID */\n sub?: string\n /** Issuer - who created the token */\n iss?: string\n /** Audience - who the token is intended for */\n aud?: string | string[]\n /** Expiration time (Unix timestamp in seconds) */\n exp?: number\n /** Not before time (Unix timestamp in seconds) */\n nbf?: number\n /** Issued at time (Unix timestamp in seconds) */\n iat?: number\n /** JWT ID - unique identifier */\n jti?: string\n\n // Common custom claims\n /** User email address */\n email?: string\n /** User display name */\n name?: string\n /** User roles */\n roles?: string[]\n /** User permissions */\n permissions?: string[]\n /** OAuth2 scope */\n scope?: string\n\n // Allow any additional custom claims\n [key: string]: unknown\n}\n\n/**\n * JWT header information\n */\nexport interface TokenHeader {\n /** Algorithm used to sign the token */\n alg: string\n /** Token type (usually 'JWT') */\n typ?: string\n /** Key ID used to sign the token */\n kid?: string\n [key: string]: unknown\n}\n\n/**\n * Complete token information including decoded parts\n */\nexport interface TokenInfo {\n /** Raw JWT string */\n raw: string\n /** Decoded payload */\n payload: TokenPayload\n /** Decoded header */\n header: TokenHeader\n /** When the token expires (null if no expiry) */\n expiresAt: Date | null\n /** Whether the token is expired */\n isExpired: boolean\n /** Time until expiry in milliseconds (null if no expiry) */\n expiresIn: number | null\n}\n\n/**\n * Stored token data with metadata\n */\nexport interface StoredTokens {\n /** Access token */\n accessToken: string\n /** Refresh token (null if not available) */\n refreshToken: string | null\n /** Token type (e.g., 'Bearer') */\n tokenType: string\n /** Expiration timestamp in milliseconds (null if no expiry) */\n expiresAt: number | null\n /** When tokens were set (timestamp in milliseconds) */\n setAt: number\n /** Number of times tokens have been refreshed */\n refreshCount: number\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error codes for authentication errors\n */\nexport type AuthErrorCode =\n | 'TOKEN_EXPIRED'\n | 'TOKEN_INVALID'\n | 'TOKEN_DECODE_FAILED'\n | 'REFRESH_FAILED'\n | 'REFRESH_TOKEN_MISSING'\n | 'STORAGE_ERROR'\n | 'NETWORK_ERROR'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'OAUTH_ERROR'\n | 'PKCE_ERROR'\n | 'CALLBACK_ERROR'\n | 'CONFIG_ERROR'\n\n/**\n * Options for creating an AuthError\n */\nexport interface AuthErrorOptions {\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n}\n\n/**\n * Custom error class for authentication errors\n */\nexport class AuthError extends Error {\n /** Error code identifying the type of error */\n code: AuthErrorCode\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n\n constructor(code: AuthErrorCode, message: string, options?: AuthErrorOptions) {\n super(message)\n this.name = 'AuthError'\n this.code = code\n this.context = options?.context\n this.cause = options?.cause\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AuthError)\n }\n }\n}\n\n// ============================================================================\n// Event Types\n// ============================================================================\n\n/**\n * All possible event types\n */\nexport type EventType =\n | 'login'\n | 'logout'\n | 'refresh'\n | 'expired'\n | 'error'\n | 'storage-change'\n | 'tab-sync'\n\n/**\n * Login event - fired when user logs in\n */\nexport interface LoginEvent {\n type: 'login'\n tokens: TokenSet\n timestamp: number\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n}\n\n/**\n * Refresh event - fired when tokens are refreshed\n */\nexport interface RefreshEvent {\n type: 'refresh'\n tokens: TokenSet\n previousExpiresAt: Date | null\n newExpiresAt: Date | null\n timestamp: number\n}\n\n/**\n * Expired event - fired when token expires\n */\nexport interface ExpiredEvent {\n type: 'expired'\n expiredAt: Date\n timestamp: number\n}\n\n/**\n * Error event - fired when an error occurs\n */\nexport interface ErrorEvent {\n type: 'error'\n error: AuthError\n context: 'refresh' | 'storage' | 'decode' | 'network' | 'plugin'\n timestamp: number\n}\n\n/**\n * Storage change event - fired when storage changes\n */\nexport interface StorageChangeEvent {\n type: 'storage-change'\n key: string\n oldValue: string | null\n newValue: string | null\n timestamp: number\n}\n\n/**\n * Tab sync event - fired when syncing across tabs\n */\nexport interface TabSyncEvent {\n type: 'tab-sync'\n action: 'login' | 'logout' | 'refresh'\n sourceTabId: string\n timestamp: number\n}\n\n/**\n * Union of all event types\n */\nexport type AuthEvent =\n | LoginEvent\n | LogoutEvent\n | RefreshEvent\n | ExpiredEvent\n | ErrorEvent\n | StorageChangeEvent\n | TabSyncEvent\n\n/**\n * Event handler function type\n */\nexport type EventHandler<E extends EventType> = (\n event: Extract<AuthEvent, { type: E }>\n) => void\n\n/**\n * Unsubscribe function returned from event handlers\n */\nexport type Unsubscribe = () => void\n\n// ============================================================================\n// Storage Types\n// ============================================================================\n\n/**\n * Storage adapter interface for token persistence\n */\nexport interface StorageAdapter {\n /** Get value by key */\n get(key: string): string | null\n /** Set value by key */\n set(key: string, value: string): void\n /** Remove value by key */\n remove(key: string): void\n /** Clear all values */\n clear(): void\n}\n\n/**\n * Built-in storage types\n */\nexport type StorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'cookie'\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n/**\n * Plugin interface for extending AuthKeeper\n */\nexport interface Plugin {\n /** Unique plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Plugin type */\n type: 'core' | 'optional'\n\n /** Install plugin and return API */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kept (not `unknown`) so existing plugin APIs stay usable without casts\n install(kernel: AuthKeeper): any\n /** Uninstall plugin and cleanup */\n uninstall?(): void | Promise<void>\n\n /** Reserved lifecycle hooks; not invoked by the kernel yet */\n hooks?: {\n /** Called before tokens are set */\n beforeSetTokens?: (tokens: TokenSet) => TokenSet | false\n /** Called after tokens are set */\n afterSetTokens?: (tokens: TokenSet) => void\n /** Called before refresh */\n beforeRefresh?: () => boolean\n /** Called after refresh */\n afterRefresh?: (tokens: TokenSet) => void\n /** Called before logout */\n beforeLogout?: () => boolean\n /** Called after logout */\n afterLogout?: () => void\n /** Called when token expires */\n onExpired?: () => void\n /** Called on error */\n onError?: (error: AuthError) => void\n /** Called before request */\n beforeRequest?: (request: Request) => Request\n /** Called after response */\n afterResponse?: (response: Response) => Response\n }\n\n /** Plugin API exposed to consumers */\n api?: Record<string, unknown>\n}\n\n/**\n * Plugin information\n */\nexport interface PluginInfo {\n name: string\n version: string\n type: 'core' | 'optional'\n enabled: boolean\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Refresh token function type\n */\nexport type RefreshTokenFn = (refreshToken: string) => Promise<TokenSet>\n\n/**\n * Kernel configuration options\n */\nexport interface KernelOptions {\n /**\n * Where tokens are persisted (default: 'memory', i.e. not persisted).\n * 'localStorage' / 'sessionStorage' / 'cookie' fall back to memory where\n * unavailable. Persistent storage is readable by any script on the page.\n */\n storage?: StorageType | StorageAdapter\n /** Function to refresh tokens */\n refreshToken: RefreshTokenFn\n /** Enable automatic token refresh (default: true) */\n autoRefresh?: boolean\n /** Seconds before expiry to refresh (default: 60) */\n refreshThreshold?: number\n /**\n * Reserved for multi-tab sync; not implemented yet (currently a no-op).\n * `getOptions().syncTabs` always reports `false`.\n */\n syncTabs?: boolean\n /** Error handler */\n onError?: (error: AuthError) => void\n /** Additional plugins to install */\n plugins?: Plugin[]\n}\n\n/**\n * Logout options\n */\nexport interface LogoutOptions {\n /** Reserved for multi-tab logout; not implemented yet (currently a no-op) */\n allTabs?: boolean\n /** Redirect URL after logout */\n redirect?: string\n}\n\n// ============================================================================\n// Fetch Interceptor Types\n// ============================================================================\n\n/**\n * Authenticated fetch function\n */\nexport type AuthFetch = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>\n\n/**\n * Fetch interceptor options\n */\nexport interface FetchInterceptorOptions {\n /** Header name for auth token (default: 'Authorization') */\n headerName?: string\n /** Header prefix (default: 'Bearer ') */\n headerPrefix?: string\n /** Only include auth header for these URLs */\n includeUrls?: (string | RegExp)[]\n /** Exclude auth header for these URLs */\n excludeUrls?: (string | RegExp)[]\n /** Callback on 401 response */\n onUnauthorized?: (response: Response) => void\n /** Retry on 401 after refresh (default: true) */\n retry401?: boolean\n /** Max retries (default: 1) */\n maxRetries?: number\n}\n\n// ============================================================================\n// OAuth2 Types\n// ============================================================================\n\n/**\n * OAuth2 login options\n */\nexport interface LoginOptions {\n /** OAuth2 scope */\n scope?: string\n /** OAuth2 state parameter */\n state?: string\n /** OAuth2 prompt parameter */\n prompt?: 'none' | 'login' | 'consent' | 'select_account'\n /** Login hint (email, etc.) */\n loginHint?: string\n /** Additional OAuth2 parameters */\n extraParams?: Record<string, string>\n}\n\n/**\n * User info from OIDC userinfo endpoint\n */\nexport interface UserInfo {\n sub: string\n email?: string\n name?: string\n picture?: string\n [key: string]: unknown\n}\n\n// ============================================================================\n// Main AuthKeeper Interface\n// ============================================================================\n\n/**\n * Main AuthKeeper interface - the kernel\n */\nexport interface AuthKeeper {\n // Token Management\n /** Set authentication tokens */\n setTokens(tokens: TokenSet): void\n /** Get access token */\n getAccessToken(): string | null\n /** Get refresh token */\n getRefreshToken(): string | null\n /** Clear all tokens */\n clearTokens(): void\n\n // Auth State\n /** Check if user is authenticated */\n isAuthenticated(): boolean\n /** Check if token is expired */\n isExpired(): boolean\n /** Get token expiration date */\n getExpiresAt(): Date | null\n /** Get time until expiry in milliseconds */\n getTimeUntilExpiry(): number | null\n\n // Token Decoding\n /** Decode token payload */\n decode<T = TokenPayload>(): T | null\n /** Get specific claim from token */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined\n /** Get multiple claims from token */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>\n\n // Refresh\n /** Manually refresh tokens */\n refresh(): Promise<TokenSet>\n /** Schedule automatic refresh */\n scheduleRefresh(): void\n /** Cancel scheduled refresh */\n cancelScheduledRefresh(): void\n\n // Logout\n /** Logout user */\n logout(options?: LogoutOptions): void\n\n // Interceptors\n /** Create authenticated fetch function */\n createFetch(options?: FetchInterceptorOptions): AuthFetch\n /** Wrap global fetch with auth */\n wrapFetch(fetch: typeof globalThis.fetch): void\n\n // Plugin Management\n /**\n * Register and install a plugin. Rejects if installation fails; the failure\n * is also emitted as an 'error' event with context 'plugin'.\n */\n register(plugin: Plugin): Promise<void>\n /** Unregister a plugin */\n unregister(pluginName: string): Promise<void>\n /** Get plugin by name */\n getPlugin<P extends Plugin>(name: string): P | undefined\n /** List all plugins */\n listPlugins(): PluginInfo[]\n\n // Event System\n /** Emit an event */\n emit(event: AuthEvent): void\n /** Subscribe to events */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe\n /** Unsubscribe from events */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void\n\n // Lifecycle\n /** Initialize kernel */\n init(): Promise<void>\n /** Destroy kernel and cleanup */\n destroy(): void\n\n // Configuration\n /** Update configuration */\n configure(options: Partial<KernelOptions>): void\n /** Get current configuration */\n getOptions(): KernelOptions\n}\n\n// ============================================================================\n// Export all types\n// ============================================================================\n\nexport type {\n // Re-export for convenience\n AuthKeeper as default,\n}\n"]}
|