@tuwaio/satellite-siwe-next-auth 1.0.0-fix-test-alpha.21.76f200b

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 FOP Tkach Oleksandr
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # Satellite SIWE Next.js Auth
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/@tuwaio/satellite-siwe-next-auth.svg)](https://www.npmjs.com/package/@tuwaio/satellite-siwe-next-auth)
4
+ [![License](https://img.shields.io/npm/l/@tuwaio/satellite-siwe-next-auth.svg)](./LICENSE)
5
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/TuwaIO/satellite-connect/release.yml?branch=main)](https://github.com/TuwaIO/satellite-connect/actions)
6
+
7
+ A robust connector module for enabling secure Web3 authentication (Sign-In with Ethereum, SIWE) in Next.js App Router using **Iron Session** for state management.
8
+
9
+ -----
10
+
11
+ ## 🏛️ What is `@tuwaio/satellite-siwe-next-auth`?
12
+
13
+ `@tuwaio/satellite-siwe-next-auth` provides a secure, boilerplate-free solution for integrating **Sign-In with Ethereum (SIWE)** authentication into Next.js applications using the **App Router**.
14
+
15
+ It replaces the complexity of traditional NextAuth setup by leveraging **Iron Session** for robust, encrypted, server-side session management, ensuring a seamless and fully decentralized authentication experience.
16
+
17
+ Built on top of `@tuwaio/satellite-connect` and compatible with **Wagmi/Viem** for signature generation.
18
+
19
+ -----
20
+
21
+ ## ✨ Key Features
22
+
23
+ - **Full App Router Support:** Provides a single-file API handler designed specifically for the Next.js `app/api/[...]/route.ts` pattern.
24
+ - **No NextAuth Dependency:** Uses the lightweight **Iron Session** for session encryption, eliminating compatibility issues with NextAuth.
25
+ - **Auto-Session Management:** Handles automatic re-authentication and session cleanup upon wallet disconnection or address/chain change.
26
+ - **Flexible Configuration:** Allows custom configuration of Iron Session settings (password, cookie name) and support for **Async Hooks** (e.g., `afterVerify`, `afterLogout`).
27
+
28
+ -----
29
+
30
+ ## 💾 Installation
31
+
32
+ ### Requirements
33
+
34
+ - Node.js 20+
35
+ - TypeScript 5.9+
36
+ - Wagmi v2+
37
+ - Viem v2+
38
+ - Iron Session v8+
39
+
40
+ ```bash
41
+ # Using pnpm (recommended)
42
+ pnpm add @tuwaio/satellite-siwe-next-auth siwe iron-session wagmi viem
43
+
44
+ # Using npm
45
+ npm install @tuwaio/satellite-siwe-next-auth siwe iron-session wagmi viem
46
+ ```
47
+
48
+ ### Environment Setup
49
+
50
+ This package requires two **private** server environment variables for security:
51
+
52
+ | Variable | Description |
53
+ | :--- | :--- |
54
+ | `SIWE_SESSION_SECRET` | **Required.** A cryptographically secure secret (minimum 32 characters) used by Iron Session to encrypt the session cookie. |
55
+ | `SIWE_SESSION_URL` | **Required.** The full base URL of your application (e.g., `http://localhost:3000` or `https://myapp.com`). Used for SIWE domain verification. |
56
+
57
+ **Example `.env.local`:**
58
+
59
+ ```env
60
+ SIWE_SESSION_SECRET="oowX51fBPYHSVQxPbktPrfM8Lb3Kbeg3oQ6aCKdeLLo="
61
+ SIWE_SESSION_URL="http://localhost:3000"
62
+ ```
63
+
64
+ -----
65
+
66
+ ## 🚀 Quick Start
67
+
68
+ ### 1\. Server Setup (API Route)
69
+
70
+ Create the dynamic API route file at **`src/api/siwe/[...siwe]/route.ts`** and export the handler from the package. This handles `/login`, `/logout`, and `/session` requests.
71
+
72
+ ```typescript
73
+ // src/api/siwe/[...siwe]/route.ts
74
+
75
+ import { createSiweApiHandler } from '@tuwaio/satellite-siwe-next-auth/server';
76
+
77
+ // Initialize the handler. Configuration is read from the .env file by default.
78
+ const siweApiHandler = createSiweApiHandler();
79
+
80
+ // Export the methods expected by Next.js App Router
81
+ export const { GET, POST, DELETE } = siweApiHandler;
82
+ ```
83
+
84
+ ### 2\. Client Setup (Provider)
85
+
86
+ Wrap your application in the `SiweNextAuthProvider`. This provider manages the authentication state, session fetching, and handles auto-sign-out/re-authentication on wallet changes.
87
+
88
+ ```tsx
89
+ // src/providers/Providers.tsx
90
+
91
+ import { SiweNextAuthProvider } from '@tuwaio/satellite-siwe-next-auth';
92
+ // ... other imports (WagmiProvider, QueryClientProvider)
93
+
94
+ export function Providers({ children }: { children: React.ReactNode }) {
95
+ return (
96
+ <WagmiProvider config={wagmiConfig}>
97
+ <QueryClientProvider client={queryClient}>
98
+ {/* WAGMI AND REACT-QUERY MUST WRAP THE SIWE PROVIDER */}
99
+ <SiweNextAuthProvider
100
+ enabled={true}
101
+ onSignOut={() => console.log('User signed out')}
102
+ onSignIn={(session) => console.log('User signed in:', session)}
103
+ >
104
+ {children}
105
+ </SiweNextAuthProvider>
106
+ </QueryClientProvider>
107
+ </WagmiProvider>
108
+ );
109
+ }
110
+ ```
111
+
112
+ ### 3\. Usage (Login Component)
113
+
114
+ Use the `useSiweAuth` hook to access the sign-in function and state.
115
+
116
+ ```tsx
117
+ // src/components/WalletConnect.tsx
118
+
119
+ import { useSiweAuth } from '@tuwaio/satellite-siwe-next-auth';
120
+ // ... other imports (Wagmi hooks, etc.)
121
+
122
+ export function SatelliteConnectProviders({ children }: { children: React.ReactNode }) {
123
+ const { signInWithSiwe, isSignedIn, isRejected, enabled } = useSiweAuth();
124
+
125
+ // Example usage: Pass signInWithSiwe as the connection handler to a wallet adapter
126
+ // The adapter will call signInWithSiwe() after a wallet connection is established.
127
+ return (
128
+ <SatelliteConnectProvider
129
+ adapter={[
130
+ // Pass signInWithSiwe to your EVM adapter
131
+ satelliteEVMAdapter(wagmiConfig, enabled ? signInWithSiwe : undefined),
132
+ // ...
133
+ ]}
134
+ autoConnect={true}
135
+ >
136
+ {/* ... your components */}
137
+ </SatelliteConnectProvider>
138
+ );
139
+ }
140
+ ```
141
+
142
+ -----
143
+
144
+ ## ⚙️ Custom Configuration
145
+
146
+ The `createSiweApiHandler` accepts an optional configuration object to override session settings and define asynchronous hooks.
147
+
148
+ ### Configuration Parameters (`SiweApiConfig` Type)
149
+
150
+ | Parameter | Type | Default | Description |
151
+ | :--- | :--- | :--- | :--- |
152
+ | `session.password` | `string` | `SIWE_SESSION_SECRET` | Overrides the secret key for encryption. |
153
+ | `session.cookieName` | `string` | `'satellite_siwe'` | Overrides the name of the session cookie. |
154
+ | `session.cookieOptions` | `SiweCookieOptions` | `{ maxAge: 30 days, secure: false (dev) }` | Allows overriding standard cookie settings (e.g., `maxAge`). |
155
+ | `options.afterVerify` | `() => Promise<void>` | `undefined` | Hook executed **after** the SIWE signature is cryptographically verified. Ideal for fetching user data. |
156
+ | `options.afterLogout` | `() => Promise<void>` | `undefined` | Hook executed **after** the session cookie is destroyed. |
157
+
158
+ ### Example Custom Initialization
159
+
160
+ ```typescript
161
+ // src/api/siwe/[...siwe]/route.ts
162
+
163
+ import { createSiweApiHandler } from '@tuwaio/satellite-siwe-next-auth/server';
164
+
165
+ const siweApiHandler = createSiweApiHandler({
166
+ // Custom Session Settings
167
+ session: {
168
+ cookieName: "my_app_session",
169
+ cookieOptions: {
170
+ maxAge: 60 * 60 * 24 * 7, // 7 days
171
+ }
172
+ },
173
+ // Custom Hooks
174
+ options: {
175
+ afterVerify: async () => {
176
+ // This logic runs on the server side after a valid signature is confirmed.
177
+ console.log("User verified, ready to create DB record.");
178
+ },
179
+ afterLogout: () => {
180
+ console.log("User session destroyed.");
181
+ }
182
+ }
183
+ });
184
+
185
+ export const { GET, POST, DELETE } = siweApiHandler;
186
+ ```
187
+
188
+ -----
189
+
190
+ ## 🤝 Contributing & Support
191
+
192
+ Contributions are welcome! Please read our main **[Contribution Guidelines](https://github.com/TuwaIO/workflows/blob/main/CONTRIBUTING.md)**.
193
+
194
+ If you find this library useful, please consider supporting its development. Every contribution helps!
195
+
196
+ [**➡️ View Support Options**](https://github.com/TuwaIO/workflows/blob/main/Donation.md)
197
+
198
+ ## 📄 License
199
+
200
+ This project is licensed under the **Apache-2.0 License** - see the [LICENSE](./LICENSE) file for details.
201
+
202
+ ## 👥 Contributors
203
+
204
+ - **Oleksandr Tkach** - [GitHub](https://github.com/Argeare5)
@@ -0,0 +1,210 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { Address } from 'viem';
4
+ import { SiweMessage } from 'viem/siwe';
5
+ import * as react_jsx_runtime from 'react/jsx-runtime';
6
+
7
+ /**
8
+ * @function useInterval
9
+ * Creates a stable interval hook safe for client-side execution.
10
+ */
11
+ declare function useInterval(callback: () => void, delay: number | null): void;
12
+
13
+ /**
14
+ * Interface for the optional cookie serialization options.
15
+ * Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
16
+ */
17
+ interface SiweCookieOptions {
18
+ /** The value of the Max-Age Set-Cookie attribute in seconds. */
19
+ maxAge?: number;
20
+ /** The "Domain" Set-Cookie attribute. */
21
+ domain?: string;
22
+ /** The "Path" Set-Cookie attribute. */
23
+ path?: string;
24
+ /** The "Expires" Set-Cookie attribute. */
25
+ expires?: Date;
26
+ /** The "HttpOnly" Set-Cookie attribute. */
27
+ httpOnly?: boolean;
28
+ /** The "Secure" Set-Cookie attribute. */
29
+ secure?: boolean;
30
+ /** The "SameSite" Set-Cookie attribute. */
31
+ sameSite?: boolean | 'lax' | 'strict' | 'none';
32
+ }
33
+ /**
34
+ * Interface for the session settings block provided by the user.
35
+ */
36
+ interface SiweSessionSettings {
37
+ /** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
38
+ cookieName?: string;
39
+ /** * The password/secret used to encrypt the session data.
40
+ * Defaults to `process.env.SESSION_SECRET`.
41
+ */
42
+ password?: string;
43
+ /** Optional options for cookie serialization. */
44
+ cookieOptions?: SiweCookieOptions;
45
+ }
46
+ /**
47
+ * Interface for the custom SIWE API hooks block provided by the user.
48
+ */
49
+ interface SiweApiHooks {
50
+ /** Hook executed after the user is successfully logged out. */
51
+ afterLogout?: () => Promise<void> | void;
52
+ /** Hook executed before SIWE message verification (e.g., when the message is available). */
53
+ afterNonce?: () => Promise<void> | void;
54
+ /** Hook executed after the session is successfully created/saved. */
55
+ afterSession?: () => Promise<void> | void;
56
+ /** Hook executed after the SIWE signature is successfully verified. */
57
+ afterVerify?: () => Promise<void> | void;
58
+ }
59
+ /**
60
+ * The complete configuration object for the SIWE API handler factory.
61
+ */
62
+ interface SiweApiConfig {
63
+ /** Session configuration settings for Iron Session. */
64
+ session?: SiweSessionSettings;
65
+ /** Custom callback hooks for various steps of the SIWE process. */
66
+ options?: SiweApiHooks;
67
+ }
68
+ /**
69
+ * Defines the data structure stored inside the Iron Session.
70
+ */
71
+ interface SiweSessionData {
72
+ address: string;
73
+ chainId: number;
74
+ isLoggedIn: boolean;
75
+ }
76
+ /**
77
+ * Type alias for the Iron Session data.
78
+ */
79
+ type Session = SiweSessionData;
80
+ /**
81
+ * @typedef {Object} UnconfigurableMessageOptions
82
+ * Fields in the SIWE message that are controlled internally by the adapter logic.
83
+ * @property {Address} address - The Ethereum address signing the message (Viem type).
84
+ * @property {number} chainId - The chain ID of the network.
85
+ * @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
86
+ */
87
+ type UnconfigurableMessageOptions = {
88
+ address: Address;
89
+ chainId: number;
90
+ nonce: string;
91
+ };
92
+ /**
93
+ * @typedef {Object} ConfigurableMessageOptions
94
+ * Partial set of SIWE message fields that a consumer can optionally override.
95
+ * Unconfigurable fields are omitted.
96
+ */
97
+ type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
98
+ /**
99
+ * @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
100
+ * Function signature for customizing SIWE message options.
101
+ */
102
+ type GetSiweMessageOptions = () => ConfigurableMessageOptions;
103
+ /**
104
+ * @interface SIWESession
105
+ * The authenticated user data structure derived from the NextAuth session.
106
+ */
107
+ interface SIWESession {
108
+ address: Address;
109
+ chainId: number;
110
+ }
111
+ /**
112
+ * @interface SiweAuthContextType
113
+ * Interface for the SIWE authentication context state and actions.
114
+ * @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
115
+ * @property {boolean} isReadyToSign - True if an EVM wallet is connected and ready to sign.
116
+ * @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
117
+ * @property {boolean} isLoading - True if the session status is loading.
118
+ * @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
119
+ * @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
120
+ * @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
121
+ */
122
+ interface SiweAuthContextType {
123
+ data: SIWESession | undefined;
124
+ isReadyToSign: boolean;
125
+ isRejected: boolean;
126
+ isLoading: boolean;
127
+ isSignedIn: boolean;
128
+ enabled: boolean;
129
+ signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
130
+ signOutSiwe: (onSignOut?: () => void) => Promise<void>;
131
+ }
132
+ /**
133
+ * @interface UseSiweSignatureResult
134
+ * @property {boolean} isReadyToSign - True if an EVM wallet is connected and ready to sign.
135
+ * @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
136
+ * @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
137
+ */
138
+ interface UseSiweSignatureResult {
139
+ isReadyToSign: boolean;
140
+ isRejected: boolean;
141
+ getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
142
+ message: string;
143
+ signature: Address;
144
+ } | undefined>;
145
+ }
146
+ /**
147
+ * @interface SiweNextAuthProviderProps
148
+ * @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
149
+ * @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
150
+ * @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
151
+ * @property {() => void} [onSignOut] - Callback executed after a successful sign-out or wallet disconnect.
152
+ * @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
153
+ * @property {ReactNode} children - Child components.
154
+ */
155
+ interface SiweNextAuthProviderProps {
156
+ enabled?: boolean;
157
+ nonceRefetchInterval?: number;
158
+ onSignIn?: (session?: SIWESession) => void;
159
+ onSignOut?: () => void;
160
+ getSiweMessageOptions?: GetSiweMessageOptions;
161
+ children: ReactNode;
162
+ }
163
+
164
+ /**
165
+ * @function useSiweAuth
166
+ * @description Hook to access the SIWE authentication state and methods.
167
+ * @param {object} [options] - Optional callbacks that override provider-level callbacks.
168
+ * @param {(session?: SIWESession) => void} [options.onSignIn] - Callback executed after a successful sign-in.
169
+ * @param {() => void} [options.onSignOut] - Callback executed after a successful sign-out.
170
+ * @returns {SiweAuthContextType}
171
+ * * @example
172
+ * // const { isSignedIn, signInWithSiwe, data, isRejected } = useSiweAuth();
173
+ */
174
+ declare function useSiweAuth(options?: {
175
+ onSignIn?: (session?: SIWESession) => void;
176
+ onSignOut?: () => void;
177
+ }): SiweAuthContextType;
178
+
179
+ /**
180
+ * @function useSiweAuthAdapter
181
+ * Internal hook containing the core SIWE/Iron Session logic, acting as the authentication adapter.
182
+ * @returns {SiweAuthContextType}
183
+ */
184
+ declare function useSiweAuthAdapter({ enabled, nonceRefetchInterval, // 5 minutes (300,000 ms)
185
+ onSignIn: providerOnSignIn, onSignOut: providerOnSignOut, getSiweMessageOptions, }: SiweNextAuthProviderProps): SiweAuthContextType;
186
+
187
+ /**
188
+ * @function useSiweSignature
189
+ * @description A low-level hook that handles the core SIWE cryptographic flow:
190
+ * getting the nonce, creating the message, and getting the signature using Wagmi/Viem.
191
+ * This is the building block for custom backend authentication.
192
+ * @returns {UseSiweSignatureResult}
193
+ * * @example
194
+ * // const { getSiweSignature, isReadyToSign, isRejected } = useSiweSignature();
195
+ */
196
+ declare function useSiweSignature(): UseSiweSignatureResult;
197
+
198
+ declare const SiweAuthContext: react.Context<SiweAuthContextType | undefined>;
199
+
200
+ /**
201
+ * @component
202
+ * @name SiweNextAuthProvider
203
+ * @description Universal Provider for Sign-In with Ethereum (SIWE) using NextAuth.js.
204
+ * This component handles the SIWE authentication logic.
205
+ * It must be nested inside NextAuth's `<SessionProvider>` and your Wagmi Provider.
206
+ * * **Note**: This provider requires the server-side NextAuth configuration to be set up.
207
+ */
208
+ declare function SiweNextAuthProvider(props: SiweNextAuthProviderProps): react_jsx_runtime.JSX.Element;
209
+
210
+ export { type ConfigurableMessageOptions, type GetSiweMessageOptions, type SIWESession, type Session, type SiweApiConfig, type SiweApiHooks, SiweAuthContext, type SiweAuthContextType, type SiweCookieOptions, SiweNextAuthProvider, type SiweNextAuthProviderProps, type SiweSessionData, type SiweSessionSettings, type UnconfigurableMessageOptions, type UseSiweSignatureResult, useInterval, useSiweAuth, useSiweAuthAdapter, useSiweSignature };
@@ -0,0 +1,210 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { Address } from 'viem';
4
+ import { SiweMessage } from 'viem/siwe';
5
+ import * as react_jsx_runtime from 'react/jsx-runtime';
6
+
7
+ /**
8
+ * @function useInterval
9
+ * Creates a stable interval hook safe for client-side execution.
10
+ */
11
+ declare function useInterval(callback: () => void, delay: number | null): void;
12
+
13
+ /**
14
+ * Interface for the optional cookie serialization options.
15
+ * Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
16
+ */
17
+ interface SiweCookieOptions {
18
+ /** The value of the Max-Age Set-Cookie attribute in seconds. */
19
+ maxAge?: number;
20
+ /** The "Domain" Set-Cookie attribute. */
21
+ domain?: string;
22
+ /** The "Path" Set-Cookie attribute. */
23
+ path?: string;
24
+ /** The "Expires" Set-Cookie attribute. */
25
+ expires?: Date;
26
+ /** The "HttpOnly" Set-Cookie attribute. */
27
+ httpOnly?: boolean;
28
+ /** The "Secure" Set-Cookie attribute. */
29
+ secure?: boolean;
30
+ /** The "SameSite" Set-Cookie attribute. */
31
+ sameSite?: boolean | 'lax' | 'strict' | 'none';
32
+ }
33
+ /**
34
+ * Interface for the session settings block provided by the user.
35
+ */
36
+ interface SiweSessionSettings {
37
+ /** The name of the cookie to store the session data. Defaults to "satellite-siwe". */
38
+ cookieName?: string;
39
+ /** * The password/secret used to encrypt the session data.
40
+ * Defaults to `process.env.SESSION_SECRET`.
41
+ */
42
+ password?: string;
43
+ /** Optional options for cookie serialization. */
44
+ cookieOptions?: SiweCookieOptions;
45
+ }
46
+ /**
47
+ * Interface for the custom SIWE API hooks block provided by the user.
48
+ */
49
+ interface SiweApiHooks {
50
+ /** Hook executed after the user is successfully logged out. */
51
+ afterLogout?: () => Promise<void> | void;
52
+ /** Hook executed before SIWE message verification (e.g., when the message is available). */
53
+ afterNonce?: () => Promise<void> | void;
54
+ /** Hook executed after the session is successfully created/saved. */
55
+ afterSession?: () => Promise<void> | void;
56
+ /** Hook executed after the SIWE signature is successfully verified. */
57
+ afterVerify?: () => Promise<void> | void;
58
+ }
59
+ /**
60
+ * The complete configuration object for the SIWE API handler factory.
61
+ */
62
+ interface SiweApiConfig {
63
+ /** Session configuration settings for Iron Session. */
64
+ session?: SiweSessionSettings;
65
+ /** Custom callback hooks for various steps of the SIWE process. */
66
+ options?: SiweApiHooks;
67
+ }
68
+ /**
69
+ * Defines the data structure stored inside the Iron Session.
70
+ */
71
+ interface SiweSessionData {
72
+ address: string;
73
+ chainId: number;
74
+ isLoggedIn: boolean;
75
+ }
76
+ /**
77
+ * Type alias for the Iron Session data.
78
+ */
79
+ type Session = SiweSessionData;
80
+ /**
81
+ * @typedef {Object} UnconfigurableMessageOptions
82
+ * Fields in the SIWE message that are controlled internally by the adapter logic.
83
+ * @property {Address} address - The Ethereum address signing the message (Viem type).
84
+ * @property {number} chainId - The chain ID of the network.
85
+ * @property {string} nonce - A unique, session-bound nonce from NextAuth CSRF token.
86
+ */
87
+ type UnconfigurableMessageOptions = {
88
+ address: Address;
89
+ chainId: number;
90
+ nonce: string;
91
+ };
92
+ /**
93
+ * @typedef {Object} ConfigurableMessageOptions
94
+ * Partial set of SIWE message fields that a consumer can optionally override.
95
+ * Unconfigurable fields are omitted.
96
+ */
97
+ type ConfigurableMessageOptions = Partial<Omit<SiweMessage, keyof UnconfigurableMessageOptions>>;
98
+ /**
99
+ * @typedef {function(): ConfigurableMessageOptions} GetSiweMessageOptions
100
+ * Function signature for customizing SIWE message options.
101
+ */
102
+ type GetSiweMessageOptions = () => ConfigurableMessageOptions;
103
+ /**
104
+ * @interface SIWESession
105
+ * The authenticated user data structure derived from the NextAuth session.
106
+ */
107
+ interface SIWESession {
108
+ address: Address;
109
+ chainId: number;
110
+ }
111
+ /**
112
+ * @interface SiweAuthContextType
113
+ * Interface for the SIWE authentication context state and actions.
114
+ * @property {SIWESession | undefined} data - The authenticated SIWE data (address, chainId) if signed in.
115
+ * @property {boolean} isReadyToSign - True if an EVM wallet is connected and ready to sign.
116
+ * @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
117
+ * @property {boolean} isLoading - True if the session status is loading.
118
+ * @property {boolean} isSignedIn - True if the user has a valid NextAuth session.
119
+ * @property {function(onSignIn?: (session?: SIWESession) => void): Promise<void>} signInWithSiwe - Initiates the SIWE sign-in flow.
120
+ * @property {function(onSignOut?: () => void): Promise<void>} signOutSiwe - Terminates the NextAuth session.
121
+ */
122
+ interface SiweAuthContextType {
123
+ data: SIWESession | undefined;
124
+ isReadyToSign: boolean;
125
+ isRejected: boolean;
126
+ isLoading: boolean;
127
+ isSignedIn: boolean;
128
+ enabled: boolean;
129
+ signInWithSiwe: (onSignIn?: (session?: SIWESession) => void) => Promise<void>;
130
+ signOutSiwe: (onSignOut?: () => void) => Promise<void>;
131
+ }
132
+ /**
133
+ * @interface UseSiweSignatureResult
134
+ * @property {boolean} isReadyToSign - True if an EVM wallet is connected and ready to sign.
135
+ * @property {boolean} isRejected - True if the last signing attempt was explicitly rejected by the user.
136
+ * @property {function(GetSiweMessageOptions?): Promise<{message: string, signature: Address} | undefined>} getSiweSignature - Function to generate message and get signature.
137
+ */
138
+ interface UseSiweSignatureResult {
139
+ isReadyToSign: boolean;
140
+ isRejected: boolean;
141
+ getSiweSignature: (customOptions?: GetSiweMessageOptions) => Promise<{
142
+ message: string;
143
+ signature: Address;
144
+ } | undefined>;
145
+ }
146
+ /**
147
+ * @interface SiweNextAuthProviderProps
148
+ * @property {boolean} [enabled=true] - Enables or disables SIWE authentication globally.
149
+ * @property {number} [nonceRefetchInterval=300000] - Interval (ms) for refetching session/nonce token (defaults to 5 mins).
150
+ * @property {(session?: SIWESession) => void} [onSignIn] - Callback executed after a successful SIWE sign-in.
151
+ * @property {() => void} [onSignOut] - Callback executed after a successful sign-out or wallet disconnect.
152
+ * @property {GetSiweMessageOptions} [getSiweMessageOptions] - Optional function to customize the SIWE message fields.
153
+ * @property {ReactNode} children - Child components.
154
+ */
155
+ interface SiweNextAuthProviderProps {
156
+ enabled?: boolean;
157
+ nonceRefetchInterval?: number;
158
+ onSignIn?: (session?: SIWESession) => void;
159
+ onSignOut?: () => void;
160
+ getSiweMessageOptions?: GetSiweMessageOptions;
161
+ children: ReactNode;
162
+ }
163
+
164
+ /**
165
+ * @function useSiweAuth
166
+ * @description Hook to access the SIWE authentication state and methods.
167
+ * @param {object} [options] - Optional callbacks that override provider-level callbacks.
168
+ * @param {(session?: SIWESession) => void} [options.onSignIn] - Callback executed after a successful sign-in.
169
+ * @param {() => void} [options.onSignOut] - Callback executed after a successful sign-out.
170
+ * @returns {SiweAuthContextType}
171
+ * * @example
172
+ * // const { isSignedIn, signInWithSiwe, data, isRejected } = useSiweAuth();
173
+ */
174
+ declare function useSiweAuth(options?: {
175
+ onSignIn?: (session?: SIWESession) => void;
176
+ onSignOut?: () => void;
177
+ }): SiweAuthContextType;
178
+
179
+ /**
180
+ * @function useSiweAuthAdapter
181
+ * Internal hook containing the core SIWE/Iron Session logic, acting as the authentication adapter.
182
+ * @returns {SiweAuthContextType}
183
+ */
184
+ declare function useSiweAuthAdapter({ enabled, nonceRefetchInterval, // 5 minutes (300,000 ms)
185
+ onSignIn: providerOnSignIn, onSignOut: providerOnSignOut, getSiweMessageOptions, }: SiweNextAuthProviderProps): SiweAuthContextType;
186
+
187
+ /**
188
+ * @function useSiweSignature
189
+ * @description A low-level hook that handles the core SIWE cryptographic flow:
190
+ * getting the nonce, creating the message, and getting the signature using Wagmi/Viem.
191
+ * This is the building block for custom backend authentication.
192
+ * @returns {UseSiweSignatureResult}
193
+ * * @example
194
+ * // const { getSiweSignature, isReadyToSign, isRejected } = useSiweSignature();
195
+ */
196
+ declare function useSiweSignature(): UseSiweSignatureResult;
197
+
198
+ declare const SiweAuthContext: react.Context<SiweAuthContextType | undefined>;
199
+
200
+ /**
201
+ * @component
202
+ * @name SiweNextAuthProvider
203
+ * @description Universal Provider for Sign-In with Ethereum (SIWE) using NextAuth.js.
204
+ * This component handles the SIWE authentication logic.
205
+ * It must be nested inside NextAuth's `<SessionProvider>` and your Wagmi Provider.
206
+ * * **Note**: This provider requires the server-side NextAuth configuration to be set up.
207
+ */
208
+ declare function SiweNextAuthProvider(props: SiweNextAuthProviderProps): react_jsx_runtime.JSX.Element;
209
+
210
+ export { type ConfigurableMessageOptions, type GetSiweMessageOptions, type SIWESession, type Session, type SiweApiConfig, type SiweApiHooks, SiweAuthContext, type SiweAuthContextType, type SiweCookieOptions, SiweNextAuthProvider, type SiweNextAuthProviderProps, type SiweSessionData, type SiweSessionSettings, type UnconfigurableMessageOptions, type UseSiweSignatureResult, useInterval, useSiweAuth, useSiweAuthAdapter, useSiweSignature };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
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(e,t){let i=react.useRef(e);react.useEffect(()=>{i.current=e;},[e]),react.useEffect(()=>{if(t!==null&&typeof window<"u"&&window.setInterval){let n=window.setInterval(()=>i.current(),t);return ()=>window.clearInterval(n)}},[t]);}var C=react.createContext(void 0);function Se(e){let t=react.useContext(C);if(t===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let i=react.useCallback(async()=>t.signInWithSiwe(e?.onSignIn),[t.signInWithSiwe,e?.onSignIn]),n=react.useCallback(async()=>t.signOutSiwe(e?.onSignOut),[t.signOutSiwe,e?.onSignOut]);return react.useMemo(()=>({...t,signInWithSiwe:i,signOutSiwe:n}),[t,i,n])}async function Y(){return crypto.randomUUID().replace(/-/g,"")}function k(){let e=wagmi.useConfig(),{isConnected:t,address:i,chainId:n}=wagmi.useAccount({config:e}),[p,c]=react.useState(false),f=react.useMemo(()=>t&&!!i&&!!n,[t,i,n]);return react.useEffect(()=>{f&&c(false);},[f]),{getSiweSignature:async a=>{c(false);let u=core.getAccount(e);if(!u.isConnected||!u.address||!u.chainId)throw new Error("Wallet not connected or connection details are missing from Wagmi snapshot.");try{let o=await Y();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let d=siwe.createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...a?a():{},address:u.address,chainId:u.chainId,nonce:o}),h=await core.signMessage(e,{message:d});if(!h)throw c(!0),await core.disconnect(e),new Error("Message signing cancelled by user or failed.");return {message:d,signature:h}}catch(o){await core.disconnect(e),console.error("Error during signature generation:",o);let d=o;throw (d.name==="UserRejectedRequestError"||d.code===4001||/user rejected/i.test(d.message))&&c(true),o}},isReadyToSign:f,isRejected:p}}async function ne(){try{let e=await fetch("/api/siwe/session");if(e.status===401||e.status===404)return {session:void 0,status:"unauthenticated"};if(!e.ok)throw new Error("Failed to fetch session data.");let t=await e.json();return t.isLoggedIn&&t.address&&t.chainId?{session:{address:t.address,chainId:t.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(e){return console.error("Error fetching session:",e),{session:void 0,status:"unauthenticated"}}}function O({enabled:e=true,nonceRefetchInterval:t=300*1e3,onSignIn:i,onSignOut:n,getSiweMessageOptions:p}){let[c,f]=react.useState(void 0),[g,a]=react.useState("loading"),u=wagmi.useConfig(),{isReadyToSign:o,getSiweSignature:d,isRejected:h}=k(),{address:y,chainId:W,isConnected:v}=wagmi.useAccount({config:u}),[P,T]=react.useState(false),w=g==="authenticated",R=g==="loading",N=c,F=react.useCallback(async()=>{a("loading");let{session:s,status:r}=await ne();return f(s),a(r),s},[]);L(()=>{w&&F();},t);let m=react.useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),f(void 0),a("unauthenticated"),n?.(),s?.();},[n]),I=react.useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");a("loading");try{let r=await d(p);if(!r){a("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:r.message,signature:r.signature})}),S=await l.json();if(!l.ok||S.isLoggedIn!==!0)throw new Error(`Verification error: ${S.message||"Login failed."}`);console.log("SIWE Authentication successful.");let A={address:S.address,chainId:S.chainId};f(A),a("authenticated"),i?.(A),s?.(A);}catch(r){throw await core.disconnect(u),a("unauthenticated"),new Error(`SIWE Sign-In failed: ${r instanceof Error?r.message:"Unknown error"}`)}},[e,d,p,i,u]);return react.useEffect(()=>{if(w&&e){let s=c?.address?.toLowerCase(),r=y?.toLowerCase(),l=c?.chainId,S=W;s&&r&&s!==r||l&&S&&l!==S?(console.log("SIWE: Wallet context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!v&&(console.log("SIWE: Wallet disconnected. Disconnecting session."),m(),n?.());}},[w,y,W,v,c,m,e,n]),react.useEffect(()=>{P&&g==="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,g,o,I,e]),react.useMemo(()=>({data:N,isReadyToSign:o,isRejected:h,isLoading:R,isSignedIn:w,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,h,R,w,I,m,e])}function Pe(e){let t=O(e);return jsxRuntime.jsx(C.Provider,{value:t,children:e.children})}exports.SiweAuthContext=C;exports.SiweNextAuthProvider=Pe;exports.useInterval=L;exports.useSiweAuth=Se;exports.useSiweAuthAdapter=O;exports.useSiweSignature=k;//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
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","useConfig","isConnected","address","chainId","useAccount","isRejected","setIsRejected","useState","isReadyToSign","customOptions","walletSnapshot","getAccount","nonce","messageToSign","createSiweMessage","signature","signMessage","disconnect","error","err","fetchSession","res","data","useSiweAuthAdapter","enabled","nonceRefetchInterval","providerOnSignIn","providerOnSignOut","getSiweMessageOptions","localSession","setLocalSession","sessionStatus","setSessionStatus","config","getSiweSignature","isSigningInAfterContextChange","setIsSigningInAfterContextChange","isAuthenticated","isAuthenticating","updateSession","session","status","userOnSignOut","userOnSignIn","signatureData","response","responseBody","finalSession","sessionAddress","currentAddress","sessionChainId","currentChainId","e","SiweNextAuthProvider","props","siweAuth","jsx"],"mappings":"6JAQO,SAASA,CAAAA,CAAYC,CAAAA,CAAsBC,CAAAA,CAAsB,CACtE,IAAMC,CAAAA,CAAgBC,aAAOH,CAAQ,CAAA,CAErCI,eAAAA,CAAU,IAAM,CACdF,CAAAA,CAAc,OAAA,CAAUF,EAC1B,CAAA,CAAG,CAACA,CAAQ,CAAC,CAAA,CAEbI,eAAAA,CAAU,IAAM,CACd,GAAIH,CAAAA,GAAU,IAAA,EAAQ,OAAO,MAAA,CAAW,KAAe,MAAA,CAAO,WAAA,CAAa,CAEzE,IAAMI,CAAAA,CAAK,MAAA,CAAO,YAAY,IAAMH,CAAAA,CAAc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AA,CAAa4B,CAAAA,CAAclC,CAAAA,CAAa6B,EAASG,CAAiB,CAAC,CAAA,CAG1G1C,eAAAA,CAAU,IAAM,CAEVkD,CAAAA,EAAiCJ,CAAAA,GAAkB,iBAAA,EAAqBvB,CAAAA,EAAiBgB,CAAAA,GAC3F,OAAA,CAAQ,GAAA,CAAI,oFAAoF,EAEhGY,CAAAA,CAAiC,KAAK,CAAA,CAGtC3C,CAAAA,EAAe,CAAE,KAAA,CAAO2D,GAAM,CAC5B,MAAM,IAAI,KAAA,CACR,CAAA,+CAAA,EAAkDA,CAAAA,YAAa,MAAQA,CAAAA,CAAE,OAAA,CAAU,eAAe,CAAA,CACpG,CACF,CAAC,CAAA,EAEL,CAAA,CAAG,CAACjB,CAAAA,CAA+BJ,CAAAA,CAAevB,CAAAA,CAAef,CAAAA,CAAgB+B,CAAO,CAAC,CAAA,CAIlF5B,aAAAA,CACL,KAAO,CACL,IAAA,CAAA0B,CAAAA,CACA,cAAAd,CAAAA,CACA,UAAA,CAAAH,CAAAA,CACA,SAAA,CAAWiC,CAAAA,CACX,UAAA,CAAYD,EACZ,cAAA,CAAA5C,CAAAA,CACA,WAAA,CAAAE,CAAAA,CACA,OAAA,CAAA6B,CACF,CAAA,CAAA,CACA,CAACF,CAAAA,CAAMd,CAAAA,CAAeH,CAAAA,CAAYiC,CAAAA,CAAkBD,CAAAA,CAAiB5C,CAAAA,CAAgBE,EAAa6B,CAAO,CAC3G,CACF,CCpNO,SAAS6B,EAAAA,CAAqBC,CAAAA,CAAkC,CACrE,IAAMC,CAAAA,CAAWhC,EAAmB+B,CAAK,CAAA,CACzC,OAAOE,cAAAA,CAACrE,CAAAA,CAAgB,QAAA,CAAhB,CAAyB,KAAA,CAAOoE,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 { disconnect, getAccount, signMessage } from '@wagmi/core';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Address } from 'viem';\nimport { createSiweMessage } from 'viem/siwe';\nimport { useAccount, useConfig } 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(): UseSiweSignatureResult {\n const wagmiConfig = useConfig();\n const { isConnected, address, chainId } = useAccount({ 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 = getAccount(wagmiConfig);\n\n if (!walletSnapshot.isConnected || !walletSnapshot.address || !walletSnapshot.chainId) {\n throw new Error('Wallet 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 { useAccount, useConfig } 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 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 config = useConfig();\n const { isReadyToSign, getSiweSignature, isRejected } = useSiweSignature();\n\n const { address, chainId, isConnected } = useAccount({ config });\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(config);\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, config],\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: Wallet 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 wallet disconnection: Always sign out.\n console.log('SIWE: Wallet 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 ADDED
@@ -0,0 +1,2 @@
1
+ import {createContext,useRef,useEffect,useContext,useCallback,useMemo,useState}from'react';import {getAccount,signMessage,disconnect}from'@wagmi/core';import {useConfig,useAccount}from'wagmi';import {createSiweMessage}from'viem/siwe';import {jsx}from'react/jsx-runtime';function L(e,t){let i=useRef(e);useEffect(()=>{i.current=e;},[e]),useEffect(()=>{if(t!==null&&typeof window<"u"&&window.setInterval){let n=window.setInterval(()=>i.current(),t);return ()=>window.clearInterval(n)}},[t]);}var C=createContext(void 0);function Se(e){let t=useContext(C);if(t===void 0)throw new Error("useSiweAuth must be used within a SiweNextAuthProvider");let i=useCallback(async()=>t.signInWithSiwe(e?.onSignIn),[t.signInWithSiwe,e?.onSignIn]),n=useCallback(async()=>t.signOutSiwe(e?.onSignOut),[t.signOutSiwe,e?.onSignOut]);return useMemo(()=>({...t,signInWithSiwe:i,signOutSiwe:n}),[t,i,n])}async function Y(){return crypto.randomUUID().replace(/-/g,"")}function k(){let e=useConfig(),{isConnected:t,address:i,chainId:n}=useAccount({config:e}),[p,c]=useState(false),f=useMemo(()=>t&&!!i&&!!n,[t,i,n]);return useEffect(()=>{f&&c(false);},[f]),{getSiweSignature:async a=>{c(false);let u=getAccount(e);if(!u.isConnected||!u.address||!u.chainId)throw new Error("Wallet not connected or connection details are missing from Wagmi snapshot.");try{let o=await Y();if(!o)throw new Error("Failed to retrieve CSRF token/nonce.");let d=createSiweMessage({domain:window.location.host,statement:"Sign in with Ethereum to the application.",uri:window.location.origin,version:"1",...a?a():{},address:u.address,chainId:u.chainId,nonce:o}),h=await signMessage(e,{message:d});if(!h)throw c(!0),await disconnect(e),new Error("Message signing cancelled by user or failed.");return {message:d,signature:h}}catch(o){await disconnect(e),console.error("Error during signature generation:",o);let d=o;throw (d.name==="UserRejectedRequestError"||d.code===4001||/user rejected/i.test(d.message))&&c(true),o}},isReadyToSign:f,isRejected:p}}async function ne(){try{let e=await fetch("/api/siwe/session");if(e.status===401||e.status===404)return {session:void 0,status:"unauthenticated"};if(!e.ok)throw new Error("Failed to fetch session data.");let t=await e.json();return t.isLoggedIn&&t.address&&t.chainId?{session:{address:t.address,chainId:t.chainId},status:"authenticated"}:{session:void 0,status:"unauthenticated"}}catch(e){return console.error("Error fetching session:",e),{session:void 0,status:"unauthenticated"}}}function O({enabled:e=true,nonceRefetchInterval:t=300*1e3,onSignIn:i,onSignOut:n,getSiweMessageOptions:p}){let[c,f]=useState(void 0),[g,a]=useState("loading"),u=useConfig(),{isReadyToSign:o,getSiweSignature:d,isRejected:h}=k(),{address:y,chainId:W,isConnected:v}=useAccount({config:u}),[P,T]=useState(false),w=g==="authenticated",R=g==="loading",N=c,F=useCallback(async()=>{a("loading");let{session:s,status:r}=await ne();return f(s),a(r),s},[]);L(()=>{w&&F();},t);let m=useCallback(async s=>{await fetch("/api/siwe/logout",{method:"POST"}),f(void 0),a("unauthenticated"),n?.(),s?.();},[n]),I=useCallback(async s=>{if(!e)throw new Error("SIWE is currently disabled via provider configuration.");a("loading");try{let r=await d(p);if(!r){a("unauthenticated");return}let l=await fetch("/api/siwe/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:r.message,signature:r.signature})}),S=await l.json();if(!l.ok||S.isLoggedIn!==!0)throw new Error(`Verification error: ${S.message||"Login failed."}`);console.log("SIWE Authentication successful.");let A={address:S.address,chainId:S.chainId};f(A),a("authenticated"),i?.(A),s?.(A);}catch(r){throw await disconnect(u),a("unauthenticated"),new Error(`SIWE Sign-In failed: ${r instanceof Error?r.message:"Unknown error"}`)}},[e,d,p,i,u]);return useEffect(()=>{if(w&&e){let s=c?.address?.toLowerCase(),r=y?.toLowerCase(),l=c?.chainId,S=W;s&&r&&s!==r||l&&S&&l!==S?(console.log("SIWE: Wallet context changed (Address or Chain ID). Initiating re-authentication."),T(true),m()):!v&&(console.log("SIWE: Wallet disconnected. Disconnecting session."),m(),n?.());}},[w,y,W,v,c,m,e,n]),useEffect(()=>{P&&g==="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,g,o,I,e]),useMemo(()=>({data:N,isReadyToSign:o,isRejected:h,isLoading:R,isSignedIn:w,signInWithSiwe:I,signOutSiwe:m,enabled:e}),[N,o,h,R,w,I,m,e])}function Pe(e){let t=O(e);return jsx(C.Provider,{value:t,children:e.children})}export{C as SiweAuthContext,Pe as SiweNextAuthProvider,L as useInterval,Se as useSiweAuth,O as useSiweAuthAdapter,k as useSiweSignature};//# sourceMappingURL=index.mjs.map
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
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","useConfig","isConnected","address","chainId","useAccount","isRejected","setIsRejected","useState","isReadyToSign","customOptions","walletSnapshot","getAccount","nonce","messageToSign","createSiweMessage","signature","signMessage","disconnect","error","err","fetchSession","res","data","useSiweAuthAdapter","enabled","nonceRefetchInterval","providerOnSignIn","providerOnSignOut","getSiweMessageOptions","localSession","setLocalSession","sessionStatus","setSessionStatus","config","getSiweSignature","isSigningInAfterContextChange","setIsSigningInAfterContextChange","isAuthenticated","isAuthenticating","updateSession","session","status","userOnSignOut","userOnSignIn","signatureData","response","responseBody","finalSession","sessionAddress","currentAddress","sessionChainId","currentChainId","e","SiweNextAuthProvider","props","siweAuth","jsx"],"mappings":"8QAQO,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,CAA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CAAyB,KAAA,CAAOoE,CAAAA,CAAW,QAAA,CAAAD,CAAAA,CAAM,QAAA,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 { disconnect, getAccount, signMessage } from '@wagmi/core';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Address } from 'viem';\nimport { createSiweMessage } from 'viem/siwe';\nimport { useAccount, useConfig } 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(): UseSiweSignatureResult {\n const wagmiConfig = useConfig();\n const { isConnected, address, chainId } = useAccount({ 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 = getAccount(wagmiConfig);\n\n if (!walletSnapshot.isConnected || !walletSnapshot.address || !walletSnapshot.chainId) {\n throw new Error('Wallet 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 { useAccount, useConfig } 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 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 config = useConfig();\n const { isReadyToSign, getSiweSignature, isRejected } = useSiweSignature();\n\n const { address, chainId, isConnected } = useAccount({ config });\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(config);\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, config],\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: Wallet 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 wallet disconnection: Always sign out.\n console.log('SIWE: Wallet 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"]}
@@ -0,0 +1,76 @@
1
+ import { SessionOptions } from 'iron-session';
2
+ import { NextRequest } from 'next/server';
3
+
4
+ /**
5
+ * Interface for the optional cookie serialization options.
6
+ * Matches common fields of `CookieSerializeOptions` from the 'cookie' package.
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
+ }
59
+
60
+ /**
61
+ * @function getSessionOptions
62
+ * @description Generates the Iron Session options object based on user configuration.
63
+ * @param userConfig - The complete user configuration including session settings.
64
+ * @returns SessionOptions The options required by `getIronSession`.
65
+ */
66
+ declare function getSessionOptions(userConfig: SiweApiConfig): SessionOptions;
67
+
68
+ type AppRouterHandler = (req: NextRequest, context: any) => Promise<Response>;
69
+ interface SiweApiRoutes {
70
+ GET: AppRouterHandler;
71
+ POST: AppRouterHandler;
72
+ DELETE: AppRouterHandler;
73
+ }
74
+ declare function createSiweApiHandler(config?: SiweApiConfig): SiweApiRoutes;
75
+
76
+ export { createSiweApiHandler, getSessionOptions };
@@ -0,0 +1,3 @@
1
+ import {getIronSession}from'iron-session';import {NextResponse}from'next/server';import {SiweMessage}from'siwe';function g(t){let e=t.session||{},c=process.env.SIWE_SESSION_SECRET,r=e.password||c;if(!r||r.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 d={...{secure:process.env.NODE_ENV==="production",maxAge:300*60,httpOnly:true,sameSite:"lax",path:"/"},...e.cookieOptions};return {password:r,cookieName:e.cookieName||"satellite_siwe",cookieOptions:d}}function l(t){if(!t)return console.warn("SIWE WARN: SIWE_SESSION_URL is not defined. Defaulting domain check to 'localhost'."),"localhost";try{return new URL(t.startsWith("http")?t:`https://${t}`).host}catch(e){return console.error(`SIWE ERROR: Invalid URL provided in SIWE_SESSION_URL: ${t}. Error: ${typeof e=="string"?e:e.message}`),"localhost"}}function y(t={}){let e=t.options||{},c=g(t);async function r(s){let o=new Response;return getIronSession(s,o,c)}async function f(s){try{let{message:o,signature:u}=await s.json();if(!o||!u)return NextResponse.json({message:"Missing message or signature"},{status:400});e.afterNonce&&await e.afterNonce();let n=new SiweMessage(o),a=l(process.env.SIWE_SESSION_URL);if(!(await n.verify({signature:u,domain:a})).success)return NextResponse.json({message:"SIWE verification failed"},{status:401});e.afterVerify&&await e.afterVerify();let p=await r(s);return p.address=n.address,p.chainId=n.chainId,p.isLoggedIn=!0,await p.save(),e.afterSession&&await e.afterSession(),NextResponse.json({isLoggedIn:!0,address:n.address,chainId:n.chainId},{status:200})}catch(o){return console.error("SIWE CRITICAL LOGIN ERROR:",o),NextResponse.json({message:"Internal Server Error during login"},{status:500})}}async function d(s){let o=await r(s);return s.method==="POST"||s.method==="DELETE"?(o.destroy(),e.afterLogout&&await e.afterLogout(),NextResponse.json({isLoggedIn:false},{status:200})):o.isLoggedIn&&o.address&&o.chainId?NextResponse.json({isLoggedIn:true,address:o.address,chainId:o.chainId}):NextResponse.json({isLoggedIn:false},{status:401})}let S=async(s,o)=>{let n=(await o.params||{})?.siwe||[],a=n[n.length-1];return a==="login"&&s.method==="POST"?f(s):a==="session"&&s.method==="GET"||a==="logout"&&(s.method==="POST"||s.method==="DELETE")?d(s):Promise.resolve(new Response("Not Found",{status:404}))};return {GET:S,POST:S,DELETE:S}}
2
+ export{y as createSiweApiHandler,g as getSessionOptions};//# sourceMappingURL=index.mjs.map
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
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","getSession","req","response","getIronSession","handleLogin","message","signature","NextResponse","siweMessage","SiweMessage","domain","session","error","handleGetSessionAndLogout","universalHandler","context","pathSegments","action"],"mappings":"gHAUO,SAASA,CAAAA,CAAkBC,EAA2C,CAC3E,IAAMC,EAAkBD,CAAAA,CAAW,OAAA,EAAW,EAAC,CAEzCE,CAAAA,CAAkB,OAAA,CAAQ,IAAI,mBAAA,CAC9BC,CAAAA,CAAgBF,CAAAA,CAAgB,QAAA,EAAYC,C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,CAAG,CAAA,CAIrBgB,CAAAA,GAAW,SAAA,EAAahB,CAAAA,CAAI,SAAW,KAAA,EACvCgB,CAAAA,GAAW,QAAA,GAAahB,CAAAA,CAAI,MAAA,GAAW,MAAA,EAAUA,EAAI,MAAA,GAAW,QAAA,CAAA,CAE1DY,CAAAA,CAA0BZ,CAAG,CAAA,CAG/B,OAAA,CAAQ,QAAQ,IAAI,QAAA,CAAS,WAAA,CAAa,CAAE,MAAA,CAAQ,GAAI,CAAC,CAAC,CACnE,CAAA,CAEA,OAAO,CACL,GAAA,CAAKa,EACL,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 getSession\n * @description Retrieves the Iron Session object from the request using the configured options.\n */\n async function getSession(req: NextRequest): Promise<IronSession<Session>> {\n const response = new Response();\n return getIronSession<Session>(req, response, currentSessionOptions);\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 // ИСПОЛЬЗУЕМ НОВУЮ ПЕРЕМЕННУЮ ДЛЯ ДОМЕНА\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 = await getSession(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 return NextResponse.json(\n { isLoggedIn: true, address: siweMessage.address, chainId: siweMessage.chainId },\n { status: 200 },\n );\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 // ... (логика без изменений)\n const session = await getSession(req);\n\n if (req.method === 'POST' || req.method === 'DELETE') {\n session.destroy();\n\n if (hooks.afterLogout) await hooks.afterLogout();\n\n return NextResponse.json({ isLoggedIn: false }, { status: 200 });\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"]}
package/package.json ADDED
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "@tuwaio/satellite-siwe-next-auth",
3
+ "version": "1.0.0-fix-test-alpha.21.76f200b",
4
+ "private": false,
5
+ "author": "Oleksandr Tkach",
6
+ "license": "Apache-2.0",
7
+ "description": "A robust connector module for enabling secure Web3 authentication in Next.js by combining NextAuth with the SIWE standard.",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.mjs",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.mjs",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./server": {
18
+ "types": "./dist/server/index.d.ts",
19
+ "import": "./dist/server/index.mjs",
20
+ "default": "./dist/server/index.js"
21
+ }
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "keywords": [
30
+ "web3",
31
+ "siwe",
32
+ "next-auth",
33
+ "connect",
34
+ "evm",
35
+ "wagmi",
36
+ "viem"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/TuwaIO/satellite-connect.git",
41
+ "directory": "packages/satellite-siwe-next-auth"
42
+ },
43
+ "homepage": "https://github.com/TuwaIO/satellite-connect",
44
+ "bugs": {
45
+ "url": "https://github.com/TuwaIO/satellite-connect/issues"
46
+ },
47
+ "contributors": [
48
+ {
49
+ "name": "Oleksandr Tkach",
50
+ "url": "https://github.com/Argeare5"
51
+ }
52
+ ],
53
+ "peerDependencies": {
54
+ "@wagmi/core": "2.x.x",
55
+ "siwe": "3.x.x",
56
+ "next": "15.x.x",
57
+ "iron-session": "8.x.x",
58
+ "react": "19.x.x",
59
+ "viem": "2.x.x",
60
+ "wagmi": "2.x.x"
61
+ },
62
+ "devDependencies": {
63
+ "@wagmi/core": "^2.21.1",
64
+ "@types/react": "^19.1.13",
65
+ "siwe": "^3.0.0",
66
+ "next": "15.5.3",
67
+ "iron-session": "^8.0.4",
68
+ "react": "^19.1.1",
69
+ "tsup": "^8.5.0",
70
+ "typescript": "^5.9.2",
71
+ "viem": "^2.37.8",
72
+ "wagmi": "^2.17.2"
73
+ },
74
+ "scripts": {
75
+ "start": "tsup src/index.ts --watch",
76
+ "build": "tsup",
77
+ "test": "vitest"
78
+ }
79
+ }