@originals/auth 1.8.2 → 1.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{src/client/index.ts → dist/client/index.d.ts} +2 -15
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +23 -0
- package/dist/client/index.js.map +1 -0
- package/{src/client/server-auth.ts → dist/client/server-auth.d.ts} +5 -45
- package/dist/client/server-auth.d.ts.map +1 -0
- package/dist/client/server-auth.js +77 -0
- package/dist/client/server-auth.js.map +1 -0
- package/dist/client/turnkey-client.d.ts +59 -0
- package/dist/client/turnkey-client.d.ts.map +1 -0
- package/dist/client/turnkey-client.js +279 -0
- package/dist/client/turnkey-client.js.map +1 -0
- package/dist/client/turnkey-did-signer.d.ts +58 -0
- package/dist/client/turnkey-did-signer.d.ts.map +1 -0
- package/dist/client/turnkey-did-signer.js +131 -0
- package/dist/client/turnkey-did-signer.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/{src/index.ts → dist/index.js} +1 -6
- package/dist/index.js.map +1 -0
- package/dist/server/email-auth.d.ts +42 -0
- package/dist/server/email-auth.d.ts.map +1 -0
- package/dist/server/email-auth.js +187 -0
- package/dist/server/email-auth.js.map +1 -0
- package/dist/server/index.d.ts +22 -0
- package/dist/server/index.d.ts.map +1 -0
- package/{src/server/index.ts → dist/server/index.js} +3 -23
- package/dist/server/index.js.map +1 -0
- package/dist/server/jwt.d.ts +49 -0
- package/dist/server/jwt.d.ts.map +1 -0
- package/dist/server/jwt.js +113 -0
- package/dist/server/jwt.js.map +1 -0
- package/dist/server/middleware.d.ts +39 -0
- package/dist/server/middleware.d.ts.map +1 -0
- package/dist/server/middleware.js +112 -0
- package/dist/server/middleware.js.map +1 -0
- package/dist/server/turnkey-client.d.ts +24 -0
- package/dist/server/turnkey-client.d.ts.map +1 -0
- package/dist/server/turnkey-client.js +118 -0
- package/dist/server/turnkey-client.js.map +1 -0
- package/dist/server/turnkey-signer.d.ts +40 -0
- package/dist/server/turnkey-signer.d.ts.map +1 -0
- package/dist/server/turnkey-signer.js +121 -0
- package/dist/server/turnkey-signer.js.map +1 -0
- package/dist/types.d.ts +155 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/package.json +13 -12
- package/src/client/turnkey-client.ts +0 -364
- package/src/client/turnkey-did-signer.ts +0 -203
- package/src/server/email-auth.ts +0 -258
- package/src/server/jwt.ts +0 -154
- package/src/server/middleware.ts +0 -142
- package/src/server/turnkey-client.ts +0 -156
- package/src/server/turnkey-signer.ts +0 -170
- package/src/types.ts +0 -172
package/src/server/email-auth.ts
DELETED
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Turnkey Email Authentication Service
|
|
3
|
-
* Implements email-based authentication using Turnkey's OTP flow
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { Turnkey } from '@turnkey/sdk-server';
|
|
7
|
-
import { sha256 } from '@noble/hashes/sha2.js';
|
|
8
|
-
import { bytesToHex } from '@noble/hashes/utils.js';
|
|
9
|
-
import type { EmailAuthSession, InitiateAuthResult, VerifyAuthResult } from '../types';
|
|
10
|
-
import { getOrCreateTurnkeySubOrg } from './turnkey-client';
|
|
11
|
-
|
|
12
|
-
// Session timeout (15 minutes to match Turnkey OTP)
|
|
13
|
-
const SESSION_TIMEOUT = 15 * 60 * 1000;
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Session storage interface for pluggable session management
|
|
17
|
-
*/
|
|
18
|
-
export interface SessionStorage {
|
|
19
|
-
get(sessionId: string): EmailAuthSession | undefined;
|
|
20
|
-
set(sessionId: string, session: EmailAuthSession): void;
|
|
21
|
-
delete(sessionId: string): void;
|
|
22
|
-
cleanup(): void;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Create an in-memory session storage
|
|
27
|
-
* For production, consider using Redis or a database
|
|
28
|
-
*/
|
|
29
|
-
export function createInMemorySessionStorage(): SessionStorage {
|
|
30
|
-
const sessions = new Map<string, EmailAuthSession>();
|
|
31
|
-
|
|
32
|
-
// Start cleanup interval
|
|
33
|
-
const cleanupInterval = setInterval(() => {
|
|
34
|
-
const now = Date.now();
|
|
35
|
-
for (const [sessionId, session] of sessions.entries()) {
|
|
36
|
-
if (now - session.timestamp > SESSION_TIMEOUT) {
|
|
37
|
-
sessions.delete(sessionId);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
}, 60 * 1000);
|
|
41
|
-
|
|
42
|
-
// Keep the interval from preventing process exit
|
|
43
|
-
if (cleanupInterval.unref) {
|
|
44
|
-
cleanupInterval.unref();
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
return {
|
|
48
|
-
get: (sessionId: string) => sessions.get(sessionId),
|
|
49
|
-
set: (sessionId: string, session: EmailAuthSession) => sessions.set(sessionId, session),
|
|
50
|
-
delete: (sessionId: string) => sessions.delete(sessionId),
|
|
51
|
-
cleanup: () => {
|
|
52
|
-
clearInterval(cleanupInterval);
|
|
53
|
-
sessions.clear();
|
|
54
|
-
},
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Default session storage
|
|
59
|
-
let defaultSessionStorage: SessionStorage | null = null;
|
|
60
|
-
|
|
61
|
-
function getDefaultSessionStorage(): SessionStorage {
|
|
62
|
-
if (!defaultSessionStorage) {
|
|
63
|
-
defaultSessionStorage = createInMemorySessionStorage();
|
|
64
|
-
}
|
|
65
|
-
return defaultSessionStorage;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Generate a random session ID
|
|
70
|
-
*/
|
|
71
|
-
function generateSessionId(): string {
|
|
72
|
-
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Initiate email authentication using Turnkey OTP
|
|
77
|
-
* Sends a 6-digit OTP code to the user's email
|
|
78
|
-
*/
|
|
79
|
-
export async function initiateEmailAuth(
|
|
80
|
-
email: string,
|
|
81
|
-
turnkeyClient: Turnkey,
|
|
82
|
-
sessionStorage?: SessionStorage
|
|
83
|
-
): Promise<InitiateAuthResult> {
|
|
84
|
-
const storage = sessionStorage ?? getDefaultSessionStorage();
|
|
85
|
-
|
|
86
|
-
// Validate email format
|
|
87
|
-
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
88
|
-
if (!emailRegex.test(email)) {
|
|
89
|
-
throw new Error('Invalid email format');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
console.log(`\n🚀 Initiating email auth for: ${email}`);
|
|
93
|
-
|
|
94
|
-
// Step 1: Get or create Turnkey sub-organization
|
|
95
|
-
const subOrgId = await getOrCreateTurnkeySubOrg(email, turnkeyClient);
|
|
96
|
-
|
|
97
|
-
// Step 2: Send OTP via Turnkey
|
|
98
|
-
console.log(`📨 Sending OTP to ${email} via Turnkey...`);
|
|
99
|
-
|
|
100
|
-
// Generate a unique user identifier for rate limiting
|
|
101
|
-
const data = new TextEncoder().encode(email);
|
|
102
|
-
const hash = sha256(data);
|
|
103
|
-
const userIdentifier = bytesToHex(hash);
|
|
104
|
-
|
|
105
|
-
const otpResult = await turnkeyClient.apiClient().initOtp({
|
|
106
|
-
otpType: 'OTP_TYPE_EMAIL',
|
|
107
|
-
contact: email,
|
|
108
|
-
userIdentifier: userIdentifier,
|
|
109
|
-
appName: 'Originals',
|
|
110
|
-
otpLength: 6,
|
|
111
|
-
alphanumeric: false,
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
const otpId = otpResult.otpId;
|
|
115
|
-
|
|
116
|
-
if (!otpId) {
|
|
117
|
-
throw new Error('Failed to initiate OTP - no OTP ID returned');
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
console.log(`✅ OTP sent! OTP ID: ${otpId}`);
|
|
121
|
-
|
|
122
|
-
// Create auth session
|
|
123
|
-
const sessionId = generateSessionId();
|
|
124
|
-
storage.set(sessionId, {
|
|
125
|
-
email,
|
|
126
|
-
subOrgId,
|
|
127
|
-
otpId,
|
|
128
|
-
timestamp: Date.now(),
|
|
129
|
-
verified: false,
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
console.log('='.repeat(60));
|
|
133
|
-
console.log(`📧 Check ${email} for the verification code!`);
|
|
134
|
-
console.log(` Session ID: ${sessionId}`);
|
|
135
|
-
console.log(` Valid for: 15 minutes`);
|
|
136
|
-
console.log('='.repeat(60) + '\n');
|
|
137
|
-
|
|
138
|
-
return {
|
|
139
|
-
sessionId,
|
|
140
|
-
message: 'Verification code sent to your email. Check your inbox!',
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* Verify email authentication code using Turnkey OTP
|
|
146
|
-
*/
|
|
147
|
-
export async function verifyEmailAuth(
|
|
148
|
-
sessionId: string,
|
|
149
|
-
code: string,
|
|
150
|
-
turnkeyClient: Turnkey,
|
|
151
|
-
sessionStorage?: SessionStorage
|
|
152
|
-
): Promise<VerifyAuthResult> {
|
|
153
|
-
const storage = sessionStorage ?? getDefaultSessionStorage();
|
|
154
|
-
const session = storage.get(sessionId);
|
|
155
|
-
|
|
156
|
-
if (!session) {
|
|
157
|
-
throw new Error('Invalid or expired session');
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
// Check if session has expired
|
|
161
|
-
if (Date.now() - session.timestamp > SESSION_TIMEOUT) {
|
|
162
|
-
storage.delete(sessionId);
|
|
163
|
-
throw new Error('Session expired. Please request a new code.');
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (!session.otpId) {
|
|
167
|
-
throw new Error('OTP ID not found in session');
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
if (!session.subOrgId) {
|
|
171
|
-
throw new Error('Sub-organization ID not found');
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
console.log(`\n🔐 Verifying OTP for session ${sessionId}...`);
|
|
175
|
-
|
|
176
|
-
try {
|
|
177
|
-
// Verify the OTP code with Turnkey
|
|
178
|
-
const verifyResult = await turnkeyClient.apiClient().verifyOtp({
|
|
179
|
-
otpId: session.otpId,
|
|
180
|
-
otpCode: code,
|
|
181
|
-
expirationSeconds: '900', // 15 minutes
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
if (!verifyResult.verificationToken) {
|
|
185
|
-
throw new Error('OTP verification failed - no verification token returned');
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
console.log(`✅ OTP verified successfully!`);
|
|
189
|
-
|
|
190
|
-
// Mark session as verified
|
|
191
|
-
session.verified = true;
|
|
192
|
-
storage.set(sessionId, session);
|
|
193
|
-
|
|
194
|
-
return {
|
|
195
|
-
verified: true,
|
|
196
|
-
email: session.email,
|
|
197
|
-
subOrgId: session.subOrgId,
|
|
198
|
-
};
|
|
199
|
-
} catch (error) {
|
|
200
|
-
console.error('❌ OTP verification failed:', error);
|
|
201
|
-
throw new Error(
|
|
202
|
-
`Invalid verification code: ${error instanceof Error ? error.message : String(error)}`
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Check if a session is verified
|
|
209
|
-
*/
|
|
210
|
-
export function isSessionVerified(
|
|
211
|
-
sessionId: string,
|
|
212
|
-
sessionStorage?: SessionStorage
|
|
213
|
-
): boolean {
|
|
214
|
-
const storage = sessionStorage ?? getDefaultSessionStorage();
|
|
215
|
-
const session = storage.get(sessionId);
|
|
216
|
-
|
|
217
|
-
if (!session) return false;
|
|
218
|
-
|
|
219
|
-
if (Date.now() - session.timestamp > SESSION_TIMEOUT) {
|
|
220
|
-
storage.delete(sessionId);
|
|
221
|
-
return false;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
return session.verified;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Clean up a session after successful login
|
|
229
|
-
*/
|
|
230
|
-
export function cleanupSession(
|
|
231
|
-
sessionId: string,
|
|
232
|
-
sessionStorage?: SessionStorage
|
|
233
|
-
): void {
|
|
234
|
-
const storage = sessionStorage ?? getDefaultSessionStorage();
|
|
235
|
-
storage.delete(sessionId);
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Get session data
|
|
240
|
-
*/
|
|
241
|
-
export function getSession(
|
|
242
|
-
sessionId: string,
|
|
243
|
-
sessionStorage?: SessionStorage
|
|
244
|
-
): EmailAuthSession | undefined {
|
|
245
|
-
const storage = sessionStorage ?? getDefaultSessionStorage();
|
|
246
|
-
const session = storage.get(sessionId);
|
|
247
|
-
|
|
248
|
-
if (!session) return undefined;
|
|
249
|
-
|
|
250
|
-
// Check if expired
|
|
251
|
-
if (Date.now() - session.timestamp > SESSION_TIMEOUT) {
|
|
252
|
-
storage.delete(sessionId);
|
|
253
|
-
return undefined;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
return session;
|
|
257
|
-
}
|
|
258
|
-
|
package/src/server/jwt.ts
DELETED
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* JWT Authentication Module
|
|
3
|
-
* Implements secure token issuance and validation with HTTP-only cookies
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import jwt from 'jsonwebtoken';
|
|
7
|
-
import type { TokenPayload, AuthCookieConfig } from '../types';
|
|
8
|
-
|
|
9
|
-
// 7 days in seconds
|
|
10
|
-
const DEFAULT_JWT_EXPIRES_IN = 7 * 24 * 60 * 60;
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Get JWT secret from config or environment
|
|
14
|
-
*/
|
|
15
|
-
function getJwtSecret(configSecret?: string): string {
|
|
16
|
-
const secret = configSecret ?? process.env.JWT_SECRET;
|
|
17
|
-
if (!secret) {
|
|
18
|
-
throw new Error('JWT_SECRET environment variable is required');
|
|
19
|
-
}
|
|
20
|
-
return secret;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Sign a JWT token for a user
|
|
25
|
-
* @param subOrgId - Turnkey sub-organization ID (stable identifier)
|
|
26
|
-
* @param email - User email (metadata)
|
|
27
|
-
* @param sessionToken - Optional Turnkey session token for user authentication
|
|
28
|
-
* @param options - Additional options
|
|
29
|
-
* @returns Signed JWT token string
|
|
30
|
-
*/
|
|
31
|
-
export function signToken(
|
|
32
|
-
subOrgId: string,
|
|
33
|
-
email: string,
|
|
34
|
-
sessionToken?: string,
|
|
35
|
-
options?: {
|
|
36
|
-
secret?: string;
|
|
37
|
-
expiresIn?: number;
|
|
38
|
-
issuer?: string;
|
|
39
|
-
audience?: string;
|
|
40
|
-
}
|
|
41
|
-
): string {
|
|
42
|
-
if (!subOrgId) {
|
|
43
|
-
throw new Error('Sub-organization ID is required for token signing');
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const secret = getJwtSecret(options?.secret);
|
|
47
|
-
|
|
48
|
-
const payload: Record<string, unknown> = {
|
|
49
|
-
sub: subOrgId,
|
|
50
|
-
email,
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
if (sessionToken) {
|
|
54
|
-
payload.sessionToken = sessionToken;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const signOptions: jwt.SignOptions = {
|
|
58
|
-
expiresIn: options?.expiresIn ?? DEFAULT_JWT_EXPIRES_IN,
|
|
59
|
-
issuer: options?.issuer ?? 'originals-auth',
|
|
60
|
-
audience: options?.audience ?? 'originals-api',
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
return jwt.sign(payload, secret, signOptions);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Verify and decode a JWT token
|
|
68
|
-
* @param token - JWT token string
|
|
69
|
-
* @param options - Additional options
|
|
70
|
-
* @returns Decoded token payload
|
|
71
|
-
* @throws Error if token is invalid or expired
|
|
72
|
-
*/
|
|
73
|
-
export function verifyToken(
|
|
74
|
-
token: string,
|
|
75
|
-
options?: {
|
|
76
|
-
secret?: string;
|
|
77
|
-
issuer?: string;
|
|
78
|
-
audience?: string;
|
|
79
|
-
}
|
|
80
|
-
): TokenPayload {
|
|
81
|
-
const secret = getJwtSecret(options?.secret);
|
|
82
|
-
|
|
83
|
-
try {
|
|
84
|
-
const payload = jwt.verify(token, secret, {
|
|
85
|
-
issuer: options?.issuer ?? 'originals-auth',
|
|
86
|
-
audience: options?.audience ?? 'originals-api',
|
|
87
|
-
}) as TokenPayload;
|
|
88
|
-
|
|
89
|
-
if (!payload.sub) {
|
|
90
|
-
throw new Error('Token missing sub-organization ID');
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
return payload;
|
|
94
|
-
} catch (error) {
|
|
95
|
-
if (error instanceof jwt.TokenExpiredError) {
|
|
96
|
-
throw new Error('Token has expired');
|
|
97
|
-
}
|
|
98
|
-
if (error instanceof jwt.JsonWebTokenError) {
|
|
99
|
-
throw new Error('Invalid token');
|
|
100
|
-
}
|
|
101
|
-
throw error;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Generate a secure cookie configuration for authentication tokens
|
|
107
|
-
* @param token - JWT token to set in cookie
|
|
108
|
-
* @param options - Cookie options
|
|
109
|
-
* @returns Cookie configuration object
|
|
110
|
-
*/
|
|
111
|
-
export function getAuthCookieConfig(
|
|
112
|
-
token: string,
|
|
113
|
-
options?: {
|
|
114
|
-
cookieName?: string;
|
|
115
|
-
maxAge?: number;
|
|
116
|
-
secure?: boolean;
|
|
117
|
-
}
|
|
118
|
-
): AuthCookieConfig {
|
|
119
|
-
const isProduction = process.env.NODE_ENV === 'production';
|
|
120
|
-
|
|
121
|
-
return {
|
|
122
|
-
name: options?.cookieName ?? 'auth_token',
|
|
123
|
-
value: token,
|
|
124
|
-
options: {
|
|
125
|
-
httpOnly: true, // Cannot be accessed by JavaScript (XSS protection)
|
|
126
|
-
secure: options?.secure ?? isProduction, // HTTPS only in production
|
|
127
|
-
sameSite: 'strict', // CSRF protection
|
|
128
|
-
maxAge: options?.maxAge ?? 7 * 24 * 60 * 60 * 1000, // 7 days in milliseconds
|
|
129
|
-
path: '/', // Available for all routes
|
|
130
|
-
},
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Get cookie configuration for logout (clears the auth cookie)
|
|
136
|
-
* @param cookieName - Name of the cookie to clear
|
|
137
|
-
* @returns Cookie configuration for clearing
|
|
138
|
-
*/
|
|
139
|
-
export function getClearAuthCookieConfig(cookieName?: string): AuthCookieConfig {
|
|
140
|
-
const isProduction = process.env.NODE_ENV === 'production';
|
|
141
|
-
|
|
142
|
-
return {
|
|
143
|
-
name: cookieName ?? 'auth_token',
|
|
144
|
-
value: '',
|
|
145
|
-
options: {
|
|
146
|
-
httpOnly: true,
|
|
147
|
-
secure: isProduction,
|
|
148
|
-
sameSite: 'strict',
|
|
149
|
-
maxAge: 0, // Expire immediately
|
|
150
|
-
path: '/',
|
|
151
|
-
},
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
|
package/src/server/middleware.ts
DELETED
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Express authentication middleware factory
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import type { Request, Response, NextFunction } from 'express';
|
|
6
|
-
import { verifyToken } from './jwt.js';
|
|
7
|
-
import type { AuthMiddlewareOptions, AuthUser, AuthenticatedRequest } from '../types';
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Create an authentication middleware for Express
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```typescript
|
|
14
|
-
* import { createAuthMiddleware } from '@originals/auth/server';
|
|
15
|
-
*
|
|
16
|
-
* const authenticateUser = createAuthMiddleware({
|
|
17
|
-
* getUserByTurnkeyId: async (turnkeyId) => {
|
|
18
|
-
* return db.query.users.findFirst({
|
|
19
|
-
* where: eq(users.turnkeySubOrgId, turnkeyId)
|
|
20
|
-
* });
|
|
21
|
-
* },
|
|
22
|
-
* createUser: async (turnkeyId, email, temporaryDid) => {
|
|
23
|
-
* return db.insert(users).values({
|
|
24
|
-
* turnkeySubOrgId: turnkeyId,
|
|
25
|
-
* email,
|
|
26
|
-
* did: temporaryDid,
|
|
27
|
-
* }).returning().then(rows => rows[0]);
|
|
28
|
-
* }
|
|
29
|
-
* });
|
|
30
|
-
*
|
|
31
|
-
* app.get('/api/protected', authenticateUser, (req, res) => {
|
|
32
|
-
* res.json({ user: req.user });
|
|
33
|
-
* });
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export function createAuthMiddleware(
|
|
37
|
-
options: AuthMiddlewareOptions
|
|
38
|
-
): (req: Request, res: Response, next: NextFunction) => Promise<void | Response> {
|
|
39
|
-
const cookieName = options.cookieName ?? 'auth_token';
|
|
40
|
-
|
|
41
|
-
return async (req: Request, res: Response, next: NextFunction): Promise<void | Response> => {
|
|
42
|
-
try {
|
|
43
|
-
// Get JWT token from HTTP-only cookie
|
|
44
|
-
const cookies = req.cookies as Record<string, string> | undefined;
|
|
45
|
-
const token = cookies?.[cookieName];
|
|
46
|
-
|
|
47
|
-
if (!token) {
|
|
48
|
-
return res.status(401).json({ error: 'Not authenticated' });
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Verify JWT token
|
|
52
|
-
const payload = verifyToken(token, { secret: options.jwtSecret });
|
|
53
|
-
const turnkeySubOrgId = payload.sub;
|
|
54
|
-
const email = payload.email;
|
|
55
|
-
|
|
56
|
-
// Check if user already exists
|
|
57
|
-
let user: AuthUser | null = await options.getUserByTurnkeyId(turnkeySubOrgId);
|
|
58
|
-
|
|
59
|
-
// If user doesn't exist and createUser is provided, create user
|
|
60
|
-
if (!user && options.createUser) {
|
|
61
|
-
console.log(`Creating user record for ${email}...`);
|
|
62
|
-
|
|
63
|
-
// Use temporary DID as placeholder until user creates real DID
|
|
64
|
-
const temporaryDid = `temp:turnkey:${turnkeySubOrgId}`;
|
|
65
|
-
|
|
66
|
-
user = await options.createUser(turnkeySubOrgId, email, temporaryDid);
|
|
67
|
-
|
|
68
|
-
console.log(`✅ User created: ${email}`);
|
|
69
|
-
console.log(` Turnkey sub-org ID: ${turnkeySubOrgId}`);
|
|
70
|
-
console.log(` Temporary DID: ${temporaryDid}`);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
if (!user) {
|
|
74
|
-
return res.status(401).json({ error: 'User not found' });
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Add user info to request
|
|
78
|
-
(req as Request & AuthenticatedRequest).user = {
|
|
79
|
-
id: user.id,
|
|
80
|
-
turnkeySubOrgId,
|
|
81
|
-
email,
|
|
82
|
-
did: user.did,
|
|
83
|
-
sessionToken: payload.sessionToken,
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
next();
|
|
87
|
-
} catch (error) {
|
|
88
|
-
console.error('Authentication error:', error);
|
|
89
|
-
return res.status(401).json({ error: 'Invalid or expired token' });
|
|
90
|
-
}
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Optional authentication middleware - doesn't fail if not authenticated
|
|
96
|
-
* Attaches user to request if valid token exists, otherwise continues without user
|
|
97
|
-
*/
|
|
98
|
-
export function createOptionalAuthMiddleware(
|
|
99
|
-
options: AuthMiddlewareOptions
|
|
100
|
-
): (req: Request, res: Response, next: NextFunction) => Promise<void> {
|
|
101
|
-
const cookieName = options.cookieName ?? 'auth_token';
|
|
102
|
-
|
|
103
|
-
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
104
|
-
try {
|
|
105
|
-
const cookies = req.cookies as Record<string, string> | undefined;
|
|
106
|
-
const token = cookies?.[cookieName];
|
|
107
|
-
|
|
108
|
-
if (!token) {
|
|
109
|
-
next();
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const payload = verifyToken(token, { secret: options.jwtSecret });
|
|
114
|
-
const turnkeySubOrgId = payload.sub;
|
|
115
|
-
const email = payload.email;
|
|
116
|
-
|
|
117
|
-
const user = await options.getUserByTurnkeyId(turnkeySubOrgId);
|
|
118
|
-
|
|
119
|
-
if (user) {
|
|
120
|
-
(req as Request & AuthenticatedRequest).user = {
|
|
121
|
-
id: user.id,
|
|
122
|
-
turnkeySubOrgId,
|
|
123
|
-
email,
|
|
124
|
-
did: user.did,
|
|
125
|
-
sessionToken: payload.sessionToken,
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
next();
|
|
130
|
-
} catch {
|
|
131
|
-
// Token invalid or expired, continue without user
|
|
132
|
-
next();
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server-side Turnkey client utilities
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { Turnkey } from '@turnkey/sdk-server';
|
|
6
|
-
|
|
7
|
-
export interface TurnkeyClientConfig {
|
|
8
|
-
/** Turnkey API base URL (default: https://api.turnkey.com) */
|
|
9
|
-
apiBaseUrl?: string;
|
|
10
|
-
/** Turnkey API public key */
|
|
11
|
-
apiPublicKey: string;
|
|
12
|
-
/** Turnkey API private key */
|
|
13
|
-
apiPrivateKey: string;
|
|
14
|
-
/** Default organization ID */
|
|
15
|
-
organizationId: string;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Create a Turnkey server client
|
|
20
|
-
*/
|
|
21
|
-
export function createTurnkeyClient(config?: Partial<TurnkeyClientConfig>): Turnkey {
|
|
22
|
-
const apiPublicKey = config?.apiPublicKey ?? process.env.TURNKEY_API_PUBLIC_KEY;
|
|
23
|
-
const apiPrivateKey = config?.apiPrivateKey ?? process.env.TURNKEY_API_PRIVATE_KEY;
|
|
24
|
-
const organizationId = config?.organizationId ?? process.env.TURNKEY_ORGANIZATION_ID;
|
|
25
|
-
|
|
26
|
-
if (!apiPublicKey) {
|
|
27
|
-
throw new Error('TURNKEY_API_PUBLIC_KEY is required');
|
|
28
|
-
}
|
|
29
|
-
if (!apiPrivateKey) {
|
|
30
|
-
throw new Error('TURNKEY_API_PRIVATE_KEY is required');
|
|
31
|
-
}
|
|
32
|
-
if (!organizationId) {
|
|
33
|
-
throw new Error('TURNKEY_ORGANIZATION_ID is required');
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return new Turnkey({
|
|
37
|
-
apiBaseUrl: config?.apiBaseUrl ?? 'https://api.turnkey.com',
|
|
38
|
-
apiPublicKey,
|
|
39
|
-
apiPrivateKey,
|
|
40
|
-
defaultOrganizationId: organizationId,
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Get or create a Turnkey sub-organization for a user
|
|
46
|
-
* Creates sub-org with email-only root user and required wallet accounts
|
|
47
|
-
*/
|
|
48
|
-
export async function getOrCreateTurnkeySubOrg(
|
|
49
|
-
email: string,
|
|
50
|
-
turnkeyClient: Turnkey
|
|
51
|
-
): Promise<string> {
|
|
52
|
-
const organizationId = process.env.TURNKEY_ORGANIZATION_ID;
|
|
53
|
-
if (!organizationId) {
|
|
54
|
-
throw new Error('TURNKEY_ORGANIZATION_ID is required');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Generate a consistent base name for lookup
|
|
58
|
-
const baseSubOrgName = `user-${email.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`;
|
|
59
|
-
|
|
60
|
-
console.log(`🔍 Checking for existing sub-organization for ${email}...`);
|
|
61
|
-
|
|
62
|
-
try {
|
|
63
|
-
// Try to get existing sub-organizations by email filter
|
|
64
|
-
const subOrgs = await turnkeyClient.apiClient().getSubOrgIds({
|
|
65
|
-
organizationId,
|
|
66
|
-
filterType: 'EMAIL',
|
|
67
|
-
filterValue: email,
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
const subOrgIds = subOrgs.organizationIds || [];
|
|
71
|
-
const existingSubOrgId = subOrgIds.length > 0 ? subOrgIds[0] : null;
|
|
72
|
-
|
|
73
|
-
if (existingSubOrgId) {
|
|
74
|
-
console.log(`✅ Found existing sub-organization: ${existingSubOrgId}`);
|
|
75
|
-
|
|
76
|
-
// Check if this sub-org has a wallet
|
|
77
|
-
try {
|
|
78
|
-
const walletsCheck = await turnkeyClient.apiClient().getWallets({
|
|
79
|
-
organizationId: existingSubOrgId,
|
|
80
|
-
});
|
|
81
|
-
const walletCount = walletsCheck.wallets?.length || 0;
|
|
82
|
-
|
|
83
|
-
if (walletCount > 0) {
|
|
84
|
-
return existingSubOrgId;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
console.log(`⚠️ Sub-org has no wallet, creating new sub-org with wallet...`);
|
|
88
|
-
} catch (walletCheckErr) {
|
|
89
|
-
console.error('Could not check wallet in sub-org:', walletCheckErr);
|
|
90
|
-
return existingSubOrgId;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
} catch {
|
|
94
|
-
console.log(`📝 No existing sub-org found, will create new one`);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// Generate a unique name for the new sub-org
|
|
98
|
-
const subOrgName = `${baseSubOrgName}-${Date.now()}`;
|
|
99
|
-
|
|
100
|
-
console.log(`📧 Creating new Turnkey sub-organization for ${email}...`);
|
|
101
|
-
|
|
102
|
-
// Create sub-organization with wallet containing required keys
|
|
103
|
-
const result = await turnkeyClient.apiClient().createSubOrganization({
|
|
104
|
-
subOrganizationName: subOrgName,
|
|
105
|
-
rootUsers: [
|
|
106
|
-
{
|
|
107
|
-
userName: email,
|
|
108
|
-
userEmail: email,
|
|
109
|
-
apiKeys: [],
|
|
110
|
-
authenticators: [],
|
|
111
|
-
oauthProviders: [],
|
|
112
|
-
},
|
|
113
|
-
],
|
|
114
|
-
rootQuorumThreshold: 1,
|
|
115
|
-
wallet: {
|
|
116
|
-
walletName: 'default-wallet',
|
|
117
|
-
accounts: [
|
|
118
|
-
{
|
|
119
|
-
curve: 'CURVE_SECP256K1',
|
|
120
|
-
pathFormat: 'PATH_FORMAT_BIP32',
|
|
121
|
-
path: "m/44'/0'/0'/0/0", // Bitcoin path for auth-key
|
|
122
|
-
addressFormat: 'ADDRESS_FORMAT_ETHEREUM',
|
|
123
|
-
},
|
|
124
|
-
{
|
|
125
|
-
curve: 'CURVE_ED25519',
|
|
126
|
-
pathFormat: 'PATH_FORMAT_BIP32',
|
|
127
|
-
path: "m/44'/501'/0'/0'", // Ed25519 for assertion-key
|
|
128
|
-
addressFormat: 'ADDRESS_FORMAT_SOLANA',
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
curve: 'CURVE_ED25519',
|
|
132
|
-
pathFormat: 'PATH_FORMAT_BIP32',
|
|
133
|
-
path: "m/44'/501'/1'/0'", // Ed25519 for update-key
|
|
134
|
-
addressFormat: 'ADDRESS_FORMAT_SOLANA',
|
|
135
|
-
},
|
|
136
|
-
],
|
|
137
|
-
},
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
const subOrgId = result.activity?.result?.createSubOrganizationResultV7?.subOrganizationId;
|
|
141
|
-
|
|
142
|
-
if (!subOrgId) {
|
|
143
|
-
throw new Error('No sub-organization ID returned from Turnkey');
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
console.log(`✅ Created sub-organization: ${subOrgId}`);
|
|
147
|
-
|
|
148
|
-
return subOrgId;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|