@absolutejs/auth 0.4.0 → 0.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.
@@ -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,89 +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
- userProfile: {
27
- [key: string]: string | undefined;
28
- };
29
- };
30
-
31
- export type CreateUser<UserType> = ({
32
- userProfile,
33
- authProvider
34
- }: UserFunctionProps) => Promise<UserType>;
35
-
36
- export type GetUser<UserType> = ({
37
- userProfile,
38
- authProvider
39
- }: UserFunctionProps) => Promise<UserType | null>;
40
-
41
- export type OnCallback<UserType> = ({
42
- authProvider,
43
- userProfile,
44
- session,
45
- user_session_id
46
- }: {
47
- authProvider: string;
48
- userProfile: {
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
- >;
79
-
80
- export type InsantiateUserSessionProps<UserType> = {
81
- authProvider: string;
82
- userProfile: {
83
- [key: string]: string | undefined;
84
- };
85
- session: SessionRecord<UserType>;
86
- user_session_id: Cookie<string | undefined>;
87
- createUser: () => UserType | Promise<UserType>;
88
- getUser: () => UserType | Promise<UserType | null>;
89
- };
package/src/utils.ts DELETED
@@ -1,35 +0,0 @@
1
- import { MILLISECONDS_IN_A_DAY } from './constants';
2
- import { AbsoluteAuthProps, InsantiateUserSessionProps } from './types';
3
- import { isValidUser } from './typeGuards';
4
-
5
- export const instantiateUserSession = async <UserType>({
6
- user_session_id,
7
- session,
8
- getUser,
9
- createUser
10
- }: InsantiateUserSessionProps<UserType>) => {
11
- let user = await getUser();
12
- user = user ?? (await createUser());
13
-
14
- // TODO : See if theres a better way to check valid user and not throw an error
15
- if (!isValidUser<UserType>(user))
16
- throw new Error('Internal Server Error - Invalid user schema');
17
-
18
- const sessionKey = crypto.randomUUID();
19
-
20
- session[sessionKey] = {
21
- expiresAt: Date.now() + MILLISECONDS_IN_A_DAY,
22
- user
23
- };
24
-
25
- user_session_id.set({
26
- httpOnly: true,
27
- sameSite: 'lax',
28
- secure: true,
29
- value: sessionKey
30
- });
31
- };
32
-
33
- export const createAuthConfig = <UserType>(
34
- props: AbsoluteAuthProps<UserType>
35
- ) => 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
- }