@goscribe/server 1.3.0 → 1.3.1

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.
Files changed (79) hide show
  1. package/dist/context.d.ts +5 -1
  2. package/dist/lib/activity_human_description.d.ts +13 -0
  3. package/dist/lib/activity_human_description.js +221 -0
  4. package/dist/lib/activity_human_description.test.d.ts +1 -0
  5. package/dist/lib/activity_human_description.test.js +16 -0
  6. package/dist/lib/activity_log_service.d.ts +87 -0
  7. package/dist/lib/activity_log_service.js +276 -0
  8. package/dist/lib/activity_log_service.test.d.ts +1 -0
  9. package/dist/lib/activity_log_service.test.js +27 -0
  10. package/dist/lib/ai-session.d.ts +15 -2
  11. package/dist/lib/ai-session.js +147 -85
  12. package/dist/lib/constants.d.ts +13 -0
  13. package/dist/lib/constants.js +12 -0
  14. package/dist/lib/email.d.ts +11 -0
  15. package/dist/lib/email.js +193 -0
  16. package/dist/lib/env.d.ts +13 -0
  17. package/dist/lib/env.js +16 -0
  18. package/dist/lib/inference.d.ts +4 -1
  19. package/dist/lib/inference.js +3 -3
  20. package/dist/lib/logger.d.ts +4 -4
  21. package/dist/lib/logger.js +30 -8
  22. package/dist/lib/notification-service.d.ts +152 -0
  23. package/dist/lib/notification-service.js +473 -0
  24. package/dist/lib/notification-service.test.d.ts +1 -0
  25. package/dist/lib/notification-service.test.js +87 -0
  26. package/dist/lib/prisma.d.ts +2 -1
  27. package/dist/lib/prisma.js +5 -1
  28. package/dist/lib/pusher.d.ts +23 -0
  29. package/dist/lib/pusher.js +69 -5
  30. package/dist/lib/retry.d.ts +15 -0
  31. package/dist/lib/retry.js +37 -0
  32. package/dist/lib/storage.js +2 -2
  33. package/dist/lib/stripe.d.ts +9 -0
  34. package/dist/lib/stripe.js +36 -0
  35. package/dist/lib/subscription_service.d.ts +37 -0
  36. package/dist/lib/subscription_service.js +654 -0
  37. package/dist/lib/usage_service.d.ts +26 -0
  38. package/dist/lib/usage_service.js +59 -0
  39. package/dist/lib/worksheet-generation.d.ts +91 -0
  40. package/dist/lib/worksheet-generation.js +95 -0
  41. package/dist/lib/worksheet-generation.test.d.ts +1 -0
  42. package/dist/lib/worksheet-generation.test.js +20 -0
  43. package/dist/lib/workspace-access.d.ts +18 -0
  44. package/dist/lib/workspace-access.js +13 -0
  45. package/dist/routers/_app.d.ts +1349 -253
  46. package/dist/routers/_app.js +10 -0
  47. package/dist/routers/admin.d.ts +361 -0
  48. package/dist/routers/admin.js +633 -0
  49. package/dist/routers/annotations.d.ts +219 -0
  50. package/dist/routers/annotations.js +187 -0
  51. package/dist/routers/auth.d.ts +88 -7
  52. package/dist/routers/auth.js +339 -19
  53. package/dist/routers/chat.d.ts +6 -12
  54. package/dist/routers/copilot.d.ts +199 -0
  55. package/dist/routers/copilot.js +571 -0
  56. package/dist/routers/flashcards.d.ts +47 -81
  57. package/dist/routers/flashcards.js +143 -27
  58. package/dist/routers/members.d.ts +36 -7
  59. package/dist/routers/members.js +200 -19
  60. package/dist/routers/notifications.d.ts +99 -0
  61. package/dist/routers/notifications.js +127 -0
  62. package/dist/routers/payment.d.ts +89 -0
  63. package/dist/routers/payment.js +403 -0
  64. package/dist/routers/podcast.d.ts +8 -13
  65. package/dist/routers/podcast.js +54 -31
  66. package/dist/routers/studyguide.d.ts +1 -29
  67. package/dist/routers/studyguide.js +80 -71
  68. package/dist/routers/worksheets.d.ts +105 -38
  69. package/dist/routers/worksheets.js +258 -68
  70. package/dist/routers/workspace.d.ts +139 -60
  71. package/dist/routers/workspace.js +455 -315
  72. package/dist/scripts/purge-deleted-users.d.ts +1 -0
  73. package/dist/scripts/purge-deleted-users.js +149 -0
  74. package/dist/server.js +130 -10
  75. package/dist/services/flashcard-progress.service.d.ts +18 -66
  76. package/dist/services/flashcard-progress.service.js +51 -42
  77. package/dist/trpc.d.ts +20 -21
  78. package/dist/trpc.js +150 -1
  79. package/package.json +1 -1
