@zodic/shared 0.0.102 → 0.0.103
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/middleware/index.ts +14 -6
- package/package.json +1 -1
- package/types/scopes/generic.ts +12 -0
- package/utils/index.ts +59 -17
package/middleware/index.ts
CHANGED
|
@@ -12,27 +12,35 @@ export const jwtMiddleware = async (c: AuthCtx, next: () => Promise<void>) => {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
if (!token) {
|
|
15
|
-
token = getCookie(c, 'authToken');
|
|
15
|
+
token = getCookie(c, 'sessionToken') || getCookie(c, 'authToken');
|
|
16
16
|
if (token) {
|
|
17
17
|
console.log('Token extracted from cookie:', token);
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
if (!token) {
|
|
22
|
-
console.warn('Unauthorized: No token provided');
|
|
22
|
+
console.warn('🔴 Unauthorized: No token provided');
|
|
23
23
|
return c.json({ error: 'Unauthorized: No token provided' }, 401);
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
try {
|
|
27
|
-
console.log('Verifying token...');
|
|
27
|
+
console.log('🔄 Verifying token...');
|
|
28
28
|
const payload = await verifyToken(c, token);
|
|
29
29
|
|
|
30
|
-
console.log('Token verified successfully. Payload:', payload);
|
|
31
|
-
|
|
30
|
+
console.log('✅ Token verified successfully. Payload:', payload);
|
|
31
|
+
|
|
32
|
+
// Ensure userId exists
|
|
33
|
+
const userId = payload.userId;
|
|
34
|
+
if (!userId) {
|
|
35
|
+
console.error('❌ Missing userId in JWT payload:', payload);
|
|
36
|
+
return c.json({ error: 'Unauthorized: Invalid token payload' }, 401);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
c.set('jwtPayload', { userId });
|
|
32
40
|
|
|
33
41
|
await next();
|
|
34
42
|
} catch (err: any) {
|
|
35
|
-
console.error('Token verification failed:', err.message);
|
|
43
|
+
console.error('❌ Token verification failed:', err.message);
|
|
36
44
|
return c.json({ error: 'Unauthorized: Invalid or expired token' }, 401);
|
|
37
45
|
}
|
|
38
46
|
};
|
package/package.json
CHANGED
package/types/scopes/generic.ts
CHANGED
|
@@ -285,3 +285,15 @@ export interface SignupBody {
|
|
|
285
285
|
birthLocation: string;
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
+
export interface JWK {
|
|
289
|
+
kid: string; // Key ID
|
|
290
|
+
kty: string; // Key Type (e.g., "RSA")
|
|
291
|
+
alg: string; // Algorithm (e.g., "RS256")
|
|
292
|
+
use: string; // Usage (e.g., "sig" for signature verification)
|
|
293
|
+
n: string; // Public Modulus (Base64url-encoded)
|
|
294
|
+
e: string; // Exponent (Base64url-encoded)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export interface JWKS {
|
|
298
|
+
keys: JWK[];
|
|
299
|
+
}
|
package/utils/index.ts
CHANGED
|
@@ -1,32 +1,74 @@
|
|
|
1
1
|
import { jwtVerify } from 'jose';
|
|
2
|
-
import {
|
|
2
|
+
import { webcrypto } from 'node:crypto';
|
|
3
|
+
import { AuthCtx, Gender, JWKS, VALID_GENDERS_ARRAY } from '../types';
|
|
3
4
|
|
|
4
5
|
export const verifyToken = async (
|
|
5
6
|
c: AuthCtx,
|
|
6
7
|
token: string
|
|
7
8
|
): Promise<{ userId: string; email?: string; roles?: string[] }> => {
|
|
8
9
|
const jwtSecret = c.env.JWT_SECRET;
|
|
9
|
-
const audience = c.env.
|
|
10
|
-
const issuer =
|
|
10
|
+
const audience = c.env.GOOGLE_OAUTH_CLIENT_ID;
|
|
11
|
+
const issuer = 'https://accounts.google.com';
|
|
11
12
|
|
|
12
|
-
if (!jwtSecret)
|
|
13
|
-
throw new Error('Jwt Secret is not defined in the environment');
|
|
14
|
-
if (!audience) throw new Error('Audience is not defined in the environment');
|
|
15
|
-
if (!issuer) throw new Error('Issuer is not defined in the environment');
|
|
16
|
-
|
|
17
|
-
const secret = new TextEncoder().encode(jwtSecret);
|
|
13
|
+
if (!jwtSecret) throw new Error('JWT Secret is not defined in the environment');
|
|
18
14
|
|
|
19
15
|
try {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
// ✅ Detect if token is from Google OAuth (ID Token)
|
|
17
|
+
const decodedHeader = JSON.parse(
|
|
18
|
+
Buffer.from(token.split('.')[0], 'base64').toString('utf8')
|
|
19
|
+
);
|
|
24
20
|
|
|
25
|
-
if (
|
|
26
|
-
|
|
27
|
-
|
|
21
|
+
if (decodedHeader.alg.startsWith('RS')) {
|
|
22
|
+
// 🔹 Google OAuth Token Detected → Verify with Google Public Keys
|
|
23
|
+
const kid = decodedHeader.kid;
|
|
24
|
+
|
|
25
|
+
const googleKeysResponse = await fetch(
|
|
26
|
+
'https://www.googleapis.com/oauth2/v3/certs'
|
|
27
|
+
);
|
|
28
|
+
const googleKeys = (await googleKeysResponse.json()) as JWKS;
|
|
29
|
+
|
|
30
|
+
const key = googleKeys.keys.find((k: any) => k.kid === kid);
|
|
31
|
+
if (!key) throw new Error('Google public key not found');
|
|
32
|
+
|
|
33
|
+
const publicKey = await webcrypto.subtle.importKey(
|
|
34
|
+
'jwk',
|
|
35
|
+
key,
|
|
36
|
+
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
37
|
+
false,
|
|
38
|
+
['verify']
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
const { payload } = await jwtVerify(token, publicKey, {
|
|
42
|
+
audience,
|
|
43
|
+
issuer,
|
|
44
|
+
});
|
|
28
45
|
|
|
29
|
-
|
|
46
|
+
if (!payload.sub) {
|
|
47
|
+
throw new Error('Google token is missing required "sub" claim');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
userId: payload.sub, // Google User ID
|
|
52
|
+
email: payload.email as string || undefined, // Email might be missing, so fallback to undefined
|
|
53
|
+
};
|
|
54
|
+
} else {
|
|
55
|
+
// 🔹 Regular User Token → Verify with JWT_SECRET
|
|
56
|
+
const secret = new TextEncoder().encode(jwtSecret);
|
|
57
|
+
const { payload } = await jwtVerify(token, secret, {
|
|
58
|
+
audience: c.env.CLOUDFLARE_ACCOUNT_ID,
|
|
59
|
+
issuer: c.env.ISSUER,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (!payload.userId) {
|
|
63
|
+
throw new Error('JWT is missing required claims (userId)');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (payload.exp && payload.exp * 1000 < Date.now()) {
|
|
67
|
+
throw new Error('Token has expired');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return payload as { userId: string; email?: string; roles?: string[] };
|
|
71
|
+
}
|
|
30
72
|
} catch (err) {
|
|
31
73
|
throw new Error('Invalid or expired token');
|
|
32
74
|
}
|