critiqs-react 0.3.0 → 0.5.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.
Files changed (58) hide show
  1. package/AGENT_SETUP.md +198 -66
  2. package/README.md +214 -31
  3. package/bin/critiqs.mjs +3 -1
  4. package/dist/index.js +16877 -4770
  5. package/dist/server/index.d.ts +1 -87
  6. package/dist/server/index.js +1 -4889
  7. package/package.json +6 -5
  8. package/bin/cli.d.mts +0 -21
  9. package/bin/cli.mjs +0 -293
  10. package/bin/env.d.mts +0 -41
  11. package/bin/env.mjs +0 -384
  12. package/bin/init.d.mts +0 -126
  13. package/bin/init.mjs +0 -965
  14. package/bin/mcp.d.mts +0 -20
  15. package/bin/mcp.mjs +0 -314
  16. package/bin/setup.d.mts +0 -183
  17. package/bin/setup.mjs +0 -1054
  18. package/dist/backend/convex/_generated/api.d.ts +0 -95
  19. package/dist/backend/convex/_generated/api.js +0 -23
  20. package/dist/backend/convex/_generated/dataModel.d.ts +0 -60
  21. package/dist/backend/convex/_generated/server.d.ts +0 -162
  22. package/dist/backend/convex/_generated/server.js +0 -101
  23. package/dist/backend/convex/ai.ts +0 -93
  24. package/dist/backend/convex/aiSettings.ts +0 -43
  25. package/dist/backend/convex/auth.config.ts +0 -18
  26. package/dist/backend/convex/captureHttp.ts +0 -96
  27. package/dist/backend/convex/captures.ts +0 -167
  28. package/dist/backend/convex/crons.ts +0 -14
  29. package/dist/backend/convex/deviceSignIn.ts +0 -151
  30. package/dist/backend/convex/grouping.ts +0 -41
  31. package/dist/backend/convex/http.ts +0 -724
  32. package/dist/backend/convex/lib/ai.ts +0 -6
  33. package/dist/backend/convex/lib/links.ts +0 -12
  34. package/dist/backend/convex/lib/pages.ts +0 -207
  35. package/dist/backend/convex/lib/r2.ts +0 -75
  36. package/dist/backend/convex/lib/store.ts +0 -509
  37. package/dist/backend/convex/lib/tokens.ts +0 -101
  38. package/dist/backend/convex/lib/validators.ts +0 -73
  39. package/dist/backend/convex/lib/vendor/aws4fetch.js +0 -289
  40. package/dist/backend/convex/lib/vendor/critiqs_ai.js +0 -49081
  41. package/dist/backend/convex/lib/vendor/critiqs_core.js +0 -385
  42. package/dist/backend/convex/lib/vendor/critiqs_server.js +0 -3108
  43. package/dist/backend/convex/notificationEmails.ts +0 -61
  44. package/dist/backend/convex/notifications.ts +0 -182
  45. package/dist/backend/convex/plans.ts +0 -67
  46. package/dist/backend/convex/projects.ts +0 -46
  47. package/dist/backend/convex/schema.ts +0 -343
  48. package/dist/backend/convex/search.ts +0 -26
  49. package/dist/backend/convex/signIn.ts +0 -368
  50. package/dist/backend/convex/tags.ts +0 -68
  51. package/dist/backend/convex/threads.ts +0 -146
  52. package/dist/backend/convex/users.ts +0 -13
  53. package/dist/server/chunks/driver-n9zpr0k3.js +0 -21
  54. package/dist/server/chunks/index-9bg7tmnq.js +0 -522
  55. package/dist/server/chunks/index-askcfn7t.js +0 -148
  56. package/dist/server/chunks/providers-rv184xvj.js +0 -48444
  57. package/dist/server/chunks/token-kzddms7r.js +0 -63
  58. package/dist/server/chunks/token-util-k8bee1wc.js +0 -4
