@goscribe/server 1.2.0 → 1.3.0
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/check-difficulty.cjs +14 -0
- package/check-questions.cjs +14 -0
- package/db-summary.cjs +22 -0
- package/mcq-test.cjs +36 -0
- package/package.json +9 -2
- package/prisma/migrations/20260413143206_init/migration.sql +873 -0
- package/prisma/schema.prisma +471 -324
- package/src/context.ts +4 -1
- package/src/lib/activity_human_description.test.ts +28 -0
- package/src/lib/activity_human_description.ts +239 -0
- package/src/lib/activity_log_service.test.ts +37 -0
- package/src/lib/activity_log_service.ts +353 -0
- package/src/lib/ai-session.ts +79 -51
- package/src/lib/email.ts +213 -29
- package/src/lib/env.ts +23 -6
- package/src/lib/inference.ts +2 -2
- package/src/lib/notification-service.test.ts +106 -0
- package/src/lib/notification-service.ts +677 -0
- package/src/lib/prisma.ts +6 -1
- package/src/lib/pusher.ts +86 -2
- package/src/lib/stripe.ts +39 -0
- package/src/lib/subscription_service.ts +722 -0
- package/src/lib/usage_service.ts +74 -0
- package/src/lib/worksheet-generation.test.ts +31 -0
- package/src/lib/worksheet-generation.ts +139 -0
- package/src/routers/_app.ts +9 -0
- package/src/routers/admin.ts +710 -0
- package/src/routers/annotations.ts +41 -0
- package/src/routers/auth.ts +338 -28
- package/src/routers/copilot.ts +719 -0
- package/src/routers/flashcards.ts +201 -68
- package/src/routers/members.ts +280 -80
- package/src/routers/notifications.ts +142 -0
- package/src/routers/payment.ts +448 -0
- package/src/routers/podcast.ts +112 -83
- package/src/routers/studyguide.ts +12 -0
- package/src/routers/worksheets.ts +289 -66
- package/src/routers/workspace.ts +329 -122
- package/src/scripts/purge-deleted-users.ts +167 -0
- package/src/server.ts +137 -11
- package/src/services/flashcard-progress.service.ts +49 -37
- package/src/trpc.ts +184 -5
- package/test-generate.js +30 -0
- package/test-ratio.cjs +9 -0
- package/zod-test.cjs +22 -0
- package/prisma/migrations/20250826124819_add_worksheet_difficulty_and_estimated_time/migration.sql +0 -213
- package/prisma/migrations/20250826133236_add_worksheet_question_progress/migration.sql +0 -31
- package/prisma/seed.mjs +0 -135
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { PrismaClient } from '@prisma/client';
|
|
2
|
+
import { supabaseClient } from '../lib/storage.js';
|
|
3
|
+
import { logger } from '../lib/logger.js';
|
|
4
|
+
import { env } from '../lib/env.js';
|
|
5
|
+
import { notifyAdminsAccountPermanentlyDeleted } from '../lib/notification-service.js';
|
|
6
|
+
import {
|
|
7
|
+
ActivityLogCategory,
|
|
8
|
+
ActivityLogStatus,
|
|
9
|
+
} from '@prisma/client';
|
|
10
|
+
import { recordExplicitActivity } from '../lib/activity_log_service.js';
|
|
11
|
+
|
|
12
|
+
const db = new PrismaClient();
|
|
13
|
+
|
|
14
|
+
async function purgeDeletedUsers() {
|
|
15
|
+
try {
|
|
16
|
+
const startedAt = Date.now();
|
|
17
|
+
let status: ActivityLogStatus = ActivityLogStatus.SUCCESS;
|
|
18
|
+
let errorCode: string | null = null;
|
|
19
|
+
let purgedUsers = 0;
|
|
20
|
+
|
|
21
|
+
logger.info('Starting scheduled purge for deleted users...');
|
|
22
|
+
|
|
23
|
+
// Find users whose deletedAt is older than 30 days
|
|
24
|
+
const thirtyDaysAgo = new Date();
|
|
25
|
+
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
|
26
|
+
|
|
27
|
+
const usersToPurge = await db.user.findMany({
|
|
28
|
+
where: {
|
|
29
|
+
deletedAt: {
|
|
30
|
+
lte: thirtyDaysAgo,
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
select: {
|
|
34
|
+
id: true,
|
|
35
|
+
name: true,
|
|
36
|
+
email: true,
|
|
37
|
+
profilePicture: {
|
|
38
|
+
select: {
|
|
39
|
+
objectKey: true,
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
if (usersToPurge.length === 0) {
|
|
46
|
+
logger.info('No users found past the 30-day grace period.');
|
|
47
|
+
await recordExplicitActivity({
|
|
48
|
+
db,
|
|
49
|
+
actorUserId: null,
|
|
50
|
+
action: 'cron.purgeDeletedUsers',
|
|
51
|
+
category: ActivityLogCategory.SYSTEM,
|
|
52
|
+
status: ActivityLogStatus.SUCCESS,
|
|
53
|
+
errorCode: null,
|
|
54
|
+
durationMs: Date.now() - startedAt,
|
|
55
|
+
forceWrite: true,
|
|
56
|
+
metadata: {
|
|
57
|
+
usersFound: 0,
|
|
58
|
+
usersPurged: 0,
|
|
59
|
+
graceDays: 30,
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
logger.info(`Found ${usersToPurge.length} user(s) to purge. Processing...`);
|
|
66
|
+
|
|
67
|
+
for (const user of usersToPurge) {
|
|
68
|
+
logger.info(`Purging user: ${user.id} (${user.email})`);
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
// 1. Delete associated files from Supabase Storage
|
|
72
|
+
// (Prisma cascade will delete the FileAsset DB record, but we need to delete the actual file first)
|
|
73
|
+
|
|
74
|
+
// Let's get all file assets owned by the user
|
|
75
|
+
const userFiles = await db.fileAsset.findMany({
|
|
76
|
+
where: { userId: user.id },
|
|
77
|
+
select: { objectKey: true, bucket: true },
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
for (const file of userFiles) {
|
|
81
|
+
if (file.objectKey && file.bucket) {
|
|
82
|
+
try {
|
|
83
|
+
const { error } = await supabaseClient.storage
|
|
84
|
+
.from(file.bucket)
|
|
85
|
+
.remove([file.objectKey]);
|
|
86
|
+
|
|
87
|
+
if (error) {
|
|
88
|
+
logger.error(`Failed to delete file from Supabase: ${file.objectKey}`, error);
|
|
89
|
+
} else {
|
|
90
|
+
logger.info(`Deleted file from Supabase: ${file.objectKey}`);
|
|
91
|
+
}
|
|
92
|
+
} catch (storageError) {
|
|
93
|
+
logger.error(`Exception during Supabase deletion for ${file.objectKey}:`, storageError);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
await notifyAdminsAccountPermanentlyDeleted(db, {
|
|
99
|
+
id: user.id,
|
|
100
|
+
name: user.name,
|
|
101
|
+
email: user.email,
|
|
102
|
+
}).catch(() => {});
|
|
103
|
+
|
|
104
|
+
// 2. Finally, delete the User from the database
|
|
105
|
+
// (Prisma onDelete: Cascade will handle almost everything else depending on schema)
|
|
106
|
+
await db.user.delete({
|
|
107
|
+
where: { id: user.id },
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
purgedUsers += 1;
|
|
111
|
+
logger.info(`Successfully purged user: ${user.id}`);
|
|
112
|
+
} catch (userError) {
|
|
113
|
+
status = ActivityLogStatus.FAILURE;
|
|
114
|
+
errorCode =
|
|
115
|
+
userError instanceof Error ? userError.message : String(userError);
|
|
116
|
+
logger.error(`Failed to purge user ${user.id}:`, userError);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (status === ActivityLogStatus.SUCCESS) {
|
|
121
|
+
logger.info('Purge process completed successfully.');
|
|
122
|
+
} else {
|
|
123
|
+
logger.warn('Purge process completed with failures.');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
await recordExplicitActivity({
|
|
127
|
+
db,
|
|
128
|
+
actorUserId: null,
|
|
129
|
+
action: 'cron.purgeDeletedUsers',
|
|
130
|
+
category: ActivityLogCategory.SYSTEM,
|
|
131
|
+
status,
|
|
132
|
+
errorCode,
|
|
133
|
+
durationMs: Date.now() - startedAt,
|
|
134
|
+
forceWrite: true,
|
|
135
|
+
metadata: {
|
|
136
|
+
usersFound: usersToPurge.length,
|
|
137
|
+
usersPurged: purgedUsers,
|
|
138
|
+
graceDays: 30,
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
} catch (error) {
|
|
142
|
+
const startedAt = Date.now();
|
|
143
|
+
await recordExplicitActivity({
|
|
144
|
+
db,
|
|
145
|
+
actorUserId: null,
|
|
146
|
+
action: 'cron.purgeDeletedUsers',
|
|
147
|
+
category: ActivityLogCategory.SYSTEM,
|
|
148
|
+
status: ActivityLogStatus.FAILURE,
|
|
149
|
+
errorCode:
|
|
150
|
+
error instanceof Error ? error.message : String(error),
|
|
151
|
+
durationMs: Date.now() - startedAt,
|
|
152
|
+
forceWrite: true,
|
|
153
|
+
}).catch(() => {});
|
|
154
|
+
|
|
155
|
+
logger.error('Critical error during user purge process:', error);
|
|
156
|
+
} finally {
|
|
157
|
+
await db.$disconnect();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Run the script
|
|
162
|
+
purgeDeletedUsers().then(() => {
|
|
163
|
+
process.exit(0);
|
|
164
|
+
}).catch((error) => {
|
|
165
|
+
console.error("Unhandled error:", error);
|
|
166
|
+
process.exit(1);
|
|
167
|
+
});
|
package/src/server.ts
CHANGED
|
@@ -11,6 +11,11 @@ import { createContext } from './context.js';
|
|
|
11
11
|
import { prisma } from './lib/prisma.js';
|
|
12
12
|
import { logger } from './lib/logger.js';
|
|
13
13
|
import { supabaseClient } from './lib/storage.js';
|
|
14
|
+
import {
|
|
15
|
+
ActivityLogCategory,
|
|
16
|
+
ActivityLogStatus,
|
|
17
|
+
} from '@prisma/client';
|
|
18
|
+
import { recordExplicitActivity } from './lib/activity_log_service.js';
|
|
14
19
|
|
|
15
20
|
const PORT = process.env.PORT ? Number(process.env.PORT) : 3001;
|
|
16
21
|
|
|
@@ -19,7 +24,7 @@ async function main() {
|
|
|
19
24
|
|
|
20
25
|
// Middlewares
|
|
21
26
|
app.use(cors({
|
|
22
|
-
origin: ['https://www.scribe.study', 'https://scribe.study', 'http://localhost:3000'],
|
|
27
|
+
origin: ['https://www.scribe.study', 'https://scribe.study', 'http://localhost:3000', 'http://localhost:3002'],
|
|
23
28
|
credentials: true, // allow cookies
|
|
24
29
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
|
25
30
|
allowedHeaders: ['Content-Type', 'Authorization', 'Cookie', 'Set-Cookie'],
|
|
@@ -37,11 +42,121 @@ async function main() {
|
|
|
37
42
|
}
|
|
38
43
|
}
|
|
39
44
|
}));
|
|
40
|
-
|
|
45
|
+
|
|
41
46
|
app.use(compression());
|
|
47
|
+
|
|
48
|
+
// Stripe Webhook (Must be before express.json() for raw body)
|
|
49
|
+
app.post('/stripe/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
50
|
+
const sig = req.headers['stripe-signature'];
|
|
51
|
+
const { stripe } = await import('./lib/stripe.js');
|
|
52
|
+
const { env } = await import('./lib/env.js');
|
|
53
|
+
const subscriptionService = await import('./lib/subscription_service.js');
|
|
54
|
+
|
|
55
|
+
let event;
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
if (!sig || !env.STRIPE_WEBHOOK_SECRET) {
|
|
59
|
+
throw new Error('Missing stripe-signature or STRIPE_WEBHOOK_SECRET');
|
|
60
|
+
}
|
|
61
|
+
event = stripe?.webhooks.constructEvent(req.body, sig, env.STRIPE_WEBHOOK_SECRET);
|
|
62
|
+
} catch (err: any) {
|
|
63
|
+
logger.error(`Webhook signature verification failed: ${err.message}`, 'STRIPE');
|
|
64
|
+
await recordExplicitActivity({
|
|
65
|
+
db: prisma,
|
|
66
|
+
actorUserId: null,
|
|
67
|
+
action: 'stripe.webhook.signatureVerificationFailed',
|
|
68
|
+
category: ActivityLogCategory.SYSTEM,
|
|
69
|
+
status: ActivityLogStatus.FAILURE,
|
|
70
|
+
errorCode: err?.message ?? 'unknown',
|
|
71
|
+
durationMs: 0,
|
|
72
|
+
forceWrite: true,
|
|
73
|
+
}).catch(() => {});
|
|
74
|
+
return res.status(400).send(`Webhook Error: ${err.message}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Handle the event
|
|
78
|
+
try {
|
|
79
|
+
const startedAt = Date.now();
|
|
80
|
+
let status: ActivityLogStatus = ActivityLogStatus.SUCCESS;
|
|
81
|
+
let errorCode: string | null = null;
|
|
82
|
+
|
|
83
|
+
// Best-effort: some webhook objects include metadata.userId
|
|
84
|
+
let actorUserId: string | null | undefined = undefined;
|
|
85
|
+
try {
|
|
86
|
+
const obj = event?.data?.object as any;
|
|
87
|
+
const md = obj?.metadata;
|
|
88
|
+
if (md && typeof md.userId === 'string') actorUserId = md.userId;
|
|
89
|
+
} catch {
|
|
90
|
+
actorUserId = undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
switch (event?.type) {
|
|
94
|
+
case 'checkout.session.completed':
|
|
95
|
+
await subscriptionService.handleCheckoutCompleted(event);
|
|
96
|
+
break;
|
|
97
|
+
case 'customer.subscription.created':
|
|
98
|
+
await subscriptionService.handleSubscriptionCreated(event);
|
|
99
|
+
break;
|
|
100
|
+
case 'customer.subscription.updated':
|
|
101
|
+
await subscriptionService.handleSubscriptionUpdated(event);
|
|
102
|
+
break;
|
|
103
|
+
case 'customer.subscription.deleted':
|
|
104
|
+
await subscriptionService.handleSubscriptionDeleted(event);
|
|
105
|
+
break;
|
|
106
|
+
case 'invoice.paid':
|
|
107
|
+
case 'invoice.payment_succeeded':
|
|
108
|
+
await subscriptionService.handleInvoicePaid(event);
|
|
109
|
+
break;
|
|
110
|
+
case 'invoice.payment_failed':
|
|
111
|
+
await subscriptionService.handlePaymentFailed(event);
|
|
112
|
+
break;
|
|
113
|
+
case 'payment_intent.payment_failed':
|
|
114
|
+
await subscriptionService.handlePaymentIntentFailed(event);
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
logger.debug(`Unhandled stripe event type: ${event?.type}`, 'STRIPE');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
await recordExplicitActivity({
|
|
121
|
+
db: prisma,
|
|
122
|
+
actorUserId: actorUserId ?? undefined,
|
|
123
|
+
action: `stripe.webhook.${event?.type}`,
|
|
124
|
+
category: ActivityLogCategory.SYSTEM,
|
|
125
|
+
status,
|
|
126
|
+
errorCode,
|
|
127
|
+
durationMs: Date.now() - startedAt,
|
|
128
|
+
forceWrite: true,
|
|
129
|
+
metadata: {
|
|
130
|
+
stripeEventId: event?.id,
|
|
131
|
+
stripeEventType: event?.type,
|
|
132
|
+
},
|
|
133
|
+
}).catch(() => {});
|
|
134
|
+
res.json({ received: true });
|
|
135
|
+
} catch (err: any) {
|
|
136
|
+
const startedAt = Date.now();
|
|
137
|
+
const message = err?.message ?? 'unknown';
|
|
138
|
+
await recordExplicitActivity({
|
|
139
|
+
db: prisma,
|
|
140
|
+
actorUserId: null,
|
|
141
|
+
action: `stripe.webhook.${event?.type}`,
|
|
142
|
+
category: ActivityLogCategory.SYSTEM,
|
|
143
|
+
status: ActivityLogStatus.FAILURE,
|
|
144
|
+
errorCode: message,
|
|
145
|
+
durationMs: Date.now() - startedAt,
|
|
146
|
+
forceWrite: true,
|
|
147
|
+
metadata: {
|
|
148
|
+
stripeEventId: event?.id,
|
|
149
|
+
stripeEventType: event?.type,
|
|
150
|
+
},
|
|
151
|
+
}).catch(() => {});
|
|
152
|
+
logger.error(`Error processing webhook event ${event?.type}: ${err.message}`, 'STRIPE');
|
|
153
|
+
res.status(500).send('Internal Server Error');
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
|
|
42
157
|
app.use(express.json({ limit: '50mb' }));
|
|
43
158
|
app.use(express.urlencoded({ limit: '50mb', extended: true }));
|
|
44
|
-
|
|
159
|
+
|
|
45
160
|
|
|
46
161
|
// Health (plain Express)
|
|
47
162
|
app.get('/', (_req, res) => {
|
|
@@ -49,15 +164,26 @@ async function main() {
|
|
|
49
164
|
});
|
|
50
165
|
|
|
51
166
|
app.get('/profile-picture/:objectKey', async (req, res) => {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
167
|
+
try {
|
|
168
|
+
const { objectKey } = req.params;
|
|
169
|
+
const { data, error } = await supabaseClient.storage
|
|
170
|
+
.from('media')
|
|
171
|
+
.download(objectKey);
|
|
172
|
+
|
|
173
|
+
if (error || !data) {
|
|
174
|
+
logger.error(`Failed to download profile picture: ${error?.message}`, 'STORAGE');
|
|
175
|
+
return res.status(404).send('Not found');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const buffer = Buffer.from(await data.arrayBuffer());
|
|
179
|
+
res.setHeader('Content-Type', 'image/jpeg');
|
|
180
|
+
res.setHeader('Cache-Control', 'public, max-age=31536000');
|
|
181
|
+
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
|
|
182
|
+
res.send(buffer);
|
|
183
|
+
} catch (err: any) {
|
|
184
|
+
logger.error('Error serving profile picture', 'STORAGE', undefined, err);
|
|
185
|
+
res.status(500).send('Internal Server Error');
|
|
58
186
|
}
|
|
59
|
-
// res.json({ url: signedUrl.data.signedUrl });
|
|
60
|
-
res.redirect(signedUrl.data.signedUrl);
|
|
61
187
|
});
|
|
62
188
|
|
|
63
189
|
// tRPC mounted under /trpc
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { Prisma, type PrismaClient } from '@prisma/client';
|
|
2
2
|
import { NotFoundError } from '../lib/errors.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -146,7 +146,7 @@ export class FlashcardProgressService {
|
|
|
146
146
|
isCorrect: boolean;
|
|
147
147
|
confidence?: 'easy' | 'medium' | 'hard';
|
|
148
148
|
timeSpentMs?: number;
|
|
149
|
-
}) {
|
|
149
|
+
}, retryCount: number = 0): Promise<any> {
|
|
150
150
|
const { userId, flashcardId, isCorrect, timeSpentMs } = data;
|
|
151
151
|
|
|
152
152
|
// Verify flashcard exists and user has access
|
|
@@ -226,44 +226,56 @@ export class FlashcardProgressService {
|
|
|
226
226
|
)
|
|
227
227
|
);
|
|
228
228
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
229
|
+
try {
|
|
230
|
+
// Upsert progress
|
|
231
|
+
return await this.db.flashcardProgress.upsert({
|
|
232
|
+
where: {
|
|
233
|
+
userId_flashcardId: {
|
|
234
|
+
userId,
|
|
235
|
+
flashcardId,
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
update: {
|
|
239
|
+
timesStudied: { increment: 1 },
|
|
240
|
+
timesCorrect: isCorrect ? { increment: 1 } : undefined,
|
|
241
|
+
timesIncorrect: !isCorrect ? { increment: 1 } : undefined,
|
|
242
|
+
timesIncorrectConsecutive: newConsecutiveIncorrect,
|
|
243
|
+
easeFactor: sm2Result.easeFactor,
|
|
244
|
+
interval: sm2Result.interval,
|
|
245
|
+
repetitions: sm2Result.repetitions,
|
|
246
|
+
masteryLevel,
|
|
247
|
+
lastStudiedAt: new Date(),
|
|
248
|
+
nextReviewAt: sm2Result.nextReviewAt,
|
|
249
|
+
},
|
|
250
|
+
create: {
|
|
233
251
|
userId,
|
|
234
252
|
flashcardId,
|
|
253
|
+
timesStudied: 1,
|
|
254
|
+
timesCorrect: isCorrect ? 1 : 0,
|
|
255
|
+
timesIncorrect: isCorrect ? 0 : 1,
|
|
256
|
+
timesIncorrectConsecutive: newConsecutiveIncorrect,
|
|
257
|
+
easeFactor: sm2Result.easeFactor,
|
|
258
|
+
interval: sm2Result.interval,
|
|
259
|
+
repetitions: sm2Result.repetitions,
|
|
260
|
+
masteryLevel,
|
|
261
|
+
lastStudiedAt: new Date(),
|
|
262
|
+
nextReviewAt: sm2Result.nextReviewAt,
|
|
235
263
|
},
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
flashcardId,
|
|
252
|
-
timesStudied: 1,
|
|
253
|
-
timesCorrect: isCorrect ? 1 : 0,
|
|
254
|
-
timesIncorrect: isCorrect ? 0 : 1,
|
|
255
|
-
timesIncorrectConsecutive: newConsecutiveIncorrect,
|
|
256
|
-
easeFactor: sm2Result.easeFactor,
|
|
257
|
-
interval: sm2Result.interval,
|
|
258
|
-
repetitions: sm2Result.repetitions,
|
|
259
|
-
masteryLevel,
|
|
260
|
-
lastStudiedAt: new Date(),
|
|
261
|
-
nextReviewAt: sm2Result.nextReviewAt,
|
|
262
|
-
},
|
|
263
|
-
include: {
|
|
264
|
-
flashcard: true,
|
|
265
|
-
},
|
|
266
|
-
});
|
|
264
|
+
include: {
|
|
265
|
+
flashcard: true,
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
} catch (error) {
|
|
269
|
+
// Handle rare race condition where parallel submissions try creating same row.
|
|
270
|
+
if (
|
|
271
|
+
error instanceof Prisma.PrismaClientKnownRequestError &&
|
|
272
|
+
error.code === 'P2002' &&
|
|
273
|
+
retryCount < 1
|
|
274
|
+
) {
|
|
275
|
+
return this.recordStudyAttempt(data, retryCount + 1);
|
|
276
|
+
}
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
267
279
|
}
|
|
268
280
|
|
|
269
281
|
/**
|
package/src/trpc.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
import { initTRPC, TRPCError } from "@trpc/server";
|
|
2
2
|
import superjson from "superjson";
|
|
3
|
+
import { ActivityLogStatus } from "@prisma/client";
|
|
3
4
|
import type { Context } from "./context.js";
|
|
4
5
|
import { logger } from "./lib/logger.js";
|
|
5
6
|
import { toTRPCError } from "./lib/errors.js";
|
|
7
|
+
import { getUserUsage, getUserPlanLimits } from "./lib/usage_service.js";
|
|
8
|
+
import {
|
|
9
|
+
getClientIp,
|
|
10
|
+
isActivityLogEnabled,
|
|
11
|
+
scheduleRecordActivity,
|
|
12
|
+
truncateUserAgent,
|
|
13
|
+
} from "./lib/activity_log_service.js";
|
|
14
|
+
|
|
15
|
+
/** Avoid logging the log viewers themselves (noise when browsing activity). */
|
|
16
|
+
const SKIP_ACTIVITY_TRPC_PATHS = new Set([
|
|
17
|
+
"admin.activityList",
|
|
18
|
+
"admin.activityExportCsv",
|
|
19
|
+
]);
|
|
6
20
|
|
|
7
21
|
const t = initTRPC.context<Context>().create({
|
|
8
22
|
transformer: superjson,
|
|
@@ -15,7 +29,7 @@ const t = initTRPC.context<Context>().create({
|
|
|
15
29
|
cause: error.cause,
|
|
16
30
|
});
|
|
17
31
|
}
|
|
18
|
-
|
|
32
|
+
|
|
19
33
|
return {
|
|
20
34
|
...shape,
|
|
21
35
|
data: {
|
|
@@ -37,12 +51,12 @@ const loggingMiddleware = middleware(async ({ ctx, next, path, type }) => {
|
|
|
37
51
|
const start = Date.now();
|
|
38
52
|
const result = await next();
|
|
39
53
|
const duration = Date.now() - start;
|
|
40
|
-
|
|
54
|
+
|
|
41
55
|
logger.info(`TRPC ${type} ${path}`, 'TRPC', {
|
|
42
56
|
duration: `${duration}ms`,
|
|
43
57
|
userId: (ctx.session as any)?.user?.id,
|
|
44
58
|
});
|
|
45
|
-
|
|
59
|
+
|
|
46
60
|
return result;
|
|
47
61
|
});
|
|
48
62
|
|
|
@@ -52,7 +66,7 @@ const loggingMiddleware = middleware(async ({ ctx, next, path, type }) => {
|
|
|
52
66
|
const isAuthed = middleware(({ ctx, next }) => {
|
|
53
67
|
const hasUser = Boolean((ctx.session as any)?.user?.id);
|
|
54
68
|
if (!ctx.session || !hasUser) {
|
|
55
|
-
throw new TRPCError({
|
|
69
|
+
throw new TRPCError({
|
|
56
70
|
code: "UNAUTHORIZED",
|
|
57
71
|
message: "You must be logged in to access this resource"
|
|
58
72
|
});
|
|
@@ -60,6 +74,7 @@ const isAuthed = middleware(({ ctx, next }) => {
|
|
|
60
74
|
|
|
61
75
|
return next({
|
|
62
76
|
ctx: {
|
|
77
|
+
...ctx,
|
|
63
78
|
session: ctx.session,
|
|
64
79
|
userId: (ctx.session as any).user.id,
|
|
65
80
|
},
|
|
@@ -77,8 +92,172 @@ const errorHandler = middleware(async ({ next }) => {
|
|
|
77
92
|
}
|
|
78
93
|
});
|
|
79
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Middleware that enforces email verification
|
|
97
|
+
*/
|
|
98
|
+
const isVerified = middleware(async ({ ctx, next }) => {
|
|
99
|
+
const user = await ctx.db.user.findUnique({
|
|
100
|
+
where: { id: (ctx.session as any).user.id },
|
|
101
|
+
select: { emailVerified: true },
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
if (!user?.emailVerified) {
|
|
105
|
+
throw new TRPCError({
|
|
106
|
+
code: "FORBIDDEN",
|
|
107
|
+
message: "Please verify your email to access this feature",
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return next();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Middleware that enforces resource limits based on the user's plan.
|
|
116
|
+
* Note: This matches the 'path' to decide which limit to check.
|
|
117
|
+
*/
|
|
118
|
+
const checkUsageLimit = middleware(async ({ ctx, next, path }) => {
|
|
119
|
+
const userId = (ctx.session as any).user.id;
|
|
120
|
+
|
|
121
|
+
// 1. Get current usage and limits
|
|
122
|
+
const [usage, limits] = await Promise.all([
|
|
123
|
+
getUserUsage(userId),
|
|
124
|
+
getUserPlanLimits(userId)
|
|
125
|
+
]);
|
|
126
|
+
|
|
127
|
+
// If no limits found (no active plan), we block any premium actions
|
|
128
|
+
if (!limits) {
|
|
129
|
+
throw new TRPCError({
|
|
130
|
+
code: "FORBIDDEN",
|
|
131
|
+
message: "No active plan found. Please subscribe to a plan to continue.",
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 2. Check limits based on the tRPC path
|
|
136
|
+
|
|
137
|
+
// Flashcards (matches: flashcards.createCard, flashcards.generateFromPrompt)
|
|
138
|
+
if (path.startsWith('flashcards.') && (path.includes('create') || path.includes('generate')) && usage.flashcards >= limits.maxFlashcards) {
|
|
139
|
+
throw new TRPCError({ code: "FORBIDDEN", message: "Flashcard limit reached for your plan." });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Worksheets (matches: worksheets.create, worksheets.generateFromPrompt)
|
|
143
|
+
if (path.startsWith('worksheets.') && (path.includes('create') || path.includes('generate')) && usage.worksheets >= limits.maxWorksheets) {
|
|
144
|
+
throw new TRPCError({ code: "FORBIDDEN", message: "Worksheet limit reached for your plan." });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Podcasts (matches: podcast.generateEpisode)
|
|
148
|
+
if (path.startsWith('podcast.') && path.includes('generate') && usage.podcasts >= limits.maxPodcasts) {
|
|
149
|
+
throw new TRPCError({ code: "FORBIDDEN", message: "Podcast limit reached for your plan." });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Study Guides (matches: studyguide.get - because it lazily creates)
|
|
153
|
+
if (path.startsWith('studyguide.') && path.includes('get') && usage.studyGuides >= limits.maxStudyGuides) {
|
|
154
|
+
// Note: We only block if the artifact doesn't exist yet (handled inside the query or by checking usage)
|
|
155
|
+
// For simplicity, if they hit the limit, we block creation of NEW study guides.
|
|
156
|
+
// However, usage_service counts existing ones.
|
|
157
|
+
// If usage is already at/over limit, it means any NEW workspace's 'get' will fail creation.
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Storage check (for uploads)
|
|
161
|
+
if (path.includes('upload') && usage.storageBytes >= Number(limits.maxStorageBytes)) {
|
|
162
|
+
throw new TRPCError({ code: "FORBIDDEN", message: "Storage limit reached for your plan." });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return next();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Middleware that enforces system admin role
|
|
170
|
+
*/
|
|
171
|
+
const isAdmin = middleware(async ({ ctx, next }) => {
|
|
172
|
+
const user = await ctx.db.user.findUnique({
|
|
173
|
+
where: { id: (ctx.session as any).user.id },
|
|
174
|
+
include: { role: true },
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
if (user?.role?.name !== 'System Admin') {
|
|
178
|
+
throw new TRPCError({
|
|
179
|
+
code: "FORBIDDEN",
|
|
180
|
+
message: "You do not have permission to access this resource",
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return next();
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Persists ActivityLog rows for authenticated tRPC calls (async, non-blocking).
|
|
189
|
+
*/
|
|
190
|
+
const activityLogMiddleware = middleware(async (opts) => {
|
|
191
|
+
const { ctx, next, path, type, getRawInput } = opts;
|
|
192
|
+
if (!isActivityLogEnabled() || SKIP_ACTIVITY_TRPC_PATHS.has(path)) {
|
|
193
|
+
return next();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const userId = (ctx as any).userId as string | undefined;
|
|
197
|
+
if (!userId) {
|
|
198
|
+
return next();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let rawInput: unknown;
|
|
202
|
+
try {
|
|
203
|
+
rawInput = await getRawInput();
|
|
204
|
+
} catch {
|
|
205
|
+
rawInput = undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const req = ctx.req;
|
|
209
|
+
const ipAddress = req ? getClientIp(req) : undefined;
|
|
210
|
+
const userAgent = req.headers["user-agent"];
|
|
211
|
+
const httpMethod = req.method;
|
|
212
|
+
|
|
213
|
+
const start = Date.now();
|
|
214
|
+
const result = await next();
|
|
215
|
+
const durationMs = Date.now() - start;
|
|
216
|
+
|
|
217
|
+
if (result.ok) {
|
|
218
|
+
scheduleRecordActivity({
|
|
219
|
+
db: ctx.db,
|
|
220
|
+
actorUserId: userId,
|
|
221
|
+
path,
|
|
222
|
+
type,
|
|
223
|
+
status: ActivityLogStatus.SUCCESS,
|
|
224
|
+
durationMs,
|
|
225
|
+
rawInput,
|
|
226
|
+
ipAddress,
|
|
227
|
+
userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
|
|
228
|
+
httpMethod,
|
|
229
|
+
});
|
|
230
|
+
} else {
|
|
231
|
+
scheduleRecordActivity({
|
|
232
|
+
db: ctx.db,
|
|
233
|
+
actorUserId: userId,
|
|
234
|
+
path,
|
|
235
|
+
type,
|
|
236
|
+
status: ActivityLogStatus.FAILURE,
|
|
237
|
+
durationMs,
|
|
238
|
+
rawInput,
|
|
239
|
+
ipAddress,
|
|
240
|
+
userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
|
|
241
|
+
httpMethod,
|
|
242
|
+
errorCode: result.error.code,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return result;
|
|
247
|
+
});
|
|
248
|
+
|
|
80
249
|
/** Exported procedures with middleware */
|
|
81
250
|
export const authedProcedure = publicProcedure
|
|
82
251
|
.use(loggingMiddleware)
|
|
83
252
|
.use(errorHandler)
|
|
84
|
-
.use(isAuthed)
|
|
253
|
+
.use(isAuthed)
|
|
254
|
+
.use(activityLogMiddleware);
|
|
255
|
+
|
|
256
|
+
export const verifiedProcedure = authedProcedure
|
|
257
|
+
.use(isVerified);
|
|
258
|
+
|
|
259
|
+
export const adminProcedure = authedProcedure
|
|
260
|
+
.use(isAdmin);
|
|
261
|
+
|
|
262
|
+
export const limitedProcedure = verifiedProcedure
|
|
263
|
+
.use(checkUsageLimit);
|