@zodic/shared 0.0.101 → 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.
@@ -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
- c.set('jwtPayload', payload);
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zodic/shared",
3
- "version": "0.0.101",
3
+ "version": "0.0.103",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -268,6 +268,7 @@ export interface OAuthCompleteBody {
268
268
  longitude: number;
269
269
  instagramUsername?: string | null;
270
270
  tiktokUsername?: string | null;
271
+ birthLocation: string;
271
272
  }
272
273
 
273
274
  export interface SignupBody {
@@ -281,5 +282,18 @@ export interface SignupBody {
281
282
  longitude: number;
282
283
  birthDate: string; // Expected format: "YYYY-MM-DD"
283
284
  birthTime?: string | null; // Optional, format: "HH:mm" or null
285
+ birthLocation: string;
284
286
  }
285
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 { AuthCtx, Gender, VALID_GENDERS_ARRAY } from '../types';
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.CLOUDFLARE_ACCOUNT_ID;
10
- const issuer = c.env.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
- const { payload } = await jwtVerify(token, secret, {
21
- audience,
22
- issuer,
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 (payload.exp && payload.exp * 1000 < Date.now()) {
26
- throw new Error('Token has expired');
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
- return payload as { userId: string; email?: string; roles?: string[] };
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
  }