@@ -1,509 +0,0 @@
1
- import type { PageRequest } from "./vendor/critiqs_core.js";
2
- import {
3
- CritiqsError,
4
- type Identity,
5
- type PageResult,
6
- PAGE_SIZE,
7
- type StoredCapture,
8
- type Store,
9
- type ThreadRecord,
10
- } from "./vendor/critiqs_server.js";
11
- import type { PaginationOptions, PaginationResult, UserIdentity } from "convex/server";
12
- import { ConvexError } from "convex/values";
13
- import type { Doc, Id } from "../_generated/dataModel";
14
- import type { MutationCtx, QueryCtx } from "../_generated/server";
15
-
16
- // Critiqs's server rules (@critiqs/server) on Convex. Each Convex function is
17
- // one transaction, so an operation's reads and writes commit together.
18
-
19
- /** The storage interface over a query's or mutation's database. Writes need a mutation. */
20
- export function convexStore(ctx: QueryCtx | MutationCtx): Store {
21
- const db = ctx.db;
22
- const writer = () => {
23
- if (!("insert" in db)) throw new Error("This Critiqs operation changes data and must run in a mutation.");
24
- return (ctx as MutationCtx).db;
25
- };
26
- const page = <T, R>(result: PaginationResult<T>, map: (row: T) => R): PageResult<R> => ({
27
- page: result.page.map(map),
28
- isDone: result.isDone,
29
- continueCursor: result.continueCursor,
30
- });
31
-
32
- return {
33
- normalizeId: (table, raw) => {
34
- switch (table) {
35
- case "files":
36
- return db.normalizeId("captureFiles", raw) ?? db.system.normalizeId("_storage", raw);
37
- case "projects":
38
- return db.normalizeId("projects", raw);
39
- case "threads":
40
- return db.normalizeId("threads", raw);
41
- case "messages":
42
- return db.normalizeId("messages", raw);
43
- case "users":
44
- return db.normalizeId("users", raw);
45
- case "deliveries":
46
- return db.normalizeId("deliveries", raw);
47
- case "tagGroups":
48
- return db.normalizeId("tagGroups", raw);
49
- }
50
- },
51
-
52
- users: {
53
- byToken: async (tokenIdentifier) =>
54
- await db
55
- .query("users")
56
- .withIndex("by_token", (q) => q.eq("tokenIdentifier", tokenIdentifier))
57
- .unique(),
58
- get: async (id) => await db.get(id as Id<"users">),
59
- insert: async (user) => await writer().insert("users", user),
60
- patch: async (id, changes) => await writer().patch(id as Id<"users">, defined(changes)),
61
- },
62
- projects: {
63
- get: async (id) => await db.get(id as Id<"projects">),
64
- insert: async (project) => await writer().insert("projects", { ...project, createdBy: project.createdBy as Id<"users"> }),
65
- patch: async (id, changes) => await writer().patch(id as Id<"projects">, defined(changes)),
66
- listByCreator: async (userId, request) =>
67
- page(
68
- await db
69
- .query("projects")
70
- .withIndex("by_creator", (q) => q.eq("createdBy", userId as Id<"users">))
71
- .paginate(bounded(request)),
72
- (project) => project,
73
- ),
74
- },
75
- threads: {
76
- get: async (id) => {
77
- const thread = await db.get(id as Id<"threads">);
78
- return thread === null ? null : threadRecord(thread);
79
- },
80
- insert: async (thread) => await writer().insert("threads", threadDoc(thread)),
81
- patch: async (id, changes) => await writer().patch(id as Id<"threads">, threadDoc(defined(changes))),
82
- listVisible: async (projectId, request) =>
83
- page(
84
- await db
85
- .query("threads")
86
- .withIndex("by_project", (q) => q.eq("projectId", projectId as Id<"projects">))
87
- .filter((q) => q.neq(q.field("status"), "deleted"))
88
- .paginate(bounded(request)),
89
- threadRecord,
90
- ),
91
- byCaptureFile: async (fileId) => {
92
- const thread = await db
93
- .query("threads")
94
- .withIndex("by_capture_storage", (q) => q.eq("capture.storageId", fileId as Id<"_storage">))
95
- .first();
96
- return thread === null ? null : threadRecord(thread);
97
- },
98
- recent: async (projectId, limit) =>
99
- (
100
- await db
101
- .query("threads")
102
- .withIndex("by_project_activity", (q) => q.eq("projectId", projectId as Id<"projects">))
103
- .order("desc")
104
- .filter((q) => q.neq(q.field("status"), "deleted"))
105
- .take(limit)
106
- ).map(threadRecord),
107
- },
108
- messages: {
109
- get: async (id) => await db.get(id as Id<"messages">),
110
- insert: async (message) =>
111
- await writer().insert("messages", {
112
- threadId: message.threadId as Id<"threads">,
113
- authorId: message.authorId as Id<"users">,
114
- body: message.body,
115
- createdAt: message.createdAt,
116
- editedAt: message.editedAt,
117
- revision: message.revision,
118
- ...(message.mentions === undefined
119
- ? {}
120
- : { mentions: message.mentions.map((mention) => ({ userId: mention.userId as Id<"users">, label: mention.label })) }),
121
- ...(message.projectId === undefined ? {} : { projectId: message.projectId as Id<"projects"> }),
122
- ...(message.hashtags === undefined ? {} : { hashtags: message.hashtags }),
123
- }),
124
- patch: async (id, changes) => await writer().patch(id as Id<"messages">, defined(changes) as Partial<Doc<"messages">>),
125
- list: async (threadId, request) =>
126
- page(
127
- await db
128
- .query("messages")
129
- .withIndex("by_thread", (q) => q.eq("threadId", threadId as Id<"threads">))
130
- .paginate(bounded(request)),
131
- (message) => message,
132
- ),
133
- first: async (threadId) =>
134
- await db
135
- .query("messages")
136
- .withIndex("by_thread", (q) => q.eq("threadId", threadId as Id<"threads">))
137
- .first(),
138
- search: async (projectId, terms, limit) => {
139
- const text = terms.map((term) => term.trim()).filter(Boolean).slice(0, 16).join(" ");
140
- if (text === "") return [];
141
- return await db
142
- .query("messages")
143
- .withSearchIndex("search_body", (q) => q.search("body", text).eq("projectId", projectId as Id<"projects">))
144
- .take(limit);
145
- },
146
- },
147
- tags: {
148
- find: async (projectId, key) =>
149
- await db
150
- .query("projectTags")
151
- .withIndex("by_project_key", (q) => q.eq("projectId", projectId as Id<"projects">).eq("key", key))
152
- .unique(),
153
- get: async (id) => {
154
- const tagId = db.normalizeId("projectTags", id);
155
- return tagId === null ? null : await db.get(tagId);
156
- },
157
- insert: async (tag) =>
158
- await writer().insert("projectTags", {
159
- ...tag,
160
- projectId: tag.projectId as Id<"projects">,
161
- groupIds: tag.groupIds as Id<"tagGroups">[],
162
- }),
163
- patch: async (id, changes) =>
164
- await writer().patch(id as Id<"projectTags">, defined(changes) as Partial<Doc<"projectTags">>),
165
- list: async (projectId, limit) =>
166
- await db
167
- .query("projectTags")
168
- .withIndex("by_project_used", (q) => q.eq("projectId", projectId as Id<"projects">))
169
- .order("desc")
170
- .take(limit),
171
- due: async (now, limit) =>
172
- await db
173
- .query("projectTags")
174
- .withIndex("by_due", (q) => q.eq("grouping", "pending").lte("nextAttemptAt", now))
175
- .take(limit),
176
- dueInProject: async (projectId, now, limit) =>
177
- await db
178
- .query("projectTags")
179
- .withIndex("by_project_grouping", (q) =>
180
- q.eq("projectId", projectId as Id<"projects">).eq("grouping", "pending").lte("nextAttemptAt", now),
181
- )
182
- .take(limit),
183
- inState: async (projectId, grouping, limit) =>
184
- await db
185
- .query("projectTags")
186
- .withIndex("by_project_grouping", (q) => q.eq("projectId", projectId as Id<"projects">).eq("grouping", grouping))
187
- .take(limit),
188
- },
189
- tagGroups: {
190
- get: async (id) => await db.get(id as Id<"tagGroups">),
191
- byName: async (projectId, nameKey) =>
192
- await db
193
- .query("tagGroups")
194
- .withIndex("by_project_name", (q) => q.eq("projectId", projectId as Id<"projects">).eq("nameKey", nameKey))
195
- .unique(),
196
- list: async (projectId, limit) =>
197
- await db
198
- .query("tagGroups")
199
- .withIndex("by_project_name", (q) => q.eq("projectId", projectId as Id<"projects">))
200
- .take(limit),
201
- insert: async (group) => await writer().insert("tagGroups", { ...group, projectId: group.projectId as Id<"projects"> }),
202
- patch: async (id, changes) => await writer().patch(id as Id<"tagGroups">, defined(changes)),
203
- delete: async (id) => await writer().delete(id as Id<"tagGroups">),
204
- },
205
- threadTags: {
206
- forThread: async (threadId) =>
207
- await db
208
- .query("threadTags")
209
- .withIndex("by_thread", (q) => q.eq("threadId", threadId as Id<"threads">))
210
- .collect(),
211
- insert: async (row) =>
212
- await writer().insert("threadTags", {
213
- projectId: row.projectId as Id<"projects">,
214
- threadId: row.threadId as Id<"threads">,
215
- key: row.key,
216
- }),
217
- delete: async (id) => await writer().delete(id as Id<"threadTags">),
218
- byKey: async (projectId, key, limit) =>
219
- await db
220
- .query("threadTags")
221
- .withIndex("by_project_key", (q) => q.eq("projectId", projectId as Id<"projects">).eq("key", key))
222
- .order("desc")
223
- .take(limit),
224
- },
225
- aiSettings: {
226
- find: async (projectId) =>
227
- await db
228
- .query("aiSettings")
229
- .withIndex("by_project", (q) => q.eq("projectId", projectId as Id<"projects">))
230
- .unique(),
231
- insert: async (settings) => await writer().insert("aiSettings", { ...settings, projectId: settings.projectId as Id<"projects"> }),
232
- patch: async (id, changes) => {
233
- // `null` clears an optional field; Convex removes fields patched to undefined.
234
- const fields = Object.fromEntries(
235
- Object.entries(changes)
236
- .filter(([, value]) => value !== undefined)
237
- .map(([key, value]) => [key, value === null ? undefined : value]),
238
- );
239
- await writer().patch(id as Id<"aiSettings">, fields as Partial<Doc<"aiSettings">>);
240
- },
241
- },
242
- rateLimits: {
243
- hit: async (key, limit, windowMs, now) => {
244
- const row = await db
245
- .query("aiRateLimits")
246
- .withIndex("by_key", (q) => q.eq("key", key))
247
- .unique();
248
- if (row !== null && row.expiresAt > now && row.count >= limit) return false;
249
- if (row === null) await writer().insert("aiRateLimits", { key, count: 1, expiresAt: now + windowMs });
250
- else if (row.expiresAt <= now) await writer().patch(row._id, { count: 1, expiresAt: now + windowMs });
251
- else await writer().patch(row._id, { count: row.count + 1 });
252
- return true;
253
- },
254
- },
255
- reactions: {
256
- find: async (messageId, userId, emoji) =>
257
- await db
258
- .query("reactions")
259
- .withIndex("by_message_user_emoji", (q) =>
260
- q.eq("messageId", messageId as Id<"messages">).eq("userId", userId as Id<"users">).eq("emoji", emoji),
261
- )
262
- .unique(),
263
- insert: async (reaction) =>
264
- await writer().insert("reactions", {
265
- threadId: reaction.threadId as Id<"threads">,
266
- messageId: reaction.messageId as Id<"messages">,
267
- userId: reaction.userId as Id<"users">,
268
- emoji: reaction.emoji,
269
- }),
270
- delete: async (id) => await writer().delete(id as Id<"reactions">),
271
- list: async (threadId, request) =>
272
- page(
273
- await db
274
- .query("reactions")
275
- .withIndex("by_thread", (q) => q.eq("threadId", threadId as Id<"threads">))
276
- .paginate(bounded(request)),
277
- (reaction) => reaction,
278
- ),
279
- },
280
- readStates: {
281
- find: async (userId, threadId) =>
282
- await db
283
- .query("readStates")
284
- .withIndex("by_user_thread", (q) => q.eq("userId", userId as Id<"users">).eq("threadId", threadId as Id<"threads">))
285
- .unique(),
286
- insert: async (state) =>
287
- await writer().insert("readStates", {
288
- ...state,
289
- userId: state.userId as Id<"users">,
290
- threadId: state.threadId as Id<"threads">,
291
- }),
292
- patch: async (id, changes) => await writer().patch(id as Id<"readStates">, defined(changes) as Partial<Doc<"readStates">>),
293
- },
294
- participants: {
295
- find: async (projectId, userId) =>
296
- await db
297
- .query("participants")
298
- .withIndex("by_project_user", (q) => q.eq("projectId", projectId as Id<"projects">).eq("userId", userId as Id<"users">))
299
- .unique(),
300
- insert: async (participant) =>
301
- await writer().insert("participants", {
302
- projectId: participant.projectId as Id<"projects">,
303
- userId: participant.userId as Id<"users">,
304
- lastActiveAt: participant.lastActiveAt,
305
- }),
306
- patch: async (id, changes) => await writer().patch(id as Id<"participants">, defined(changes)),
307
- recent: async (projectId, limit) =>
308
- await db
309
- .query("participants")
310
- .withIndex("by_project_activity", (q) => q.eq("projectId", projectId as Id<"projects">))
311
- .order("desc")
312
- .take(limit),
313
- },
314
- deliveries: {
315
- get: async (id) => await db.get(id as Id<"deliveries">),
316
- insert: async (delivery) =>
317
- await writer().insert("deliveries", {
318
- ...delivery,
319
- recipientId: delivery.recipientId as Id<"users">,
320
- projectId: delivery.projectId as Id<"projects">,
321
- threadId: delivery.threadId as Id<"threads">,
322
- payload: delivery.payload === undefined ? undefined : { ...delivery.payload, fileId: delivery.payload.fileId as Id<"_storage"> },
323
- }),
324
- patch: async (id, changes) =>
325
- await writer().patch(id as Id<"deliveries">, defined(changes) as Partial<Doc<"deliveries">>),
326
- gathering: async (recipientId, threadId) =>
327
- await db
328
- .query("deliveries")
329
- .withIndex("by_recipient_thread", (q) =>
330
- q
331
- .eq("recipientId", recipientId as Id<"users">)
332
- .eq("threadId", threadId as Id<"threads">)
333
- .eq("status", "pending")
334
- .eq("attempts", 0),
335
- )
336
- .order("desc")
337
- .first(),
338
- due: async (now, limit) => {
339
- const pending = await db
340
- .query("deliveries")
341
- .withIndex("by_status_due", (q) => q.eq("status", "pending").lte("dueAt", now))
342
- .take(limit);
343
- const stalled = await db
344
- .query("deliveries")
345
- .withIndex("by_status_lease", (q) => q.eq("status", "sending").lte("leaseUntil", now))
346
- .take(limit);
347
- return [...pending, ...stalled].sort((a, b) => a.dueAt - b.dueAt).slice(0, limit);
348
- },
349
- finishedBefore: async (before, limit) =>
350
- await db
351
- .query("deliveries")
352
- .withIndex("by_finished", (q) => q.gt("finishedAt", 0).lt("finishedAt", before))
353
- .take(limit),
354
- delete: async (id) => await writer().delete(id as Id<"deliveries">),
355
- },
356
- notifications: {
357
- insert: async (notification) =>
358
- await writer().insert("notifications", {
359
- deliveryId: notification.deliveryId as Id<"deliveries">,
360
- recipientId: notification.recipientId as Id<"users">,
361
- messageId: notification.messageId as Id<"messages">,
362
- authorId: notification.authorId as Id<"users">,
363
- createdAt: notification.createdAt,
364
- }),
365
- forDelivery: async (deliveryId, limit) =>
366
- await db
367
- .query("notifications")
368
- .withIndex("by_delivery", (q) => q.eq("deliveryId", deliveryId as Id<"deliveries">))
369
- .take(limit),
370
- delete: async (id) => await writer().delete(id as Id<"notifications">),
371
- },
372
- preferences: {
373
- find: async (userId) =>
374
- await db
375
- .query("preferences")
376
- .withIndex("by_user", (q) => q.eq("userId", userId as Id<"users">))
377
- .unique(),
378
- insert: async (preference) =>
379
- await writer().insert("preferences", {
380
- userId: preference.userId as Id<"users">,
381
- mentionEmails: preference.mentionEmails,
382
- mutedProjects: preference.mutedProjects as Id<"projects">[],
383
- }),
384
- patch: async (id, changes) =>
385
- await writer().patch(id as Id<"preferences">, defined(changes) as Partial<Doc<"preferences">>),
386
- },
387
- limits: {
388
- // Only Critiqs Cloud limits usage; a team's own deployment leaves this unset.
389
- enabled: () => process.env.CRITIQS_PLANS === "enabled",
390
- plan: async (name) => {
391
- const plan = await db.query("plans").withIndex("by_name", (q) => q.eq("name", name)).unique();
392
- return plan === null ? null : { name: plan.name, label: plan.label, limits: plan.limits };
393
- },
394
- },
395
- usage: {
396
- find: async (key) => await db.query("usage").withIndex("by_key", (q) => q.eq("key", key)).unique(),
397
- insert: async (usage) => await writer().insert("usage", usage),
398
- patch: async (id, changes) => await writer().patch(id as Id<"usage">, changes),
399
- isMember: async (key, member) =>
400
- (await db
401
- .query("usageMembers")
402
- .withIndex("by_key_member", (q) => q.eq("key", key).eq("member", member))
403
- .unique()) !== null,
404
- addMember: async (key, member) => {
405
- await writer().insert("usageMembers", { key, member });
406
- },
407
- },
408
- files: {
409
- info: async (fileId) => {
410
- const id = db.normalizeId("captureFiles", fileId);
411
- if (id !== null) {
412
- const file = await db.get(id);
413
- return file === null || (file.status !== "ready" && file.status !== "attached") || file.size === undefined
414
- ? null
415
- : { contentType: file.contentType, size: file.size, createdAt: file.createdAt };
416
- }
417
- const file = await db.system.get(fileId as Id<"_storage">);
418
- return file === null
419
- ? null
420
- : { ...(file.contentType === undefined ? {} : { contentType: file.contentType }), size: file.size, createdAt: file._creationTime };
421
- },
422
- delete: async (fileId) => {
423
- writer();
424
- if ((await db.system.get(fileId as Id<"_storage">)) !== null) await (ctx as MutationCtx).storage.delete(fileId as Id<"_storage">);
425
- },
426
- },
427
- };
428
- }
429
-
430
- /** The signed-in reviewer as Critiqs's rules see them, from Convex's view of the token. */
431
- export async function identityOf(ctx: { auth: QueryCtx["auth"] }): Promise<Identity | null> {
432
- const identity: UserIdentity | null = await ctx.auth.getUserIdentity();
433
- if (identity === null) return null;
434
- // Convex keeps custom JWT claims under their own names (`email_verified`,
435
- // `picture`) rather than the OpenID field names it uses for other providers.
436
- const picture = identity.pictureUrl ?? identity.picture;
437
- const version = identity.profile_version;
438
- return {
439
- tokenIdentifier: identity.tokenIdentifier,
440
- name: identity.name ?? null,
441
- email: identity.email ?? null,
442
- emailVerified: identity.emailVerified === true || identity.email_verified === true,
443
- pictureUrl: typeof picture === "string" ? picture : null,
444
- profileVersion: typeof version === "number" ? version : null,
445
- };
446
- }
447
-
448
- /** Runs one of Critiqs's operations, reporting refusals as Convex errors the interface understands. */
449
- export async function run<T>(operation: () => Promise<T>): Promise<T> {
450
- try {
451
- return await operation();
452
- } catch (error) {
453
- if (error instanceof CritiqsError) throw new ConvexError({ code: error.code, message: error.message });
454
- throw error;
455
- }
456
- }
457
-
458
- /**
459
- * Changes without fields set to `undefined`. Convex would remove such a field;
460
- * Critiqs's stores treat it as unchanged, as SQLite does.
461
- */
462
- function defined<T extends object>(changes: T): T {
463
- return Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined)) as T;
464
- }
465
-
466
- /** Convex reads a bounded number of rows and bytes per page, besides the item count. */
467
- function bounded(request: PageRequest): PaginationOptions {
468
- return { ...request, maximumRowsRead: PAGE_SIZE * 2, maximumBytesRead: 512_000 };
469
- }
470
-
471
- function threadRecord(thread: Doc<"threads">): ThreadRecord {
472
- const { _creationTime: _created, capture, ...rest } = thread;
473
- return { ...rest, capture: storedCapture(capture) };
474
- }
475
-
476
- function storedCapture(capture: Doc<"threads">["capture"]): StoredCapture {
477
- switch (capture.status) {
478
- case "captured":
479
- return { status: "captured", fileId: capture.storageId };
480
- case "supplied":
481
- return { status: "supplied", fileId: capture.storageId, failureReason: capture.failureReason };
482
- case "failed":
483
- return capture;
484
- }
485
- }
486
-
487
- /** Convex's shape of a thread or of changes to one. */
488
- function threadDoc<T extends Partial<Omit<ThreadRecord, "_id">>>(thread: T) {
489
- const { capture, projectId, createdBy, statusChangedBy, reattachment, ...rest } = thread;
490
- return {
491
- ...rest,
492
- ...(projectId === undefined ? {} : { projectId: projectId as Id<"projects"> }),
493
- ...(createdBy === undefined ? {} : { createdBy: createdBy as Id<"users"> }),
494
- ...(statusChangedBy === undefined ? {} : { statusChangedBy: statusChangedBy as Id<"users"> }),
495
- ...(reattachment === undefined
496
- ? {}
497
- : { reattachment: { ...reattachment, reattachedBy: reattachment.reattachedBy as Id<"users"> } }),
498
- ...(capture === undefined
499
- ? {}
500
- : {
501
- capture:
502
- capture.status === "failed"
503
- ? capture
504
- : capture.status === "captured"
505
- ? { status: "captured" as const, storageId: capture.fileId as Id<"_storage"> }
506
- : { status: "supplied" as const, storageId: capture.fileId as Id<"_storage">, failureReason: capture.failureReason },
507
- }),
508
- } as Omit<Doc<"threads">, "_id" | "_creationTime">;
509
- }
@@ -1,101 +0,0 @@
1
- // Critiqs's own sign-in tokens. Once a reviewer proves they control their email
2
- // address with a one-time code, Critiqs issues a short-lived ES256 token that names the reviewer, their verified
3
- // email, and the site they allowed. Every Critiqs deployment trusts this issuer
4
- // (see auth.config.ts), so own deployments need no sign-in setup of their own.
5
-
6
- /** Audience every Critiqs token carries; deployments reject tokens without it. */
7
- export const TOKEN_AUDIENCE = "critiqs";
8
- export const ACCESS_TOKEN_SECONDS = 15 * 60;
9
- export const SESSION_DAYS = 30;
10
- /** A session ends this long after sign-in, however often it is used. */
11
- export const SESSION_MAX_DAYS = 90;
12
-
13
- export interface ReviewerProfile {
14
- /** The reviewer's permanent Critiqs ID, independent of how they signed in. */
15
- subject: string;
16
- name: string;
17
- email: string;
18
- pictureUrl: string | null;
19
- /** Increases with each display name change, so deployments ignore names from older tokens. */
20
- profileVersion?: number;
21
- }
22
-
23
- interface SigningKey {
24
- key: CryptoKey;
25
- publicJwk: JsonWebKey & { kid: string };
26
- }
27
-
28
- let cachedKey: { source: string; signing: Promise<SigningKey> } | null = null;
29
-
30
- /** Reads the private signing key (a P-256 JWK) from `CRITIQS_AUTH_PRIVATE_KEY`. */
31
- export function signingKey(): Promise<SigningKey> {
32
- const source = process.env.CRITIQS_AUTH_PRIVATE_KEY;
33
- if (source === undefined || source === "") throw new Error("CRITIQS_AUTH_PRIVATE_KEY is not set.");
34
- if (cachedKey?.source !== source) cachedKey = { source, signing: importSigningKey(source) };
35
- return cachedKey.signing;
36
- }
37
-
38
- async function importSigningKey(source: string): Promise<SigningKey> {
39
- const jwk = JSON.parse(source) as JsonWebKey & { kid?: string };
40
- const key = await crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
41
- const { kty, crv, x, y } = jwk;
42
- const kid = jwk.kid ?? (await thumbprint({ crv, kty, x, y }));
43
- return { key, publicJwk: { kty, crv, x, y, kid, alg: "ES256", use: "sig" } };
44
- }
45
-
46
- /** RFC 7638 key thumbprint, used as the key ID when none is configured. */
47
- async function thumbprint(members: Record<string, unknown>): Promise<string> {
48
- const canonical = JSON.stringify(members, Object.keys(members).sort());
49
- return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical))));
50
- }
51
-
52
- /**
53
- * Issues an access token for one reviewer and one allowed site. It never
54
- * outlives `notAfter`, the end of the session it comes from.
55
- */
56
- export async function issueAccessToken(
57
- issuer: string,
58
- profile: ReviewerProfile,
59
- origin: string,
60
- now = Date.now(),
61
- notAfter = Number.POSITIVE_INFINITY,
62
- ) {
63
- const { key, publicJwk } = await signingKey();
64
- const issuedAt = Math.floor(now / 1000);
65
- const expiresAt = Math.min(issuedAt + ACCESS_TOKEN_SECONDS, Math.floor(notAfter / 1000));
66
- const header = { alg: "ES256", typ: "JWT", kid: publicJwk.kid };
67
- const claims = {
68
- iss: issuer,
69
- aud: TOKEN_AUDIENCE,
70
- sub: profile.subject,
71
- iat: issuedAt,
72
- exp: expiresAt,
73
- name: profile.name,
74
- email: profile.email,
75
- email_verified: true,
76
- picture: profile.pictureUrl ?? undefined,
77
- profile_version: profile.profileVersion,
78
- origin,
79
- };
80
- const encoder = new TextEncoder();
81
- const input = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(encoder.encode(JSON.stringify(claims)))}`;
82
- // WebCrypto's ECDSA signature is the raw r||s form that JWS ES256 uses.
83
- const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, encoder.encode(input));
84
- return { accessToken: `${input}.${base64url(new Uint8Array(signature))}`, expiresAt: expiresAt * 1000 };
85
- }
86
-
87
- /** A random opaque secret, such as a refresh token. */
88
- export function randomSecret(bytes = 32): string {
89
- return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
90
- }
91
-
92
- /** Refresh tokens are stored only as hashes. */
93
- export async function hashSecret(secret: string): Promise<string> {
94
- return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))));
95
- }
96
-
97
- export function base64url(bytes: Uint8Array): string {
98
- let binary = "";
99
- for (const byte of bytes) binary += String.fromCharCode(byte);
100
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
101
- }
@@ -1,73 +0,0 @@
1
- import type { Anchor, TargetLocation } from "./vendor/critiqs_core.js";
2
- import { type Infer, v } from "convex/values";
3
-
4
- export const viewStateValidator = v.record(
5
- v.string(),
6
- v.union(v.string(), v.number(), v.boolean(), v.null()),
7
- );
8
-
9
- const rectValidator = v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() });
10
-
11
- const targetValidator = v.object({
12
- purposeId: v.union(v.string(), v.null()),
13
- recordKey: v.union(v.string(), v.null()),
14
- clues: v.object({
15
- tagName: v.string(),
16
- role: v.union(v.string(), v.null()),
17
- label: v.union(v.string(), v.null()),
18
- path: v.string(),
19
- }),
20
- });
21
-
22
- const scopeValidator = v.union(v.literal("shared"), v.literal("record"));
23
-
24
- /** Where a target is: screen, view state, element, and scope. */
25
- export const locationValidator = v.object({
26
- screen: v.string(),
27
- viewState: viewStateValidator,
28
- target: targetValidator,
29
- scope: scopeValidator,
30
- });
31
-
32
- export const anchorValidator = v.object({
33
- screen: v.string(),
34
- viewState: viewStateValidator,
35
- target: targetValidator,
36
- scope: scopeValidator,
37
- evidence: v.object({
38
- url: v.string(),
39
- viewport: v.object({ width: v.number(), height: v.number() }),
40
- marker: v.union(rectValidator, v.null()),
41
- capturedAt: v.number(),
42
- revision: v.union(v.string(), v.null()),
43
- persona: v.union(v.string(), v.null()),
44
- userAgent: v.union(v.string(), v.null()),
45
- }),
46
- });
47
-
48
- // Keep the stored anchor and location identical to @critiqs/core's types.
49
- type StoredAnchor = Infer<typeof anchorValidator>;
50
- export const anchorTypesMatch: [StoredAnchor, Anchor] extends [Anchor, StoredAnchor] ? true : never = true;
51
- type StoredLocation = Infer<typeof locationValidator>;
52
- export const locationTypesMatch: [StoredLocation, TargetLocation] extends [TargetLocation, StoredLocation]
53
- ? true
54
- : never = true;
55
-
56
- /** Original image state (F6). A failed capture still saves the comment. */
57
- export const captureFileValidator = v.union(v.id("_storage"), v.id("captureFiles"));
58
- export const captureValidator = v.union(
59
- v.object({ status: v.literal("captured"), storageId: captureFileValidator }),
60
- v.object({ status: v.literal("supplied"), storageId: captureFileValidator, failureReason: v.string() }),
61
- v.object({ status: v.literal("failed"), failureReason: v.string() }),
62
- );
63
-
64
- export const revisionValidator = v.union(v.string(), v.null());
65
-
66
- /** A reviewer verified by the sign-in provider. */
67
- export const profileValidator = v.object({
68
- subject: v.string(),
69
- name: v.string(),
70
- email: v.string(),
71
- pictureUrl: v.union(v.string(), v.null()),
72
- profileVersion: v.optional(v.number()),
73
- });