@tuwaio/satellite-siwe-next-auth 1.0.0-fix-adapters-independ-alpha.11.e869dab → 1.0.0-fix-optimization-alpha.1.d6a8b2d
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/dist/index.d.mts +5 -156
- package/dist/index.d.ts +5 -156
- package/dist/index.js +1 -2
- package/dist/index.mjs +1 -2
- package/dist/server/index.d.mts +5 -56
- package/dist/server/index.d.ts +25 -0
- package/dist/server/index.js +2 -0
- package/dist/server/index.mjs +1 -2
- package/dist/types-D5pX4B-f.d.mts +158 -0
- package/dist/types-D5pX4B-f.d.ts +158 -0
- package/package.json +1 -1
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/server/index.mjs.map +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { S as SIWESession, a as SiweAuthContextType, b as SiweNextAuthProviderProps, U as UseSiweSignatureResult } from './types-D5pX4B-f.mjs';
|
|
2
|
+
export { C as ConfigurableMessageOptions, G as GetSiweMessageOptions, h as Session, f as SiweApiConfig, e as SiweApiHooks, c as SiweCookieOptions, g as SiweSessionData, d as SiweSessionSettings, i as UnconfigurableMessageOptions } from './types-D5pX4B-f.mjs';
|
|
1
3
|
import { Config } from '@wagmi/core';
|
|
2
4
|
import * as react from 'react';
|
|
3
|
-
import { ReactNode } from 'react';
|
|
4
|
-
import { Address } from 'viem';
|
|
5
|
-
import { SiweMessage } from 'viem/siwe';
|
|
6
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
6
|
+
import 'viem';
|
|
7
|
+
import 'viem/siwe';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* @function useInterval
|
|
@@ -11,158 +12,6 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
11
12
|
*/
|
|
12
13
|
declare function useInterval(callback: () => void, delay: number | null): void;
|
|
13
14
|
|
|
14
|
-
/**
|
|
15
|
-
* Interface for the optional cookie serialization options.
|
|
16
|
-
* Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
|
|
17
|
-
*/
|
|
18
|
-
interface SiweCookieOptions {
|
|
19
|
-
/** The value of the Max-Age Set-Cookie attribute in seconds. */
|
|
20
|
-
maxAge?: number;
|
|
21
|
-
/** The "Domain" Set-Cookie attribute. */
|
|
22
|
-
domain?: string;
|
|
23
|
-
/** The "Path" Set-Cookie attribute. */
|
|
24
|
-
path?: string;
|
|
25
|
-
/** The "Expires" Set-Cookie attribute. */
|
|
26
|
-
expires?: Date;
|
|
27
|
-
/** The "HttpOnly" Set-Cookie attribute. */
|
|
28
|
-
httpOnly?: boolean;
|
|
29
|
-
/** The "Secure" Set-Cookie attribute. */
|
|
30
|
-
secure?: boolean;
|
|
31
|
-
/** The "SameSite" Set-Cookie attribute. */
|
|
32
|
-
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Interface for the session settings block provided by the user.
|
|
36
|
-
*/
|
|
37
|
-
interface SiweSessionSettings {
|
|
38
|
-
/** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
|
|
39
|
-
cookieName?: string;
|
|
40
|
-
/** * The password/secret used to encrypt the session data.
|
|
41
|
-
* Defaults to `process.env.SESSION_SECRET`.
|
|
42
|
-
*/
|
|
43
|
-
password?: string;
|
|
44
|
-
/** Optional options for cookie serialization. */
|
|
45
|
-
cookieOptions?: SiweCookieOptions;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Interface for the custom SIWE API hooks block provided by the user.
|
|
49
|
-
*/
|
|
50
|
-
interface SiweApiHooks {
|
|
51
|
-
/** Hook executed after the user is successfully logged out. */
|
|
52
|
-
afterLogout?: () => Promise<void> | void;
|
|
53
|
-
/** Hook executed before SIWE message verification (e.g., when the message is available). */
|
|
54
|
-
afterNonce?: () => Promise<void> | void;
|
|
55
|
-
/** Hook executed after the session is successfully created/saved. */
|
|
56
|
-
afterSession?: () => Promise<void> | void;
|
|
57
|
-
/** Hook executed after the SIWE signature is successfully verified. */
|
|
58
|
-
afterVerify?: () => Promise<void> | void;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* The complete configuration object for the SIWE API handler factory.
|
|
62
|
-
*/
|
|
63
|
-
interface SiweApiConfig {
|
|
64
|
-
/** Session configuration settings for Iron Session. */
|
|
65
|
-
session?: SiweSessionSettings;
|
|
66
|
-
/** Custom callback hooks for various steps of the SIWE process. */
|
|
67
|
-
options?: SiweApiHooks;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Defines the data structure stored inside the Iron Session.
|
|
71
|
-
*/
|
|
72
|
-
interface SiweSessionData {
|
|
73
|
-
address: string;
|
|
74
|
-
chainId: number;
|
|
75
|
-
isLoggedIn: boolean;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Type alias for the Iron Session data.
|
|
79
|
-
*/
|
|
80
|
-
type Session = SiweSessionData;
|
|
81
|
-
/**
|
|
82
|
-
* @typedef {Object} UnconfigurableMessageOptions
|
|
83
|
-
* Fields in the SIWE message that are controlled internally by the adapter logic.
|
|
84
|
-
* @property {Address} address - The Ethereum address signing the message (Viem type).
|
|
85
|
-
* @property {number} chainId - The chain ID of the network.
|
|
86
|
-
* @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
|
|
87
|
-
*/
|
|
88
|
-
type UnconfigurableMessageOptions = {
|
|
89
|
-
address: Address;
|
|
90
|
-
chainId: number;
|
|
91
|
-
nonce: string;
|
|
92
|
-
};
|
|
93
|
-
/**
|
|
94
|
-
* @typedef {Object} ConfigurableMessageOptions
|
|
95
|
-
* Partial set of SIWE message fields that a consumer can optionally override.
|
|
96
|
-
* Unconfigurable fields are omitted.
|
|
97
|
-
*/
|
|
98
|
-
type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
|
|
99
|
-
/**
|
|
100
|
-
* @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
|
|
101
|
-
* Function signature for customizing SIWE message options.
|
|
102
|
-
*/
|
|
103
|
-
type GetSiweMessageOptions = () => ConfigurableMessageOptions;
|
|
104
|
-
/**
|
|
105
|
-
* @interface SIWESession
|
|
106
|
-
* The authenticated user data structure derived from the NextAuth session.
|
|
107
|
-
*/
|
|
108
|
-
interface SIWESession {
|
|
109
|
-
address: Address;
|
|
110
|
-
chainId: number;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* @interface SiweAuthContextType
|
|
114
|
-
* Interface for the SIWE authentication context state and actions.
|
|
115
|
-
* @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
|
|
116
|
-
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
117
|
-
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
118
|
-
* @property {boolean} isLoading - True if the session status is loading.
|
|
119
|
-
* @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
|
|
120
|
-
* @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
|
|
121
|
-
* @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
|
|
122
|
-
*/
|
|
123
|
-
interface SiweAuthContextType {
|
|
124
|
-
data: SIWESession | undefined;
|
|
125
|
-
isReadyToSign: boolean;
|
|
126
|
-
isRejected: boolean;
|
|
127
|
-
isLoading: boolean;
|
|
128
|
-
isSignedIn: boolean;
|
|
129
|
-
enabled: boolean;
|
|
130
|
-
signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
|
|
131
|
-
signOutSiwe: (onSignOut?: () => void) => Promise<void>;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* @interface UseSiweSignatureResult
|
|
135
|
-
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
136
|
-
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
137
|
-
* @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
|
|
138
|
-
*/
|
|
139
|
-
interface UseSiweSignatureResult {
|
|
140
|
-
isReadyToSign: boolean;
|
|
141
|
-
isRejected: boolean;
|
|
142
|
-
getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
|
|
143
|
-
message: string;
|
|
144
|
-
signature: Address;
|
|
145
|
-
} | undefined>;
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* @interface SiweNextAuthProviderProps
|
|
149
|
-
* @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
|
|
150
|
-
* @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
|
|
151
|
-
* @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
|
|
152
|
-
* @property {() => void} [onSignOut] - Callback executed after a successful sign-out or connector disconnect.
|
|
153
|
-
* @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
|
|
154
|
-
* @property {ReactNode} children - Child components.
|
|
155
|
-
*/
|
|
156
|
-
interface SiweNextAuthProviderProps {
|
|
157
|
-
wagmiConfig: Config;
|
|
158
|
-
enabled?: boolean;
|
|
159
|
-
nonceRefetchInterval?: number;
|
|
160
|
-
onSignIn?: (session?: SIWESession) => void;
|
|
161
|
-
onSignOut?: () => void;
|
|
162
|
-
getSiweMessageOptions?: GetSiweMessageOptions;
|
|
163
|
-
children: ReactNode;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
15
|
/**
|
|
167
16
|
* @function useSiweAuth
|
|
168
17
|
* @description Hook to access the SIWE authentication state and methods.
|
|
@@ -211,4 +60,4 @@ declare const SiweAuthContext: react.Context<SiweAuthContextType | undefined>;
|
|
|
211
60
|
*/
|
|
212
61
|
declare function SiweNextAuthProvider(props: SiweNextAuthProviderProps): react_jsx_runtime.JSX.Element;
|
|
213
62
|
|
|
214
|
-
export {
|
|
63
|
+
export { SIWESession, SiweAuthContext, SiweAuthContextType, SiweNextAuthProvider, SiweNextAuthProviderProps, UseSiweSignatureResult, useInterval, useSiweAuth, useSiweAuthAdapter, useSiweSignature };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { S as SIWESession, a as SiweAuthContextType, b as SiweNextAuthProviderProps, U as UseSiweSignatureResult } from './types-D5pX4B-f.js';
|
|
2
|
+
export { C as ConfigurableMessageOptions, G as GetSiweMessageOptions, h as Session, f as SiweApiConfig, e as SiweApiHooks, c as SiweCookieOptions, g as SiweSessionData, d as SiweSessionSettings, i as UnconfigurableMessageOptions } from './types-D5pX4B-f.js';
|
|
1
3
|
import { Config } from '@wagmi/core';
|
|
2
4
|
import * as react from 'react';
|
|
3
|
-
import { ReactNode } from 'react';
|
|
4
|
-
import { Address } from 'viem';
|
|
5
|
-
import { SiweMessage } from 'viem/siwe';
|
|
6
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
6
|
+
import 'viem';
|
|
7
|
+
import 'viem/siwe';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* @function useInterval
|
|
@@ -11,158 +12,6 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
11
12
|
*/
|
|
12
13
|
declare function useInterval(callback: () => void, delay: number | null): void;
|
|
13
14
|
|
|
14
|
-
/**
|
|
15
|
-
* Interface for the optional cookie serialization options.
|
|
16
|
-
* Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
|
|
17
|
-
*/
|
|
18
|
-
interface SiweCookieOptions {
|
|
19
|
-
/** The value of the Max-Age Set-Cookie attribute in seconds. */
|
|
20
|
-
maxAge?: number;
|
|
21
|
-
/** The "Domain" Set-Cookie attribute. */
|
|
22
|
-
domain?: string;
|
|
23
|
-
/** The "Path" Set-Cookie attribute. */
|
|
24
|
-
path?: string;
|
|
25
|
-
/** The "Expires" Set-Cookie attribute. */
|
|
26
|
-
expires?: Date;
|
|
27
|
-
/** The "HttpOnly" Set-Cookie attribute. */
|
|
28
|
-
httpOnly?: boolean;
|
|
29
|
-
/** The "Secure" Set-Cookie attribute. */
|
|
30
|
-
secure?: boolean;
|
|
31
|
-
/** The "SameSite" Set-Cookie attribute. */
|
|
32
|
-
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Interface for the session settings block provided by the user.
|
|
36
|
-
*/
|
|
37
|
-
interface SiweSessionSettings {
|
|
38
|
-
/** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
|
|
39
|
-
cookieName?: string;
|
|
40
|
-
/** * The password/secret used to encrypt the session data.
|
|
41
|
-
* Defaults to `process.env.SESSION_SECRET`.
|
|
42
|
-
*/
|
|
43
|
-
password?: string;
|
|
44
|
-
/** Optional options for cookie serialization. */
|
|
45
|
-
cookieOptions?: SiweCookieOptions;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Interface for the custom SIWE API hooks block provided by the user.
|
|
49
|
-
*/
|
|
50
|
-
interface SiweApiHooks {
|
|
51
|
-
/** Hook executed after the user is successfully logged out. */
|
|
52
|
-
afterLogout?: () => Promise<void> | void;
|
|
53
|
-
/** Hook executed before SIWE message verification (e.g., when the message is available). */
|
|
54
|
-
afterNonce?: () => Promise<void> | void;
|
|
55
|
-
/** Hook executed after the session is successfully created/saved. */
|
|
56
|
-
afterSession?: () => Promise<void> | void;
|
|
57
|
-
/** Hook executed after the SIWE signature is successfully verified. */
|
|
58
|
-
afterVerify?: () => Promise<void> | void;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* The complete configuration object for the SIWE API handler factory.
|
|
62
|
-
*/
|
|
63
|
-
interface SiweApiConfig {
|
|
64
|
-
/** Session configuration settings for Iron Session. */
|
|
65
|
-
session?: SiweSessionSettings;
|
|
66
|
-
/** Custom callback hooks for various steps of the SIWE process. */
|
|
67
|
-
options?: SiweApiHooks;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Defines the data structure stored inside the Iron Session.
|
|
71
|
-
*/
|
|
72
|
-
interface SiweSessionData {
|
|
73
|
-
address: string;
|
|
74
|
-
chainId: number;
|
|
75
|
-
isLoggedIn: boolean;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Type alias for the Iron Session data.
|
|
79
|
-
*/
|
|
80
|
-
type Session = SiweSessionData;
|
|
81
|
-
/**
|
|
82
|
-
* @typedef {Object} UnconfigurableMessageOptions
|
|
83
|
-
* Fields in the SIWE message that are controlled internally by the adapter logic.
|
|
84
|
-
* @property {Address} address - The Ethereum address signing the message (Viem type).
|
|
85
|
-
* @property {number} chainId - The chain ID of the network.
|
|
86
|
-
* @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
|
|
87
|
-
*/
|
|
88
|
-
type UnconfigurableMessageOptions = {
|
|
89
|
-
address: Address;
|
|
90
|
-
chainId: number;
|
|
91
|
-
nonce: string;
|
|
92
|
-
};
|
|
93
|
-
/**
|
|
94
|
-
* @typedef {Object} ConfigurableMessageOptions
|
|
95
|
-
* Partial set of SIWE message fields that a consumer can optionally override.
|
|
96
|
-
* Unconfigurable fields are omitted.
|
|
97
|
-
*/
|
|
98
|
-
type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
|
|
99
|
-
/**
|
|
100
|
-
* @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
|
|
101
|
-
* Function signature for customizing SIWE message options.
|
|
102
|
-
*/
|
|
103
|
-
type GetSiweMessageOptions = () => ConfigurableMessageOptions;
|
|
104
|
-
/**
|
|
105
|
-
* @interface SIWESession
|
|
106
|
-
* The authenticated user data structure derived from the NextAuth session.
|
|
107
|
-
*/
|
|
108
|
-
interface SIWESession {
|
|
109
|
-
address: Address;
|
|
110
|
-
chainId: number;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* @interface SiweAuthContextType
|
|
114
|
-
* Interface for the SIWE authentication context state and actions.
|
|
115
|
-
* @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
|
|
116
|
-
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
117
|
-
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
118
|
-
* @property {boolean} isLoading - True if the session status is loading.
|
|
119
|
-
* @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
|
|
120
|
-
* @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
|
|
121
|
-
* @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
|
|
122
|
-
*/
|
|
123
|
-
interface SiweAuthContextType {
|
|
124
|
-
data: SIWESession | undefined;
|
|
125
|
-
isReadyToSign: boolean;
|
|
126
|
-
isRejected: boolean;
|
|
127
|
-
isLoading: boolean;
|
|
128
|
-
isSignedIn: boolean;
|
|
129
|
-
enabled: boolean;
|
|
130
|
-
signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
|
|
131
|
-
signOutSiwe: (onSignOut?: () => void) => Promise<void>;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* @interface UseSiweSignatureResult
|
|
135
|
-
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
136
|
-
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
137
|
-
* @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
|
|
138
|
-
*/
|
|
139
|
-
interface UseSiweSignatureResult {
|
|
140
|
-
isReadyToSign: boolean;
|
|
141
|
-
isRejected: boolean;
|
|
142
|
-
getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
|
|
143
|
-
message: string;
|
|
144
|
-
signature: Address;
|
|
145
|
-
} | undefined>;
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* @interface SiweNextAuthProviderProps
|
|
149
|
-
* @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
|
|
150
|
-
* @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
|
|
151
|
-
* @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
|
|
152
|
-
* @property {() => void} [onSignOut] - Callback executed after a successful sign-out or connector disconnect.
|
|
153
|
-
* @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
|
|
154
|
-
* @property {ReactNode} children - Child components.
|
|
155
|
-
*/
|
|
156
|
-
interface SiweNextAuthProviderProps {
|
|
157
|
-
wagmiConfig: Config;
|
|
158
|
-
enabled?: boolean;
|
|
159
|
-
nonceRefetchInterval?: number;
|
|
160
|
-
onSignIn?: (session?: SIWESession) => void;
|
|
161
|
-
onSignOut?: () => void;
|
|
162
|
-
getSiweMessageOptions?: GetSiweMessageOptions;
|
|
163
|
-
children: ReactNode;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
15
|
/**
|
|
167
16
|
* @function useSiweAuth
|
|
168
17
|
* @description Hook to access the SIWE authentication state and methods.
|
|
@@ -211,4 +60,4 @@ declare const SiweAuthContext: react.Context<SiweAuthContextType | undefined>;
|
|
|
211
60
|
*/
|
|
212
61
|
declare function SiweNextAuthProvider(props: SiweNextAuthProviderProps): react_jsx_runtime.JSX.Element;
|
|
213
62
|
|
|
214
|
-
export {
|
|
63
|
+
export { SIWESession, SiweAuthContext, SiweAuthContextType, SiweNextAuthProvider, SiweNextAuthProviderProps, UseSiweSignatureResult, useInterval, useSiweAuth, useSiweAuthAdapter, useSiweSignature };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
'use strict';var react=require('react'),core=require('@wagmi/core'),wagmi=require('wagmi'),siwe=require('viem/siwe'),jsxRuntime=require('react/jsx-runtime');function L(t,e){let r=react.useRef(t);react.useEffect(()=>{r.current=t;},[t]),react.useEffect(()=>{if(e!==null&&typeof window<"u"&&window.setInterval){let a=window.setInterval(()=>r.current(),e);return ()=>window.clearInterval(a)}},[e]);}var A=react.createContext(void 0);function de(t){let e=react.useContext(A);if(e===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let r=react.useCallback(async()=>e.signInWithSiwe(t?.onSignIn),[e.signInWithSiwe,t?.onSignIn]),a=react.useCallback(async()=>e.signOutSiwe(t?.onSignOut),[e.signOutSiwe,t?.onSignOut]);return react.useMemo(()=>({...e,signInWithSiwe:r,signOutSiwe:a}),[e,r,a])}async function X(){return crypto.randomUUID().replace(/-/g,"")}function k({wagmiConfig:t}){let{isConnected:e,address:r,chainId:a}=wagmi.useConnection({config:t}),[h,d]=react.useState(false),u=react.useMemo(()=>e&&!!r&&!!a,[e,r,a]);return react.useEffect(()=>{u&&d(false);},[u]),{getSiweSignature:async S=>{d(false);let n=core.getConnection(t);if(!n.isConnected||!n.address||!n.chainId)throw new Error("Connector not connected or connection details are missing from Wagmi snapshot.");try{let o=await X();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let c=siwe.createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...S?S():{},address:n.address,chainId:n.chainId,nonce:o}),w=await core.signMessage(t,{message:c});if(!w)throw d(!0),await core.disconnect(t),new Error("Message signing cancelled by user or failed.");return {message:c,signature:w}}catch(o){await core.disconnect(t),console.error("Error during signature generation:",o);let c=o;throw (c.name==="UserRejectedRequestError"||c.code===4001||/user rejected/i.test(c.message))&&d(true),o}},isReadyToSign:u,isRejected:h}}async function ee(){try{let t=await fetch("/api/siwe/session");if(t.status===401||t.status===404)return {session:void 0,status:"unauthenticated"};if(!t.ok)throw new Error("Failed to fetch session data.");let e=await t.json();return e.isLoggedIn&&e.address&&e.chainId?{session:{address:e.address,chainId:e.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(t){return console.error("Error fetching session:",t),{session:void 0,status:"unauthenticated"}}}function O({wagmiConfig:t,enabled:e=true,nonceRefetchInterval:r=300*1e3,onSignIn:a,onSignOut:h,getSiweMessageOptions:d}){let[u,p]=react.useState(void 0),[S,n]=react.useState("loading"),{isReadyToSign:o,getSiweSignature:c,isRejected:w}=k({wagmiConfig:t}),{address:y,chainId:v,isConnected:W}=wagmi.useConnection({config:t}),[P,T]=react.useState(false),g=S==="authenticated",R=S==="loading",N=u,F=react.useCallback(async()=>{n("loading");let{session:s,status:i}=await ee();return p(s),n(i),s},[]);L(()=>{g&&F();},r);let m=react.useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),p(void 0),n("unauthenticated"),h?.(),s?.();},[h]),I=react.useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");n("loading");try{let i=await c(d);if(!i){n("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i.message,signature:i.signature})}),f=await l.json();if(!l.ok||f.isLoggedIn!==!0)throw new Error(`Verification error: ${f.message||"Login failed."}`);console.log("SIWE Authentication successful.");let x={address:f.address,chainId:f.chainId};p(x),n("authenticated"),a?.(x),s?.(x);}catch(i){throw await core.disconnect(t),n("unauthenticated"),new Error(`SIWE Sign-In failed: ${i instanceof Error?i.message:"Unknown error"}`)}},[e,c,d,a,t]);return react.useEffect(()=>{if(g&&e){let s=u?.address?.toLowerCase(),i=y?.toLowerCase(),l=u?.chainId,f=v;s&&i&&s!==i||l&&f&&l!==f?(console.log("SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!W&&(console.log("SIWE: Connector disconnected. Disconnecting session."),m(),h?.());}},[g,y,v,W,u,m,e,h]),react.useEffect(()=>{P&&S==="unauthenticated"&&o&&e&&(console.log("SIWE: State reset detected. Attempting automatic sign-in to establish new session."),T(false),I().catch(s=>{throw new Error(`SIWE Auto Sign-In failed after context change: ${s instanceof Error?s.message:"Unknown error"}`)}));},[P,S,o,I,e]),react.useMemo(()=>({data:N,isReadyToSign:o,isRejected:w,isLoading:R,isSignedIn:g,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,w,R,g,I,m,e])}function We(t){let e=O(t);return jsxRuntime.jsx(A.Provider,{value:e,children:t.children})}exports.SiweAuthContext=A;exports.SiweNextAuthProvider=We;exports.useInterval=L;exports.useSiweAuth=de;exports.useSiweAuthAdapter=O;exports.useSiweSignature=k
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
'use strict';var react=require('react'),core=require('@wagmi/core'),wagmi=require('wagmi'),siwe=require('viem/siwe'),jsxRuntime=require('react/jsx-runtime');function L(t,e){let r=react.useRef(t);react.useEffect(()=>{r.current=t;},[t]),react.useEffect(()=>{if(e!==null&&typeof window<"u"&&window.setInterval){let a=window.setInterval(()=>r.current(),e);return ()=>window.clearInterval(a)}},[e]);}var A=react.createContext(void 0);function de(t){let e=react.useContext(A);if(e===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let r=react.useCallback(async()=>e.signInWithSiwe(t?.onSignIn),[e.signInWithSiwe,t?.onSignIn]),a=react.useCallback(async()=>e.signOutSiwe(t?.onSignOut),[e.signOutSiwe,t?.onSignOut]);return react.useMemo(()=>({...e,signInWithSiwe:r,signOutSiwe:a}),[e,r,a])}async function X(){return crypto.randomUUID().replace(/-/g,"")}function k({wagmiConfig:t}){let{isConnected:e,address:r,chainId:a}=wagmi.useConnection({config:t}),[h,d]=react.useState(false),u=react.useMemo(()=>e&&!!r&&!!a,[e,r,a]);return react.useEffect(()=>{u&&d(false);},[u]),{getSiweSignature:async S=>{d(false);let n=core.getConnection(t);if(!n.isConnected||!n.address||!n.chainId)throw new Error("Connector not connected or connection details are missing from Wagmi snapshot.");try{let o=await X();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let c=siwe.createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...S?S():{},address:n.address,chainId:n.chainId,nonce:o}),w=await core.signMessage(t,{message:c});if(!w)throw d(!0),await core.disconnect(t),new Error("Message signing cancelled by user or failed.");return {message:c,signature:w}}catch(o){await core.disconnect(t),console.error("Error during signature generation:",o);let c=o;throw (c.name==="UserRejectedRequestError"||c.code===4001||/user rejected/i.test(c.message))&&d(true),o}},isReadyToSign:u,isRejected:h}}async function ee(){try{let t=await fetch("/api/siwe/session");if(t.status===401||t.status===404)return {session:void 0,status:"unauthenticated"};if(!t.ok)throw new Error("Failed to fetch session data.");let e=await t.json();return e.isLoggedIn&&e.address&&e.chainId?{session:{address:e.address,chainId:e.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(t){return console.error("Error fetching session:",t),{session:void 0,status:"unauthenticated"}}}function O({wagmiConfig:t,enabled:e=true,nonceRefetchInterval:r=300*1e3,onSignIn:a,onSignOut:h,getSiweMessageOptions:d}){let[u,p]=react.useState(void 0),[S,n]=react.useState("loading"),{isReadyToSign:o,getSiweSignature:c,isRejected:w}=k({wagmiConfig:t}),{address:y,chainId:v,isConnected:W}=wagmi.useConnection({config:t}),[P,T]=react.useState(false),g=S==="authenticated",R=S==="loading",N=u,F=react.useCallback(async()=>{n("loading");let{session:s,status:i}=await ee();return p(s),n(i),s},[]);L(()=>{g&&F();},r);let m=react.useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),p(void 0),n("unauthenticated"),h?.(),s?.();},[h]),I=react.useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");n("loading");try{let i=await c(d);if(!i){n("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i.message,signature:i.signature})}),f=await l.json();if(!l.ok||f.isLoggedIn!==!0)throw new Error(`Verification error: ${f.message||"Login failed."}`);console.log("SIWE Authentication successful.");let x={address:f.address,chainId:f.chainId};p(x),n("authenticated"),a?.(x),s?.(x);}catch(i){throw await core.disconnect(t),n("unauthenticated"),new Error(`SIWE Sign-In failed: ${i instanceof Error?i.message:"Unknown error"}`)}},[e,c,d,a,t]);return react.useEffect(()=>{if(g&&e){let s=u?.address?.toLowerCase(),i=y?.toLowerCase(),l=u?.chainId,f=v;s&&i&&s!==i||l&&f&&l!==f?(console.log("SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!W&&(console.log("SIWE: Connector disconnected. Disconnecting session."),m(),h?.());}},[g,y,v,W,u,m,e,h]),react.useEffect(()=>{P&&S==="unauthenticated"&&o&&e&&(console.log("SIWE: State reset detected. Attempting automatic sign-in to establish new session."),T(false),I().catch(s=>{throw new Error(`SIWE Auto Sign-In failed after context change: ${s instanceof Error?s.message:"Unknown error"}`)}));},[P,S,o,I,e]),react.useMemo(()=>({data:N,isReadyToSign:o,isRejected:w,isLoading:R,isSignedIn:g,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,w,R,g,I,m,e])}function We(t){let e=O(t);return jsxRuntime.jsx(A.Provider,{value:e,children:t.children})}exports.SiweAuthContext=A;exports.SiweNextAuthProvider=We;exports.useInterval=L;exports.useSiweAuth=de;exports.useSiweAuthAdapter=O;exports.useSiweSignature=k;
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import {createContext,useRef,useEffect,useContext,useCallback,useMemo,useState}from'react';import {getConnection,signMessage,disconnect}from'@wagmi/core';import {useConnection}from'wagmi';import {createSiweMessage}from'viem/siwe';import {jsx}from'react/jsx-runtime';function L(t,e){let r=useRef(t);useEffect(()=>{r.current=t;},[t]),useEffect(()=>{if(e!==null&&typeof window<"u"&&window.setInterval){let a=window.setInterval(()=>r.current(),e);return ()=>window.clearInterval(a)}},[e]);}var A=createContext(void 0);function de(t){let e=useContext(A);if(e===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let r=useCallback(async()=>e.signInWithSiwe(t?.onSignIn),[e.signInWithSiwe,t?.onSignIn]),a=useCallback(async()=>e.signOutSiwe(t?.onSignOut),[e.signOutSiwe,t?.onSignOut]);return useMemo(()=>({...e,signInWithSiwe:r,signOutSiwe:a}),[e,r,a])}async function X(){return crypto.randomUUID().replace(/-/g,"")}function k({wagmiConfig:t}){let{isConnected:e,address:r,chainId:a}=useConnection({config:t}),[h,d]=useState(false),u=useMemo(()=>e&&!!r&&!!a,[e,r,a]);return useEffect(()=>{u&&d(false);},[u]),{getSiweSignature:async S=>{d(false);let n=getConnection(t);if(!n.isConnected||!n.address||!n.chainId)throw new Error("Connector not connected or connection details are missing from Wagmi snapshot.");try{let o=await X();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let c=createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...S?S():{},address:n.address,chainId:n.chainId,nonce:o}),w=await signMessage(t,{message:c});if(!w)throw d(!0),await disconnect(t),new Error("Message signing cancelled by user or failed.");return {message:c,signature:w}}catch(o){await disconnect(t),console.error("Error during signature generation:",o);let c=o;throw (c.name==="UserRejectedRequestError"||c.code===4001||/user rejected/i.test(c.message))&&d(true),o}},isReadyToSign:u,isRejected:h}}async function ee(){try{let t=await fetch("/api/siwe/session");if(t.status===401||t.status===404)return {session:void 0,status:"unauthenticated"};if(!t.ok)throw new Error("Failed to fetch session data.");let e=await t.json();return e.isLoggedIn&&e.address&&e.chainId?{session:{address:e.address,chainId:e.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(t){return console.error("Error fetching session:",t),{session:void 0,status:"unauthenticated"}}}function O({wagmiConfig:t,enabled:e=true,nonceRefetchInterval:r=300*1e3,onSignIn:a,onSignOut:h,getSiweMessageOptions:d}){let[u,p]=useState(void 0),[S,n]=useState("loading"),{isReadyToSign:o,getSiweSignature:c,isRejected:w}=k({wagmiConfig:t}),{address:y,chainId:v,isConnected:W}=useConnection({config:t}),[P,T]=useState(false),g=S==="authenticated",R=S==="loading",N=u,F=useCallback(async()=>{n("loading");let{session:s,status:i}=await ee();return p(s),n(i),s},[]);L(()=>{g&&F();},r);let m=useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),p(void 0),n("unauthenticated"),h?.(),s?.();},[h]),I=useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");n("loading");try{let i=await c(d);if(!i){n("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i.message,signature:i.signature})}),f=await l.json();if(!l.ok||f.isLoggedIn!==!0)throw new Error(`Verification error: ${f.message||"Login failed."}`);console.log("SIWE Authentication successful.");let x={address:f.address,chainId:f.chainId};p(x),n("authenticated"),a?.(x),s?.(x);}catch(i){throw await disconnect(t),n("unauthenticated"),new Error(`SIWE Sign-In failed: ${i instanceof Error?i.message:"Unknown error"}`)}},[e,c,d,a,t]);return useEffect(()=>{if(g&&e){let s=u?.address?.toLowerCase(),i=y?.toLowerCase(),l=u?.chainId,f=v;s&&i&&s!==i||l&&f&&l!==f?(console.log("SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!W&&(console.log("SIWE: Connector disconnected. Disconnecting session."),m(),h?.());}},[g,y,v,W,u,m,e,h]),useEffect(()=>{P&&S==="unauthenticated"&&o&&e&&(console.log("SIWE: State reset detected. Attempting automatic sign-in to establish new session."),T(false),I().catch(s=>{throw new Error(`SIWE Auto Sign-In failed after context change: ${s instanceof Error?s.message:"Unknown error"}`)}));},[P,S,o,I,e]),useMemo(()=>({data:N,isReadyToSign:o,isRejected:w,isLoading:R,isSignedIn:g,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,w,R,g,I,m,e])}function We(t){let e=O(t);return jsx(A.Provider,{value:e,children:t.children})}export{A as SiweAuthContext,We as SiweNextAuthProvider,L as useInterval,de as useSiweAuth,O as useSiweAuthAdapter,k as useSiweSignature}
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import {createContext,useRef,useEffect,useContext,useCallback,useMemo,useState}from'react';import {getConnection,signMessage,disconnect}from'@wagmi/core';import {useConnection}from'wagmi';import {createSiweMessage}from'viem/siwe';import {jsx}from'react/jsx-runtime';function L(t,e){let r=useRef(t);useEffect(()=>{r.current=t;},[t]),useEffect(()=>{if(e!==null&&typeof window<"u"&&window.setInterval){let a=window.setInterval(()=>r.current(),e);return ()=>window.clearInterval(a)}},[e]);}var A=createContext(void 0);function de(t){let e=useContext(A);if(e===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let r=useCallback(async()=>e.signInWithSiwe(t?.onSignIn),[e.signInWithSiwe,t?.onSignIn]),a=useCallback(async()=>e.signOutSiwe(t?.onSignOut),[e.signOutSiwe,t?.onSignOut]);return useMemo(()=>({...e,signInWithSiwe:r,signOutSiwe:a}),[e,r,a])}async function X(){return crypto.randomUUID().replace(/-/g,"")}function k({wagmiConfig:t}){let{isConnected:e,address:r,chainId:a}=useConnection({config:t}),[h,d]=useState(false),u=useMemo(()=>e&&!!r&&!!a,[e,r,a]);return useEffect(()=>{u&&d(false);},[u]),{getSiweSignature:async S=>{d(false);let n=getConnection(t);if(!n.isConnected||!n.address||!n.chainId)throw new Error("Connector not connected or connection details are missing from Wagmi snapshot.");try{let o=await X();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let c=createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...S?S():{},address:n.address,chainId:n.chainId,nonce:o}),w=await signMessage(t,{message:c});if(!w)throw d(!0),await disconnect(t),new Error("Message signing cancelled by user or failed.");return {message:c,signature:w}}catch(o){await disconnect(t),console.error("Error during signature generation:",o);let c=o;throw (c.name==="UserRejectedRequestError"||c.code===4001||/user rejected/i.test(c.message))&&d(true),o}},isReadyToSign:u,isRejected:h}}async function ee(){try{let t=await fetch("/api/siwe/session");if(t.status===401||t.status===404)return {session:void 0,status:"unauthenticated"};if(!t.ok)throw new Error("Failed to fetch session data.");let e=await t.json();return e.isLoggedIn&&e.address&&e.chainId?{session:{address:e.address,chainId:e.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(t){return console.error("Error fetching session:",t),{session:void 0,status:"unauthenticated"}}}function O({wagmiConfig:t,enabled:e=true,nonceRefetchInterval:r=300*1e3,onSignIn:a,onSignOut:h,getSiweMessageOptions:d}){let[u,p]=useState(void 0),[S,n]=useState("loading"),{isReadyToSign:o,getSiweSignature:c,isRejected:w}=k({wagmiConfig:t}),{address:y,chainId:v,isConnected:W}=useConnection({config:t}),[P,T]=useState(false),g=S==="authenticated",R=S==="loading",N=u,F=useCallback(async()=>{n("loading");let{session:s,status:i}=await ee();return p(s),n(i),s},[]);L(()=>{g&&F();},r);let m=useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),p(void 0),n("unauthenticated"),h?.(),s?.();},[h]),I=useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");n("loading");try{let i=await c(d);if(!i){n("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i.message,signature:i.signature})}),f=await l.json();if(!l.ok||f.isLoggedIn!==!0)throw new Error(`Verification error: ${f.message||"Login failed."}`);console.log("SIWE Authentication successful.");let x={address:f.address,chainId:f.chainId};p(x),n("authenticated"),a?.(x),s?.(x);}catch(i){throw await disconnect(t),n("unauthenticated"),new Error(`SIWE Sign-In failed: ${i instanceof Error?i.message:"Unknown error"}`)}},[e,c,d,a,t]);return useEffect(()=>{if(g&&e){let s=u?.address?.toLowerCase(),i=y?.toLowerCase(),l=u?.chainId,f=v;s&&i&&s!==i||l&&f&&l!==f?(console.log("SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!W&&(console.log("SIWE: Connector disconnected. Disconnecting session."),m(),h?.());}},[g,y,v,W,u,m,e,h]),useEffect(()=>{P&&S==="unauthenticated"&&o&&e&&(console.log("SIWE: State reset detected. Attempting automatic sign-in to establish new session."),T(false),I().catch(s=>{throw new Error(`SIWE Auto Sign-In failed after context change: ${s instanceof Error?s.message:"Unknown error"}`)}));},[P,S,o,I,e]),useMemo(()=>({data:N,isReadyToSign:o,isRejected:w,isLoading:R,isSignedIn:g,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,w,R,g,I,m,e])}function We(t){let e=O(t);return jsx(A.Provider,{value:e,children:t.children})}export{A as SiweAuthContext,We as SiweNextAuthProvider,L as useInterval,de as useSiweAuth,O as useSiweAuthAdapter,k as useSiweSignature};
|
package/dist/server/index.d.mts
CHANGED
|
@@ -1,61 +1,10 @@
|
|
|
1
1
|
import { SessionOptions } from 'iron-session';
|
|
2
|
+
import { f as SiweApiConfig } from '../types-D5pX4B-f.mjs';
|
|
2
3
|
import { NextRequest } from 'next/server';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
interface SiweCookieOptions {
|
|
9
|
-
/** The value of the Max-Age Set-Cookie attribute in seconds. */
|
|
10
|
-
maxAge?: number;
|
|
11
|
-
/** The "Domain" Set-Cookie attribute. */
|
|
12
|
-
domain?: string;
|
|
13
|
-
/** The "Path" Set-Cookie attribute. */
|
|
14
|
-
path?: string;
|
|
15
|
-
/** The "Expires" Set-Cookie attribute. */
|
|
16
|
-
expires?: Date;
|
|
17
|
-
/** The "HttpOnly" Set-Cookie attribute. */
|
|
18
|
-
httpOnly?: boolean;
|
|
19
|
-
/** The "Secure" Set-Cookie attribute. */
|
|
20
|
-
secure?: boolean;
|
|
21
|
-
/** The "SameSite" Set-Cookie attribute. */
|
|
22
|
-
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Interface for the session settings block provided by the user.
|
|
26
|
-
*/
|
|
27
|
-
interface SiweSessionSettings {
|
|
28
|
-
/** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
|
|
29
|
-
cookieName?: string;
|
|
30
|
-
/** * The password/secret used to encrypt the session data.
|
|
31
|
-
* Defaults to `process.env.SESSION_SECRET`.
|
|
32
|
-
*/
|
|
33
|
-
password?: string;
|
|
34
|
-
/** Optional options for cookie serialization. */
|
|
35
|
-
cookieOptions?: SiweCookieOptions;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Interface for the custom SIWE API hooks block provided by the user.
|
|
39
|
-
*/
|
|
40
|
-
interface SiweApiHooks {
|
|
41
|
-
/** Hook executed after the user is successfully logged out. */
|
|
42
|
-
afterLogout?: () => Promise<void> | void;
|
|
43
|
-
/** Hook executed before SIWE message verification (e.g., when the message is available). */
|
|
44
|
-
afterNonce?: () => Promise<void> | void;
|
|
45
|
-
/** Hook executed after the session is successfully created/saved. */
|
|
46
|
-
afterSession?: () => Promise<void> | void;
|
|
47
|
-
/** Hook executed after the SIWE signature is successfully verified. */
|
|
48
|
-
afterVerify?: () => Promise<void> | void;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* The complete configuration object for the SIWE API handler factory.
|
|
52
|
-
*/
|
|
53
|
-
interface SiweApiConfig {
|
|
54
|
-
/** Session configuration settings for Iron Session. */
|
|
55
|
-
session?: SiweSessionSettings;
|
|
56
|
-
/** Custom callback hooks for various steps of the SIWE process. */
|
|
57
|
-
options?: SiweApiHooks;
|
|
58
|
-
}
|
|
4
|
+
import '@wagmi/core';
|
|
5
|
+
import 'react';
|
|
6
|
+
import 'viem';
|
|
7
|
+
import 'viem/siwe';
|
|
59
8
|
|
|
60
9
|
/**
|
|
61
10
|
* @function getSessionOptions
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { SessionOptions } from 'iron-session';
|
|
2
|
+
import { f as SiweApiConfig } from '../types-D5pX4B-f.js';
|
|
3
|
+
import { NextRequest } from 'next/server';
|
|
4
|
+
import '@wagmi/core';
|
|
5
|
+
import 'react';
|
|
6
|
+
import 'viem';
|
|
7
|
+
import 'viem/siwe';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @function getSessionOptions
|
|
11
|
+
* @description Generates the Iron Session options object based on user configuration.
|
|
12
|
+
* @param userConfig - The complete user configuration including session settings.
|
|
13
|
+
* @returns SessionOptions The options required by `getIronSession`.
|
|
14
|
+
*/
|
|
15
|
+
declare function getSessionOptions(userConfig: SiweApiConfig): SessionOptions;
|
|
16
|
+
|
|
17
|
+
type AppRouterHandler = (req: NextRequest, context: any) => Promise<Response>;
|
|
18
|
+
interface SiweApiRoutes {
|
|
19
|
+
GET: AppRouterHandler;
|
|
20
|
+
POST: AppRouterHandler;
|
|
21
|
+
DELETE: AppRouterHandler;
|
|
22
|
+
}
|
|
23
|
+
declare function createSiweApiHandler(config?: SiweApiConfig): SiweApiRoutes;
|
|
24
|
+
|
|
25
|
+
export { createSiweApiHandler, getSessionOptions };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var ironSession=require('iron-session'),server=require('next/server'),siwe=require('siwe');function E(n){let e=n.session||{},d=process.env.SIWE_SESSION_SECRET,a=e.password||d;if(!a||a.length<32)throw new Error("SIWE Error: Iron Session requires a 'password' option (min 32 chars) or SIWE_SESSION_SECRET environment variable to be set.");let S={...{secure:process.env.NODE_ENV==="production",maxAge:300*60,httpOnly:true,sameSite:"lax",path:"/"},...e.cookieOptions};return {password:a,cookieName:e.cookieName||"satellite_siwe",cookieOptions:S}}function O(n){if(!n)return console.warn("SIWE WARN: SIWE_SESSION_URL is not defined. Defaulting domain check to 'localhost'."),"localhost";try{return new URL(n.startsWith("http")?n:`https://${n}`).host}catch(e){return console.error(`SIWE ERROR: Invalid URL provided in SIWE_SESSION_URL: ${n}. Error: ${typeof e=="string"?e:e.message}`),"localhost"}}function x(n={}){let e=n.options||{},d=E(n);async function a(o){let s=new Response;return {session:await ironSession.getIronSession(o,s,d),response:s}}async function f(o){try{let{message:s,signature:p}=await o.json();if(!s||!p)return server.NextResponse.json({message:"Missing message or signature"},{status:400});e.afterNonce&&await e.afterNonce();let t=new siwe.SiweMessage(s),i=O(process.env.SIWE_SESSION_URL);if(!(await t.verify({signature:p,domain:i})).success)return server.NextResponse.json({message:"SIWE verification failed"},{status:401});e.afterVerify&&await e.afterVerify();let{session:c,response:l}=await a(o);c.address=t.address,c.chainId=t.chainId,c.isLoggedIn=!0,await c.save(),e.afterSession&&await e.afterSession();let m=server.NextResponse.json({isLoggedIn:!0,address:c.address,chainId:c.chainId},{status:200});return l.headers.forEach((w,h)=>{h.toLowerCase()==="set-cookie"&&m.headers.append("Set-Cookie",w);}),m}catch(s){return console.error("SIWE CRITICAL LOGIN ERROR:",s),server.NextResponse.json({message:"Internal Server Error during login"},{status:500})}}async function S(o){let{session:s,response:p}=await a(o);if(o.method==="POST"||o.method==="DELETE"){s.destroy(),e.afterLogout&&await e.afterLogout();let t=server.NextResponse.json({isLoggedIn:false},{status:200});return p.headers.forEach((i,g)=>{g.toLowerCase()==="set-cookie"&&t.headers.append("Set-Cookie",i);}),t}return s.isLoggedIn&&s.address&&s.chainId?server.NextResponse.json({isLoggedIn:true,address:s.address,chainId:s.chainId}):server.NextResponse.json({isLoggedIn:false},{status:401})}let u=async(o,s)=>{let t=(await s.params||{})?.siwe||[],i=t[t.length-1];return i==="login"&&o.method==="POST"?f(o):i==="session"&&o.method==="GET"||i==="logout"&&(o.method==="POST"||o.method==="DELETE")?S(o):Promise.resolve(new Response("Not Found",{status:404}))};return {GET:u,POST:u,DELETE:u}}
|
|
2
|
+
exports.createSiweApiHandler=x;exports.getSessionOptions=E;
|
package/dist/server/index.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
import {getIronSession}from'iron-session';import {NextResponse}from'next/server';import {SiweMessage}from'siwe';function E(n){let e=n.session||{},d=process.env.SIWE_SESSION_SECRET,a=e.password||d;if(!a||a.length<32)throw new Error("SIWE Error: Iron Session requires a 'password' option (min 32 chars) or SIWE_SESSION_SECRET environment variable to be set.");let S={...{secure:process.env.NODE_ENV==="production",maxAge:300*60,httpOnly:true,sameSite:"lax",path:"/"},...e.cookieOptions};return {password:a,cookieName:e.cookieName||"satellite_siwe",cookieOptions:S}}function O(n){if(!n)return console.warn("SIWE WARN: SIWE_SESSION_URL is not defined. Defaulting domain check to 'localhost'."),"localhost";try{return new URL(n.startsWith("http")?n:`https://${n}`).host}catch(e){return console.error(`SIWE ERROR: Invalid URL provided in SIWE_SESSION_URL: ${n}. Error: ${typeof e=="string"?e:e.message}`),"localhost"}}function x(n={}){let e=n.options||{},d=E(n);async function a(o){let s=new Response;return {session:await getIronSession(o,s,d),response:s}}async function f(o){try{let{message:s,signature:p}=await o.json();if(!s||!p)return NextResponse.json({message:"Missing message or signature"},{status:400});e.afterNonce&&await e.afterNonce();let t=new SiweMessage(s),i=O(process.env.SIWE_SESSION_URL);if(!(await t.verify({signature:p,domain:i})).success)return NextResponse.json({message:"SIWE verification failed"},{status:401});e.afterVerify&&await e.afterVerify();let{session:c,response:l}=await a(o);c.address=t.address,c.chainId=t.chainId,c.isLoggedIn=!0,await c.save(),e.afterSession&&await e.afterSession();let m=NextResponse.json({isLoggedIn:!0,address:c.address,chainId:c.chainId},{status:200});return l.headers.forEach((w,h)=>{h.toLowerCase()==="set-cookie"&&m.headers.append("Set-Cookie",w);}),m}catch(s){return console.error("SIWE CRITICAL LOGIN ERROR:",s),NextResponse.json({message:"Internal Server Error during login"},{status:500})}}async function S(o){let{session:s,response:p}=await a(o);if(o.method==="POST"||o.method==="DELETE"){s.destroy(),e.afterLogout&&await e.afterLogout();let t=NextResponse.json({isLoggedIn:false},{status:200});return p.headers.forEach((i,g)=>{g.toLowerCase()==="set-cookie"&&t.headers.append("Set-Cookie",i);}),t}return s.isLoggedIn&&s.address&&s.chainId?NextResponse.json({isLoggedIn:true,address:s.address,chainId:s.chainId}):NextResponse.json({isLoggedIn:false},{status:401})}let u=async(o,s)=>{let t=(await s.params||{})?.siwe||[],i=t[t.length-1];return i==="login"&&o.method==="POST"?f(o):i==="session"&&o.method==="GET"||i==="logout"&&(o.method==="POST"||o.method==="DELETE")?S(o):Promise.resolve(new Response("Not Found",{status:404}))};return {GET:u,POST:u,DELETE:u}}
|
|
2
|
-
export{x as createSiweApiHandler,E as getSessionOptions}
|
|
3
|
-
//# sourceMappingURL=index.mjs.map
|
|
2
|
+
export{x as createSiweApiHandler,E as getSessionOptions};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { Config } from '@wagmi/core';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { Address } from 'viem';
|
|
4
|
+
import { SiweMessage } from 'viem/siwe';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Interface for the optional cookie serialization options.
|
|
8
|
+
* Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
|
|
9
|
+
*/
|
|
10
|
+
interface SiweCookieOptions {
|
|
11
|
+
/** The value of the Max-Age Set-Cookie attribute in seconds. */
|
|
12
|
+
maxAge?: number;
|
|
13
|
+
/** The "Domain" Set-Cookie attribute. */
|
|
14
|
+
domain?: string;
|
|
15
|
+
/** The "Path" Set-Cookie attribute. */
|
|
16
|
+
path?: string;
|
|
17
|
+
/** The "Expires" Set-Cookie attribute. */
|
|
18
|
+
expires?: Date;
|
|
19
|
+
/** The "HttpOnly" Set-Cookie attribute. */
|
|
20
|
+
httpOnly?: boolean;
|
|
21
|
+
/** The "Secure" Set-Cookie attribute. */
|
|
22
|
+
secure?: boolean;
|
|
23
|
+
/** The "SameSite" Set-Cookie attribute. */
|
|
24
|
+
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Interface for the session settings block provided by the user.
|
|
28
|
+
*/
|
|
29
|
+
interface SiweSessionSettings {
|
|
30
|
+
/** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
|
|
31
|
+
cookieName?: string;
|
|
32
|
+
/** * The password/secret used to encrypt the session data.
|
|
33
|
+
* Defaults to `process.env.SESSION_SECRET`.
|
|
34
|
+
*/
|
|
35
|
+
password?: string;
|
|
36
|
+
/** Optional options for cookie serialization. */
|
|
37
|
+
cookieOptions?: SiweCookieOptions;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Interface for the custom SIWE API hooks block provided by the user.
|
|
41
|
+
*/
|
|
42
|
+
interface SiweApiHooks {
|
|
43
|
+
/** Hook executed after the user is successfully logged out. */
|
|
44
|
+
afterLogout?: () => Promise<void> | void;
|
|
45
|
+
/** Hook executed before SIWE message verification (e.g., when the message is available). */
|
|
46
|
+
afterNonce?: () => Promise<void> | void;
|
|
47
|
+
/** Hook executed after the session is successfully created/saved. */
|
|
48
|
+
afterSession?: () => Promise<void> | void;
|
|
49
|
+
/** Hook executed after the SIWE signature is successfully verified. */
|
|
50
|
+
afterVerify?: () => Promise<void> | void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The complete configuration object for the SIWE API handler factory.
|
|
54
|
+
*/
|
|
55
|
+
interface SiweApiConfig {
|
|
56
|
+
/** Session configuration settings for Iron Session. */
|
|
57
|
+
session?: SiweSessionSettings;
|
|
58
|
+
/** Custom callback hooks for various steps of the SIWE process. */
|
|
59
|
+
options?: SiweApiHooks;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Defines the data structure stored inside the Iron Session.
|
|
63
|
+
*/
|
|
64
|
+
interface SiweSessionData {
|
|
65
|
+
address: string;
|
|
66
|
+
chainId: number;
|
|
67
|
+
isLoggedIn: boolean;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Type alias for the Iron Session data.
|
|
71
|
+
*/
|
|
72
|
+
type Session = SiweSessionData;
|
|
73
|
+
/**
|
|
74
|
+
* @typedef {Object} UnconfigurableMessageOptions
|
|
75
|
+
* Fields in the SIWE message that are controlled internally by the adapter logic.
|
|
76
|
+
* @property {Address} address - The Ethereum address signing the message (Viem type).
|
|
77
|
+
* @property {number} chainId - The chain ID of the network.
|
|
78
|
+
* @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
|
|
79
|
+
*/
|
|
80
|
+
type UnconfigurableMessageOptions = {
|
|
81
|
+
address: Address;
|
|
82
|
+
chainId: number;
|
|
83
|
+
nonce: string;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* @typedef {Object} ConfigurableMessageOptions
|
|
87
|
+
* Partial set of SIWE message fields that a consumer can optionally override.
|
|
88
|
+
* Unconfigurable fields are omitted.
|
|
89
|
+
*/
|
|
90
|
+
type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
|
|
91
|
+
/**
|
|
92
|
+
* @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
|
|
93
|
+
* Function signature for customizing SIWE message options.
|
|
94
|
+
*/
|
|
95
|
+
type GetSiweMessageOptions = () => ConfigurableMessageOptions;
|
|
96
|
+
/**
|
|
97
|
+
* @interface SIWESession
|
|
98
|
+
* The authenticated user data structure derived from the NextAuth session.
|
|
99
|
+
*/
|
|
100
|
+
interface SIWESession {
|
|
101
|
+
address: Address;
|
|
102
|
+
chainId: number;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* @interface SiweAuthContextType
|
|
106
|
+
* Interface for the SIWE authentication context state and actions.
|
|
107
|
+
* @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
|
|
108
|
+
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
109
|
+
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
110
|
+
* @property {boolean} isLoading - True if the session status is loading.
|
|
111
|
+
* @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
|
|
112
|
+
* @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
|
|
113
|
+
* @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
|
|
114
|
+
*/
|
|
115
|
+
interface SiweAuthContextType {
|
|
116
|
+
data: SIWESession | undefined;
|
|
117
|
+
isReadyToSign: boolean;
|
|
118
|
+
isRejected: boolean;
|
|
119
|
+
isLoading: boolean;
|
|
120
|
+
isSignedIn: boolean;
|
|
121
|
+
enabled: boolean;
|
|
122
|
+
signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
|
|
123
|
+
signOutSiwe: (onSignOut?: () => void) => Promise<void>;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* @interface UseSiweSignatureResult
|
|
127
|
+
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
128
|
+
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
129
|
+
* @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
|
|
130
|
+
*/
|
|
131
|
+
interface UseSiweSignatureResult {
|
|
132
|
+
isReadyToSign: boolean;
|
|
133
|
+
isRejected: boolean;
|
|
134
|
+
getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
|
|
135
|
+
message: string;
|
|
136
|
+
signature: Address;
|
|
137
|
+
} | undefined>;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* @interface SiweNextAuthProviderProps
|
|
141
|
+
* @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
|
|
142
|
+
* @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
|
|
143
|
+
* @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
|
|
144
|
+
* @property {() => void} [onSignOut] - Callback executed after a successful sign-out or connector disconnect.
|
|
145
|
+
* @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
|
|
146
|
+
* @property {ReactNode} children - Child components.
|
|
147
|
+
*/
|
|
148
|
+
interface SiweNextAuthProviderProps {
|
|
149
|
+
wagmiConfig: Config;
|
|
150
|
+
enabled?: boolean;
|
|
151
|
+
nonceRefetchInterval?: number;
|
|
152
|
+
onSignIn?: (session?: SIWESession) => void;
|
|
153
|
+
onSignOut?: () => void;
|
|
154
|
+
getSiweMessageOptions?: GetSiweMessageOptions;
|
|
155
|
+
children: ReactNode;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type { ConfigurableMessageOptions as C, GetSiweMessageOptions as G, SIWESession as S, UseSiweSignatureResult as U, SiweAuthContextType as a, SiweNextAuthProviderProps as b, SiweCookieOptions as c, SiweSessionSettings as d, SiweApiHooks as e, SiweApiConfig as f, SiweSessionData as g, Session as h, UnconfigurableMessageOptions as i };
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { Config } from '@wagmi/core';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { Address } from 'viem';
|
|
4
|
+
import { SiweMessage } from 'viem/siwe';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Interface for the optional cookie serialization options.
|
|
8
|
+
* Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
|
|
9
|
+
*/
|
|
10
|
+
interface SiweCookieOptions {
|
|
11
|
+
/** The value of the Max-Age Set-Cookie attribute in seconds. */
|
|
12
|
+
maxAge?: number;
|
|
13
|
+
/** The "Domain" Set-Cookie attribute. */
|
|
14
|
+
domain?: string;
|
|
15
|
+
/** The "Path" Set-Cookie attribute. */
|
|
16
|
+
path?: string;
|
|
17
|
+
/** The "Expires" Set-Cookie attribute. */
|
|
18
|
+
expires?: Date;
|
|
19
|
+
/** The "HttpOnly" Set-Cookie attribute. */
|
|
20
|
+
httpOnly?: boolean;
|
|
21
|
+
/** The "Secure" Set-Cookie attribute. */
|
|
22
|
+
secure?: boolean;
|
|
23
|
+
/** The "SameSite" Set-Cookie attribute. */
|
|
24
|
+
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Interface for the session settings block provided by the user.
|
|
28
|
+
*/
|
|
29
|
+
interface SiweSessionSettings {
|
|
30
|
+
/** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
|
|
31
|
+
cookieName?: string;
|
|
32
|
+
/** * The password/secret used to encrypt the session data.
|
|
33
|
+
* Defaults to `process.env.SESSION_SECRET`.
|
|
34
|
+
*/
|
|
35
|
+
password?: string;
|
|
36
|
+
/** Optional options for cookie serialization. */
|
|
37
|
+
cookieOptions?: SiweCookieOptions;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Interface for the custom SIWE API hooks block provided by the user.
|
|
41
|
+
*/
|
|
42
|
+
interface SiweApiHooks {
|
|
43
|
+
/** Hook executed after the user is successfully logged out. */
|
|
44
|
+
afterLogout?: () => Promise<void> | void;
|
|
45
|
+
/** Hook executed before SIWE message verification (e.g., when the message is available). */
|
|
46
|
+
afterNonce?: () => Promise<void> | void;
|
|
47
|
+
/** Hook executed after the session is successfully created/saved. */
|
|
48
|
+
afterSession?: () => Promise<void> | void;
|
|
49
|
+
/** Hook executed after the SIWE signature is successfully verified. */
|
|
50
|
+
afterVerify?: () => Promise<void> | void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The complete configuration object for the SIWE API handler factory.
|
|
54
|
+
*/
|
|
55
|
+
interface SiweApiConfig {
|
|
56
|
+
/** Session configuration settings for Iron Session. */
|
|
57
|
+
session?: SiweSessionSettings;
|
|
58
|
+
/** Custom callback hooks for various steps of the SIWE process. */
|
|
59
|
+
options?: SiweApiHooks;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Defines the data structure stored inside the Iron Session.
|
|
63
|
+
*/
|
|
64
|
+
interface SiweSessionData {
|
|
65
|
+
address: string;
|
|
66
|
+
chainId: number;
|
|
67
|
+
isLoggedIn: boolean;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Type alias for the Iron Session data.
|
|
71
|
+
*/
|
|
72
|
+
type Session = SiweSessionData;
|
|
73
|
+
/**
|
|
74
|
+
* @typedef {Object} UnconfigurableMessageOptions
|
|
75
|
+
* Fields in the SIWE message that are controlled internally by the adapter logic.
|
|
76
|
+
* @property {Address} address - The Ethereum address signing the message (Viem type).
|
|
77
|
+
* @property {number} chainId - The chain ID of the network.
|
|
78
|
+
* @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
|
|
79
|
+
*/
|
|
80
|
+
type UnconfigurableMessageOptions = {
|
|
81
|
+
address: Address;
|
|
82
|
+
chainId: number;
|
|
83
|
+
nonce: string;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* @typedef {Object} ConfigurableMessageOptions
|
|
87
|
+
* Partial set of SIWE message fields that a consumer can optionally override.
|
|
88
|
+
* Unconfigurable fields are omitted.
|
|
89
|
+
*/
|
|
90
|
+
type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
|
|
91
|
+
/**
|
|
92
|
+
* @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
|
|
93
|
+
* Function signature for customizing SIWE message options.
|
|
94
|
+
*/
|
|
95
|
+
type GetSiweMessageOptions = () => ConfigurableMessageOptions;
|
|
96
|
+
/**
|
|
97
|
+
* @interface SIWESession
|
|
98
|
+
* The authenticated user data structure derived from the NextAuth session.
|
|
99
|
+
*/
|
|
100
|
+
interface SIWESession {
|
|
101
|
+
address: Address;
|
|
102
|
+
chainId: number;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* @interface SiweAuthContextType
|
|
106
|
+
* Interface for the SIWE authentication context state and actions.
|
|
107
|
+
* @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
|
|
108
|
+
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
109
|
+
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
110
|
+
* @property {boolean} isLoading - True if the session status is loading.
|
|
111
|
+
* @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
|
|
112
|
+
* @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
|
|
113
|
+
* @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
|
|
114
|
+
*/
|
|
115
|
+
interface SiweAuthContextType {
|
|
116
|
+
data: SIWESession | undefined;
|
|
117
|
+
isReadyToSign: boolean;
|
|
118
|
+
isRejected: boolean;
|
|
119
|
+
isLoading: boolean;
|
|
120
|
+
isSignedIn: boolean;
|
|
121
|
+
enabled: boolean;
|
|
122
|
+
signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
|
|
123
|
+
signOutSiwe: (onSignOut?: () => void) => Promise<void>;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* @interface UseSiweSignatureResult
|
|
127
|
+
* @property {boolean} isReadyToSign - True if an EVM connector is connected and ready to sign.
|
|
128
|
+
* @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
|
|
129
|
+
* @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
|
|
130
|
+
*/
|
|
131
|
+
interface UseSiweSignatureResult {
|
|
132
|
+
isReadyToSign: boolean;
|
|
133
|
+
isRejected: boolean;
|
|
134
|
+
getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
|
|
135
|
+
message: string;
|
|
136
|
+
signature: Address;
|
|
137
|
+
} | undefined>;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* @interface SiweNextAuthProviderProps
|
|
141
|
+
* @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
|
|
142
|
+
* @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
|
|
143
|
+
* @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
|
|
144
|
+
* @property {() => void} [onSignOut] - Callback executed after a successful sign-out or connector disconnect.
|
|
145
|
+
* @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
|
|
146
|
+
* @property {ReactNode} children - Child components.
|
|
147
|
+
*/
|
|
148
|
+
interface SiweNextAuthProviderProps {
|
|
149
|
+
wagmiConfig: Config;
|
|
150
|
+
enabled?: boolean;
|
|
151
|
+
nonceRefetchInterval?: number;
|
|
152
|
+
onSignIn?: (session?: SIWESession) => void;
|
|
153
|
+
onSignOut?: () => void;
|
|
154
|
+
getSiweMessageOptions?: GetSiweMessageOptions;
|
|
155
|
+
children: ReactNode;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type { ConfigurableMessageOptions as C, GetSiweMessageOptions as G, SIWESession as S, UseSiweSignatureResult as U, SiweAuthContextType as a, SiweNextAuthProviderProps as b, SiweCookieOptions as c, SiweSessionSettings as d, SiweApiHooks as e, SiweApiConfig as f, SiweSessionData as g, Session as h, UnconfigurableMessageOptions as i };
|
package/package.json
CHANGED
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/useInterval.tsx","../src/provider/SiweAuthContext.tsx","../src/hooks/useSiweAuth.tsx","../src/hooks/useSiweSignature.tsx","../src/hooks/useSiweAuthAdapter.tsx","../src/provider/SiweNextAuthProvider.tsx"],"names":["useInterval","callback","delay","savedCallback","useRef","useEffect","id","SiweAuthContext","createContext","useSiweAuth","options","context","useContext","signInWithSiwe","useCallback","signOutSiwe","useMemo","fetchNonce","useSiweSignature","wagmiConfig","isConnected","address","chainId","useConnection","isRejected","setIsRejected","useState","isReadyToSign","customOptions","walletSnapshot","getConnection","nonce","messageToSign","createSiweMessage","signature","signMessage","disconnect","error","err","fetchSession","res","data","e","useSiweAuthAdapter","enabled","nonceRefetchInterval","providerOnSignIn","providerOnSignOut","getSiweMessageOptions","localSession","setLocalSession","sessionStatus","setSessionStatus","getSiweSignature","isSigningInAfterContextChange","setIsSigningInAfterContextChange","isAuthenticated","isAuthenticating","updateSession","session","status","userOnSignOut","userOnSignIn","signatureData","response","responseBody","finalSession","sessionAddress","currentAddress","sessionChainId","currentChainId","SiweNextAuthProvider","props","siweAuth","jsx"],"mappings":"6JAQO,SAAS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,CAC3G,CACF,CCpNO,SAAS2B,EAAAA,CAAqBC,CAAAA,CAAkC,CACrE,IAAMC,CAAAA,CAAW9B,EAAmB6B,CAAK,CAAA,CACzC,OAAOE,cAAAA,CAACnE,CAAAA,CAAgB,QAAA,CAAhB,CAAyB,KAAA,CAAOkE,CAAAA,CAAW,QAAA,CAAAD,CAAAA,CAAM,QAAA,CAAS,CACpE","file":"index.js","sourcesContent":["'use client';\n\nimport { useEffect, useRef } from 'react';\n\n/**\n * @function useInterval\n * Creates a stable interval hook safe for client-side execution.\n */\nexport function useInterval(callback: () => void, delay: number | null) {\n const savedCallback = useRef(callback);\n\n useEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n useEffect(() => {\n if (delay !== null && typeof window !== 'undefined' && window.setInterval) {\n // Use window.setInterval and cast the ID to number to satisfy clearInterval's type\n const id = window.setInterval(() => savedCallback.current(), delay);\n return () => window.clearInterval(id);\n }\n }, [delay]);\n}\n","'use client';\n\nimport { createContext } from 'react';\n\nimport { SiweAuthContextType } from '../types';\n\nexport const SiweAuthContext = createContext<SiweAuthContextType | undefined>(undefined);\n","'use client';\n\nimport { useCallback, useContext, useMemo } from 'react';\n\nimport { SiweAuthContext } from '../provider/SiweAuthContext';\nimport { SiweAuthContextType, SIWESession } from '../types';\n\n/**\n * @function useSiweAuth\n * @description Hook to access the SIWE authentication state and methods.\n * @param {object} [options] - Optional callbacks that override provider-level callbacks.\n * @param {(session?: SIWESession) => void} [options.onSignIn] - Callback executed after a successful sign-in.\n * @param {() => void} [options.onSignOut] - Callback executed after a successful sign-out.\n * @returns {SiweAuthContextType}\n * * @example\n * // const { isSignedIn, signInWithSiwe, data, isRejected } = useSiweAuth();\n */\nexport function useSiweAuth(options?: {\n onSignIn?: (session?: SIWESession) => void;\n onSignOut?: () => void;\n}): SiweAuthContextType {\n const context = useContext(SiweAuthContext);\n if (context === undefined) {\n throw new Error('useSiweAuth must be used within a SiweNextAuthProvider');\n }\n\n // Overrides the context's signOutSiwe/signInWithSiwe with local callbacks\n const signInWithSiwe = useCallback(async () => {\n return context.signInWithSiwe(options?.onSignIn);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [context.signInWithSiwe, options?.onSignIn]);\n\n const signOutSiwe = useCallback(async () => {\n return context.signOutSiwe(options?.onSignOut);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [context.signOutSiwe, options?.onSignOut]);\n\n return useMemo(\n () => ({\n ...context,\n signInWithSiwe,\n signOutSiwe,\n }),\n [context, signInWithSiwe, signOutSiwe],\n );\n}\n","'use client';\n\nimport { Config, disconnect, getConnection, signMessage } from '@wagmi/core';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Address } from 'viem';\nimport { createSiweMessage } from 'viem/siwe';\nimport { useConnection } from 'wagmi';\n\nimport { GetSiweMessageOptions, UseSiweSignatureResult } from '../types';\n\n/**\n * @function fetchNonce\n * @description Generates a cryptographically secure, alphanumeric random string to use as the SIWE nonce,\n * satisfying the viem/SIWE requirement (at least 8 chars, alphanumeric).\n * @returns {Promise<string>} The valid alphanumeric nonce string.\n */\nasync function fetchNonce(): Promise<string> {\n // Generate UUID and remove hyphens to create a secure, alphanumeric nonce.\n return crypto.randomUUID().replace(/-/g, '');\n}\n\n/**\n * @function useSiweSignature\n * @description A low-level hook that handles the core SIWE cryptographic flow:\n * getting the nonce, creating the message, and getting the signature using Wagmi/Viem.\n * This is the building block for custom backend authentication.\n * @returns {UseSiweSignatureResult}\n * * @example\n * // const { getSiweSignature, isReadyToSign, isRejected } = useSiweSignature();\n */\nexport function useSiweSignature({ wagmiConfig }: { wagmiConfig: Config }): UseSiweSignatureResult {\n const { isConnected, address, chainId } = useConnection({ config: wagmiConfig });\n const [isRejected, setIsRejected] = useState(false);\n\n const isReadyToSign = useMemo(() => isConnected && !!address && !!chainId, [isConnected, address, chainId]);\n\n // Clear rejected state upon context change\n useEffect(() => {\n if (isReadyToSign) {\n setIsRejected(false);\n }\n }, [isReadyToSign]);\n\n const getSiweSignature = async (customOptions?: GetSiweMessageOptions) => {\n setIsRejected(false); // Reset rejection status at the start of a new attempt\n\n const walletSnapshot = getConnection(wagmiConfig);\n\n if (!walletSnapshot.isConnected || !walletSnapshot.address || !walletSnapshot.chainId) {\n throw new Error('Connector not connected or connection details are missing from Wagmi snapshot.');\n }\n\n try {\n // Use the corrected fetchNonce\n const nonce = await fetchNonce();\n if (!nonce) throw new Error('Failed to retrieve CSRF token/nonce.');\n\n const messageToSign = createSiweMessage({\n domain: window.location.host,\n statement: 'Sign in with Ethereum to the application.',\n uri: window.location.origin,\n version: '1',\n ...(customOptions ? customOptions() : {}), // Apply custom options\n address: walletSnapshot.address,\n chainId: walletSnapshot.chainId,\n nonce,\n });\n\n const signature = await signMessage(wagmiConfig, { message: messageToSign });\n\n if (!signature) {\n setIsRejected(true); // Set rejected status if signature is null/undefined\n await disconnect(wagmiConfig);\n throw new Error('Message signing cancelled by user or failed.');\n }\n\n return { message: messageToSign, signature: signature as Address };\n } catch (error) {\n await disconnect(wagmiConfig);\n console.error('Error during signature generation:', error);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const err = error as any;\n if (err.name === 'UserRejectedRequestError' || err.code === 4001 || /user rejected/i.test(err.message)) {\n setIsRejected(true);\n }\n throw error;\n }\n };\n\n return { getSiweSignature, isReadyToSign, isRejected };\n}\n","'use client';\n\nimport { disconnect } from '@wagmi/core';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useConnection } from 'wagmi';\n\nimport { SiweAuthContextType, SiweNextAuthProviderProps, SIWESession } from '../types';\nimport { useInterval } from './useInterval';\nimport { useSiweSignature } from './useSiweSignature';\n\ntype SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\n/**\n * @function fetchSession\n * @description Fetches the current session status and data from the server.\n * @returns {Promise<{session: SIWESession | undefined, status: SessionStatus}>}\n */\nasync function fetchSession(): Promise<{ session: SIWESession | undefined; status: SessionStatus }> {\n try {\n const res = await fetch('/api/siwe/session');\n\n if (res.status === 401 || res.status === 404) {\n return { session: undefined, status: 'unauthenticated' };\n }\n\n if (!res.ok) {\n throw new Error('Failed to fetch session data.');\n }\n\n const data = await res.json();\n\n // NOTE: Data structure must match SiweSessionData {isLoggedIn, address, chainId}\n if (data.isLoggedIn && data.address && data.chainId) {\n return {\n session: { address: data.address, chainId: data.chainId },\n status: 'authenticated',\n };\n }\n return { session: undefined, status: 'unauthenticated' };\n } catch (e) {\n console.error('Error fetching session:', e);\n return { session: undefined, status: 'unauthenticated' };\n }\n}\n\n/**\n * @function useSiweAuthAdapter\n * Internal hook containing the core SIWE/Iron Session logic, acting as the authentication adapter.\n * @returns {SiweAuthContextType}\n */\nexport function useSiweAuthAdapter({\n wagmiConfig,\n enabled = true,\n nonceRefetchInterval = 5 * 60 * 1000, // 5 minutes (300,000 ms)\n onSignIn: providerOnSignIn,\n onSignOut: providerOnSignOut,\n getSiweMessageOptions,\n}: SiweNextAuthProviderProps): SiweAuthContextType {\n const [localSession, setLocalSession] = useState<SIWESession | undefined>(undefined);\n const [sessionStatus, setSessionStatus] = useState<SessionStatus>('loading');\n\n const { isReadyToSign, getSiweSignature, isRejected } = useSiweSignature({ wagmiConfig });\n\n const { address, chainId, isConnected } = useConnection({ config: wagmiConfig });\n\n const [isSigningInAfterContextChange, setIsSigningInAfterContextChange] = useState(false);\n\n const isAuthenticated = sessionStatus === 'authenticated';\n const isAuthenticating = sessionStatus === 'loading';\n const data: SIWESession | undefined = localSession;\n\n // --- SESSION REFETCH (equivalent to NextAuth's update) ---\n const updateSession = useCallback(async () => {\n setSessionStatus('loading');\n const { session, status } = await fetchSession();\n setLocalSession(session);\n setSessionStatus(status);\n return session;\n }, []);\n\n // --- NONCE REFETCH LOGIC (Managed by custom interval) ---\n useInterval(() => {\n if (isAuthenticated) {\n updateSession();\n }\n }, nonceRefetchInterval);\n\n /**\n * @async\n * @method signOutSiwe\n * Clears the session by calling the server API.\n */\n const signOutSiwe = useCallback(\n async (userOnSignOut?: () => void) => {\n await fetch('/api/siwe/logout', { method: 'POST' }); // Call your custom logout API\n setLocalSession(undefined);\n setSessionStatus('unauthenticated');\n\n providerOnSignOut?.(); // Execute provider callback\n userOnSignOut?.(); // Execute user callback\n },\n [providerOnSignOut],\n );\n\n /**\n * @async\n * @method signInWithSiwe\n * Executes the full SIWE authentication flow: signature -> verification -> session creation.\n */\n const signInWithSiwe = useCallback(\n async (userOnSignIn?: (session?: SIWESession) => void) => {\n if (!enabled) {\n throw new Error('SIWE is currently disabled via provider configuration.');\n }\n\n setSessionStatus('loading');\n\n try {\n // 1. Get Signature using the low-level hook\n const signatureData = await getSiweSignature(getSiweMessageOptions);\n\n if (!signatureData) {\n setSessionStatus('unauthenticated');\n return;\n }\n\n // 2. Send message and signature to your custom login API\n const response = await fetch('/api/siwe/login', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n message: signatureData.message,\n signature: signatureData.signature,\n }),\n });\n\n const responseBody = await response.json();\n\n if (!response.ok || responseBody.isLoggedIn !== true) {\n throw new Error(`Verification error: ${responseBody.message || 'Login failed.'}`);\n }\n\n console.log('SIWE Authentication successful.');\n\n // 3. Update session locally\n const finalSession: SIWESession = {\n address: responseBody.address,\n chainId: responseBody.chainId,\n };\n\n setLocalSession(finalSession);\n setSessionStatus('authenticated');\n\n // 4. Execute callbacks after successful sign-in\n providerOnSignIn?.(finalSession);\n userOnSignIn?.(finalSession);\n } catch (error) {\n await disconnect(wagmiConfig);\n setSessionStatus('unauthenticated');\n throw new Error(`SIWE Sign-In failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n },\n [enabled, getSiweSignature, getSiweMessageOptions, providerOnSignIn, wagmiConfig],\n );\n\n // --- OBLIGATORY SESSION RESET / AUTO-SIGN IN EFFECT ---\n\n useEffect(() => {\n if (isAuthenticated && enabled) {\n const sessionAddress = localSession?.address?.toLowerCase();\n const currentAddress = address?.toLowerCase();\n const sessionChainId = localSession?.chainId;\n const currentChainId = chainId;\n\n const addressChanged = sessionAddress && currentAddress && sessionAddress !== currentAddress;\n const chainChanged = sessionChainId && currentChainId && sessionChainId !== currentChainId;\n const walletDisconnected = !isConnected;\n\n if (addressChanged || chainChanged) {\n console.log('SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication.');\n\n setIsSigningInAfterContextChange(true);\n\n // 1. OBLIGATORY SIGN OUT for the old session (security)\n signOutSiwe();\n } else if (walletDisconnected) {\n // Handle explicit connector disconnection: Always sign out.\n console.log('SIWE: Connector disconnected. Disconnecting session.');\n signOutSiwe();\n providerOnSignOut?.(); // Execute provider callback for disconnect\n }\n }\n }, [isAuthenticated, address, chainId, isConnected, localSession, signOutSiwe, enabled, providerOnSignOut]);\n\n // --- EFFECT TO EXECUTE AUTO SIGN-IN AFTER STATE RESET ---\n useEffect(() => {\n // Triggers when: 1. Flag is set AND 2. Status transitioned to 'unauthenticated'\n if (isSigningInAfterContextChange && sessionStatus === 'unauthenticated' && isReadyToSign && enabled) {\n console.log('SIWE: State reset detected. Attempting automatic sign-in to establish new session.');\n\n setIsSigningInAfterContextChange(false); // Reset flag\n\n // Auto sign-in execution\n signInWithSiwe().catch((e) => {\n throw new Error(\n `SIWE Auto Sign-In failed after context change: ${e instanceof Error ? e.message : 'Unknown error'}`,\n );\n });\n }\n }, [isSigningInAfterContextChange, sessionStatus, isReadyToSign, signInWithSiwe, enabled]);\n\n // --- FINAL EXPORT ---\n\n return useMemo(\n () => ({\n data,\n isReadyToSign,\n isRejected,\n isLoading: isAuthenticating,\n isSignedIn: isAuthenticated,\n signInWithSiwe,\n signOutSiwe,\n enabled,\n }),\n [data, isReadyToSign, isRejected, isAuthenticating, isAuthenticated, signInWithSiwe, signOutSiwe, enabled],\n );\n}\n","'use client';\n\nimport { useSiweAuthAdapter } from '../hooks/useSiweAuthAdapter';\nimport { SiweNextAuthProviderProps } from '../types';\nimport { SiweAuthContext } from './SiweAuthContext';\n\n/**\n * @component\n * @name SiweNextAuthProvider\n * @description Universal Provider for Sign-In with Ethereum (SIWE) using NextAuth.js.\n * This component handles the SIWE authentication logic.\n * It must be nested inside NextAuth's `<SessionProvider>` and your Wagmi Provider.\n * * **Note**: This provider requires the server-side NextAuth configuration to be set up.\n */\nexport function SiweNextAuthProvider(props: SiweNextAuthProviderProps) {\n const siweAuth = useSiweAuthAdapter(props);\n return <SiweAuthContext.Provider value={siweAuth}>{props.children}</SiweAuthContext.Provider>;\n}\n"]}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/useInterval.tsx","../src/provider/SiweAuthContext.tsx","../src/hooks/useSiweAuth.tsx","../src/hooks/useSiweSignature.tsx","../src/hooks/useSiweAuthAdapter.tsx","../src/provider/SiweNextAuthProvider.tsx"],"names":["useInterval","callback","delay","savedCallback","useRef","useEffect","id","SiweAuthContext","createContext","useSiweAuth","options","context","useContext","signInWithSiwe","useCallback","signOutSiwe","useMemo","fetchNonce","useSiweSignature","wagmiConfig","isConnected","address","chainId","useConnection","isRejected","setIsRejected","useState","isReadyToSign","customOptions","walletSnapshot","getConnection","nonce","messageToSign","createSiweMessage","signature","signMessage","disconnect","error","err","fetchSession","res","data","e","useSiweAuthAdapter","enabled","nonceRefetchInterval","providerOnSignIn","providerOnSignOut","getSiweMessageOptions","localSession","setLocalSession","sessionStatus","setSessionStatus","getSiweSignature","isSigningInAfterContextChange","setIsSigningInAfterContextChange","isAuthenticated","isAuthenticating","updateSession","session","status","userOnSignOut","userOnSignIn","signatureData","response","responseBody","finalSession","sessionAddress","currentAddress","sessionChainId","currentChainId","SiweNextAuthProvider","props","siweAuth","jsx"],"mappings":"0QAQO,SAASA,CAAAA,CAAYC,CAAAA,CAAsBC,CAAAA,CAAsB,CACtE,IAAMC,CAAAA,CAAgBC,OAAOH,CAAQ,CAAA,CAErCI,SAAAA,CAAU,IAAM,CACdF,CAAAA,CAAc,OAAA,CAAUF,EAC1B,CAAA,CAAG,CAACA,CAAQ,CAAC,CAAA,CAEbI,SAAAA,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A,CAAS,CACpE","file":"index.mjs","sourcesContent":["'use client';\n\nimport { useEffect, useRef } from 'react';\n\n/**\n * @function useInterval\n * Creates a stable interval hook safe for client-side execution.\n */\nexport function useInterval(callback: () => void, delay: number | null) {\n const savedCallback = useRef(callback);\n\n useEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n useEffect(() => {\n if (delay !== null && typeof window !== 'undefined' && window.setInterval) {\n // Use window.setInterval and cast the ID to number to satisfy clearInterval's type\n const id = window.setInterval(() => savedCallback.current(), delay);\n return () => window.clearInterval(id);\n }\n }, [delay]);\n}\n","'use client';\n\nimport { createContext } from 'react';\n\nimport { SiweAuthContextType } from '../types';\n\nexport const SiweAuthContext = createContext<SiweAuthContextType | undefined>(undefined);\n","'use client';\n\nimport { useCallback, useContext, useMemo } from 'react';\n\nimport { SiweAuthContext } from '../provider/SiweAuthContext';\nimport { SiweAuthContextType, SIWESession } from '../types';\n\n/**\n * @function useSiweAuth\n * @description Hook to access the SIWE authentication state and methods.\n * @param {object} [options] - Optional callbacks that override provider-level callbacks.\n * @param {(session?: SIWESession) => void} [options.onSignIn] - Callback executed after a successful sign-in.\n * @param {() => void} [options.onSignOut] - Callback executed after a successful sign-out.\n * @returns {SiweAuthContextType}\n * * @example\n * // const { isSignedIn, signInWithSiwe, data, isRejected } = useSiweAuth();\n */\nexport function useSiweAuth(options?: {\n onSignIn?: (session?: SIWESession) => void;\n onSignOut?: () => void;\n}): SiweAuthContextType {\n const context = useContext(SiweAuthContext);\n if (context === undefined) {\n throw new Error('useSiweAuth must be used within a SiweNextAuthProvider');\n }\n\n // Overrides the context's signOutSiwe/signInWithSiwe with local callbacks\n const signInWithSiwe = useCallback(async () => {\n return context.signInWithSiwe(options?.onSignIn);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [context.signInWithSiwe, options?.onSignIn]);\n\n const signOutSiwe = useCallback(async () => {\n return context.signOutSiwe(options?.onSignOut);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [context.signOutSiwe, options?.onSignOut]);\n\n return useMemo(\n () => ({\n ...context,\n signInWithSiwe,\n signOutSiwe,\n }),\n [context, signInWithSiwe, signOutSiwe],\n );\n}\n","'use client';\n\nimport { Config, disconnect, getConnection, signMessage } from '@wagmi/core';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Address } from 'viem';\nimport { createSiweMessage } from 'viem/siwe';\nimport { useConnection } from 'wagmi';\n\nimport { GetSiweMessageOptions, UseSiweSignatureResult } from '../types';\n\n/**\n * @function fetchNonce\n * @description Generates a cryptographically secure, alphanumeric random string to use as the SIWE nonce,\n * satisfying the viem/SIWE requirement (at least 8 chars, alphanumeric).\n * @returns {Promise<string>} The valid alphanumeric nonce string.\n */\nasync function fetchNonce(): Promise<string> {\n // Generate UUID and remove hyphens to create a secure, alphanumeric nonce.\n return crypto.randomUUID().replace(/-/g, '');\n}\n\n/**\n * @function useSiweSignature\n * @description A low-level hook that handles the core SIWE cryptographic flow:\n * getting the nonce, creating the message, and getting the signature using Wagmi/Viem.\n * This is the building block for custom backend authentication.\n * @returns {UseSiweSignatureResult}\n * * @example\n * // const { getSiweSignature, isReadyToSign, isRejected } = useSiweSignature();\n */\nexport function useSiweSignature({ wagmiConfig }: { wagmiConfig: Config }): UseSiweSignatureResult {\n const { isConnected, address, chainId } = useConnection({ config: wagmiConfig });\n const [isRejected, setIsRejected] = useState(false);\n\n const isReadyToSign = useMemo(() => isConnected && !!address && !!chainId, [isConnected, address, chainId]);\n\n // Clear rejected state upon context change\n useEffect(() => {\n if (isReadyToSign) {\n setIsRejected(false);\n }\n }, [isReadyToSign]);\n\n const getSiweSignature = async (customOptions?: GetSiweMessageOptions) => {\n setIsRejected(false); // Reset rejection status at the start of a new attempt\n\n const walletSnapshot = getConnection(wagmiConfig);\n\n if (!walletSnapshot.isConnected || !walletSnapshot.address || !walletSnapshot.chainId) {\n throw new Error('Connector not connected or connection details are missing from Wagmi snapshot.');\n }\n\n try {\n // Use the corrected fetchNonce\n const nonce = await fetchNonce();\n if (!nonce) throw new Error('Failed to retrieve CSRF token/nonce.');\n\n const messageToSign = createSiweMessage({\n domain: window.location.host,\n statement: 'Sign in with Ethereum to the application.',\n uri: window.location.origin,\n version: '1',\n ...(customOptions ? customOptions() : {}), // Apply custom options\n address: walletSnapshot.address,\n chainId: walletSnapshot.chainId,\n nonce,\n });\n\n const signature = await signMessage(wagmiConfig, { message: messageToSign });\n\n if (!signature) {\n setIsRejected(true); // Set rejected status if signature is null/undefined\n await disconnect(wagmiConfig);\n throw new Error('Message signing cancelled by user or failed.');\n }\n\n return { message: messageToSign, signature: signature as Address };\n } catch (error) {\n await disconnect(wagmiConfig);\n console.error('Error during signature generation:', error);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const err = error as any;\n if (err.name === 'UserRejectedRequestError' || err.code === 4001 || /user rejected/i.test(err.message)) {\n setIsRejected(true);\n }\n throw error;\n }\n };\n\n return { getSiweSignature, isReadyToSign, isRejected };\n}\n","'use client';\n\nimport { disconnect } from '@wagmi/core';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useConnection } from 'wagmi';\n\nimport { SiweAuthContextType, SiweNextAuthProviderProps, SIWESession } from '../types';\nimport { useInterval } from './useInterval';\nimport { useSiweSignature } from './useSiweSignature';\n\ntype SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\n/**\n * @function fetchSession\n * @description Fetches the current session status and data from the server.\n * @returns {Promise<{session: SIWESession | undefined, status: SessionStatus}>}\n */\nasync function fetchSession(): Promise<{ session: SIWESession | undefined; status: SessionStatus }> {\n try {\n const res = await fetch('/api/siwe/session');\n\n if (res.status === 401 || res.status === 404) {\n return { session: undefined, status: 'unauthenticated' };\n }\n\n if (!res.ok) {\n throw new Error('Failed to fetch session data.');\n }\n\n const data = await res.json();\n\n // NOTE: Data structure must match SiweSessionData {isLoggedIn, address, chainId}\n if (data.isLoggedIn && data.address && data.chainId) {\n return {\n session: { address: data.address, chainId: data.chainId },\n status: 'authenticated',\n };\n }\n return { session: undefined, status: 'unauthenticated' };\n } catch (e) {\n console.error('Error fetching session:', e);\n return { session: undefined, status: 'unauthenticated' };\n }\n}\n\n/**\n * @function useSiweAuthAdapter\n * Internal hook containing the core SIWE/Iron Session logic, acting as the authentication adapter.\n * @returns {SiweAuthContextType}\n */\nexport function useSiweAuthAdapter({\n wagmiConfig,\n enabled = true,\n nonceRefetchInterval = 5 * 60 * 1000, // 5 minutes (300,000 ms)\n onSignIn: providerOnSignIn,\n onSignOut: providerOnSignOut,\n getSiweMessageOptions,\n}: SiweNextAuthProviderProps): SiweAuthContextType {\n const [localSession, setLocalSession] = useState<SIWESession | undefined>(undefined);\n const [sessionStatus, setSessionStatus] = useState<SessionStatus>('loading');\n\n const { isReadyToSign, getSiweSignature, isRejected } = useSiweSignature({ wagmiConfig });\n\n const { address, chainId, isConnected } = useConnection({ config: wagmiConfig });\n\n const [isSigningInAfterContextChange, setIsSigningInAfterContextChange] = useState(false);\n\n const isAuthenticated = sessionStatus === 'authenticated';\n const isAuthenticating = sessionStatus === 'loading';\n const data: SIWESession | undefined = localSession;\n\n // --- SESSION REFETCH (equivalent to NextAuth's update) ---\n const updateSession = useCallback(async () => {\n setSessionStatus('loading');\n const { session, status } = await fetchSession();\n setLocalSession(session);\n setSessionStatus(status);\n return session;\n }, []);\n\n // --- NONCE REFETCH LOGIC (Managed by custom interval) ---\n useInterval(() => {\n if (isAuthenticated) {\n updateSession();\n }\n }, nonceRefetchInterval);\n\n /**\n * @async\n * @method signOutSiwe\n * Clears the session by calling the server API.\n */\n const signOutSiwe = useCallback(\n async (userOnSignOut?: () => void) => {\n await fetch('/api/siwe/logout', { method: 'POST' }); // Call your custom logout API\n setLocalSession(undefined);\n setSessionStatus('unauthenticated');\n\n providerOnSignOut?.(); // Execute provider callback\n userOnSignOut?.(); // Execute user callback\n },\n [providerOnSignOut],\n );\n\n /**\n * @async\n * @method signInWithSiwe\n * Executes the full SIWE authentication flow: signature -> verification -> session creation.\n */\n const signInWithSiwe = useCallback(\n async (userOnSignIn?: (session?: SIWESession) => void) => {\n if (!enabled) {\n throw new Error('SIWE is currently disabled via provider configuration.');\n }\n\n setSessionStatus('loading');\n\n try {\n // 1. Get Signature using the low-level hook\n const signatureData = await getSiweSignature(getSiweMessageOptions);\n\n if (!signatureData) {\n setSessionStatus('unauthenticated');\n return;\n }\n\n // 2. Send message and signature to your custom login API\n const response = await fetch('/api/siwe/login', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n message: signatureData.message,\n signature: signatureData.signature,\n }),\n });\n\n const responseBody = await response.json();\n\n if (!response.ok || responseBody.isLoggedIn !== true) {\n throw new Error(`Verification error: ${responseBody.message || 'Login failed.'}`);\n }\n\n console.log('SIWE Authentication successful.');\n\n // 3. Update session locally\n const finalSession: SIWESession = {\n address: responseBody.address,\n chainId: responseBody.chainId,\n };\n\n setLocalSession(finalSession);\n setSessionStatus('authenticated');\n\n // 4. Execute callbacks after successful sign-in\n providerOnSignIn?.(finalSession);\n userOnSignIn?.(finalSession);\n } catch (error) {\n await disconnect(wagmiConfig);\n setSessionStatus('unauthenticated');\n throw new Error(`SIWE Sign-In failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n },\n [enabled, getSiweSignature, getSiweMessageOptions, providerOnSignIn, wagmiConfig],\n );\n\n // --- OBLIGATORY SESSION RESET / AUTO-SIGN IN EFFECT ---\n\n useEffect(() => {\n if (isAuthenticated && enabled) {\n const sessionAddress = localSession?.address?.toLowerCase();\n const currentAddress = address?.toLowerCase();\n const sessionChainId = localSession?.chainId;\n const currentChainId = chainId;\n\n const addressChanged = sessionAddress && currentAddress && sessionAddress !== currentAddress;\n const chainChanged = sessionChainId && currentChainId && sessionChainId !== currentChainId;\n const walletDisconnected = !isConnected;\n\n if (addressChanged || chainChanged) {\n console.log('SIWE: Connector context changed (Address or Chain ID). Initiating re-authentication.');\n\n setIsSigningInAfterContextChange(true);\n\n // 1. OBLIGATORY SIGN OUT for the old session (security)\n signOutSiwe();\n } else if (walletDisconnected) {\n // Handle explicit connector disconnection: Always sign out.\n console.log('SIWE: Connector disconnected. Disconnecting session.');\n signOutSiwe();\n providerOnSignOut?.(); // Execute provider callback for disconnect\n }\n }\n }, [isAuthenticated, address, chainId, isConnected, localSession, signOutSiwe, enabled, providerOnSignOut]);\n\n // --- EFFECT TO EXECUTE AUTO SIGN-IN AFTER STATE RESET ---\n useEffect(() => {\n // Triggers when: 1. Flag is set AND 2. Status transitioned to 'unauthenticated'\n if (isSigningInAfterContextChange && sessionStatus === 'unauthenticated' && isReadyToSign && enabled) {\n console.log('SIWE: State reset detected. Attempting automatic sign-in to establish new session.');\n\n setIsSigningInAfterContextChange(false); // Reset flag\n\n // Auto sign-in execution\n signInWithSiwe().catch((e) => {\n throw new Error(\n `SIWE Auto Sign-In failed after context change: ${e instanceof Error ? e.message : 'Unknown error'}`,\n );\n });\n }\n }, [isSigningInAfterContextChange, sessionStatus, isReadyToSign, signInWithSiwe, enabled]);\n\n // --- FINAL EXPORT ---\n\n return useMemo(\n () => ({\n data,\n isReadyToSign,\n isRejected,\n isLoading: isAuthenticating,\n isSignedIn: isAuthenticated,\n signInWithSiwe,\n signOutSiwe,\n enabled,\n }),\n [data, isReadyToSign, isRejected, isAuthenticating, isAuthenticated, signInWithSiwe, signOutSiwe, enabled],\n );\n}\n","'use client';\n\nimport { useSiweAuthAdapter } from '../hooks/useSiweAuthAdapter';\nimport { SiweNextAuthProviderProps } from '../types';\nimport { SiweAuthContext } from './SiweAuthContext';\n\n/**\n * @component\n * @name SiweNextAuthProvider\n * @description Universal Provider for Sign-In with Ethereum (SIWE) using NextAuth.js.\n * This component handles the SIWE authentication logic.\n * It must be nested inside NextAuth's `<SessionProvider>` and your Wagmi Provider.\n * * **Note**: This provider requires the server-side NextAuth configuration to be set up.\n */\nexport function SiweNextAuthProvider(props: SiweNextAuthProviderProps) {\n const siweAuth = useSiweAuthAdapter(props);\n return <SiweAuthContext.Provider value={siweAuth}>{props.children}</SiweAuthContext.Provider>;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/session.config.ts","../../src/server/siweAuthServer.ts"],"names":["getSessionOptions","userConfig","sessionSettings","defaultPassword","finalPassword","finalCookieOptions","getDomain","url","createSiweApiHandler","config","hooks","currentSessionOptions","getSessionContainer","req","response","getIronSession","handleLogin","message","signature","NextResponse","siweMessage","SiweMessage","domain","session","sessionResponseContainer","finalResponse","value","key","error","handleGetSessionAndLogout","universalHandler","context","pathSegments","action"],"mappings":"gHAUO,SAASA,CAAAA,CAAkBC,CAAAA,CAA2C,CAC3E,IAAMC,CAAAA,CAAkBD,CAAAA,CAAW,OAAA,EAAW,EAAC,CAEzCE,CAAAA,CAAkB,OAAA,CAAQ,GAAA,CAAI,mBAAA,CAC9BC,CAAAA,CAAgBF,CAAAA,CAAgB,QAAA,EAAYC,CAAAA,CAElD,GAAI,CAACC,CAAAA,EAAiBA,CAAAA,CAAc,MAAA,CAAS,EAAA,CAC3C,MAAM,IAAI,KAAA,CACR,6HACF,CAAA,CAcF,IAAMC,CAAAA,CAAwC,CAC5C,GAX8C,CAE9C,MAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,YAAA,CACjC,MAAA,CAAQ,GAAA,CAAM,EAAA,CACd,QAAA,CAAU,IAAA,CACV,QAAA,CAAU,KAAA,CACV,IAAA,CAAM,GACR,CAAA,CAKE,GAAGH,CAAAA,CAAgB,aACrB,CAAA,CAEA,OAAO,CACL,QAAA,CAAUE,CAAAA,CACV,UAAA,CAAYF,CAAAA,CAAgB,UAAA,EAAc,gBAAA,CAC1C,aAAA,CAAeG,CACjB,CACF,CCxBA,SAASC,CAAAA,CAAUC,CAAAA,CAAiC,CAClD,GAAI,CAACA,CAAAA,CACH,OAAA,OAAA,CAAQ,IAAA,CAAK,qFAAqF,CAAA,CAC3F,WAAA,CAET,GAAI,CAEF,OADkB,IAAI,GAAA,CAAIA,CAAAA,CAAI,UA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ACH,IAAA,EAAQ,EAAC,CAC1CE,CAAAA,CAASD,CAAAA,CAAaA,CAAAA,CAAa,MAAA,CAAS,CAAC,CAAA,CAEnD,OAAIC,CAAAA,GAAW,OAAA,EAAWpB,CAAAA,CAAI,MAAA,GAAW,MAAA,CAChCG,CAAAA,CAAYH,CAAG,CAAA,CAIrBoB,CAAAA,GAAW,SAAA,EAAapB,CAAAA,CAAI,MAAA,GAAW,KAAA,EACvCoB,CAAAA,GAAW,QAAA,GAAapB,CAAAA,CAAI,MAAA,GAAW,MAAA,EAAUA,CAAAA,CAAI,MAAA,GAAW,QAAA,CAAA,CAE1DgB,CAAAA,CAA0BhB,CAAG,CAAA,CAG/B,OAAA,CAAQ,OAAA,CAAQ,IAAI,QAAA,CAAS,WAAA,CAAa,CAAE,MAAA,CAAQ,GAAI,CAAC,CAAC,CACnE,CAAA,CAEA,OAAO,CACL,GAAA,CAAKiB,CAAAA,CACL,IAAA,CAAMA,CAAAA,CACN,MAAA,CAAQA,CACV,CACF","file":"index.mjs","sourcesContent":["import { SessionOptions } from 'iron-session';\n\nimport { SiweApiConfig, SiweCookieOptions } from '../types';\n\n/**\n * @function getSessionOptions\n * @description Generates the Iron Session options object based on user configuration.\n * @param userConfig - The complete user configuration including session settings.\n * @returns SessionOptions The options required by `getIronSession`.\n */\nexport function getSessionOptions(userConfig: SiweApiConfig): SessionOptions {\n const sessionSettings = userConfig.session || {};\n\n const defaultPassword = process.env.SIWE_SESSION_SECRET;\n const finalPassword = sessionSettings.password || defaultPassword;\n\n if (!finalPassword || finalPassword.length < 32) {\n throw new Error(\n \"SIWE Error: Iron Session requires a 'password' option (min 32 chars) or SIWE_SESSION_SECRET environment variable to be set.\",\n );\n }\n\n // Determine cookie options\n const defaultCookieOptions: SiweCookieOptions = {\n // secure: true if NODE_ENV is production, as requested.\n secure: process.env.NODE_ENV === 'production',\n maxAge: 300 * 60, // 5 hours default\n httpOnly: true,\n sameSite: 'lax',\n path: '/',\n };\n\n // Merge default options with user provided options\n const finalCookieOptions: SiweCookieOptions = {\n ...defaultCookieOptions,\n ...sessionSettings.cookieOptions,\n };\n\n return {\n password: finalPassword as string,\n cookieName: sessionSettings.cookieName || 'satellite_siwe',\n cookieOptions: finalCookieOptions,\n } as SessionOptions;\n}\n","import { getIronSession, IronSession } from 'iron-session';\nimport { NextRequest, NextResponse } from 'next/server';\nimport { SiweMessage } from 'siwe';\n\nimport { Session, SiweApiConfig, SiweApiHooks } from '../types';\nimport { getSessionOptions } from './session.config';\n\n// App Router Handler type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AppRouterHandler = (req: NextRequest, context: any) => Promise<Response>;\n\n// ------------------------------------\n// --- UTILITIES ---\n// ------------------------------------\n\n/**\n * @function getDomain\n * @description Extracts the host/domain from SIWE_SESSION_URL for SIWE verification.\n */\nfunction getDomain(url: string | undefined): string {\n if (!url) {\n console.warn(\"SIWE WARN: SIWE_SESSION_URL is not defined. Defaulting domain check to 'localhost'.\");\n return 'localhost';\n }\n try {\n const parsedUrl = new URL(url.startsWith('http') ? url : `https://${url}`);\n return parsedUrl.host;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n console.error(\n `SIWE ERROR: Invalid URL provided in SIWE_SESSION_URL: ${url}. Error: ${typeof e === 'string' ? e : e.message}`,\n );\n return 'localhost';\n }\n}\n\n// ------------------------------------\n// --- MAIN API FACTORY ---\n// ------------------------------------\n\ninterface SiweApiRoutes {\n GET: AppRouterHandler;\n POST: AppRouterHandler;\n DELETE: AppRouterHandler;\n}\n\nexport function createSiweApiHandler(config: SiweApiConfig = {}): SiweApiRoutes {\n const hooks: SiweApiHooks = config.options || {};\n const currentSessionOptions = getSessionOptions(config);\n\n /**\n * @function getSessionContainer\n * @description Retrieves the Iron Session object and the Response container\n * used to hold the Set-Cookie headers.\n * @returns Promise<{ session: IronSession<Session>, response: Response }>\n */\n async function getSessionContainer(req: NextRequest): Promise<{ session: IronSession<Session>; response: Response }> {\n const response = new Response(); // Response-контейнер для куки\n const session = await getIronSession<Session>(req, response, currentSessionOptions);\n return { session, response };\n }\n\n // 1. Handles the SIWE login process (POST /login)\n async function handleLogin(req: NextRequest): Promise<Response> {\n try {\n const { message, signature } = await req.json();\n\n if (!message || !signature) {\n return NextResponse.json({ message: 'Missing message or signature' }, { status: 400 });\n }\n\n if (hooks.afterNonce) await hooks.afterNonce();\n\n const siweMessage = new SiweMessage(message);\n const domain = getDomain(process.env.SIWE_SESSION_URL);\n\n const result = await siweMessage.verify({\n signature: signature,\n domain: domain,\n });\n\n if (!result.success) {\n return NextResponse.json({ message: 'SIWE verification failed' }, { status: 401 });\n }\n\n if (hooks.afterVerify) await hooks.afterVerify();\n\n const { session, response: sessionResponseContainer } = await getSessionContainer(req);\n\n session.address = siweMessage.address;\n session.chainId = siweMessage.chainId;\n session.isLoggedIn = true;\n\n await session.save();\n\n if (hooks.afterSession) await hooks.afterSession();\n\n const finalResponse = NextResponse.json(\n { isLoggedIn: true, address: session.address, chainId: session.chainId },\n { status: 200 },\n );\n\n sessionResponseContainer.headers.forEach((value, key) => {\n if (key.toLowerCase() === 'set-cookie') {\n finalResponse.headers.append('Set-Cookie', value);\n }\n });\n\n return finalResponse;\n } catch (error) {\n console.error('SIWE CRITICAL LOGIN ERROR:', error);\n return NextResponse.json({ message: 'Internal Server Error during login' }, { status: 500 });\n }\n }\n\n // 2. Handles session retrieval (GET /session) and logout (POST/DELETE /logout)\n async function handleGetSessionAndLogout(req: NextRequest): Promise<Response> {\n const { session, response: sessionResponseContainer } = await getSessionContainer(req);\n\n if (req.method === 'POST' || req.method === 'DELETE') {\n session.destroy();\n\n if (hooks.afterLogout) await hooks.afterLogout();\n\n const finalResponse = NextResponse.json({ isLoggedIn: false }, { status: 200 });\n\n sessionResponseContainer.headers.forEach((value, key) => {\n if (key.toLowerCase() === 'set-cookie') {\n finalResponse.headers.append('Set-Cookie', value);\n }\n });\n return finalResponse;\n }\n\n if (session.isLoggedIn && session.address && session.chainId) {\n return NextResponse.json({\n isLoggedIn: true,\n address: session.address,\n chainId: session.chainId,\n });\n }\n\n return NextResponse.json({ isLoggedIn: false }, { status: 401 });\n }\n\n // --- UNIVERSAL DISPATCHER ---\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const universalHandler = async (req: NextRequest, context: any): Promise<Response> => {\n const params = (await context.params) || {};\n const pathSegments: string[] = params?.siwe || [];\n const action = pathSegments[pathSegments.length - 1];\n\n if (action === 'login' && req.method === 'POST') {\n return handleLogin(req);\n }\n\n if (\n (action === 'session' && req.method === 'GET') ||\n (action === 'logout' && (req.method === 'POST' || req.method === 'DELETE'))\n ) {\n return handleGetSessionAndLogout(req);\n }\n\n return Promise.resolve(new Response('Not Found', { status: 404 }));\n };\n\n return {\n GET: universalHandler,\n POST: universalHandler,\n DELETE: universalHandler,\n };\n}\n"]}
|