critiqs-react 0.3.0 → 0.4.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/AGENT_SETUP.md +198 -66
- package/README.md +214 -31
- package/bin/critiqs.mjs +3 -1
- package/dist/index.js +16877 -4770
- package/dist/server/index.d.ts +1 -87
- package/dist/server/index.js +1 -4889
- package/package.json +6 -5
- package/bin/cli.d.mts +0 -21
- package/bin/cli.mjs +0 -293
- package/bin/env.d.mts +0 -41
- package/bin/env.mjs +0 -384
- package/bin/init.d.mts +0 -126
- package/bin/init.mjs +0 -965
- package/bin/mcp.d.mts +0 -20
- package/bin/mcp.mjs +0 -314
- package/bin/setup.d.mts +0 -183
- package/bin/setup.mjs +0 -1054
- package/dist/backend/convex/_generated/api.d.ts +0 -95
- package/dist/backend/convex/_generated/api.js +0 -23
- package/dist/backend/convex/_generated/dataModel.d.ts +0 -60
- package/dist/backend/convex/_generated/server.d.ts +0 -162
- package/dist/backend/convex/_generated/server.js +0 -101
- package/dist/backend/convex/ai.ts +0 -93
- package/dist/backend/convex/aiSettings.ts +0 -43
- package/dist/backend/convex/auth.config.ts +0 -18
- package/dist/backend/convex/captureHttp.ts +0 -96
- package/dist/backend/convex/captures.ts +0 -167
- package/dist/backend/convex/crons.ts +0 -14
- package/dist/backend/convex/deviceSignIn.ts +0 -151
- package/dist/backend/convex/grouping.ts +0 -41
- package/dist/backend/convex/http.ts +0 -724
- package/dist/backend/convex/lib/ai.ts +0 -6
- package/dist/backend/convex/lib/links.ts +0 -12
- package/dist/backend/convex/lib/pages.ts +0 -207
- package/dist/backend/convex/lib/r2.ts +0 -75
- package/dist/backend/convex/lib/store.ts +0 -509
- package/dist/backend/convex/lib/tokens.ts +0 -101
- package/dist/backend/convex/lib/validators.ts +0 -73
- package/dist/backend/convex/lib/vendor/aws4fetch.js +0 -289
- package/dist/backend/convex/lib/vendor/critiqs_ai.js +0 -49081
- package/dist/backend/convex/lib/vendor/critiqs_core.js +0 -385
- package/dist/backend/convex/lib/vendor/critiqs_server.js +0 -3108
- package/dist/backend/convex/notificationEmails.ts +0 -61
- package/dist/backend/convex/notifications.ts +0 -182
- package/dist/backend/convex/plans.ts +0 -67
- package/dist/backend/convex/projects.ts +0 -46
- package/dist/backend/convex/schema.ts +0 -343
- package/dist/backend/convex/search.ts +0 -26
- package/dist/backend/convex/signIn.ts +0 -368
- package/dist/backend/convex/tags.ts +0 -68
- package/dist/backend/convex/threads.ts +0 -146
- package/dist/backend/convex/users.ts +0 -13
- package/dist/server/chunks/driver-n9zpr0k3.js +0 -21
- package/dist/server/chunks/index-9bg7tmnq.js +0 -522
- package/dist/server/chunks/index-askcfn7t.js +0 -148
- package/dist/server/chunks/providers-rv184xvj.js +0 -48444
- package/dist/server/chunks/token-kzddms7r.js +0 -63
- package/dist/server/chunks/token-util-k8bee1wc.js +0 -4
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { IMAGE_TYPES, MAX_IMAGE_BYTES } from "./lib/vendor/critiqs_server.js";
|
|
2
|
-
import { ConvexError } from "convex/values";
|
|
3
|
-
import { internal } from "./_generated/api";
|
|
4
|
-
import type { Id } from "./_generated/dataModel";
|
|
5
|
-
import { httpAction } from "./_generated/server";
|
|
6
|
-
import { r2Config, r2Storage } from "./lib/r2";
|
|
7
|
-
|
|
8
|
-
// Bearer-token requests, without cookies, can come from any host prototype.
|
|
9
|
-
export const CAPTURE_CORS = {
|
|
10
|
-
"Access-Control-Allow-Origin": "*",
|
|
11
|
-
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
12
|
-
"Access-Control-Allow-Headers": "Authorization, Content-Type",
|
|
13
|
-
Vary: "Authorization",
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
function failure(error: unknown) {
|
|
17
|
-
if (error instanceof ConvexError) {
|
|
18
|
-
const data = error.data as { code: string; message: string };
|
|
19
|
-
const status = ({ unauthenticated: 401, "email-unverified": 403, forbidden: 403, "not-found": 404, unavailable: 404, "too-large": 413, invalid: 400, "plan-limit": 429 } as Record<string, number>)[data.code] ?? 400;
|
|
20
|
-
return new Response(data.message, { status, headers: CAPTURE_CORS });
|
|
21
|
-
}
|
|
22
|
-
// Provider responses and request signatures must never appear in errors.
|
|
23
|
-
return new Response("Screenshot storage is unavailable. Try again shortly.", { status: 503, headers: CAPTURE_CORS });
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/** Bounded streaming read: Content-Length is only an early check, never trusted. */
|
|
27
|
-
export async function readCaptureBody(request: Request): Promise<ArrayBuffer> {
|
|
28
|
-
const length = request.headers.get("Content-Length");
|
|
29
|
-
if (length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_IMAGE_BYTES)) {
|
|
30
|
-
throw new ConvexError({ code: "too-large", message: "Images are limited to 10 MB." });
|
|
31
|
-
}
|
|
32
|
-
const reader = request.body?.getReader();
|
|
33
|
-
if (!reader) throw new ConvexError({ code: "invalid", message: "The image is empty." });
|
|
34
|
-
const chunks: Uint8Array[] = [];
|
|
35
|
-
let size = 0;
|
|
36
|
-
while (true) {
|
|
37
|
-
const { done, value } = await reader.read();
|
|
38
|
-
if (done) break;
|
|
39
|
-
size += value.byteLength;
|
|
40
|
-
if (size > MAX_IMAGE_BYTES) {
|
|
41
|
-
await reader.cancel();
|
|
42
|
-
throw new ConvexError({ code: "too-large", message: "Images are limited to 10 MB." });
|
|
43
|
-
}
|
|
44
|
-
chunks.push(value);
|
|
45
|
-
}
|
|
46
|
-
if (size === 0) throw new ConvexError({ code: "invalid", message: "The image is empty." });
|
|
47
|
-
const body = new Uint8Array(size);
|
|
48
|
-
let offset = 0;
|
|
49
|
-
for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; }
|
|
50
|
-
return body.buffer;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export const uploadCapture = httpAction(async (ctx, request): Promise<Response> => {
|
|
54
|
-
try {
|
|
55
|
-
const fileId = new URL(request.url).searchParams.get("fileId");
|
|
56
|
-
if (fileId === null) throw new ConvexError({ code: "invalid", message: "Missing fileId." });
|
|
57
|
-
const contentType = (request.headers.get("Content-Type") ?? "").split(";")[0]!.trim().toLowerCase();
|
|
58
|
-
const file = await ctx.runMutation(internal.captures.beginUpload, { fileId, contentType });
|
|
59
|
-
const body = await readCaptureBody(request);
|
|
60
|
-
await r2Storage(r2Config()).put(file, body, contentType);
|
|
61
|
-
await ctx.runMutation(internal.captures.finishUpload, { fileId: file._id, size: body.byteLength });
|
|
62
|
-
return Response.json({ storageId: file._id }, { headers: { ...CAPTURE_CORS, "Cache-Control": "no-store" } });
|
|
63
|
-
} catch (error) {
|
|
64
|
-
// The reservation remains discoverable for cleanup even if PUT succeeded but finalization failed.
|
|
65
|
-
return failure(error);
|
|
66
|
-
}
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
export const downloadCapture = httpAction(async (ctx, request): Promise<Response> => {
|
|
70
|
-
try {
|
|
71
|
-
const threadId = new URL(request.url).searchParams.get("threadId");
|
|
72
|
-
if (threadId === null) return new Response("Missing threadId", { status: 400, headers: CAPTURE_CORS });
|
|
73
|
-
const fileId = await ctx.runQuery(internal.captures.authorizedCapture, { threadId });
|
|
74
|
-
if (fileId === null) return new Response("No capture", { status: 404, headers: CAPTURE_CORS });
|
|
75
|
-
const location = await ctx.runQuery(internal.captures.fileLocation, { fileId: fileId as Id<"_storage"> | Id<"captureFiles"> });
|
|
76
|
-
const headers = {
|
|
77
|
-
...CAPTURE_CORS,
|
|
78
|
-
"X-Content-Type-Options": "nosniff",
|
|
79
|
-
"Content-Security-Policy": "default-src 'none'; sandbox",
|
|
80
|
-
"Cache-Control": "private, no-store",
|
|
81
|
-
};
|
|
82
|
-
if (location !== null) {
|
|
83
|
-
if (location.status !== "attached") return new Response("No capture", { status: 404, headers });
|
|
84
|
-
const response = await r2Storage(r2Config()).get(location);
|
|
85
|
-
return response === null
|
|
86
|
-
? new Response("No capture", { status: 404, headers })
|
|
87
|
-
: new Response(response.body, { headers: { ...headers, "Content-Type": location.contentType ?? "application/octet-stream" } });
|
|
88
|
-
}
|
|
89
|
-
const image = await ctx.storage.get(fileId as Id<"_storage">);
|
|
90
|
-
return image === null
|
|
91
|
-
? new Response("No capture", { status: 404, headers })
|
|
92
|
-
: new Response(image, { headers: { ...headers, "Content-Type": IMAGE_TYPES.includes(image.type) ? image.type : "application/octet-stream" } });
|
|
93
|
-
} catch (error) {
|
|
94
|
-
return failure(error);
|
|
95
|
-
}
|
|
96
|
-
});
|
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { IMAGE_TYPES, MAX_IMAGE_BYTES, operations, UPLOAD_MINUTES, type Identity } from "./lib/vendor/critiqs_server.js";
|
|
2
|
-
import { ConvexError, v } from "convex/values";
|
|
3
|
-
import { internal } from "./_generated/api";
|
|
4
|
-
import type { Doc, Id } from "./_generated/dataModel";
|
|
5
|
-
import { internalAction, internalMutation, internalQuery, mutation, type MutationCtx } from "./_generated/server";
|
|
6
|
-
import { captureProvider, r2Config, r2Storage } from "./lib/r2";
|
|
7
|
-
import { convexStore, identityOf, run } from "./lib/store";
|
|
8
|
-
import { captureFileValidator } from "./lib/validators";
|
|
9
|
-
|
|
10
|
-
const UPLOAD_MS = UPLOAD_MINUTES * 60_000;
|
|
11
|
-
const RETRY_MS = 10 * 60_000;
|
|
12
|
-
const TOMBSTONE_MS = 24 * 60 * 60_000;
|
|
13
|
-
|
|
14
|
-
function invalid(message: string): never {
|
|
15
|
-
throw new ConvexError({ code: "invalid", message });
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** A fresh one-use reservation, or the existing native Convex upload URL. */
|
|
19
|
-
export const generateUploadUrl = mutation({
|
|
20
|
-
args: { projectId: v.id("projects") },
|
|
21
|
-
handler: async (ctx, args): Promise<string> => run(async () => {
|
|
22
|
-
const store = convexStore(ctx);
|
|
23
|
-
const identity = await identityOf(ctx);
|
|
24
|
-
await operations.authorizeUpload(store, identity, args);
|
|
25
|
-
if (captureProvider() === "convex") return await ctx.storage.generateUploadUrl();
|
|
26
|
-
const config = r2Config();
|
|
27
|
-
const user = await operations.requireUser(store, identity);
|
|
28
|
-
let pending = 0;
|
|
29
|
-
for (const status of ["reserved", "uploading", "ready"] as const) {
|
|
30
|
-
pending += (await ctx.db.query("captureFiles")
|
|
31
|
-
.withIndex("by_uploader_status", q => q.eq("uploadedBy", user._id as Id<"users">).eq("status", status))
|
|
32
|
-
.take(20)).length;
|
|
33
|
-
}
|
|
34
|
-
if (pending >= 20) invalid("Too many unfinished screenshots. Try again after unused uploads expire.");
|
|
35
|
-
const site = process.env.CONVEX_SITE_URL;
|
|
36
|
-
if (!site) throw new Error("CONVEX_SITE_URL is not configured.");
|
|
37
|
-
const now = Date.now();
|
|
38
|
-
const id = await ctx.db.insert("captureFiles", {
|
|
39
|
-
projectId: args.projectId, uploadedBy: user._id as Id<"users">,
|
|
40
|
-
accountId: config.accountId, bucket: config.bucket, key: "",
|
|
41
|
-
status: "reserved", createdAt: now, cleanupAt: now + UPLOAD_MS,
|
|
42
|
-
});
|
|
43
|
-
await ctx.db.patch(id, { key: `captures/${id}` });
|
|
44
|
-
return `${site.replace(/\/$/, "")}/capture/upload?fileId=${id}`;
|
|
45
|
-
}),
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
/** Atomically claims a reservation before any body is read or bytes are written. */
|
|
49
|
-
export const beginUpload = internalMutation({
|
|
50
|
-
args: { fileId: v.string(), contentType: v.string() },
|
|
51
|
-
handler: async (ctx, args): Promise<Doc<"captureFiles">> => run(async () => {
|
|
52
|
-
const identity = await identityOf(ctx);
|
|
53
|
-
const user = await operations.requireUser(convexStore(ctx), identity);
|
|
54
|
-
const id = ctx.db.normalizeId("captureFiles", args.fileId);
|
|
55
|
-
const file = id === null ? null : await ctx.db.get(id);
|
|
56
|
-
if (file === null || file.uploadedBy !== user._id) invalid("This upload is unavailable.");
|
|
57
|
-
if (file.status !== "reserved" || file.createdAt + UPLOAD_MS <= Date.now()) invalid("Start a new screenshot upload.");
|
|
58
|
-
if (!IMAGE_TYPES.includes(args.contentType)) invalid("Captures and screenshots must be PNG, JPEG, WebP, or GIF images.");
|
|
59
|
-
await operations.authorizeUpload(convexStore(ctx), identity, { projectId: file.projectId });
|
|
60
|
-
const config = r2Config();
|
|
61
|
-
if (captureProvider() !== "r2" || file.accountId !== config.accountId || file.bucket !== config.bucket) {
|
|
62
|
-
invalid("Screenshot storage changed. Start a new upload.");
|
|
63
|
-
}
|
|
64
|
-
await ctx.db.patch(file._id, { status: "uploading", contentType: args.contentType });
|
|
65
|
-
return file;
|
|
66
|
-
}),
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
/** Metadata becomes attachable only after the server's R2 PUT has succeeded. */
|
|
70
|
-
export const finishUpload = internalMutation({
|
|
71
|
-
args: { fileId: v.id("captureFiles"), size: v.number() },
|
|
72
|
-
handler: async (ctx, args): Promise<void> => run(async () => {
|
|
73
|
-
const user = await operations.requireUser(convexStore(ctx), await identityOf(ctx));
|
|
74
|
-
const file = await ctx.db.get(args.fileId);
|
|
75
|
-
if (file === null || file.uploadedBy !== user._id || file.status !== "uploading" || file.createdAt + UPLOAD_MS <= Date.now()) {
|
|
76
|
-
invalid("This screenshot upload expired. Upload it again.");
|
|
77
|
-
}
|
|
78
|
-
if (!Number.isSafeInteger(args.size) || args.size <= 0 || args.size > MAX_IMAGE_BYTES) invalid("Images are limited to 10 MB.");
|
|
79
|
-
await ctx.db.patch(file._id, { status: "ready", size: args.size });
|
|
80
|
-
}),
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
/** Checks bindings in the same transaction as attachment, quota charging, and status change. */
|
|
84
|
-
export async function checkAttachment(ctx: MutationCtx, fileId: string, projectId: string, identity: Identity | null) {
|
|
85
|
-
const id = ctx.db.normalizeId("captureFiles", fileId);
|
|
86
|
-
if (id === null) return;
|
|
87
|
-
const user = await operations.requireUser(convexStore(ctx), identity);
|
|
88
|
-
const file = await ctx.db.get(id);
|
|
89
|
-
if (file?.status === "attached") invalid("This image already belongs to a thread.");
|
|
90
|
-
if (file === null || file.status !== "ready" || file.projectId !== projectId || file.uploadedBy !== user._id) {
|
|
91
|
-
invalid("This screenshot was not uploaded by you for this project.");
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
export async function markAttached(ctx: MutationCtx, fileId: string) {
|
|
96
|
-
const id = ctx.db.normalizeId("captureFiles", fileId);
|
|
97
|
-
if (id !== null) await ctx.db.patch(id, { status: "attached", cleanupAt: undefined });
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** Both legacy Convex IDs and R2 metadata IDs remain valid. */
|
|
101
|
-
export const authorizedCapture = internalQuery({
|
|
102
|
-
args: { threadId: v.string() },
|
|
103
|
-
handler: async (ctx, args) => run(async () =>
|
|
104
|
-
await operations.authorizedCapture(convexStore(ctx), await identityOf(ctx), args)),
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
export const fileLocation = internalQuery({
|
|
108
|
-
args: { fileId: captureFileValidator },
|
|
109
|
-
handler: async (ctx, { fileId }) => {
|
|
110
|
-
const id = ctx.db.normalizeId("captureFiles", fileId);
|
|
111
|
-
return id === null ? null : await ctx.db.get(id);
|
|
112
|
-
},
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
/** Claim deletion transactionally so attachment or finalization cannot race it. */
|
|
116
|
-
export const claimExpired = internalMutation({
|
|
117
|
-
args: {},
|
|
118
|
-
handler: async (ctx): Promise<Doc<"captureFiles">[]> => {
|
|
119
|
-
const now = Date.now();
|
|
120
|
-
const files = await ctx.db.query("captureFiles")
|
|
121
|
-
.withIndex("by_cleanup", q => q.gt("cleanupAt", 0).lte("cleanupAt", now)).take(40);
|
|
122
|
-
const claimed: Doc<"captureFiles">[] = [];
|
|
123
|
-
for (const file of files) {
|
|
124
|
-
const thread = await ctx.db.query("threads").withIndex("by_capture_storage", q => q.eq("capture.storageId", file._id)).first();
|
|
125
|
-
if (thread !== null || file.status === "attached") {
|
|
126
|
-
// Deleted threads retain their original evidence too.
|
|
127
|
-
await ctx.db.patch(file._id, { status: "attached", cleanupAt: undefined });
|
|
128
|
-
} else {
|
|
129
|
-
await ctx.db.patch(file._id, { status: "deleting", cleanupAt: now + RETRY_MS });
|
|
130
|
-
claimed.push(file);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return claimed;
|
|
134
|
-
},
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
export const deletedObject = internalMutation({
|
|
138
|
-
args: { fileId: v.id("captureFiles") },
|
|
139
|
-
handler: async (ctx, { fileId }) => {
|
|
140
|
-
const file = await ctx.db.get(fileId);
|
|
141
|
-
if (file?.status !== "deleting") return;
|
|
142
|
-
// Keep a tombstone and repeat deletion for a day, covering an uncertain/late PUT.
|
|
143
|
-
if (file.createdAt + TOMBSTONE_MS <= Date.now()) await ctx.db.delete(fileId);
|
|
144
|
-
else await ctx.db.patch(fileId, { cleanupAt: Date.now() + UPLOAD_MS });
|
|
145
|
-
},
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
export const cleanUp = internalAction({
|
|
149
|
-
args: {},
|
|
150
|
-
handler: async (ctx): Promise<void> => {
|
|
151
|
-
// Do not lose metadata when credentials are unavailable; report the failure to the scheduler.
|
|
152
|
-
if (captureProvider() === "convex" && !process.env.CRITIQS_R2_ACCOUNT_ID) return;
|
|
153
|
-
const storage = r2Storage(r2Config());
|
|
154
|
-
const files = await ctx.runMutation(internal.captures.claimExpired, {});
|
|
155
|
-
for (let offset = 0; offset < files.length; offset += 4) {
|
|
156
|
-
await Promise.all(files.slice(offset, offset + 4).map(async file => {
|
|
157
|
-
try {
|
|
158
|
-
await storage.remove(file);
|
|
159
|
-
await ctx.runMutation(internal.captures.deletedObject, { fileId: file._id });
|
|
160
|
-
} catch {
|
|
161
|
-
// The deleting row's lease expires and a later cron retries this exact object.
|
|
162
|
-
}
|
|
163
|
-
}));
|
|
164
|
-
}
|
|
165
|
-
if (files.length === 40) await ctx.scheduler.runAfter(0, internal.captures.cleanUp, {});
|
|
166
|
-
},
|
|
167
|
-
});
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { cronJobs } from "convex/server";
|
|
2
|
-
import { internal } from "./_generated/api";
|
|
3
|
-
|
|
4
|
-
const crons = cronJobs();
|
|
5
|
-
|
|
6
|
-
crons.interval("remove expired sign-in attempts and sessions", { hours: 1 }, internal.signIn.cleanUp, {});
|
|
7
|
-
|
|
8
|
-
crons.interval("send mention emails", { minutes: 1 }, internal.notificationEmails.deliver, {});
|
|
9
|
-
crons.interval("remove old mention emails", { hours: 24 }, internal.notifications.cleanUp, {});
|
|
10
|
-
crons.interval("remove unused R2 screenshots", { minutes: 10 }, internal.captures.cleanUp, {});
|
|
11
|
-
crons.interval("group new tags", { minutes: 1 }, internal.ai.groupTags, {});
|
|
12
|
-
crons.interval("remove expired AI request counters", { hours: 1 }, internal.grouping.cleanUpRateLimits, {});
|
|
13
|
-
|
|
14
|
-
export default crons;
|
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
import { countUse, MAX_GUESSES } from "./lib/vendor/critiqs_server.js";
|
|
2
|
-
import { v } from "convex/values";
|
|
3
|
-
import type { Id } from "./_generated/dataModel";
|
|
4
|
-
import { internalMutation, type MutationCtx } from "./_generated/server";
|
|
5
|
-
import { liveAttempt } from "./signIn";
|
|
6
|
-
|
|
7
|
-
// Approving setup from another device (see http.ts). The command line starts
|
|
8
|
-
// a grant and keeps its device secret; the person types the grant's short code
|
|
9
|
-
// into Critiqs's sign-in pages in any browser, signs in there, and approves.
|
|
10
|
-
// The command line then exchanges its secret for a short-lived access token,
|
|
11
|
-
// once. Secrets and codes are stored only as hashes, and nothing about the
|
|
12
|
-
// grant appears in a URL.
|
|
13
|
-
|
|
14
|
-
/** How long a grant waits for approval. */
|
|
15
|
-
export const DEVICE_MINUTES = 10;
|
|
16
|
-
/** Seconds between polls; polling faster is answered with `slow_down`. */
|
|
17
|
-
export const DEVICE_INTERVAL_SECONDS = 5;
|
|
18
|
-
/** Grants started per minute across the deployment. */
|
|
19
|
-
export const DEVICE_START_LIMIT = 60;
|
|
20
|
-
/** Codes typed that match no waiting grant, per minute across the deployment, so codes can't be guessed. */
|
|
21
|
-
export const DEVICE_MISS_LIMIT = 30;
|
|
22
|
-
/** Browser sign-in attempts per minute, including starts with a valid code. */
|
|
23
|
-
export const DEVICE_BEGIN_LIMIT = 200;
|
|
24
|
-
/** A known code cannot be used to create unlimited browser attempts. */
|
|
25
|
-
export const DEVICE_BEGIN_PER_GRANT_LIMIT = 5;
|
|
26
|
-
const MINUTE_MS = 60_000;
|
|
27
|
-
/** Shown wherever a device approval names what is being signed in to. */
|
|
28
|
-
export const DEVICE_SITE = "Critiqs setup on another device";
|
|
29
|
-
|
|
30
|
-
/** Counts one use of a limit; false when it is used up. */
|
|
31
|
-
async function take(ctx: MutationCtx, key: string, limit: number, now: number) {
|
|
32
|
-
const row = await ctx.db.query("signInLimits").withIndex("by_key", (q) => q.eq("key", key)).unique();
|
|
33
|
-
const use = countUse(row === null ? null : { count: row.count, expiresAt: row.expiresAt }, limit, MINUTE_MS, now);
|
|
34
|
-
if (!use.allowed) return { allowed: false as const, retryAfter: Math.ceil(use.retryAfterMs / 1000) };
|
|
35
|
-
if (row === null) await ctx.db.insert("signInLimits", { key, ...use.next });
|
|
36
|
-
else await ctx.db.patch(row._id, use.next);
|
|
37
|
-
return { allowed: true as const, retryAfter: 0 };
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function grantByCode(ctx: MutationCtx, userCodeHash: string, now: number) {
|
|
41
|
-
const grant = await ctx.db.query("deviceGrants").withIndex("by_user_code", (q) => q.eq("userCodeHash", userCodeHash)).first();
|
|
42
|
-
return grant !== null && grant.expiresAt > now ? grant : null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Starts a grant. A code already waiting is refused, so the caller draws another. */
|
|
46
|
-
export const start = internalMutation({
|
|
47
|
-
args: { deviceHash: v.string(), userCodeHash: v.string() },
|
|
48
|
-
handler: async (ctx, { deviceHash, userCodeHash }) => {
|
|
49
|
-
const now = Date.now();
|
|
50
|
-
if ((await grantByCode(ctx, userCodeHash, now)) !== null) return { status: "collision" as const };
|
|
51
|
-
const limit = await take(ctx, "device-start:global", DEVICE_START_LIMIT, now);
|
|
52
|
-
if (!limit.allowed) return { status: "rate-limited" as const, retryAfter: limit.retryAfter };
|
|
53
|
-
await ctx.db.insert("deviceGrants", {
|
|
54
|
-
deviceHash,
|
|
55
|
-
userCodeHash,
|
|
56
|
-
createdAt: now,
|
|
57
|
-
expiresAt: now + DEVICE_MINUTES * MINUTE_MS,
|
|
58
|
-
interval: DEVICE_INTERVAL_SECONDS,
|
|
59
|
-
status: "pending",
|
|
60
|
-
});
|
|
61
|
-
return { status: "started" as const, expiresIn: DEVICE_MINUTES * 60, interval: DEVICE_INTERVAL_SECONDS };
|
|
62
|
-
},
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* A typed code starts a sign-in in this browser for its grant. Codes that
|
|
67
|
-
* match no waiting grant count toward a deployment-wide limit.
|
|
68
|
-
*/
|
|
69
|
-
export const begin = internalMutation({
|
|
70
|
-
args: { userCodeHash: v.string(), key: v.string(), bindingHash: v.string(), clientState: v.string() },
|
|
71
|
-
handler: async (ctx, { userCodeHash, key, bindingHash, clientState }) => {
|
|
72
|
-
const now = Date.now();
|
|
73
|
-
const misses = await ctx.db.query("signInLimits").withIndex("by_key", (q) => q.eq("key", "device-miss:global")).unique();
|
|
74
|
-
if (misses !== null && misses.expiresAt > now && misses.count >= DEVICE_MISS_LIMIT) {
|
|
75
|
-
return { status: "rate-limited" as const, retryAfter: Math.ceil((misses.expiresAt - now) / 1000) };
|
|
76
|
-
}
|
|
77
|
-
const grant = await grantByCode(ctx, userCodeHash, now);
|
|
78
|
-
if (grant === null || grant.status !== "pending") {
|
|
79
|
-
const limit = await take(ctx, "device-miss:global", DEVICE_MISS_LIMIT, now);
|
|
80
|
-
return limit.allowed ? { status: "unknown" as const } : { status: "rate-limited" as const, retryAfter: limit.retryAfter };
|
|
81
|
-
}
|
|
82
|
-
for (const [key, maximum] of [[`device-begin:${grant._id}`, DEVICE_BEGIN_PER_GRANT_LIMIT], ["device-begin:global", DEVICE_BEGIN_LIMIT]] as const) {
|
|
83
|
-
const limit = await take(ctx, key, maximum, now);
|
|
84
|
-
if (!limit.allowed) return { status: "rate-limited" as const, retryAfter: limit.retryAfter };
|
|
85
|
-
}
|
|
86
|
-
await ctx.db.insert("signInAttempts", {
|
|
87
|
-
key,
|
|
88
|
-
origin: DEVICE_SITE,
|
|
89
|
-
clientState,
|
|
90
|
-
bindingHash,
|
|
91
|
-
createdAt: now,
|
|
92
|
-
codesSent: 0,
|
|
93
|
-
codeGeneration: 0,
|
|
94
|
-
guessesLeft: MAX_GUESSES,
|
|
95
|
-
device: grant._id,
|
|
96
|
-
});
|
|
97
|
-
return { status: "started" as const };
|
|
98
|
-
},
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Approves or denies a grant, once, from the browser that signed in for it,
|
|
103
|
-
* with the token its approval page carried.
|
|
104
|
-
*/
|
|
105
|
-
export const decide = internalMutation({
|
|
106
|
-
args: { key: v.string(), bindingHash: v.string(), consentHash: v.string(), allow: v.boolean() },
|
|
107
|
-
handler: async (ctx, { key, bindingHash, consentHash, allow }) => {
|
|
108
|
-
const attempt = await liveAttempt(ctx, key, bindingHash);
|
|
109
|
-
if (attempt === null || attempt.device === undefined || attempt.profile === undefined || attempt.consentHash !== consentHash) {
|
|
110
|
-
return { status: "expired" as const };
|
|
111
|
-
}
|
|
112
|
-
await ctx.db.delete(attempt._id);
|
|
113
|
-
const grant = await ctx.db.get(attempt.device as Id<"deviceGrants">);
|
|
114
|
-
if (grant === null || grant.status !== "pending" || grant.expiresAt <= Date.now()) return { status: "expired" as const };
|
|
115
|
-
await ctx.db.patch(grant._id, allow ? { status: "approved", profile: attempt.profile } : { status: "denied" });
|
|
116
|
-
return { status: allow ? ("approved" as const) : ("denied" as const), profile: attempt.profile };
|
|
117
|
-
},
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* The command line's poll. An approved grant is used up by the poll that
|
|
122
|
-
* receives it, in the same transaction, so its secret works once.
|
|
123
|
-
*/
|
|
124
|
-
export const poll = internalMutation({
|
|
125
|
-
args: { deviceHash: v.string() },
|
|
126
|
-
handler: async (ctx, { deviceHash }) => {
|
|
127
|
-
const now = Date.now();
|
|
128
|
-
const grant = await ctx.db.query("deviceGrants").withIndex("by_device", (q) => q.eq("deviceHash", deviceHash)).unique();
|
|
129
|
-
if (grant === null) return { status: "invalid" as const };
|
|
130
|
-
if (grant.expiresAt <= now) {
|
|
131
|
-
await ctx.db.delete(grant._id);
|
|
132
|
-
return { status: "expired" as const };
|
|
133
|
-
}
|
|
134
|
-
if (grant.status === "denied") {
|
|
135
|
-
await ctx.db.delete(grant._id);
|
|
136
|
-
return { status: "denied" as const };
|
|
137
|
-
}
|
|
138
|
-
if (grant.status === "approved" && grant.profile !== undefined) {
|
|
139
|
-
await ctx.db.delete(grant._id);
|
|
140
|
-
// The current display name, as a refresh would give.
|
|
141
|
-
const id = ctx.db.normalizeId("reviewers", grant.profile.subject);
|
|
142
|
-
const reviewer = id === null ? null : await ctx.db.get(id);
|
|
143
|
-
if (reviewer === null) return { status: "invalid" as const };
|
|
144
|
-
return { status: "approved" as const, profile: { ...grant.profile, name: reviewer.name, profileVersion: reviewer.nameVersion } };
|
|
145
|
-
}
|
|
146
|
-
const early = grant.lastPolledAt !== undefined && now - grant.lastPolledAt < grant.interval * 1000;
|
|
147
|
-
// Each early poll lengthens the wait, as RFC 8628 asks.
|
|
148
|
-
await ctx.db.patch(grant._id, { lastPolledAt: now, ...(early ? { interval: grant.interval + 5 } : {}) });
|
|
149
|
-
return { status: early ? ("slow-down" as const) : ("pending" as const), interval: early ? grant.interval + 5 : grant.interval };
|
|
150
|
-
},
|
|
151
|
-
});
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { applyGrouping, claimGrouping, failGrouping, type GroupingClaim } from "./lib/vendor/critiqs_server.js";
|
|
2
|
-
import { v } from "convex/values";
|
|
3
|
-
import { internalMutation } from "./_generated/server";
|
|
4
|
-
import { deployment } from "./lib/ai";
|
|
5
|
-
import { convexStore } from "./lib/store";
|
|
6
|
-
|
|
7
|
-
// Automatic grouping's transactions, run by the `ai.groupTags` action every
|
|
8
|
-
// minute with the model called between them.
|
|
9
|
-
|
|
10
|
-
export const claim = internalMutation({
|
|
11
|
-
args: { claimToken: v.string() },
|
|
12
|
-
handler: async (ctx, { claimToken }) => await claimGrouping(convexStore(ctx), deployment(), Date.now(), claimToken),
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
export const apply = internalMutation({
|
|
16
|
-
args: { claim: v.any(), assignments: v.array(v.object({ key: v.string(), groupIds: v.array(v.string()), newGroups: v.array(v.string()) })) },
|
|
17
|
-
handler: async (ctx, { claim, assignments }) =>
|
|
18
|
-
await applyGrouping(
|
|
19
|
-
convexStore(ctx),
|
|
20
|
-
claim as GroupingClaim,
|
|
21
|
-
{ assignments: new Map(assignments.map(({ key, ...assignment }) => [key, assignment])) },
|
|
22
|
-
Date.now(),
|
|
23
|
-
),
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
export const fail = internalMutation({
|
|
27
|
-
args: { claim: v.any(), message: v.string() },
|
|
28
|
-
handler: async (ctx, { claim, message }) => await failGrouping(convexStore(ctx), claim as GroupingClaim, message, Date.now()),
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
/** Removes expired search and test counters, in bounded batches. */
|
|
32
|
-
export const cleanUpRateLimits = internalMutation({
|
|
33
|
-
args: {},
|
|
34
|
-
handler: async (ctx) => {
|
|
35
|
-
const expired = await ctx.db
|
|
36
|
-
.query("aiRateLimits")
|
|
37
|
-
.withIndex("by_expiry", (q) => q.lt("expiresAt", Date.now()))
|
|
38
|
-
.take(500);
|
|
39
|
-
for (const row of expired) await ctx.db.delete(row._id);
|
|
40
|
-
},
|
|
41
|
-
});
|