package/dist/trpc.js CHANGED
@@ -1,7 +1,15 @@
1
1
  import { initTRPC, TRPCError } from "@trpc/server";
2
2
  import superjson from "superjson";
3
+ import { ActivityLogStatus } from "@prisma/client";
3
4
  import { logger } from "./lib/logger.js";
4
5
  import { toTRPCError } from "./lib/errors.js";
6
+ import { getUserUsage, getUserPlanLimits } from "./lib/usage_service.js";
7
+ import { getClientIp, isActivityLogEnabled, scheduleRecordActivity, truncateUserAgent, } from "./lib/activity_log_service.js";
8
+ /** Avoid logging the log viewers themselves (noise when browsing activity). */
9
+ const SKIP_ACTIVITY_TRPC_PATHS = new Set([
10
+ "admin.activityList",
11
+ "admin.activityExportCsv",
12
+ ]);
5
13
  const t = initTRPC.context().create({
6
14
  transformer: superjson,
7
15
  errorFormatter({ shape, error }) {
@@ -51,6 +59,7 @@ const isAuthed = middleware(({ ctx, next }) => {
51
59
  }
52
60
  return next({
53
61
  ctx: {
62
+ ...ctx,
54
63
  session: ctx.session,
55
64
  userId: ctx.session.user.id,
56
65
  },
@@ -67,8 +76,148 @@ const errorHandler = middleware(async ({ next }) => {
67
76
  throw toTRPCError(error);
68
77
  }
69
78
  });
79
+ /**
80
+ * Middleware that enforces email verification
81
+ */
82
+ const isVerified = middleware(async ({ ctx, next }) => {
83
+ const user = await ctx.db.user.findUnique({
84
+ where: { id: ctx.session.user.id },
85
+ select: { emailVerified: true },
86
+ });
87
+ if (!user?.emailVerified) {
88
+ throw new TRPCError({
89
+ code: "FORBIDDEN",
90
+ message: "Please verify your email to access this feature",
91
+ });
92
+ }
93
+ return next();
94
+ });
95
+ /**
96
+ * Middleware that enforces resource limits based on the user's plan.
97
+ * Note: This matches the 'path' to decide which limit to check.
98
+ */
99
+ const checkUsageLimit = middleware(async ({ ctx, next, path }) => {
100
+ const userId = ctx.session.user.id;
101
+ // 1. Get current usage and limits
102
+ const [usage, limits] = await Promise.all([
103
+ getUserUsage(userId),
104
+ getUserPlanLimits(userId)
105
+ ]);
106
+ // If no limits found (no active plan), we block any premium actions
107
+ if (!limits) {
108
+ throw new TRPCError({
109
+ code: "FORBIDDEN",
110
+ message: "No active plan found. Please subscribe to a plan to continue.",
111
+ });
112
+ }
113
+ // 2. Check limits based on the tRPC path
114
+ // Flashcards (matches: flashcards.createCard, flashcards.generateFromPrompt)
115
+ if (path.startsWith('flashcards.') && (path.includes('create') || path.includes('generate')) && usage.flashcards >= limits.maxFlashcards) {
116
+ throw new TRPCError({ code: "FORBIDDEN", message: "Flashcard limit reached for your plan." });
117
+ }
118
+ // Worksheets (matches: worksheets.create, worksheets.generateFromPrompt)
119
+ if (path.startsWith('worksheets.') && (path.includes('create') || path.includes('generate')) && usage.worksheets >= limits.maxWorksheets) {
120
+ throw new TRPCError({ code: "FORBIDDEN", message: "Worksheet limit reached for your plan." });
121
+ }
122
+ // Podcasts (matches: podcast.generateEpisode)
123
+ if (path.startsWith('podcast.') && path.includes('generate') && usage.podcasts >= limits.maxPodcasts) {
124
+ throw new TRPCError({ code: "FORBIDDEN", message: "Podcast limit reached for your plan." });
125
+ }
126
+ // Study Guides (matches: studyguide.get - because it lazily creates)
127
+ if (path.startsWith('studyguide.') && path.includes('get') && usage.studyGuides >= limits.maxStudyGuides) {
128
+ // Note: We only block if the artifact doesn't exist yet (handled inside the query or by checking usage)
129
+ // For simplicity, if they hit the limit, we block creation of NEW study guides.
130
+ // However, usage_service counts existing ones.
131
+ // If usage is already at/over limit, it means any NEW workspace's 'get' will fail creation.
132
+ }
133
+ // Storage check (for uploads)
134
+ if (path.includes('upload') && usage.storageBytes >= Number(limits.maxStorageBytes)) {
135
+ throw new TRPCError({ code: "FORBIDDEN", message: "Storage limit reached for your plan." });
136
+ }
137
+ return next();
138
+ });
139
+ /**
140
+ * Middleware that enforces system admin role
141
+ */
142
+ const isAdmin = middleware(async ({ ctx, next }) => {
143
+ const user = await ctx.db.user.findUnique({
144
+ where: { id: ctx.session.user.id },
145
+ include: { role: true },
146
+ });
147
+ if (user?.role?.name !== 'System Admin') {
148
+ throw new TRPCError({
149
+ code: "FORBIDDEN",
150
+ message: "You do not have permission to access this resource",
151
+ });
152
+ }
153
+ return next();
154
+ });
155
+ /**
156
+ * Persists ActivityLog rows for authenticated tRPC calls (async, non-blocking).
157
+ */
158
+ const activityLogMiddleware = middleware(async (opts) => {
159
+ const { ctx, next, path, type, getRawInput } = opts;
160
+ if (!isActivityLogEnabled() || SKIP_ACTIVITY_TRPC_PATHS.has(path)) {
161
+ return next();
162
+ }
163
+ const userId = ctx.userId;
164
+ if (!userId) {
165
+ return next();
166
+ }
167
+ let rawInput;
168
+ try {
169
+ rawInput = await getRawInput();
170
+ }
171
+ catch {
172
+ rawInput = undefined;
173
+ }
174
+ const req = ctx.req;
175
+ const ipAddress = req ? getClientIp(req) : undefined;
176
+ const userAgent = req.headers["user-agent"];
177
+ const httpMethod = req.method;
178
+ const start = Date.now();
179
+ const result = await next();
180
+ const durationMs = Date.now() - start;
181
+ if (result.ok) {
182
+ scheduleRecordActivity({
183
+ db: ctx.db,
184
+ actorUserId: userId,
185
+ path,
186
+ type,
187
+ status: ActivityLogStatus.SUCCESS,
188
+ durationMs,
189
+ rawInput,
190
+ ipAddress,
191
+ userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
192
+ httpMethod,
193
+ });
194
+ }
195
+ else {
196
+ scheduleRecordActivity({
197
+ db: ctx.db,
198
+ actorUserId: userId,
199
+ path,
200
+ type,
201
+ status: ActivityLogStatus.FAILURE,
202
+ durationMs,
203
+ rawInput,
204
+ ipAddress,
205
+ userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
206
+ httpMethod,
207
+ errorCode: result.error.code,
208
+ });
209
+ }
210
+ return result;
211
+ });
70
212
  /** Exported procedures with middleware */
71
213
  export const authedProcedure = publicProcedure
72
214
  .use(loggingMiddleware)
73
215
  .use(errorHandler)
74
- .use(isAuthed);
216
+ .use(isAuthed)
217
+ .use(activityLogMiddleware);
218
+ export const verifiedProcedure = authedProcedure
219
+ .use(isVerified);
220
+ export const adminProcedure = authedProcedure
221
+ .use(isAdmin);
222
+ export const limitedProcedure = verifiedProcedure
223
+ .use(checkUsageLimit);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goscribe/server",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",