Monorepo for Aesthetic.Computer
aesthetic.computer
1#!/usr/bin/env node
2// diagnose-user-code-generation.mjs
3// Test the user code generation function to identify the actual error
4
5import { shell } from '../../system/backend/shell.mjs';
6import { connect } from '../../system/backend/database.mjs';
7import { generateUniqueUserCode, ensureUserCodeIndex } from '../../system/public/aesthetic.computer/lib/user-code.mjs';
8import { config } from 'dotenv';
9
10config();
11
12async function testUserCodeGeneration() {
13 console.log('\n================================================================================');
14 console.log('🧪 TESTING USER CODE GENERATION');
15 console.log('================================================================================\n');
16
17 const database = await connect();
18
19 try {
20 console.log('📋 Step 1: Ensuring user code index exists...');
21 await ensureUserCodeIndex(database);
22 console.log(' ✅ Index check complete\n');
23
24 console.log('📋 Step 2: Testing code generation with current timestamp...');
25 const now = new Date();
26 console.log(` Test date: ${now.toISOString()}`);
27
28 try {
29 const code1 = await generateUniqueUserCode(database, now);
30 console.log(` ✅ Generated code: ${code1}\n`);
31
32 console.log('📋 Step 3: Testing second generation (should get different code)...');
33 const code2 = await generateUniqueUserCode(database, now);
34 console.log(` ✅ Generated code: ${code2}`);
35 console.log(` ${code1 === code2 ? '⚠️ SAME CODE!' : '✅ Different codes'}\n`);
36
37 console.log('📋 Step 4: Checking users collection for test codes...');
38 const users = database.db.collection('users');
39
40 const testUser1 = await users.findOne({ code: code1 });
41 const testUser2 = await users.findOne({ code: code2 });
42
43 console.log(` Code ${code1}: ${testUser1 ? '✅ Exists in DB' : '❌ Not in DB'}`);
44 console.log(` Code ${code2}: ${testUser2 ? '✅ Exists in DB' : '❌ Not in DB'}\n`);
45
46 console.log('📋 Step 5: Testing with past date (like Auth0 signup)...');
47 const pastDate = new Date('2025-10-14T13:29:20.565Z');
48 console.log(` Test date: ${pastDate.toISOString()}`);
49
50 const code3 = await generateUniqueUserCode(database, pastDate);
51 console.log(` ✅ Generated code: ${code3}\n`);
52
53 console.log('📋 Step 6: Checking database state...');
54 const userCount = await users.countDocuments();
55 const usersWithCode = await users.countDocuments({ code: { $exists: true } });
56
57 console.log(` Total users: ${userCount}`);
58 console.log(` Users with code: ${usersWithCode}`);
59
60 // Sample some recent codes
61 const recentUsers = await users.find({ code: { $exists: true } })
62 .sort({ when: -1 })
63 .limit(5)
64 .toArray();
65
66 console.log(`\n Recent codes (last 5):`);
67 recentUsers.forEach(u => {
68 console.log(` ${u.code} - ${u._id} - ${u.when}`);
69 });
70
71 console.log('\n================================================================================');
72 console.log('✅ USER CODE GENERATION TEST PASSED');
73 console.log('================================================================================\n');
74 console.log('💡 The user code generation function is working correctly.');
75 console.log(' The issue must be elsewhere in the auth0-events webhook flow.\n');
76
77 } catch (error) {
78 console.log(` ❌ Code generation failed!\n`);
79 console.log(' Error name:', error.name);
80 console.log(' Error message:', error.message);
81 console.log(' Error stack:', error.stack);
82
83 console.log('\n================================================================================');
84 console.log('❌ USER CODE GENERATION TEST FAILED');
85 console.log('================================================================================\n');
86 console.log('🔍 This is likely the root cause of why users records are not being created.\n');
87
88 throw error;
89 }
90
91 } catch (error) {
92 console.error('\n❌ Test suite failed:', error.message);
93 throw error;
94 } finally {
95 await database.disconnect();
96 }
97}
98
99// Additional test: Simulate the exact auth0-events flow
100async function testAuth0EventsFlow() {
101 console.log('\n================================================================================');
102 console.log('🧪 SIMULATING AUTH0-EVENTS.MJS FLOW');
103 console.log('================================================================================\n');
104
105 const database = await connect();
106
107 try {
108 // Simulate auth0 signup event data
109 const mockAuthSub = `auth0|TEST_${Date.now()}`;
110 const mockEmail = 'test@example.com';
111 const mockSignupDate = new Date();
112
113 console.log('📋 Simulating signup event for:', mockAuthSub);
114 console.log(' Email:', mockEmail);
115 console.log(' Date:', mockSignupDate.toISOString(), '\n');
116
117 // Step 1: Create verifications record (this works)
118 console.log(' Step 1: Creating verifications record...');
119 const verifications = database.db.collection("verifications");
120 await verifications.insertOne({ _id: mockAuthSub, count: 0 });
121 console.log(' ✅ Verifications record created\n');
122
123 // Step 2: Generate user code and create user record (this fails)
124 console.log(' Step 2: Generating user code and creating user record...');
125 try {
126 await ensureUserCodeIndex(database);
127 const code = await generateUniqueUserCode(database, mockSignupDate);
128
129 const users = database.db.collection("users");
130 await users.insertOne({
131 _id: mockAuthSub,
132 code,
133 when: mockSignupDate
134 });
135
136 console.log(` ✅ User record created with code: ${code}\n`);
137
138 // Clean up test records
139 console.log(' Cleaning up test records...');
140 await verifications.deleteOne({ _id: mockAuthSub });
141 await users.deleteOne({ _id: mockAuthSub });
142 console.log(' ✅ Test records deleted\n');
143
144 console.log('================================================================================');
145 console.log('✅ AUTH0 FLOW SIMULATION PASSED');
146 console.log('================================================================================\n');
147 console.log('💡 The auth0-events flow simulation works correctly.');
148 console.log(' This suggests the webhook might not be receiving events,');
149 console.log(' or there\'s an environment/permissions difference in production.\n');
150
151 } catch (error) {
152 console.log(` ❌ User record creation failed!\n`);
153 console.log(' Error:', error.message);
154 console.log(' Stack:', error.stack);
155
156 // Try to clean up verifications record
157 await verifications.deleteOne({ _id: mockAuthSub }).catch(() => {});
158
159 throw error;
160 }
161
162 } catch (error) {
163 console.error('\n❌ Flow simulation failed:', error.message);
164 throw error;
165 } finally {
166 await database.disconnect();
167 }
168}
169
170// Run both tests
171try {
172 await testUserCodeGeneration();
173 await testAuth0EventsFlow();
174
175 console.log('🎉 ALL TESTS PASSED!\n');
176 console.log('🔍 Next steps:');
177 console.log(' 1. Check Netlify function logs for actual production errors');
178 console.log(' 2. Verify Auth0 webhook is actually being called');
179 console.log(' 3. Check if there are any environment differences in production');
180 console.log(' 4. Consider running backfill script to fix existing users\n');
181
182} catch (error) {
183 console.error('\n💥 TESTS FAILED\n');
184 process.exit(1);
185}