@vite-hub/comments 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +242 -2
- package/dist/anchor.d.ts +40 -0
- package/dist/anchor.js +128 -0
- package/dist/client.d.ts +101 -0
- package/dist/client.js +553 -0
- package/dist/console-BIz9t2cO.d.ts +243 -0
- package/dist/database/postgres.d.ts +1011 -0
- package/dist/database/postgres.js +60 -0
- package/dist/database-BSnVrwHn.js +60 -0
- package/dist/database-C-ktS9Do.js +95 -0
- package/dist/database-Cb2xjC1V.d.ts +1096 -0
- package/dist/database.d.ts +104 -0
- package/dist/database.js +3 -0
- package/dist/define-BzW2Ychn.d.ts +46 -0
- package/dist/define-Cbhl6QVJ.js +32 -0
- package/dist/errors-BAQYcy3_.d.ts +89 -0
- package/dist/errors-DeD6wTCl.js +77 -0
- package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
- package/dist/identity-3qtVC4rF.js +34 -0
- package/dist/index-DklG2Etf.d.ts +111 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +5 -0
- package/dist/operations-0B0QTVWX.d.ts +138 -0
- package/dist/operations-NZG5dB8y.js +732 -0
- package/dist/operations.d.ts +7 -0
- package/dist/operations.js +2 -0
- package/dist/overlay/overlay.js +195 -0
- package/dist/page/loader.js +22 -0
- package/dist/page-BtXADR6d.d.ts +21 -0
- package/dist/page-BuroSMXO.js +38 -0
- package/dist/page-tools-shared-D-amu6sx.js +53 -0
- package/dist/plugin-QElKQYkA.js +725 -0
- package/dist/realtime.d.ts +18 -0
- package/dist/realtime.js +48 -0
- package/dist/request-DVc3M_AG.js +14 -0
- package/dist/rpc.d.ts +29 -0
- package/dist/rpc.js +75 -0
- package/dist/runtime/auth.d.ts +6 -0
- package/dist/runtime/auth.js +15 -0
- package/dist/runtime/connect/node.d.ts +1 -0
- package/dist/runtime/connect/node.js +2 -0
- package/dist/runtime/connect.d.ts +1 -0
- package/dist/runtime/connect.js +2 -0
- package/dist/runtime/console.d.ts +5 -0
- package/dist/runtime/console.js +59 -0
- package/dist/runtime/index.d.ts +222 -0
- package/dist/runtime/index.js +665 -0
- package/dist/server-BomGg3Gb.js +63 -0
- package/dist/server.d.ts +94 -0
- package/dist/server.js +326 -0
- package/dist/src-CRTwnaEG.js +1362 -0
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +175 -0
- package/dist/types-Cj8K7Vx7.d.ts +176 -0
- package/dist/types-Un2dcJWD.d.ts +288 -0
- package/dist/vite.d.ts +304 -0
- package/dist/vite.js +1921 -0
- package/package.json +156 -3
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
import { _ as commentsErrors, a as rememberGitHubToken, c as getCloudflareEnv, d as anchorSchema, f as bodySchema, g as pageSchema, h as mentionsSchema, i as forgetGitHubToken, l as resolveWaitUntil, m as describeIssue, p as contextSchema, s as getActiveCloudflareBinding, u as runWithActiveCloudflareEnv } from "../src-CRTwnaEG.js";
|
|
2
|
+
import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-BuroSMXO.js";
|
|
3
|
+
import { n as guestFromHeaders, r as text, t as authorOf } from "../identity-3qtVC4rF.js";
|
|
4
|
+
import { t as requestOf } from "../request-DVc3M_AG.js";
|
|
5
|
+
import { a as viteHubPageSessionHandler, i as resolveCommentsUser, n as installedComments, o as forwardedRequestOrigin, r as commentsMcpTools, t as defineCommentsPlugin } from "../plugin-QElKQYkA.js";
|
|
6
|
+
import * as v from "valibot";
|
|
7
|
+
import { createAuthForRequest } from "@vite-hub/auth/server";
|
|
8
|
+
import { defineGrant } from "@vite-hub/runtime/internal/grant";
|
|
9
|
+
import { defineEventHandler } from "h3";
|
|
10
|
+
import { hkdfSync } from "node:crypto";
|
|
11
|
+
import { defineAuth } from "@vite-hub/auth";
|
|
12
|
+
import { stateless } from "@vite-hub/auth/presets";
|
|
13
|
+
//#region src/runtime/handler.ts
|
|
14
|
+
/** Issued by `access()` after `authorize` allows an action, for that action on that thread. Each write needs one. */
|
|
15
|
+
const actionGrant = defineGrant("vitehub.comments.action", (input) => Object.freeze({ ...input }));
|
|
16
|
+
/** Spends a grant for one of `actions` on `threadId`. A grant for another action or thread is a bug, so it throws. */
|
|
17
|
+
function spend(grant, actions, threadId) {
|
|
18
|
+
const allowed = actionGrant.consume(grant);
|
|
19
|
+
if (!actions.includes(allowed.action) || allowed.threadId !== threadId) throw new TypeError(`[vitehub] A Comments write for ${actions.join(" or ")} ran with the grant of ${allowed.action}.`);
|
|
20
|
+
}
|
|
21
|
+
const fieldEditGrant = defineGrant("vitehub.comments.field-edit", (input) => input);
|
|
22
|
+
const createBody = v.object({
|
|
23
|
+
page: pageSchema,
|
|
24
|
+
anchor: anchorSchema,
|
|
25
|
+
context: v.optional(contextSchema),
|
|
26
|
+
body: bodySchema,
|
|
27
|
+
mentions: mentionsSchema
|
|
28
|
+
});
|
|
29
|
+
const replyBody = v.object({
|
|
30
|
+
body: bodySchema,
|
|
31
|
+
mentions: mentionsSchema
|
|
32
|
+
});
|
|
33
|
+
const fieldBody = v.object({
|
|
34
|
+
field: v.pipe(v.string(), v.maxLength(512)),
|
|
35
|
+
value: v.pipe(v.string(), v.maxLength(2e4)),
|
|
36
|
+
ifDigest: v.string()
|
|
37
|
+
});
|
|
38
|
+
function status(code) {
|
|
39
|
+
switch (code) {
|
|
40
|
+
case "COMMENTS_NOT_FOUND":
|
|
41
|
+
case "COMMENTS_CONTENT_MISSING": return 404;
|
|
42
|
+
case "COMMENTS_FORBIDDEN":
|
|
43
|
+
case "COMMENTS_FIELD_FORBIDDEN": return 403;
|
|
44
|
+
case "COMMENTS_RESOLVED":
|
|
45
|
+
case "COMMENTS_FIELD_CONFLICT": return 409;
|
|
46
|
+
case "COMMENTS_FIELD_LOCKED": return 423;
|
|
47
|
+
case "COMMENTS_FIELD_NOT_EDITABLE": return 422;
|
|
48
|
+
case "COMMENTS_NOT_INSTALLED": return 503;
|
|
49
|
+
default: return 400;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function json(value, init = {}) {
|
|
53
|
+
const headers = new Headers(init.headers);
|
|
54
|
+
headers.set("content-type", "application/json; charset=utf-8");
|
|
55
|
+
headers.set("cache-control", "private, no-store");
|
|
56
|
+
return new Response(JSON.stringify(value), {
|
|
57
|
+
...init,
|
|
58
|
+
headers
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function failure(error) {
|
|
62
|
+
return json({ error }, { status: status(error.code) });
|
|
63
|
+
}
|
|
64
|
+
function respond([error, data]) {
|
|
65
|
+
return error ? failure(error) : json({ data: data ?? null });
|
|
66
|
+
}
|
|
67
|
+
function sameOrigin(request) {
|
|
68
|
+
const origin = request.headers.get("origin");
|
|
69
|
+
return !origin || origin === forwardedRequestOrigin(request);
|
|
70
|
+
}
|
|
71
|
+
function readPath(data, path) {
|
|
72
|
+
let current = data;
|
|
73
|
+
for (const key of path) {
|
|
74
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
75
|
+
current = Reflect.get(current, key);
|
|
76
|
+
}
|
|
77
|
+
return current;
|
|
78
|
+
}
|
|
79
|
+
function writePath(data, path, value) {
|
|
80
|
+
const copy = structuredClone(data);
|
|
81
|
+
let current = copy;
|
|
82
|
+
for (const key of path.slice(0, -1)) current = Reflect.get(Object(current), key);
|
|
83
|
+
Reflect.set(Object(current), path.at(-1), value);
|
|
84
|
+
return copy;
|
|
85
|
+
}
|
|
86
|
+
function errorCode(error) {
|
|
87
|
+
return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
|
|
88
|
+
}
|
|
89
|
+
function leaseHolder(error) {
|
|
90
|
+
const details = error instanceof Error && "details" in error ? error.details : void 0;
|
|
91
|
+
const name = readPath(details, [
|
|
92
|
+
"holder",
|
|
93
|
+
"user",
|
|
94
|
+
"name"
|
|
95
|
+
]) ?? readPath(details, [
|
|
96
|
+
"holder",
|
|
97
|
+
"user",
|
|
98
|
+
"id"
|
|
99
|
+
]);
|
|
100
|
+
return typeof name === "string" && name ? name : "Someone";
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The Comments API at `/api/_vitehub/comments/**`. The overlay calls it; every route checks the `authorize` policy of
|
|
104
|
+
* `defineComments()` for the user of the request, and inline edits also check `content.can()`.
|
|
105
|
+
*/
|
|
106
|
+
function createCommentsHandler(options) {
|
|
107
|
+
const { comments } = options;
|
|
108
|
+
async function resolveUser(event, action = "read") {
|
|
109
|
+
return resolveCommentsUser(comments, event, {
|
|
110
|
+
...options,
|
|
111
|
+
session: async (request) => await options.session?.(request) ?? await options.githubLogin?.user(request)
|
|
112
|
+
}, action);
|
|
113
|
+
}
|
|
114
|
+
async function access(event, action, thread) {
|
|
115
|
+
const user = await resolveUser(event, action);
|
|
116
|
+
if (user === false || !await comments.can({
|
|
117
|
+
user,
|
|
118
|
+
action,
|
|
119
|
+
thread
|
|
120
|
+
})) return [commentsErrors.COMMENTS_FORBIDDEN({ action }), void 0];
|
|
121
|
+
return [void 0, {
|
|
122
|
+
user,
|
|
123
|
+
author: user ? authorOf(user) : guestFromHeaders(requestOf(event).headers),
|
|
124
|
+
grant: actionGrant.issue({
|
|
125
|
+
action,
|
|
126
|
+
threadId: thread?.id
|
|
127
|
+
})
|
|
128
|
+
}];
|
|
129
|
+
}
|
|
130
|
+
/** The writes of this API. Each one needs the grant of the `access()` check that allowed it. */
|
|
131
|
+
const writes = {
|
|
132
|
+
create: (grant, input) => {
|
|
133
|
+
spend(grant, ["comment"]);
|
|
134
|
+
return comments.create(input);
|
|
135
|
+
},
|
|
136
|
+
reply: (grant, threadId, input) => {
|
|
137
|
+
spend(grant, ["comment"], threadId);
|
|
138
|
+
return comments.reply(threadId, input);
|
|
139
|
+
},
|
|
140
|
+
resolve: (grant, threadId, by) => {
|
|
141
|
+
spend(grant, ["resolve"], threadId);
|
|
142
|
+
return comments.resolve(threadId, { by });
|
|
143
|
+
},
|
|
144
|
+
reopen: (grant, threadId) => {
|
|
145
|
+
spend(grant, ["resolve"], threadId);
|
|
146
|
+
return comments.reopen(threadId);
|
|
147
|
+
},
|
|
148
|
+
remove: (grant, threadId) => {
|
|
149
|
+
spend(grant, ["resolve"], threadId);
|
|
150
|
+
return comments.remove(threadId);
|
|
151
|
+
},
|
|
152
|
+
removeComment: (grant, threadId, commentId) => {
|
|
153
|
+
spend(grant, ["comment", "resolve"], threadId);
|
|
154
|
+
return comments.removeComment(commentId);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
/** Adds the build, and the source files of each component, to the context that the overlay read. */
|
|
158
|
+
function completeContext(context) {
|
|
159
|
+
const named = context.components?.map((component) => {
|
|
160
|
+
const files = options.components && Object.hasOwn(options.components, component.name) ? options.components[component.name] : void 0;
|
|
161
|
+
return files?.length ? {
|
|
162
|
+
name: component.name,
|
|
163
|
+
files: files.slice(0, 8)
|
|
164
|
+
} : { name: component.name };
|
|
165
|
+
});
|
|
166
|
+
const own = named?.filter((component) => component.files);
|
|
167
|
+
const components = own?.length ? own : named?.slice(-3);
|
|
168
|
+
const { build: _build, ...read } = context;
|
|
169
|
+
return {
|
|
170
|
+
...read,
|
|
171
|
+
...components ? { components } : {},
|
|
172
|
+
...options.build && Object.values(options.build).some(Boolean) ? { build: options.build } : {}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
async function readJson(event) {
|
|
176
|
+
try {
|
|
177
|
+
return await requestOf(event).json();
|
|
178
|
+
} catch {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function invalid(issues) {
|
|
183
|
+
return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(issues) }));
|
|
184
|
+
}
|
|
185
|
+
/** Who the overlay's person is and what they may do. The page tools session decides whether the overlay loads. */
|
|
186
|
+
async function session(event) {
|
|
187
|
+
const user = await resolveUser(event);
|
|
188
|
+
const [read, comment, resolve] = await Promise.all([
|
|
189
|
+
"read",
|
|
190
|
+
"comment",
|
|
191
|
+
"resolve"
|
|
192
|
+
].map((action) => can(event, user, action)));
|
|
193
|
+
const github = options.githubLogin?.configured() ? options.githubLogin : void 0;
|
|
194
|
+
const pathname = new URL(requestOf(event).url).pathname;
|
|
195
|
+
const route = pathname.slice(0, pathname.indexOf(commentsRoute) + commentsRoute.length);
|
|
196
|
+
const signIn = user !== false && !user && !comments.options.identify && github ? {
|
|
197
|
+
provider: "github",
|
|
198
|
+
url: `${route}/auth/github`
|
|
199
|
+
} : void 0;
|
|
200
|
+
const signOut = user && user.github && github ? `${route}/auth/sign-out` : void 0;
|
|
201
|
+
return json({ data: {
|
|
202
|
+
user: user ? authorOf(user) : null,
|
|
203
|
+
...user && user.github ? { github: user.github } : {},
|
|
204
|
+
can: {
|
|
205
|
+
read,
|
|
206
|
+
comment,
|
|
207
|
+
resolve
|
|
208
|
+
},
|
|
209
|
+
...signIn ? { signIn } : {},
|
|
210
|
+
...signOut ? { signOut } : {},
|
|
211
|
+
realtime: options.realtime,
|
|
212
|
+
content: Boolean(options.content)
|
|
213
|
+
} });
|
|
214
|
+
}
|
|
215
|
+
async function can(event, user, action, thread) {
|
|
216
|
+
if (user === false) return false;
|
|
217
|
+
if (action !== "read" && await options.consoleSession?.(event, action).catch(() => false) === false) return false;
|
|
218
|
+
return comments.can({
|
|
219
|
+
user,
|
|
220
|
+
action,
|
|
221
|
+
thread
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async function permissions(event, user, thread) {
|
|
225
|
+
const [comment, resolve] = await Promise.all(["comment", "resolve"].map((action) => can(event, user, action, thread)));
|
|
226
|
+
return {
|
|
227
|
+
...thread,
|
|
228
|
+
can: {
|
|
229
|
+
comment,
|
|
230
|
+
resolve
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function respondThread(event, user, [error, thread]) {
|
|
235
|
+
return error ? failure(error) : json({ data: await permissions(event, user, thread) });
|
|
236
|
+
}
|
|
237
|
+
/** A page thread. Threads of other scopes belong to the app's own UI, so this API does not show or change them. */
|
|
238
|
+
async function thread(id) {
|
|
239
|
+
const [error, found] = await comments.get(id);
|
|
240
|
+
if (error) return [error, void 0];
|
|
241
|
+
return found.scope === "pages" ? [void 0, found] : [commentsErrors.COMMENTS_NOT_FOUND({ id }), void 0];
|
|
242
|
+
}
|
|
243
|
+
async function fieldTarget(event, address) {
|
|
244
|
+
if (!options.content) return [commentsErrors.COMMENTS_CONTENT_MISSING(), void 0];
|
|
245
|
+
const [denied, allowed] = await access(event, "comment");
|
|
246
|
+
if (denied) return [denied, void 0];
|
|
247
|
+
const parsed = options.content.parseField(address);
|
|
248
|
+
const collection = parsed && options.content.runtime.collections().find((candidate) => candidate.name === parsed.collection);
|
|
249
|
+
const id = collection?.kind === "singleton" ? collection.id : parsed?.id;
|
|
250
|
+
if (!parsed || !collection || !id) return [commentsErrors.COMMENTS_FIELD_INVALID({ field: address }), void 0];
|
|
251
|
+
if (!allowed.author) return [commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }), void 0];
|
|
252
|
+
if (!await options.content.runtime.can({
|
|
253
|
+
user: allowed.user ?? void 0,
|
|
254
|
+
collection: collection.name,
|
|
255
|
+
action: "write",
|
|
256
|
+
id
|
|
257
|
+
})) return [commentsErrors.COMMENTS_FIELD_FORBIDDEN({ field: address }), void 0];
|
|
258
|
+
const document = await collection.get(id, { ref: "draft" });
|
|
259
|
+
if (!document) return [commentsErrors.COMMENTS_FIELD_INVALID({ field: address }), void 0];
|
|
260
|
+
return [void 0, {
|
|
261
|
+
collection,
|
|
262
|
+
id,
|
|
263
|
+
path: parsed.field.split("."),
|
|
264
|
+
document,
|
|
265
|
+
author: allowed.author,
|
|
266
|
+
user: allowed.user
|
|
267
|
+
}];
|
|
268
|
+
}
|
|
269
|
+
async function readField(event, address) {
|
|
270
|
+
const [error, target] = await fieldTarget(event, address);
|
|
271
|
+
if (error) return failure(error);
|
|
272
|
+
const value = readPath(target.document.data, target.path);
|
|
273
|
+
return json({ data: {
|
|
274
|
+
field: address,
|
|
275
|
+
value: typeof value === "string" ? value : null,
|
|
276
|
+
editable: typeof value === "string",
|
|
277
|
+
digest: target.document.digest,
|
|
278
|
+
collection: target.collection.name,
|
|
279
|
+
id: target.id
|
|
280
|
+
} });
|
|
281
|
+
}
|
|
282
|
+
async function saveField(event) {
|
|
283
|
+
const parsed = v.safeParse(fieldBody, await readJson(event));
|
|
284
|
+
if (!parsed.success) return invalid(parsed.issues);
|
|
285
|
+
const [error, target] = await fieldTarget(event, parsed.output.field);
|
|
286
|
+
if (error) return failure(error);
|
|
287
|
+
if (typeof readPath(target.document.data, target.path) !== "string") return failure(commentsErrors.COMMENTS_FIELD_NOT_EDITABLE({ field: parsed.output.field }));
|
|
288
|
+
if (target.document.digest !== parsed.output.ifDigest) return failure(commentsErrors.COMMENTS_FIELD_CONFLICT({ field: parsed.output.field }));
|
|
289
|
+
return await writeField(fieldEditGrant.issue({
|
|
290
|
+
collection: target.collection,
|
|
291
|
+
id: target.id,
|
|
292
|
+
field: parsed.output.field,
|
|
293
|
+
user: target.author
|
|
294
|
+
}), target, parsed.output);
|
|
295
|
+
}
|
|
296
|
+
/** Saves one field as a new draft. It needs the grant that `saveField` issues after `authorize` and `content.can()`. */
|
|
297
|
+
async function writeField(grant, target, input) {
|
|
298
|
+
const { collection, id, field, user } = fieldEditGrant.consume(grant);
|
|
299
|
+
try {
|
|
300
|
+
const saved = await collection.save(id, {
|
|
301
|
+
data: writePath(target.document.data, target.path, input.value),
|
|
302
|
+
...target.document.body === void 0 || collection.format !== "markdown" ? {} : { body: target.document.body }
|
|
303
|
+
}, {
|
|
304
|
+
ifDigest: input.ifDigest,
|
|
305
|
+
message: `Edit ${target.path.join(".")} on the page`,
|
|
306
|
+
metadata: {
|
|
307
|
+
source: "comments",
|
|
308
|
+
author: user.name
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
return json({ data: {
|
|
312
|
+
field,
|
|
313
|
+
value: input.value,
|
|
314
|
+
digest: saved.digest
|
|
315
|
+
} });
|
|
316
|
+
} catch (cause) {
|
|
317
|
+
const code = errorCode(cause);
|
|
318
|
+
if (code === "WORKSPACE_CONFLICT") return failure(commentsErrors.COMMENTS_FIELD_CONFLICT({ field }));
|
|
319
|
+
if (code === "CONTENT_LEASE_HELD") return failure(commentsErrors.COMMENTS_FIELD_LOCKED({ holder: leaseHolder(cause) }));
|
|
320
|
+
throw cause;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
async function handle(event) {
|
|
324
|
+
const request = requestOf(event);
|
|
325
|
+
const response = await route(event, request);
|
|
326
|
+
if (request.method !== "GET" && comments.options.forge) resolveWaitUntil(event, { preferHost: true })?.(comments.flush());
|
|
327
|
+
return response;
|
|
328
|
+
}
|
|
329
|
+
return defineEventHandler((event) => {
|
|
330
|
+
const env = getCloudflareEnv(event, { fallback: false });
|
|
331
|
+
return env ? runWithActiveCloudflareEnv(env, () => handle(event)) : handle(event);
|
|
332
|
+
});
|
|
333
|
+
async function route(event, request) {
|
|
334
|
+
const url = new URL(request.url);
|
|
335
|
+
const path = url.pathname.slice(url.pathname.indexOf("/api/_vitehub/comments") + 22).replace(/\/+$/, "") || "/";
|
|
336
|
+
const parts = path.split("/").filter(Boolean);
|
|
337
|
+
const method = request.method;
|
|
338
|
+
if (method !== "GET" && !sameOrigin(request)) return json({ error: {
|
|
339
|
+
code: "COMMENTS_FORBIDDEN",
|
|
340
|
+
why: "Comments requests must come from the site's own pages."
|
|
341
|
+
} }, { status: 403 });
|
|
342
|
+
if (method === "GET" && path === "/session") return await session(event);
|
|
343
|
+
if (path.startsWith("/auth/") && options.githubLogin) return await options.githubLogin.handle(event, path);
|
|
344
|
+
if (path === "/threads") {
|
|
345
|
+
if (method === "GET") {
|
|
346
|
+
const [denied, allowed] = await access(event, "read");
|
|
347
|
+
if (denied) return failure(denied);
|
|
348
|
+
const page = url.searchParams.get("page");
|
|
349
|
+
const state = url.searchParams.get("status");
|
|
350
|
+
const [error, threads] = await comments.list({
|
|
351
|
+
scope: commentsPageScope,
|
|
352
|
+
page: page ? normalizeCommentPage(page) : void 0,
|
|
353
|
+
status: state === "open" || state === "resolved" ? state : void 0
|
|
354
|
+
});
|
|
355
|
+
return error ? failure(error) : json({ data: await Promise.all(threads.map((thread) => permissions(event, allowed.user, thread))) });
|
|
356
|
+
}
|
|
357
|
+
if (method === "POST") {
|
|
358
|
+
const parsed = v.safeParse(createBody, await readJson(event));
|
|
359
|
+
if (!parsed.success) return invalid(parsed.issues);
|
|
360
|
+
const [denied, allowed] = await access(event, "comment");
|
|
361
|
+
if (denied) return failure(denied);
|
|
362
|
+
if (!allowed.author) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }));
|
|
363
|
+
const { context, ...input } = parsed.output;
|
|
364
|
+
if (context) {
|
|
365
|
+
const origin = forwardedRequestOrigin(request);
|
|
366
|
+
const page = normalizeCommentPage(input.page);
|
|
367
|
+
let submitted;
|
|
368
|
+
try {
|
|
369
|
+
submitted = new URL(context.url);
|
|
370
|
+
} catch {
|
|
371
|
+
return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Expected an absolute page URL." }));
|
|
372
|
+
}
|
|
373
|
+
if (submitted.origin !== origin || normalizeCommentPage(submitted.pathname) !== page) return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Must match the request origin and thread page." }));
|
|
374
|
+
context.url = `${origin}${page}`;
|
|
375
|
+
}
|
|
376
|
+
return await respondThread(event, allowed.user, await writes.create(allowed.grant, {
|
|
377
|
+
...input,
|
|
378
|
+
...context ? { context: completeContext(context) } : {},
|
|
379
|
+
author: allowed.author
|
|
380
|
+
}));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (parts[0] === "threads" && parts[1]) {
|
|
384
|
+
const id = decodeURIComponent(parts[1]);
|
|
385
|
+
const [missing, current] = await thread(id);
|
|
386
|
+
if (missing) return failure(missing);
|
|
387
|
+
const action = parts[2];
|
|
388
|
+
if (method === "POST" && action === "comments") {
|
|
389
|
+
const parsed = v.safeParse(replyBody, await readJson(event));
|
|
390
|
+
if (!parsed.success) return invalid(parsed.issues);
|
|
391
|
+
const [denied, allowed] = await access(event, "comment", current);
|
|
392
|
+
if (denied) return failure(denied);
|
|
393
|
+
if (!allowed.author) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }));
|
|
394
|
+
return respond(await writes.reply(allowed.grant, id, {
|
|
395
|
+
...parsed.output,
|
|
396
|
+
author: allowed.author
|
|
397
|
+
}));
|
|
398
|
+
}
|
|
399
|
+
if (method === "POST" && (action === "resolve" || action === "reopen")) {
|
|
400
|
+
const [denied, allowed] = await access(event, "resolve", current);
|
|
401
|
+
if (denied) return failure(denied);
|
|
402
|
+
if (action === "reopen") return await respondThread(event, allowed.user, await writes.reopen(allowed.grant, id));
|
|
403
|
+
return await respondThread(event, allowed.user, await writes.resolve(allowed.grant, id, allowed.author ?? {
|
|
404
|
+
id: "anonymous",
|
|
405
|
+
name: "Someone"
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
if (method === "DELETE" && action === "comments" && parts[3]) {
|
|
409
|
+
const commentId = decodeURIComponent(parts[3]);
|
|
410
|
+
const comment = current.comments.find((candidate) => candidate.id === commentId);
|
|
411
|
+
if (!comment) return failure(commentsErrors.COMMENTS_NOT_FOUND({ id: commentId }));
|
|
412
|
+
const [denied, allowed] = await access(event, "comment", current);
|
|
413
|
+
if (!denied && allowed.user && !allowed.user.guest && !comment.author.guest && comment.author.id === allowed.user.id) return respond(await writes.removeComment(allowed.grant, id, commentId));
|
|
414
|
+
const [cannot, resolver] = await access(event, "resolve", current);
|
|
415
|
+
if (cannot) return failure(cannot);
|
|
416
|
+
if (!resolver.user || resolver.user.guest) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "resolve" }));
|
|
417
|
+
return respond(await writes.removeComment(resolver.grant, id, commentId));
|
|
418
|
+
}
|
|
419
|
+
if (method === "DELETE" && !action) {
|
|
420
|
+
const [denied, allowed] = await access(event, "resolve", current);
|
|
421
|
+
if (denied) return failure(denied);
|
|
422
|
+
if (!allowed.user || allowed.user.guest) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "resolve" }));
|
|
423
|
+
return respond(await writes.remove(allowed.grant, id));
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (method === "GET" && path === "/people") {
|
|
427
|
+
const [denied, allowed] = await access(event, "read");
|
|
428
|
+
if (denied) return failure(denied);
|
|
429
|
+
return respond(await comments.people({
|
|
430
|
+
query: url.searchParams.get("q") ?? "",
|
|
431
|
+
user: allowed.user
|
|
432
|
+
}));
|
|
433
|
+
}
|
|
434
|
+
if (path === "/fields") {
|
|
435
|
+
if (method === "GET") return await readField(event, url.searchParams.get("field") ?? "");
|
|
436
|
+
if (method === "POST") return await saveField(event);
|
|
437
|
+
}
|
|
438
|
+
return json({ error: {
|
|
439
|
+
code: "COMMENTS_NOT_FOUND",
|
|
440
|
+
why: `No Comments route ${method} ${path}.`
|
|
441
|
+
} }, { status: 404 });
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region src/runtime/console-session.ts
|
|
446
|
+
/**
|
|
447
|
+
* The user of a request from the Console access rules: the person must be allowed to use the Console `comments`
|
|
448
|
+
* section. People that the Console does not allow get `false`, which denies access before Comments guest policies.
|
|
449
|
+
* A Console without accounts, such as `console: { auth: false }` or the dev server, stays anonymous to policies.
|
|
450
|
+
* Guest authors name themselves in the overlay; their browser display data never becomes a policy user.
|
|
451
|
+
*/
|
|
452
|
+
function commentsConsoleSession(access) {
|
|
453
|
+
return async (event, action = "read") => {
|
|
454
|
+
if (!await access.authorize({
|
|
455
|
+
event,
|
|
456
|
+
kind: action === "read" ? "read" : "write"
|
|
457
|
+
})) return false;
|
|
458
|
+
const user = await access.user({ event });
|
|
459
|
+
const id = text(user?.id) ?? text(user?.email);
|
|
460
|
+
if (user && id) return {
|
|
461
|
+
...user,
|
|
462
|
+
id
|
|
463
|
+
};
|
|
464
|
+
const person = await access.identify({ event });
|
|
465
|
+
const openGuest = person && !person.email && /^guest-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(person.id);
|
|
466
|
+
if (person && !openGuest) return { ...person };
|
|
467
|
+
return null;
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
new TextEncoder();
|
|
471
|
+
/** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
|
|
472
|
+
const viteHubSecretSalt = "vitehub";
|
|
473
|
+
/**
|
|
474
|
+
* Reads the root app secret from an env record: `VITEHUB_SECRET`, then `NUXT_APP_SECRET`, so a Nuxt app needs only one
|
|
475
|
+
* secret. Returns `undefined` when neither is a non-empty string.
|
|
476
|
+
*/
|
|
477
|
+
function readViteHubSecret(env) {
|
|
478
|
+
for (const name of ["VITEHUB_SECRET", "NUXT_APP_SECRET"]) {
|
|
479
|
+
const value = env[name];
|
|
480
|
+
if (typeof value === "string" && value) return value;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region src/runtime/github-login.ts
|
|
485
|
+
/** The Server Env names of the OAuth client that people sign in to Comments with: a GitHub App's, or an OAuth App's. */
|
|
486
|
+
const githubLoginEnv = {
|
|
487
|
+
clientId: "VITEHUB_GITHUB_CLIENT_ID",
|
|
488
|
+
clientSecret: "VITEHUB_GITHUB_CLIENT_SECRET"
|
|
489
|
+
};
|
|
490
|
+
/** Where Better Auth serves the GitHub sign-in of Comments. */
|
|
491
|
+
const githubLoginPath = `${commentsRoute}/auth`;
|
|
492
|
+
/** How long a sign-in lasts. The session is in an encrypted cookie, so it cannot be revoked before then. */
|
|
493
|
+
const sessionLifetime = "7d";
|
|
494
|
+
/** How long Comments trusts the repository access that GitHub reported for a person. */
|
|
495
|
+
const accessLifetime = 3e5;
|
|
496
|
+
const userResponse = v.object({ login: v.string() });
|
|
497
|
+
const repositoryResponse = v.object({ permissions: v.optional(v.object({ push: v.optional(v.boolean()) })) });
|
|
498
|
+
function serverEnv(name) {
|
|
499
|
+
const value = getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
|
|
500
|
+
return typeof value === "string" && value ? value : void 0;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* The secret of the session cookies: derived from `VITEHUB_SECRET` for Comments alone, so the app's own Auth cookies
|
|
504
|
+
* and these never open each other. Without a root secret, Better Auth uses its development secret, and fails in
|
|
505
|
+
* production.
|
|
506
|
+
*/
|
|
507
|
+
function sessionSecret() {
|
|
508
|
+
const root = readViteHubSecret({
|
|
509
|
+
VITEHUB_SECRET: serverEnv("VITEHUB_SECRET"),
|
|
510
|
+
NUXT_APP_SECRET: serverEnv("NUXT_APP_SECRET")
|
|
511
|
+
});
|
|
512
|
+
if (!root) return;
|
|
513
|
+
if (root.length < 32) throw new TypeError(`[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`);
|
|
514
|
+
const bytes = new Uint8Array(hkdfSync("sha256", root, viteHubSecretSalt, "vitehub:comments:auth", 32));
|
|
515
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
516
|
+
}
|
|
517
|
+
/** A return path on this site, so the sign-in cannot send people elsewhere. */
|
|
518
|
+
function safeReturn(value) {
|
|
519
|
+
return value && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\") ? value : "/?vitehub";
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Sign in with GitHub for Comments, with no database: ViteHub Auth's `stateless()` preset keeps the session, and the
|
|
523
|
+
* GitHub token, in encrypted cookies. A person may comment when GitHub says they can push to the repository of the
|
|
524
|
+
* build.
|
|
525
|
+
*/
|
|
526
|
+
function createCommentsGitHubLogin(options = {}) {
|
|
527
|
+
const apiUrl = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
528
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
529
|
+
const instances = /* @__PURE__ */ new Map();
|
|
530
|
+
const access = /* @__PURE__ */ new Map();
|
|
531
|
+
function auth(event, request) {
|
|
532
|
+
const clientId = serverEnv(githubLoginEnv.clientId);
|
|
533
|
+
const clientSecret = serverEnv(githubLoginEnv.clientSecret);
|
|
534
|
+
const secret = sessionSecret();
|
|
535
|
+
const origin = forwardedRequestOrigin(request);
|
|
536
|
+
const key = [
|
|
537
|
+
origin,
|
|
538
|
+
clientId,
|
|
539
|
+
clientSecret,
|
|
540
|
+
secret
|
|
541
|
+
].join("\0");
|
|
542
|
+
let instance = instances.get(key);
|
|
543
|
+
if (!instance) {
|
|
544
|
+
const definition = defineAuth(() => ({
|
|
545
|
+
baseURL: origin,
|
|
546
|
+
basePath: options.basePath ?? githubLoginPath,
|
|
547
|
+
...secret ? { secret } : {},
|
|
548
|
+
preset: stateless({ maxAge: sessionLifetime }),
|
|
549
|
+
socialProviders: { github: {
|
|
550
|
+
clientId,
|
|
551
|
+
clientSecret,
|
|
552
|
+
mapProfileToUser: (profile) => profile.email ? {} : { email: `${profile.id}+${profile.login}@users.noreply.github.com` }
|
|
553
|
+
} },
|
|
554
|
+
advanced: { cookiePrefix: "vitehub_comments" }
|
|
555
|
+
}));
|
|
556
|
+
instance = createAuthForRequest(definition, request, void 0, event);
|
|
557
|
+
if (instances.size > 20) instances.clear();
|
|
558
|
+
instances.set(key, instance);
|
|
559
|
+
}
|
|
560
|
+
return instance;
|
|
561
|
+
}
|
|
562
|
+
async function github(token, path) {
|
|
563
|
+
const response = await fetcher(`${apiUrl}${path}`, { headers: {
|
|
564
|
+
"accept": "application/vnd.github+json",
|
|
565
|
+
"authorization": `Bearer ${token}`,
|
|
566
|
+
"user-agent": "vitehub-comments",
|
|
567
|
+
"x-github-api-version": "2022-11-28"
|
|
568
|
+
} });
|
|
569
|
+
if (response.status === 404) return void 0;
|
|
570
|
+
if (!response.ok) throw new Error(`GitHub GET ${path} failed with ${response.status}`);
|
|
571
|
+
return await response.json();
|
|
572
|
+
}
|
|
573
|
+
/** The GitHub login of a person, and whether they can push to the repository. */
|
|
574
|
+
async function accessOf(userId, token) {
|
|
575
|
+
const key = `${userId}\0${options.repository ?? ""}`;
|
|
576
|
+
const cached = access.get(key);
|
|
577
|
+
if (cached && cached.until > Date.now()) return {
|
|
578
|
+
login: cached.login,
|
|
579
|
+
...cached.repository ? { repository: cached.repository } : {},
|
|
580
|
+
write: cached.write
|
|
581
|
+
};
|
|
582
|
+
const [user, repository] = await Promise.all([github(token, "/user"), options.repository ? github(token, `/repos/${options.repository}`) : void 0]);
|
|
583
|
+
const login = v.parse(userResponse, user).login;
|
|
584
|
+
const write = repository === void 0 ? false : v.parse(repositoryResponse, repository).permissions?.push === true;
|
|
585
|
+
const result = {
|
|
586
|
+
login,
|
|
587
|
+
...options.repository ? { repository: options.repository } : {},
|
|
588
|
+
write
|
|
589
|
+
};
|
|
590
|
+
if (access.size > 1e3) access.clear();
|
|
591
|
+
access.set(key, {
|
|
592
|
+
...result,
|
|
593
|
+
until: Date.now() + accessLifetime
|
|
594
|
+
});
|
|
595
|
+
return result;
|
|
596
|
+
}
|
|
597
|
+
const configured = () => Boolean(serverEnv(githubLoginEnv.clientId) && serverEnv(githubLoginEnv.clientSecret));
|
|
598
|
+
return {
|
|
599
|
+
configured,
|
|
600
|
+
async user(event) {
|
|
601
|
+
if (!configured()) return null;
|
|
602
|
+
const request = requestOf(event);
|
|
603
|
+
const instance = auth(event, request);
|
|
604
|
+
const user = (await instance.api.getSession({ headers: request.headers }))?.user;
|
|
605
|
+
if (!user || typeof user !== "object" || !("id" in user) || typeof user.id !== "string") return null;
|
|
606
|
+
const accessToken = await instance.api.getAccessToken({
|
|
607
|
+
body: { useAccountCookie: true },
|
|
608
|
+
headers: request.headers
|
|
609
|
+
}).then((tokens) => tokens.accessToken, () => void 0);
|
|
610
|
+
if (!accessToken) return null;
|
|
611
|
+
const githubAccess = await accessOf(user.id, accessToken);
|
|
612
|
+
rememberGitHubToken(user.id, accessToken);
|
|
613
|
+
const name = "name" in user && typeof user.name === "string" && user.name ? user.name : githubAccess.login;
|
|
614
|
+
return {
|
|
615
|
+
...user,
|
|
616
|
+
id: user.id,
|
|
617
|
+
name,
|
|
618
|
+
github: githubAccess
|
|
619
|
+
};
|
|
620
|
+
},
|
|
621
|
+
async handle(event, path) {
|
|
622
|
+
if (!configured()) return Response.json({ error: {
|
|
623
|
+
code: "COMMENTS_SIGN_IN_OFF",
|
|
624
|
+
why: "This site has no GitHub sign-in for Comments.",
|
|
625
|
+
fix: `Set ${githubLoginEnv.clientId} and ${githubLoginEnv.clientSecret} on the server.`
|
|
626
|
+
} }, { status: 404 });
|
|
627
|
+
const request = requestOf(event);
|
|
628
|
+
const instance = auth(event, request);
|
|
629
|
+
const url = new URL(request.url);
|
|
630
|
+
if (path === "/auth/github" && request.method === "GET") {
|
|
631
|
+
const response = await instance.api.signInSocial({
|
|
632
|
+
body: {
|
|
633
|
+
provider: "github",
|
|
634
|
+
callbackURL: safeReturn(url.searchParams.get("return")),
|
|
635
|
+
disableRedirect: true
|
|
636
|
+
},
|
|
637
|
+
headers: request.headers,
|
|
638
|
+
asResponse: true
|
|
639
|
+
});
|
|
640
|
+
const body = await response.json().catch(() => void 0);
|
|
641
|
+
const target = body && typeof body === "object" && "url" in body && typeof body.url === "string" ? body.url : void 0;
|
|
642
|
+
if (!target) return Response.json({ error: {
|
|
643
|
+
code: "COMMENTS_SIGN_IN_FAILED",
|
|
644
|
+
why: "GitHub sign-in could not start."
|
|
645
|
+
} }, { status: 502 });
|
|
646
|
+
const headers = new Headers({
|
|
647
|
+
"location": target,
|
|
648
|
+
"cache-control": "no-store"
|
|
649
|
+
});
|
|
650
|
+
for (const cookie of response.headers.getSetCookie()) headers.append("set-cookie", cookie);
|
|
651
|
+
return new Response(null, {
|
|
652
|
+
status: 302,
|
|
653
|
+
headers
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
if (path === "/auth/sign-out") {
|
|
657
|
+
const session = await instance.api.getSession({ headers: request.headers }).catch(() => null);
|
|
658
|
+
if (session?.user.id) forgetGitHubToken(session.user.id);
|
|
659
|
+
}
|
|
660
|
+
return await instance.handler(request);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
//#endregion
|
|
665
|
+
export { commentsConsoleSession, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, viteHubPageSessionHandler };
|