@absolutejs/auth 0.3.2 → 0.5.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/src/logout.ts DELETED
@@ -1,39 +0,0 @@
1
- import { Elysia } from 'elysia';
2
-
3
- type LogoutProps = {
4
- logoutRoute?: string;
5
- onLogout?: () => void;
6
- };
7
-
8
- export const logout = ({ logoutRoute = 'logout', onLogout }: LogoutProps) =>
9
- new Elysia().post(
10
- `/${logoutRoute}`,
11
- async ({ error, cookie: { user_session_id, auth_provider } }) => {
12
- if (auth_provider.value === undefined) {
13
- return error('Unauthorized', 'No auth provider found');
14
- }
15
-
16
- try {
17
- onLogout?.();
18
-
19
- user_session_id.remove();
20
- auth_provider.remove();
21
-
22
- return new Response('Succesfuly Logged Out', {
23
- status: 204
24
- });
25
- } catch (err) {
26
- if (err instanceof Error) {
27
- return error(
28
- 'Internal Server Error',
29
- `Failed to logout: ${err.message}`
30
- );
31
- }
32
-
33
- return error(
34
- 'Internal Server Error',
35
- `Failed to logout: Unknown error: ${err}`
36
- );
37
- }
38
- }
39
- );
@@ -1,33 +0,0 @@
1
- import { Elysia } from 'elysia';
2
- import { sessionStore } from './sessionStore';
3
-
4
- export const protectRoute = <UserType>() =>
5
- new Elysia()
6
- .use(sessionStore<UserType>())
7
- .derive(
8
- ({ store: { session }, cookie: { user_session_id }, error }) => ({
9
- protectRoute: async (
10
- handleAuth: () => Promise<Response>,
11
- handleAuthFail?: () => Promise<Response>
12
- ) => {
13
- if (user_session_id.value === undefined) {
14
- return (
15
- handleAuthFail?.() ??
16
- error('Unauthorized', 'No session ID found')
17
- );
18
- }
19
-
20
- const userSession = session[user_session_id.value];
21
-
22
- if (userSession === undefined) {
23
- return (
24
- handleAuthFail?.() ??
25
- error('Unauthorized', 'No session found')
26
- );
27
- }
28
-
29
- return handleAuth();
30
- }
31
- })
32
- )
33
- .as('plugin');
package/src/providers.ts DELETED
@@ -1,109 +0,0 @@
1
- import {
2
- AmazonCognito,
3
- AniList,
4
- Apple,
5
- Atlassian,
6
- Auth0,
7
- Authentik,
8
- Bitbucket,
9
- Box,
10
- Coinbase,
11
- Discord,
12
- Dribbble,
13
- Dropbox,
14
- Facebook,
15
- Figma,
16
- Intuit,
17
- GitHub,
18
- GitLab,
19
- Google,
20
- Kakao,
21
- KeyCloak,
22
- Lichess,
23
- Line,
24
- Linear,
25
- LinkedIn,
26
- MicrosoftEntraId,
27
- MyAnimeList,
28
- Notion,
29
- Okta,
30
- Osu,
31
- Patreon,
32
- Reddit,
33
- Roblox,
34
- Salesforce,
35
- Shikimori,
36
- Slack,
37
- Spotify,
38
- Strava,
39
- Tiltify,
40
- Tumblr,
41
- Twitch,
42
- Twitter,
43
- VK,
44
- WorkOS,
45
- Yahoo,
46
- Yandex,
47
- Zoom,
48
- FortyTwo
49
- } from 'arctic';
50
-
51
- // TODO: When arctic adds better way to get the providers give a type to the object
52
- // eslint-disable-next-line custom/explicit-object-types
53
- export const providers = {
54
- AmazonCognito,
55
- AniList,
56
- Apple,
57
- Atlassian,
58
- Auth0,
59
- Authentik,
60
- Bitbucket,
61
- Box,
62
- Coinbase,
63
- Discord,
64
- Dribbble,
65
- Dropbox,
66
- Facebook,
67
- Figma,
68
- FortyTwo,
69
- GitHub,
70
- GitLab,
71
- Google,
72
- Intuit,
73
- Kakao,
74
- KeyCloak,
75
- Lichess,
76
- Line,
77
- Linear,
78
- LinkedIn,
79
- MicrosoftEntraId,
80
- MyAnimeList,
81
- Notion,
82
- Okta,
83
- Osu,
84
- Patreon,
85
- Reddit,
86
- Roblox,
87
- Salesforce,
88
- Shikimori,
89
- Slack,
90
- Spotify,
91
- Strava,
92
- Tiltify,
93
- Tumblr,
94
- Twitch,
95
- Twitter,
96
- VK,
97
- WorkOS,
98
- Yahoo,
99
- Yandex,
100
- Zoom
101
- };
102
-
103
- export const normalizedProviderKeys = Object.keys(providers).reduce<
104
- Record<string, string>
105
- >((map, key) => {
106
- map[key.toLowerCase()] = key;
107
-
108
- return map;
109
- }, {});
package/src/refresh.ts DELETED
@@ -1,63 +0,0 @@
1
- import { Elysia } from 'elysia';
2
- import { isRefreshableProvider } from './typeGuards';
3
- import { ClientProviders } from './types';
4
-
5
- type RefreshProps = {
6
- clientProviders: ClientProviders;
7
- refreshRoute?: string;
8
- onRefresh?: () => void;
9
- };
10
-
11
- export const refresh = ({
12
- clientProviders,
13
- refreshRoute = 'refresh',
14
- onRefresh
15
- }: RefreshProps) =>
16
- new Elysia().post(
17
- `/${refreshRoute}`,
18
- async ({ error, cookie: { user_refresh_token, auth_provider } }) => {
19
- if (user_refresh_token.value === undefined) {
20
- return error('Unauthorized', 'No refresh token found');
21
- }
22
-
23
- if (auth_provider.value === undefined) {
24
- return error('Unauthorized', 'No auth provider found');
25
- }
26
-
27
- const normalizedProvider = auth_provider.value.toLowerCase();
28
- const { providerInstance } = clientProviders[normalizedProvider];
29
-
30
- if (!isRefreshableProvider(providerInstance)) {
31
- return error('Not Implemented', 'Provider is not refreshable');
32
- }
33
-
34
- try {
35
- //consider passing tokens to onRefresh
36
- // const tokens = await providerInstance.refreshAccessToken(
37
- // user_refresh_token.value
38
- // );
39
-
40
- await providerInstance.refreshAccessToken(
41
- user_refresh_token.value
42
- );
43
-
44
- onRefresh?.();
45
-
46
- return new Response('Token refreshed', {
47
- status: 204
48
- });
49
- } catch (err) {
50
- if (err instanceof Error) {
51
- return error(
52
- 'Internal Server Error',
53
- `Failed to refresh token: ${err.message}`
54
- );
55
- }
56
-
57
- return error(
58
- 'Internal Server Error',
59
- `Faile to refresh token: Unknown error: ${err}`
60
- );
61
- }
62
- }
63
- );
package/src/revoke.ts DELETED
@@ -1,61 +0,0 @@
1
- import { Elysia } from 'elysia';
2
- import { isRevocableProvider } from './typeGuards';
3
- import { ClientProviders } from './types';
4
-
5
- type RevokeProps = {
6
- clientProviders: ClientProviders;
7
- revokeRoute?: string;
8
- onRevoke?: () => void;
9
- };
10
-
11
- export const revoke = ({
12
- clientProviders,
13
- revokeRoute = 'revoke',
14
- onRevoke
15
- }: RevokeProps) =>
16
- new Elysia().post(
17
- `/${revokeRoute}/access-token`,
18
- async ({ error, cookie: { user_refresh_token, auth_provider } }) => {
19
- if (user_refresh_token.value === undefined) {
20
- return error('Unauthorized', 'No refresh token found');
21
- }
22
-
23
- if (auth_provider.value === undefined) {
24
- return error('Unauthorized', 'No auth provider found');
25
- }
26
-
27
- const normalizedProvider = auth_provider.value.toLowerCase();
28
- const { providerInstance } = clientProviders[normalizedProvider];
29
-
30
- if (!isRevocableProvider(providerInstance)) {
31
- return error(
32
- 'Not Implemented',
33
- 'Provider does not support revocation'
34
- );
35
- }
36
-
37
- try {
38
- await providerInstance.revokeAccessToken(
39
- user_refresh_token.value
40
- );
41
-
42
- onRevoke?.();
43
-
44
- return new Response('Token revoked', {
45
- status: 204
46
- });
47
- } catch (err) {
48
- if (err instanceof Error) {
49
- return error(
50
- 'Internal Server Error',
51
- `Failed to revoke token: ${err.message}`
52
- );
53
- }
54
-
55
- return error(
56
- 'Internal Server Error',
57
- `Failed to revoke token: Unknown error: ${err}`
58
- );
59
- }
60
- }
61
- );
@@ -1,10 +0,0 @@
1
- import { Elysia } from 'elysia';
2
- import { SessionRecord } from './types';
3
-
4
- export const sessionStore = <UserType>() => {
5
- const initialSession: SessionRecord<UserType> = {};
6
-
7
- return new Elysia({ name: 'sessionStore' }).state({
8
- session: initialSession
9
- });
10
- };
package/src/status.ts DELETED
@@ -1,100 +0,0 @@
1
- import { Elysia } from 'elysia';
2
- import { sessionStore } from './sessionStore';
3
- import { isRefreshableProvider } from './typeGuards';
4
- import { ClientProviders } from './types';
5
-
6
- type StatusProps = {
7
- clientProviders: ClientProviders;
8
- statusRoute?: string;
9
- onStatus?: () => void;
10
- };
11
-
12
- export const status = <UserType>({
13
- clientProviders,
14
- statusRoute = 'auth-status',
15
- onStatus
16
- }: StatusProps) =>
17
- new Elysia()
18
- .use(sessionStore<UserType>())
19
- .get(
20
- `/${statusRoute}`,
21
- async ({
22
- error,
23
- cookie: { user_session_id, auth_provider },
24
- store: { session }
25
- }) => {
26
- try {
27
- if (user_session_id.value === undefined) {
28
- return new Response(
29
- JSON.stringify({ isLoggedIn: false, user: null }),
30
- {
31
- headers: { 'Content-Type': 'application/json' }
32
- }
33
- );
34
- }
35
-
36
- if (auth_provider.value === undefined) {
37
- return new Response(
38
- JSON.stringify({ isLoggedIn: false, user: null }),
39
- {
40
- headers: { 'Content-Type': 'application/json' }
41
- }
42
- );
43
- }
44
-
45
- const normalizedProvider =
46
- auth_provider.value.toLowerCase();
47
- const { providerInstance } =
48
- clientProviders[normalizedProvider];
49
-
50
- // Returns an error if the provider is not refreshable but
51
- // consider another approach to be more inclusive of providers
52
- if (!isRefreshableProvider(providerInstance)) {
53
- return error(
54
- 'Not Implemented',
55
- 'Provider is not refreshable'
56
- );
57
- }
58
-
59
- const userSession = session[user_session_id.value];
60
- // console.log(
61
- // 'Session:',
62
- // session,
63
- // 'User Session ID:',
64
- // user_session_id.value
65
- // );
66
- // Return null because the user is not logged in, its not an error just a status
67
- if (userSession === undefined) {
68
- return new Response(
69
- JSON.stringify({ isLoggedIn: false, user: null }),
70
- {
71
- headers: { 'Content-Type': 'application/json' }
72
- }
73
- );
74
- }
75
-
76
- const { user } = userSession;
77
-
78
- onStatus?.();
79
-
80
- return new Response(
81
- JSON.stringify({ isLoggedIn: true, user }),
82
- {
83
- headers: { 'Content-Type': 'application/json' }
84
- }
85
- );
86
- } catch (err) {
87
- if (err instanceof Error) {
88
- return error(
89
- 'Internal Server Error',
90
- `Error: ${err.message} - ${err.stack ?? ''}`
91
- );
92
- }
93
-
94
- return error(
95
- 'Internal Server Error',
96
- `Unknown Error: ${err}`
97
- );
98
- }
99
- }
100
- );
package/src/typeGuards.ts DELETED
@@ -1,32 +0,0 @@
1
- import { OAuth2Tokens } from 'arctic';
2
- import { providers } from './providers';
3
- import { Providers } from './types';
4
-
5
- export const isRefreshableProvider = (
6
- provider: InstanceType<(typeof providers)[Providers]>
7
- ): provider is InstanceType<(typeof providers)[Providers]> & {
8
- refreshAccessToken: () => Promise<OAuth2Tokens>;
9
- } =>
10
- 'refreshAccessToken' in provider &&
11
- typeof provider.refreshAccessToken === 'function';
12
-
13
- export const isRevocableProvider = (
14
- provider: InstanceType<(typeof providers)[Providers]>
15
- ): provider is InstanceType<(typeof providers)[Providers]> & {
16
- revokeAccessToken: (token: string) => Promise<void>;
17
- } =>
18
- 'revokeAccessToken' in provider &&
19
- typeof provider.revokeAccessToken === 'function';
20
-
21
- export const isValidProviderKey = (
22
- provider: string
23
- ): provider is keyof typeof providers =>
24
- Object.keys(providers)
25
- .map((key) => key.toLowerCase())
26
- .includes(provider.toLowerCase());
27
-
28
- export const isValidUser = <UserType>(user: unknown): user is UserType => true;
29
-
30
- export const isNonEmptyString = (
31
- str: string | null | undefined
32
- ): str is string => str !== null && str !== undefined && str.trim() !== '';
package/src/types.ts DELETED
@@ -1,78 +0,0 @@
1
- import { Cookie } from 'elysia';
2
- import { providers } from './providers';
3
-
4
- type SessionData<UserType> = {
5
- user: UserType;
6
- expiresAt: number;
7
- };
8
-
9
- type Oauth2ConfigOptions = {
10
- [K in Providers]?: {
11
- credentials: ConstructorParameters<(typeof providers)[K]>;
12
- scopes?: string[];
13
- searchParams?: [string, string][];
14
- };
15
- };
16
-
17
- export type Providers = keyof typeof providers;
18
-
19
- export type SessionRecord<UserType> = Record<
20
- string,
21
- SessionData<UserType> | undefined
22
- >;
23
-
24
- export type UserFunctionProps = {
25
- authProvider: string;
26
- decodedIdToken: {
27
- [key: string]: string | undefined;
28
- };
29
- };
30
-
31
- export type CreateUser<UserType> = ({
32
- decodedIdToken,
33
- authProvider
34
- }: UserFunctionProps) => Promise<UserType>;
35
-
36
- export type GetUser<UserType> = ({
37
- decodedIdToken,
38
- authProvider
39
- }: UserFunctionProps) => Promise<UserType | null>;
40
-
41
- export type OnCallback<UserType> = ({
42
- authProvider,
43
- decodedIdToken,
44
- session,
45
- user_session_id
46
- }: {
47
- authProvider: string;
48
- decodedIdToken: {
49
- [key: string]: string | undefined;
50
- };
51
- session: SessionRecord<UserType>;
52
- user_session_id: Cookie<string | undefined>;
53
- }) => void | Promise<void>;
54
-
55
- export type AbsoluteAuthProps<UserType> = {
56
- config: Oauth2ConfigOptions;
57
- authorizeRoute?: string;
58
- callbackRoute?: string;
59
- refreshRoute?: string;
60
- revokeRoute?: string;
61
- logoutRoute?: string;
62
- statusRoute?: string;
63
- onAuthorize?: () => void;
64
- onCallback?: OnCallback<UserType>;
65
- onStatus?: () => void;
66
- onRefresh?: () => void;
67
- onLogout?: () => void;
68
- onRevoke?: () => void;
69
- };
70
-
71
- export type ClientProviders = Record<
72
- string,
73
- {
74
- providerInstance: InstanceType<(typeof providers)[Providers]>;
75
- scopes: string[];
76
- searchParams: [string, string][];
77
- }
78
- >;
package/src/utils.ts DELETED
@@ -1,47 +0,0 @@
1
- import { Cookie } from 'elysia';
2
- import { MILLISECONDS_IN_A_DAY } from './constants';
3
- import { AbsoluteAuthProps, SessionRecord } from './types';
4
- import { isValidUser } from './typeGuards';
5
-
6
- type InsantiateUserSessionProps<UserType> = {
7
- authProvider: string;
8
- decodedIdToken: {
9
- [key: string]: string | undefined;
10
- };
11
- session: SessionRecord<UserType>;
12
- user_session_id: Cookie<string | undefined>;
13
- createUser: () => UserType | Promise<UserType>;
14
- getUser: () => UserType | Promise<UserType | null>;
15
- };
16
-
17
- export const instantiateUserSession = async <UserType>({
18
- user_session_id,
19
- session,
20
- getUser,
21
- createUser
22
- }: InsantiateUserSessionProps<UserType>) => {
23
- let user = await getUser();
24
- user = user ?? (await createUser());
25
-
26
- // TODO : See if theres a better way to check valid user and not throw an error
27
- if (!isValidUser<UserType>(user))
28
- throw new Error('Internal Server Error - Invalid user schema');
29
-
30
- const sessionKey = crypto.randomUUID();
31
-
32
- session[sessionKey] = {
33
- expiresAt: Date.now() + MILLISECONDS_IN_A_DAY,
34
- user
35
- };
36
-
37
- user_session_id.set({
38
- httpOnly: true,
39
- sameSite: 'lax',
40
- secure: true,
41
- value: sessionKey
42
- });
43
- };
44
-
45
- export const createAuthConfig = <UserType>(
46
- props: AbsoluteAuthProps<UserType>
47
- ) => props;
package/tsconfig.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ESNext",
4
- "module": "ESNext",
5
- "moduleResolution": "bundler",
6
- "jsx": "react-jsx",
7
- "esModuleInterop": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "outDir": "dist",
10
- "strict": true,
11
- "declaration": true,
12
- "skipLibCheck": true,
13
- "lib": ["DOM", "DOM.Iterable", "ESNext"]
14
- },
15
- "include": ["src/**/*", "example/**/*"],
16
- "exclude": ["node_modules"]
17
- }