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.
- 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,724 +0,0 @@
|
|
|
1
|
-
import { httpRouter } from "convex/server";
|
|
2
|
-
import { internal } from "./_generated/api";
|
|
3
|
-
import { type ActionCtx, httpAction } from "./_generated/server";
|
|
4
|
-
import {
|
|
5
|
-
CODE_MINUTES,
|
|
6
|
-
cleanCode,
|
|
7
|
-
codeDigest,
|
|
8
|
-
generateCode,
|
|
9
|
-
MailError,
|
|
10
|
-
normalizeEmail,
|
|
11
|
-
readPreferenceToken,
|
|
12
|
-
resendMailer,
|
|
13
|
-
signInCodeMessage,
|
|
14
|
-
} from "./lib/vendor/critiqs_server.js";
|
|
15
|
-
import {
|
|
16
|
-
codePage,
|
|
17
|
-
consentPage,
|
|
18
|
-
deliverPage,
|
|
19
|
-
deviceApprovalPage,
|
|
20
|
-
deviceCodePage,
|
|
21
|
-
emailPage,
|
|
22
|
-
messagePage,
|
|
23
|
-
namePage,
|
|
24
|
-
preferencePage,
|
|
25
|
-
} from "./lib/pages";
|
|
26
|
-
import { linkSecret } from "./lib/links";
|
|
27
|
-
import { CAPTURE_CORS, downloadCapture, uploadCapture } from "./captureHttp";
|
|
28
|
-
import { captureStorageHealth } from "./lib/r2";
|
|
29
|
-
import { ATTEMPT_MINUTES } from "./signIn";
|
|
30
|
-
import { DEVICE_SITE } from "./deviceSignIn";
|
|
31
|
-
import { hashSecret, issueAccessToken, randomSecret, signingKey } from "./lib/tokens";
|
|
32
|
-
import { deployment } from "./lib/ai";
|
|
33
|
-
|
|
34
|
-
/** Which AI this deployment offers, without any key or address. */
|
|
35
|
-
function aiHealth() {
|
|
36
|
-
const config = deployment();
|
|
37
|
-
return { managed: config.managed !== null, defaultProvider: config.defaultProvider?.provider ?? null, keysStorable: config.encryptionKey !== null };
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const http = httpRouter();
|
|
41
|
-
|
|
42
|
-
// Captures remain protected for both native Convex storage and private R2.
|
|
43
|
-
http.route({ path: "/capture", method: "GET", handler: downloadCapture });
|
|
44
|
-
http.route({ path: "/capture/upload", method: "POST", handler: uploadCapture });
|
|
45
|
-
for (const path of ["/capture", "/capture/upload"]) {
|
|
46
|
-
http.route({ path, method: "OPTIONS", handler: httpAction(async () => new Response(null, { status: 204, headers: CAPTURE_CORS })) });
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// ---------------------------------------------------------------------------
|
|
50
|
-
// Deployment configuration
|
|
51
|
-
|
|
52
|
-
/** Critiqs's sign-in service. The hosted deployment names itself; own deployments name the hosted one. */
|
|
53
|
-
function signInUrl(): string {
|
|
54
|
-
const issuer = process.env.CRITIQS_AUTH_ISSUER;
|
|
55
|
-
if (issuer === undefined || issuer === "") throw new Error("CRITIQS_AUTH_ISSUER is not set.");
|
|
56
|
-
return issuer.replace(/\/$/, "");
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Tells the component where reviewers sign in for this deployment. */
|
|
60
|
-
http.route({
|
|
61
|
-
path: "/critiqs/config",
|
|
62
|
-
method: "GET",
|
|
63
|
-
handler: httpAction(async () =>
|
|
64
|
-
Response.json(
|
|
65
|
-
// Raise `protocol` when the component needs functions or sign-in steps an older backend lacks.
|
|
66
|
-
// `deviceSignIn`: this sign-in service lets setup on another device be approved in a browser (/auth/device).
|
|
67
|
-
{ signInUrl: signInUrl(), protocol: 5, ai: aiHealth(), deviceSignIn: true },
|
|
68
|
-
{ headers: { "Access-Control-Allow-Origin": "*", "Cache-Control": "no-store" } },
|
|
69
|
-
),
|
|
70
|
-
),
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* What `critiqs doctor` checks: whether this deployment can sign people in and
|
|
75
|
-
* send email, and whether mention emails are actually going out. With
|
|
76
|
-
* `projectId`, also whether that project exists here. Reveals no feedback.
|
|
77
|
-
*/
|
|
78
|
-
http.route({
|
|
79
|
-
path: "/critiqs/health",
|
|
80
|
-
method: "GET",
|
|
81
|
-
handler: httpAction(async (ctx, request) => {
|
|
82
|
-
const projectId = new URL(request.url).searchParams.get("projectId");
|
|
83
|
-
const state = await ctx.runQuery(internal.notifications.health, { projectId: projectId ?? undefined });
|
|
84
|
-
const email = Boolean(process.env.RESEND_API_KEY && process.env.CRITIQS_EMAIL_FROM);
|
|
85
|
-
const issuer = process.env.CRITIQS_AUTH_ISSUER?.replace(/\/$/, "") ?? "";
|
|
86
|
-
const site = (process.env.CONVEX_SITE_URL ?? "").replace(/\/$/, "");
|
|
87
|
-
return Response.json(
|
|
88
|
-
{
|
|
89
|
-
protocol: 5,
|
|
90
|
-
// Whether this deployment runs sign-in itself, and how; or trusts another's.
|
|
91
|
-
signIn: issuer === "" ? "unconfigured" : issuer !== site ? "external" : signInMode(),
|
|
92
|
-
email,
|
|
93
|
-
plans: process.env.CRITIQS_PLANS === "enabled",
|
|
94
|
-
captures: captureStorageHealth(),
|
|
95
|
-
ai: aiHealth(),
|
|
96
|
-
...state,
|
|
97
|
-
},
|
|
98
|
-
{ headers: { "Access-Control-Allow-Origin": "*", "Cache-Control": "no-store" } },
|
|
99
|
-
);
|
|
100
|
-
}),
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
// ---------------------------------------------------------------------------
|
|
104
|
-
// Sign-in service (Critiqs's hosted deployment, or a local one in development)
|
|
105
|
-
//
|
|
106
|
-
// 1. The component opens /auth/start in a popup, naming its site and a nonce.
|
|
107
|
-
// A cookie ties the attempt to that browser.
|
|
108
|
-
// 2. The reviewer enters their email; Critiqs sends a one-time code to it.
|
|
109
|
-
// Development deployments show the code instead of sending it.
|
|
110
|
-
// 3. A matching code verifies the address. A new reviewer chooses a name.
|
|
111
|
-
// 4. The first time a reviewer signs in from a site, they allow that site.
|
|
112
|
-
// 5. The popup posts tokens to that site only. The component refreshes its
|
|
113
|
-
// short-lived access token through /auth/refresh from the same site.
|
|
114
|
-
|
|
115
|
-
type SignInMode = "email" | "development" | "unavailable";
|
|
116
|
-
|
|
117
|
-
function signInMode(): SignInMode {
|
|
118
|
-
// Codes and tokens are both keyed by the signing key; without it nobody can sign in.
|
|
119
|
-
if (!process.env.CRITIQS_AUTH_PRIVATE_KEY) return "unavailable";
|
|
120
|
-
if (process.env.RESEND_API_KEY && process.env.CRITIQS_EMAIL_FROM) return "email";
|
|
121
|
-
// Development sign-in shows codes on screen, so anyone could claim any email; it only runs locally.
|
|
122
|
-
if (process.env.CRITIQS_DEV_SIGN_IN === "enabled" && isLoopback(new URL(signInUrl()).hostname)) return "development";
|
|
123
|
-
return "unavailable";
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** Key for code digests, derived from the signing key so deployments need no extra secret. */
|
|
127
|
-
function codeSecret(): string {
|
|
128
|
-
const key = process.env.CRITIQS_AUTH_PRIVATE_KEY;
|
|
129
|
-
if (key === undefined || key === "") throw new Error("CRITIQS_AUTH_PRIVATE_KEY is not set.");
|
|
130
|
-
return `critiqs-sign-in-code:${key}`;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const ATTEMPT_COOKIE = "critiqs_sign_in";
|
|
134
|
-
|
|
135
|
-
function attemptCookie(value: string, maxAgeSeconds: number): string {
|
|
136
|
-
const secure = signInUrl().startsWith("https:") ? "; Secure" : "";
|
|
137
|
-
return `${ATTEMPT_COOKIE}=${value}; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${secure}`;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** Hash of this browser's attempt cookie, or an empty string when it has none. */
|
|
141
|
-
async function browserBinding(request: Request): Promise<string> {
|
|
142
|
-
const cookies = request.headers.get("Cookie") ?? "";
|
|
143
|
-
const value = cookies
|
|
144
|
-
.split(";")
|
|
145
|
-
.map((part) => part.trim().split("="))
|
|
146
|
-
.find(([name]) => name === ATTEMPT_COOKIE)?.[1];
|
|
147
|
-
return value === undefined || value === "" ? "" : await hashSecret(value);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function withHeaders(response: Response, headers: Record<string, string>): Response {
|
|
151
|
-
const merged = new Headers(response.headers);
|
|
152
|
-
for (const [name, value] of Object.entries(headers)) merged.append(name, value);
|
|
153
|
-
return new Response(response.body, { status: response.status, headers: merged });
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
http.route({
|
|
157
|
-
path: "/.well-known/jwks.json",
|
|
158
|
-
method: "GET",
|
|
159
|
-
handler: httpAction(async () => {
|
|
160
|
-
const { publicJwk } = await signingKey();
|
|
161
|
-
return Response.json({ keys: [publicJwk] }, { headers: { "Cache-Control": "public, max-age=300" } });
|
|
162
|
-
}),
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
http.route({
|
|
166
|
-
path: "/auth/start",
|
|
167
|
-
method: "GET",
|
|
168
|
-
handler: httpAction(async (ctx, request) => {
|
|
169
|
-
const params = new URL(request.url).searchParams;
|
|
170
|
-
const origin = normalizeOrigin(params.get("origin"));
|
|
171
|
-
const clientState = params.get("state") ?? "";
|
|
172
|
-
if (origin === null || clientState === "" || clientState.length > 200) {
|
|
173
|
-
return messagePage(
|
|
174
|
-
"Can't sign in",
|
|
175
|
-
"This sign-in link is incomplete, or the prototype is not served over HTTPS. Close this window and try again.",
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
const mode = signInMode();
|
|
179
|
-
if (mode === "unavailable") {
|
|
180
|
-
return messagePage("Sign-in unavailable", "This Critiqs deployment can't send sign-in codes yet.", 503);
|
|
181
|
-
}
|
|
182
|
-
const key = randomSecret();
|
|
183
|
-
const binding = randomSecret();
|
|
184
|
-
const start = await ctx.runMutation(internal.signIn.startAttempt, {
|
|
185
|
-
key,
|
|
186
|
-
origin,
|
|
187
|
-
clientState,
|
|
188
|
-
bindingHash: await hashSecret(binding),
|
|
189
|
-
});
|
|
190
|
-
if (!start.allowed) {
|
|
191
|
-
return withHeaders(messagePage("Try sign-in again shortly", "Too many sign-in requests. Please wait a minute and try again.", 429),
|
|
192
|
-
{ "Retry-After": String(start.retryAfter) });
|
|
193
|
-
}
|
|
194
|
-
const cookie = { "Set-Cookie": attemptCookie(binding, ATTEMPT_MINUTES * 60) };
|
|
195
|
-
return withHeaders(emailPage(key, origin, { development: mode === "development" }), cookie);
|
|
196
|
-
}),
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
/** Sends a code to the address entered, or a new code to the same address. */
|
|
200
|
-
http.route({
|
|
201
|
-
path: "/auth/email",
|
|
202
|
-
method: "POST",
|
|
203
|
-
handler: httpAction(async (ctx, request) => {
|
|
204
|
-
const mode = signInMode();
|
|
205
|
-
if (mode === "unavailable") return messagePage("Sign-in unavailable", "This Critiqs deployment can't send sign-in codes yet.", 503);
|
|
206
|
-
const form = new URLSearchParams(await request.text());
|
|
207
|
-
const key = form.get("attempt") ?? "";
|
|
208
|
-
const binding = await browserBinding(request);
|
|
209
|
-
const typed = (form.get("email") ?? "").slice(0, 300);
|
|
210
|
-
const email = normalizeEmail(typed);
|
|
211
|
-
const context = await ctx.runMutation(internal.signIn.codeContext, { key, bindingHash: binding });
|
|
212
|
-
if (email === null) {
|
|
213
|
-
const origin = await attemptOrigin(ctx, key, binding);
|
|
214
|
-
if (origin === null) return expiredPage();
|
|
215
|
-
return emailPage(key, origin, { development: mode === "development", error: "Enter a valid email address.", email: typed });
|
|
216
|
-
}
|
|
217
|
-
const prepared = await ctx.runMutation(internal.signIn.prepareCode, { key, bindingHash: binding, email });
|
|
218
|
-
switch (prepared.status) {
|
|
219
|
-
case "expired":
|
|
220
|
-
return expiredPage();
|
|
221
|
-
case "locked":
|
|
222
|
-
return lockedPage();
|
|
223
|
-
case "too-many-codes":
|
|
224
|
-
case "rate-limited":
|
|
225
|
-
// The current code, if any, still works.
|
|
226
|
-
if (context !== null && context.email === email) {
|
|
227
|
-
return codePage(key, context.origin, email, {
|
|
228
|
-
development: mode === "development",
|
|
229
|
-
canResend: false,
|
|
230
|
-
error:
|
|
231
|
-
prepared.status === "too-many-codes"
|
|
232
|
-
? "No more codes can be sent from this window. Use the latest code, or close this window and start again."
|
|
233
|
-
: "Too many codes were sent recently. Wait a few minutes before asking for another.",
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
return withHeaders(
|
|
237
|
-
messagePage("Try again shortly", "Too many codes were sent recently. Wait a few minutes, then close this window and start again.", 429),
|
|
238
|
-
prepared.status === "rate-limited" ? { "Retry-After": String(prepared.retryAfter) } : {},
|
|
239
|
-
);
|
|
240
|
-
}
|
|
241
|
-
const code = generateCode();
|
|
242
|
-
const digest = await codeDigest(codeSecret(), { attempt: key, email, generation: prepared.generation, code });
|
|
243
|
-
const stored = await ctx.runMutation(internal.signIn.storeCode, {
|
|
244
|
-
key,
|
|
245
|
-
bindingHash: binding,
|
|
246
|
-
generation: prepared.generation,
|
|
247
|
-
digest,
|
|
248
|
-
expiresAt: Date.now() + CODE_MINUTES * 60 * 1000,
|
|
249
|
-
});
|
|
250
|
-
if (!stored) return expiredPage();
|
|
251
|
-
if (mode === "email") {
|
|
252
|
-
try {
|
|
253
|
-
await resendMailer({ apiKey: process.env.RESEND_API_KEY!, from: process.env.CRITIQS_EMAIL_FROM! }).send(
|
|
254
|
-
signInCodeMessage({ to: email, code, site: prepared.origin, idempotencyKey: `${key}:${prepared.generation}` }),
|
|
255
|
-
);
|
|
256
|
-
} catch (error) {
|
|
257
|
-
if (!(error instanceof MailError)) throw error;
|
|
258
|
-
return emailPage(key, prepared.origin, {
|
|
259
|
-
development: false,
|
|
260
|
-
email,
|
|
261
|
-
error: "The code couldn't be sent. Check the address, or try again in a minute.",
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
return codePage(key, prepared.origin, email, {
|
|
266
|
-
development: mode === "development",
|
|
267
|
-
...(mode === "development" ? { developmentCode: code } : {}),
|
|
268
|
-
canResend: true,
|
|
269
|
-
});
|
|
270
|
-
}),
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
/** Checks a typed code. */
|
|
274
|
-
http.route({
|
|
275
|
-
path: "/auth/code",
|
|
276
|
-
method: "POST",
|
|
277
|
-
handler: httpAction(async (ctx, request) => {
|
|
278
|
-
const mode = signInMode();
|
|
279
|
-
if (mode === "unavailable") return messagePage("Sign-in unavailable", "This Critiqs deployment can't send sign-in codes yet.", 503);
|
|
280
|
-
const form = new URLSearchParams(await request.text());
|
|
281
|
-
const key = form.get("attempt") ?? "";
|
|
282
|
-
const binding = await browserBinding(request);
|
|
283
|
-
const context = await ctx.runMutation(internal.signIn.codeContext, { key, bindingHash: binding });
|
|
284
|
-
if (context === null) return expiredPage();
|
|
285
|
-
const typed = cleanCode((form.get("code") ?? "").slice(0, 20));
|
|
286
|
-
const codeError = (error: string) =>
|
|
287
|
-
codePage(key, context.origin, context.email, { development: mode === "development", canResend: true, error });
|
|
288
|
-
if (!/^\d{6}$/.test(typed)) return codeError("Enter the 6-digit code from the email.");
|
|
289
|
-
const digest = await codeDigest(codeSecret(), { attempt: key, email: context.email, generation: context.generation, code: typed });
|
|
290
|
-
const consent = randomSecret();
|
|
291
|
-
const result = await ctx.runMutation(internal.signIn.verifyCode, {
|
|
292
|
-
key,
|
|
293
|
-
bindingHash: binding,
|
|
294
|
-
generation: context.generation,
|
|
295
|
-
digest,
|
|
296
|
-
consentHash: await hashSecret(consent),
|
|
297
|
-
});
|
|
298
|
-
switch (result.status) {
|
|
299
|
-
case "expired":
|
|
300
|
-
return expiredPage();
|
|
301
|
-
case "locked":
|
|
302
|
-
return lockedPage();
|
|
303
|
-
case "code-expired":
|
|
304
|
-
return codeError("That code has expired. Send a new code.");
|
|
305
|
-
case "wrong":
|
|
306
|
-
return codeError(`That code doesn't match. ${result.guessesLeft} ${result.guessesLeft === 1 ? "try" : "tries"} left.`);
|
|
307
|
-
case "needs-name":
|
|
308
|
-
return namePage(key, {});
|
|
309
|
-
case "verified":
|
|
310
|
-
if (result.device) return deviceApprovalPage(key, consent, result.profile);
|
|
311
|
-
if (result.allowed) return await finishSignIn(ctx, key, binding, null, true);
|
|
312
|
-
return consentPage(key, consent, result.origin, result.profile);
|
|
313
|
-
}
|
|
314
|
-
}),
|
|
315
|
-
});
|
|
316
|
-
|
|
317
|
-
/** A new reviewer's display name, after their address is verified. */
|
|
318
|
-
http.route({
|
|
319
|
-
path: "/auth/name",
|
|
320
|
-
method: "POST",
|
|
321
|
-
handler: httpAction(async (ctx, request) => {
|
|
322
|
-
const form = new URLSearchParams(await request.text());
|
|
323
|
-
const key = form.get("attempt") ?? "";
|
|
324
|
-
const binding = await browserBinding(request);
|
|
325
|
-
const consent = randomSecret();
|
|
326
|
-
const result = await ctx.runMutation(internal.signIn.registerReviewer, {
|
|
327
|
-
key,
|
|
328
|
-
bindingHash: binding,
|
|
329
|
-
name: (form.get("name") ?? "").slice(0, 200),
|
|
330
|
-
consentHash: await hashSecret(consent),
|
|
331
|
-
});
|
|
332
|
-
if (result.status === "expired") return expiredPage();
|
|
333
|
-
if (result.status === "invalid-name") return namePage(key, { error: "Use a name of 1 to 60 characters." });
|
|
334
|
-
if (result.device) return deviceApprovalPage(key, consent, result.profile);
|
|
335
|
-
if (result.allowed) return await finishSignIn(ctx, key, binding, null, true);
|
|
336
|
-
return consentPage(key, consent, result.origin, result.profile);
|
|
337
|
-
}),
|
|
338
|
-
});
|
|
339
|
-
|
|
340
|
-
http.route({
|
|
341
|
-
path: "/auth/consent",
|
|
342
|
-
method: "POST",
|
|
343
|
-
handler: httpAction(async (ctx, request) => {
|
|
344
|
-
const form = new URLSearchParams(await request.text());
|
|
345
|
-
const consent = form.get("consent") ?? "";
|
|
346
|
-
if (consent === "") return expiredPage();
|
|
347
|
-
return await finishSignIn(
|
|
348
|
-
ctx,
|
|
349
|
-
form.get("attempt") ?? "",
|
|
350
|
-
await browserBinding(request),
|
|
351
|
-
await hashSecret(consent),
|
|
352
|
-
form.get("decision") === "allow",
|
|
353
|
-
);
|
|
354
|
-
}),
|
|
355
|
-
});
|
|
356
|
-
|
|
357
|
-
// ---------------------------------------------------------------------------
|
|
358
|
-
// Approving setup from another device (RFC 8628's device flow)
|
|
359
|
-
//
|
|
360
|
-
// 1. Setup (`critiqs init --remote`, or the MCP server) posts to
|
|
361
|
-
// /auth/device/start and receives a device secret, a short setup code, and
|
|
362
|
-
// this service's /auth/device address. It shows the code and the address.
|
|
363
|
-
// 2. In any browser, the person opens /auth/device, types the code, signs in
|
|
364
|
-
// with an email code as usual, and approves or denies. A cookie ties these
|
|
365
|
-
// pages to that browser, as with sign-in windows.
|
|
366
|
-
// 3. Setup polls /auth/device/token with its secret. Once approved, the poll
|
|
367
|
-
// receives a 15-minute access token for the approver, once. No refresh
|
|
368
|
-
// token is issued, so nothing outlives setup.
|
|
369
|
-
|
|
370
|
-
/** Letters that can't spell words or be misread as digits, for setup codes. */
|
|
371
|
-
const CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
|
|
372
|
-
|
|
373
|
-
function setupCode(): string {
|
|
374
|
-
const bytes = crypto.getRandomValues(new Uint8Array(8));
|
|
375
|
-
// 256 is a multiple of 20 plus 16; the slight bias leaves about 34 bits.
|
|
376
|
-
const letters = Array.from(bytes, (byte) => CODE_LETTERS[byte % CODE_LETTERS.length]).join("");
|
|
377
|
-
return `${letters.slice(0, 4)}-${letters.slice(4)}`;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
/** The code as typed, without spaces, dashes, or case; null when it can't be one. */
|
|
381
|
-
function cleanSetupCode(typed: string): string | null {
|
|
382
|
-
const letters = typed.toUpperCase().replace(/[^A-Z]/g, "");
|
|
383
|
-
return letters.length === 8 && [...letters].every((letter) => CODE_LETTERS.includes(letter)) ? letters : null;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/** Codes are short, so their stored hash is keyed by the signing key. */
|
|
387
|
-
async function setupCodeHash(letters: string): Promise<string> {
|
|
388
|
-
return await hashSecret(`${codeSecret()}:device:${letters}`);
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
const DEVICE_HEADERS = { "Cache-Control": "no-store" };
|
|
392
|
-
|
|
393
|
-
function deviceError(error: string, status: number, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}): Response {
|
|
394
|
-
return Response.json({ error, ...extra }, { status, headers: { ...DEVICE_HEADERS, ...headers } });
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
http.route({
|
|
398
|
-
path: "/auth/device/start",
|
|
399
|
-
method: "POST",
|
|
400
|
-
handler: httpAction(async (ctx) => {
|
|
401
|
-
if (signInMode() === "unavailable") return deviceError("unavailable", 503);
|
|
402
|
-
const deviceCode = randomSecret();
|
|
403
|
-
const deviceHash = await hashSecret(deviceCode);
|
|
404
|
-
// A new code if one is already waiting; collisions are rare.
|
|
405
|
-
for (let tries = 0; tries < 5; tries++) {
|
|
406
|
-
const userCode = setupCode();
|
|
407
|
-
const started = await ctx.runMutation(internal.deviceSignIn.start, {
|
|
408
|
-
deviceHash,
|
|
409
|
-
userCodeHash: await setupCodeHash(userCode.replace("-", "")),
|
|
410
|
-
});
|
|
411
|
-
if (started.status === "rate-limited") {
|
|
412
|
-
return deviceError("slow_down", 429, { retryAfter: started.retryAfter }, { "Retry-After": String(started.retryAfter) });
|
|
413
|
-
}
|
|
414
|
-
if (started.status === "started") {
|
|
415
|
-
return Response.json(
|
|
416
|
-
{ deviceCode, userCode, verificationUrl: `${signInUrl()}/auth/device`, expiresIn: started.expiresIn, interval: started.interval },
|
|
417
|
-
{ headers: DEVICE_HEADERS },
|
|
418
|
-
);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
return deviceError("unavailable", 503);
|
|
422
|
-
}),
|
|
423
|
-
});
|
|
424
|
-
|
|
425
|
-
http.route({
|
|
426
|
-
path: "/auth/device/token",
|
|
427
|
-
method: "POST",
|
|
428
|
-
handler: httpAction(async (ctx, request) => {
|
|
429
|
-
let deviceCode: unknown;
|
|
430
|
-
try {
|
|
431
|
-
({ deviceCode } = (await request.json()) as { deviceCode?: unknown });
|
|
432
|
-
} catch {}
|
|
433
|
-
if (typeof deviceCode !== "string" || deviceCode === "" || deviceCode.length > 200) return deviceError("invalid_request", 400);
|
|
434
|
-
const result = await ctx.runMutation(internal.deviceSignIn.poll, { deviceHash: await hashSecret(deviceCode) });
|
|
435
|
-
switch (result.status) {
|
|
436
|
-
case "pending":
|
|
437
|
-
return deviceError("authorization_pending", 400, { interval: result.interval });
|
|
438
|
-
case "slow-down":
|
|
439
|
-
return deviceError("slow_down", 400, { interval: result.interval });
|
|
440
|
-
case "denied":
|
|
441
|
-
return deviceError("access_denied", 400);
|
|
442
|
-
case "expired":
|
|
443
|
-
return deviceError("expired_token", 400);
|
|
444
|
-
case "invalid":
|
|
445
|
-
return deviceError("invalid_grant", 400);
|
|
446
|
-
}
|
|
447
|
-
const { accessToken, expiresAt } = await issueAccessToken(signInUrl(), result.profile, deviceTokenOrigin());
|
|
448
|
-
return Response.json(
|
|
449
|
-
{ accessToken, expiresAt, reviewer: { name: result.profile.name, email: result.profile.email } },
|
|
450
|
-
{ headers: DEVICE_HEADERS },
|
|
451
|
-
);
|
|
452
|
-
}),
|
|
453
|
-
});
|
|
454
|
-
|
|
455
|
-
/** The site a device approval's token names: this sign-in service, since no prototype is involved. */
|
|
456
|
-
function deviceTokenOrigin(): string {
|
|
457
|
-
return new URL(signInUrl()).origin;
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
http.route({
|
|
461
|
-
path: "/auth/device",
|
|
462
|
-
method: "GET",
|
|
463
|
-
handler: httpAction(async () => {
|
|
464
|
-
if (signInMode() === "unavailable") return messagePage("Sign-in unavailable", "This Critiqs deployment can't send sign-in codes yet.", 503);
|
|
465
|
-
return deviceCodePage();
|
|
466
|
-
}),
|
|
467
|
-
});
|
|
468
|
-
|
|
469
|
-
http.route({
|
|
470
|
-
path: "/auth/device",
|
|
471
|
-
method: "POST",
|
|
472
|
-
handler: httpAction(async (ctx, request) => {
|
|
473
|
-
const mode = signInMode();
|
|
474
|
-
if (mode === "unavailable") return messagePage("Sign-in unavailable", "This Critiqs deployment can't send sign-in codes yet.", 503);
|
|
475
|
-
const letters = cleanSetupCode((new URLSearchParams(await request.text()).get("user_code") ?? "").slice(0, 40));
|
|
476
|
-
if (letters === null) return deviceCodePage({ error: "Enter the 8-letter code shown by setup, such as BCDF-GHJK.", status: 400 });
|
|
477
|
-
const key = randomSecret();
|
|
478
|
-
const binding = randomSecret();
|
|
479
|
-
const begun = await ctx.runMutation(internal.deviceSignIn.begin, {
|
|
480
|
-
userCodeHash: await setupCodeHash(letters),
|
|
481
|
-
key,
|
|
482
|
-
bindingHash: await hashSecret(binding),
|
|
483
|
-
clientState: "device",
|
|
484
|
-
});
|
|
485
|
-
if (begun.status === "rate-limited") {
|
|
486
|
-
return withHeaders(deviceCodePage({ error: "Too many codes were tried. Wait a minute, then try again.", status: 429 }), {
|
|
487
|
-
"Retry-After": String(begun.retryAfter),
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
if (begun.status === "unknown") {
|
|
491
|
-
return deviceCodePage({ error: "That code isn't waiting for approval. Check it, or start setup again if it expired.", status: 400 });
|
|
492
|
-
}
|
|
493
|
-
return withHeaders(emailPage(key, DEVICE_SITE, { development: mode === "development" }), {
|
|
494
|
-
"Set-Cookie": attemptCookie(binding, ATTEMPT_MINUTES * 60),
|
|
495
|
-
});
|
|
496
|
-
}),
|
|
497
|
-
});
|
|
498
|
-
|
|
499
|
-
http.route({
|
|
500
|
-
path: "/auth/device/decision",
|
|
501
|
-
method: "POST",
|
|
502
|
-
handler: httpAction(async (ctx, request) => {
|
|
503
|
-
const form = new URLSearchParams(await request.text());
|
|
504
|
-
const consent = form.get("consent") ?? "";
|
|
505
|
-
if (consent === "") return expiredPage();
|
|
506
|
-
const result = await ctx.runMutation(internal.deviceSignIn.decide, {
|
|
507
|
-
key: form.get("attempt") ?? "",
|
|
508
|
-
bindingHash: await browserBinding(request),
|
|
509
|
-
consentHash: await hashSecret(consent),
|
|
510
|
-
allow: form.get("decision") === "approve",
|
|
511
|
-
});
|
|
512
|
-
const clear = { "Set-Cookie": attemptCookie("", 0) };
|
|
513
|
-
if (result.status === "expired") {
|
|
514
|
-
return messagePage("Setup approval expired", "This approval took too long, was already answered, or was started in another browser. Start setup again.");
|
|
515
|
-
}
|
|
516
|
-
if (result.status === "denied") {
|
|
517
|
-
return withHeaders(messagePage("Setup denied", "Nothing was signed in. You can close this page.", 200), clear);
|
|
518
|
-
}
|
|
519
|
-
return withHeaders(
|
|
520
|
-
messagePage("Setup approved", "Return to where you started setup; it continues on its own. You can close this page.", 200),
|
|
521
|
-
clear,
|
|
522
|
-
);
|
|
523
|
-
}),
|
|
524
|
-
});
|
|
525
|
-
|
|
526
|
-
/** The site an attempt signs in to, for the browser that started it. */
|
|
527
|
-
async function attemptOrigin(ctx: ActionCtx, key: string, binding: string): Promise<string | null> {
|
|
528
|
-
return await ctx.runMutation(internal.signIn.attemptOrigin, { key, bindingHash: binding });
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
async function finishSignIn(
|
|
532
|
-
ctx: ActionCtx,
|
|
533
|
-
key: string,
|
|
534
|
-
binding: string,
|
|
535
|
-
consentHash: string | null,
|
|
536
|
-
allow: boolean,
|
|
537
|
-
): Promise<Response> {
|
|
538
|
-
const refreshToken = randomSecret();
|
|
539
|
-
const result = await ctx.runMutation(internal.signIn.finishAttempt, {
|
|
540
|
-
key,
|
|
541
|
-
bindingHash: binding,
|
|
542
|
-
consentHash,
|
|
543
|
-
allow,
|
|
544
|
-
refreshHash: await hashSecret(refreshToken),
|
|
545
|
-
});
|
|
546
|
-
if (result === null) return expiredPage();
|
|
547
|
-
const clear = { "Set-Cookie": attemptCookie("", 0) };
|
|
548
|
-
const { origin, clientState, profile } = result;
|
|
549
|
-
if (profile === null) {
|
|
550
|
-
return withHeaders(deliverPage(origin, { type: "critiqs:sign-in", state: clientState, error: "cancelled" }), clear);
|
|
551
|
-
}
|
|
552
|
-
const { accessToken, expiresAt } = await issueAccessToken(signInUrl(), profile, origin);
|
|
553
|
-
return withHeaders(
|
|
554
|
-
deliverPage(origin, { type: "critiqs:sign-in", state: clientState, accessToken, refreshToken, expiresAt }),
|
|
555
|
-
clear,
|
|
556
|
-
);
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
function lockedPage(): Response {
|
|
560
|
-
return messagePage(
|
|
561
|
-
"Too many wrong codes",
|
|
562
|
-
"This sign-in is locked after too many wrong codes. Close this window and start again.",
|
|
563
|
-
429,
|
|
564
|
-
);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
function expiredPage(): Response {
|
|
568
|
-
return messagePage(
|
|
569
|
-
"Sign-in expired",
|
|
570
|
-
"This sign-in took too long, was already used, or was started in another browser. Close this window and try again.",
|
|
571
|
-
);
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
/** Returns a fresh access token for a session, only to the site that owns it. */
|
|
575
|
-
http.route({
|
|
576
|
-
path: "/auth/refresh",
|
|
577
|
-
method: "POST",
|
|
578
|
-
handler: httpAction(async (ctx, request) => {
|
|
579
|
-
const origin = normalizeOrigin(request.headers.get("Origin"));
|
|
580
|
-
const headers = sessionCors(origin);
|
|
581
|
-
const refreshToken = await readRefreshToken(request);
|
|
582
|
-
if (origin === null || refreshToken === null) return new Response("Bad request", { status: 400, headers });
|
|
583
|
-
const nextRefreshToken = randomSecret();
|
|
584
|
-
const session = await ctx.runMutation(internal.signIn.refreshSession, {
|
|
585
|
-
refreshHash: await hashSecret(refreshToken),
|
|
586
|
-
nextRefreshHash: await hashSecret(nextRefreshToken),
|
|
587
|
-
origin,
|
|
588
|
-
});
|
|
589
|
-
if (session === null) return new Response("Signed out", { status: 401, headers });
|
|
590
|
-
const { accessToken, expiresAt } = await issueAccessToken(signInUrl(), session.profile, origin, Date.now(), session.endsAt);
|
|
591
|
-
return Response.json({ accessToken, refreshToken: nextRefreshToken, expiresAt }, { headers });
|
|
592
|
-
}),
|
|
593
|
-
});
|
|
594
|
-
|
|
595
|
-
/** Changes the signed-in reviewer's display name; the component then refreshes its token. */
|
|
596
|
-
http.route({
|
|
597
|
-
path: "/auth/profile",
|
|
598
|
-
method: "POST",
|
|
599
|
-
handler: httpAction(async (ctx, request) => {
|
|
600
|
-
const origin = normalizeOrigin(request.headers.get("Origin"));
|
|
601
|
-
const headers = sessionCors(origin);
|
|
602
|
-
let body: unknown;
|
|
603
|
-
try {
|
|
604
|
-
body = await request.json();
|
|
605
|
-
} catch {
|
|
606
|
-
return new Response("Bad request", { status: 400, headers });
|
|
607
|
-
}
|
|
608
|
-
if (typeof body !== "object" || body === null) return new Response("Bad request", { status: 400, headers });
|
|
609
|
-
const { refreshToken, name } = body as { refreshToken?: unknown; name?: unknown };
|
|
610
|
-
if (origin === null || typeof refreshToken !== "string" || refreshToken === "" || typeof name !== "string") {
|
|
611
|
-
return new Response("Bad request", { status: 400, headers });
|
|
612
|
-
}
|
|
613
|
-
const result = await ctx.runMutation(internal.signIn.renameReviewer, {
|
|
614
|
-
refreshHash: await hashSecret(refreshToken),
|
|
615
|
-
origin,
|
|
616
|
-
name,
|
|
617
|
-
});
|
|
618
|
-
if (result === "signed-out") return new Response("Signed out", { status: 401, headers });
|
|
619
|
-
if (result === "invalid") {
|
|
620
|
-
return Response.json({ error: "Use a name of 1 to 60 characters." }, { status: 400, headers });
|
|
621
|
-
}
|
|
622
|
-
return new Response(null, { status: 204, headers });
|
|
623
|
-
}),
|
|
624
|
-
});
|
|
625
|
-
|
|
626
|
-
http.route({
|
|
627
|
-
path: "/auth/sign-out",
|
|
628
|
-
method: "POST",
|
|
629
|
-
handler: httpAction(async (ctx, request) => {
|
|
630
|
-
const origin = normalizeOrigin(request.headers.get("Origin"));
|
|
631
|
-
const headers = sessionCors(origin);
|
|
632
|
-
const refreshToken = await readRefreshToken(request);
|
|
633
|
-
if (origin !== null && refreshToken !== null) {
|
|
634
|
-
await ctx.runMutation(internal.signIn.endSession, { refreshHash: await hashSecret(refreshToken), origin });
|
|
635
|
-
}
|
|
636
|
-
return new Response(null, { status: 204, headers });
|
|
637
|
-
}),
|
|
638
|
-
});
|
|
639
|
-
|
|
640
|
-
for (const path of ["/auth/refresh", "/auth/profile", "/auth/sign-out"]) {
|
|
641
|
-
http.route({
|
|
642
|
-
path,
|
|
643
|
-
method: "OPTIONS",
|
|
644
|
-
handler: httpAction(async (_, request) =>
|
|
645
|
-
new Response(null, { status: 204, headers: sessionCors(normalizeOrigin(request.headers.get("Origin"))) }),
|
|
646
|
-
),
|
|
647
|
-
});
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
function sessionCors(origin: string | null): Record<string, string> {
|
|
651
|
-
return {
|
|
652
|
-
"Access-Control-Allow-Origin": origin ?? "null",
|
|
653
|
-
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
654
|
-
"Access-Control-Allow-Headers": "Content-Type",
|
|
655
|
-
"Cache-Control": "no-store",
|
|
656
|
-
Vary: "Origin",
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
async function readRefreshToken(request: Request): Promise<string | null> {
|
|
661
|
-
try {
|
|
662
|
-
const { refreshToken } = (await request.json()) as { refreshToken?: unknown };
|
|
663
|
-
return typeof refreshToken === "string" && refreshToken !== "" ? refreshToken : null;
|
|
664
|
-
} catch {
|
|
665
|
-
return null;
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
/**
|
|
670
|
-
* Accepts only a bare origin, such as `https://proto.example`. Plain HTTP is
|
|
671
|
-
* allowed only on this computer, where a network cannot tamper with the page.
|
|
672
|
-
*/
|
|
673
|
-
function normalizeOrigin(value: string | null): string | null {
|
|
674
|
-
if (value === null) return null;
|
|
675
|
-
try {
|
|
676
|
-
const url = new URL(value);
|
|
677
|
-
if (url.origin !== value.replace(/\/$/, "")) return null;
|
|
678
|
-
if (url.protocol === "https:") return url.origin;
|
|
679
|
-
return url.protocol === "http:" && isLoopback(url.hostname) ? url.origin : null;
|
|
680
|
-
} catch {
|
|
681
|
-
return null;
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
function isLoopback(hostname: string): boolean {
|
|
686
|
-
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
// ---------------------------------------------------------------------------
|
|
690
|
-
// Mute and unsubscribe links from mention emails
|
|
691
|
-
|
|
692
|
-
http.route({
|
|
693
|
-
path: "/notifications/preferences",
|
|
694
|
-
method: "GET",
|
|
695
|
-
handler: httpAction(async (ctx, request) => {
|
|
696
|
-
const token = new URL(request.url).searchParams.get("token") ?? "";
|
|
697
|
-
const scope = await readPreferenceToken(await linkSecret(ctx), token);
|
|
698
|
-
if (scope === null) return messagePage("Link not recognized", "This link is incomplete or was changed. Use the link in your email.");
|
|
699
|
-
return preferencePage(
|
|
700
|
-
token,
|
|
701
|
-
scope.projectId === null
|
|
702
|
-
? "Stop all mention emails from Critiqs? You can turn them back on from the account menu."
|
|
703
|
-
: "Mute mention emails from this project? You can unmute it from the account menu.",
|
|
704
|
-
);
|
|
705
|
-
}),
|
|
706
|
-
});
|
|
707
|
-
|
|
708
|
-
http.route({
|
|
709
|
-
path: "/notifications/preferences",
|
|
710
|
-
method: "POST",
|
|
711
|
-
handler: httpAction(async (ctx, request) => {
|
|
712
|
-
const token = new URLSearchParams(await request.text()).get("token") ?? "";
|
|
713
|
-
const scope = await readPreferenceToken(await linkSecret(ctx), token);
|
|
714
|
-
if (scope === null) return messagePage("Link not recognized", "This link is incomplete or was changed. Use the link in your email.");
|
|
715
|
-
await ctx.runMutation(internal.notifications.applyLink, scope);
|
|
716
|
-
return messagePage(
|
|
717
|
-
"Done",
|
|
718
|
-
scope.projectId === null ? "You won't get mention emails from Critiqs any more." : "This project's mention emails are muted.",
|
|
719
|
-
200,
|
|
720
|
-
);
|
|
721
|
-
}),
|
|
722
|
-
});
|
|
723
|
-
|
|
724
|
-
export default http;
|