@hazem3500/palette 0.9.130 → 0.9.131

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hazem3500/palette",
3
- "version": "0.9.130",
3
+ "version": "0.9.131",
4
4
  "description": "Point, area, and threaded comments for website branches.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,6 +31,7 @@
31
31
  "server/iap.ts",
32
32
  "server/proxy-auth.ts",
33
33
  "server/tokens.ts",
34
+ "server/bot-tokens.ts",
34
35
  "server/account-page.ts",
35
36
  "server/public-env.ts",
36
37
  "server/snapshots.ts",
@@ -0,0 +1,38 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { check, string } from "./validation";
3
+ import type { PatAccess } from "./tokens";
4
+
5
+ const PREFIX = "palette_bot_";
6
+ const hash = async (value: string) =>
7
+ Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))), (b) => b.toString(16).padStart(2, "0")).join("");
8
+ const random = () => Array.from(crypto.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, "0")).join("");
9
+ export const isBotToken = (value: string) => value.startsWith(PREFIX);
10
+
11
+ /** Owner-only issuance. Bot grants never confer project administration. */
12
+ export async function createBotToken(env: Env, project: string, owner: string, data: Record<string, unknown>) {
13
+ const name = string(data.name, 80, "bot name");
14
+ const id = crypto.randomUUID();
15
+ const secret = random();
16
+ const userId = `bot:${id}`;
17
+ const now = Date.now();
18
+ const count = await env.DB.prepare("SELECT COUNT(*) AS used FROM project_bot_tokens WHERE project=? AND revoked_at IS NULL").bind(project).first<{ used: number }>();
19
+ check((count?.used ?? 0) < 10, 409, "Revoke a bot token before adding another.");
20
+ await env.DB.batch([
21
+ env.DB.prepare("INSERT INTO users(id,name,verified) VALUES(?,?,1)").bind(userId, name),
22
+ env.DB.prepare("INSERT INTO project_bot_tokens(id,project,user_id,token_hash,created_by,created_at,revoked_at) VALUES(?,?,?,?,?,?,NULL)").bind(id, project, userId, await hash(secret), owner, now),
23
+ ]);
24
+ return { id, userId, name, token: `${PREFIX}${id}_${secret}` };
25
+ }
26
+
27
+ export async function authenticateBotToken(env: Env, bearer: string, project: string, access: PatAccess | undefined, request: Request) {
28
+ const parts = /^palette_bot_([a-f0-9-]{36})_([a-f0-9]{64})$/.exec(bearer);
29
+ const row = parts ? await env.DB.prepare("SELECT b.project,b.token_hash,b.revoked_at,u.id,u.name,u.verified,u.avatar_url FROM project_bot_tokens b JOIN users u ON u.id=b.user_id WHERE b.id=?").bind(parts[1]).first<{project:string;token_hash:string;revoked_at:number|null;id:string;name:string;verified:number;avatar_url?:string}>() : null;
30
+ const given = await hash(parts?.[2] ?? "");
31
+ const stored = row?.token_hash ?? "0".repeat(64);
32
+ check(row && stored.length === given.length && timingSafeEqual(new TextEncoder().encode(stored), new TextEncoder().encode(given)) && row.revoked_at === null && row.project === project, 401, "Invalid or revoked bot token.");
33
+ const path = new URL(request.url).pathname;
34
+ // Read context, snapshots and identity; write replies only. No new threads,
35
+ // edits, deletes, reactions, settings or membership administration.
36
+ check(access && ((request.method === "GET" && (path === "/threads" || /^\/threads\/[^/]+\/snapshot(?:\/image)?$/.test(path) || path === "/me" || path === "/config")) || (request.method === "POST" && /^\/threads\/[^/]+\/comments$/.test(path))), 403, "Bot tokens may read threads and post replies only.");
37
+ return row;
38
+ }
package/server/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { authenticateBotToken, isBotToken } from "./bot-tokens";
1
2
  import { projectSites, saveProjectSites } from "./project-sites";
2
3
  import {
3
4
  manageProject,
@@ -110,7 +111,7 @@ function webhookEvent(
110
111
  threadId: string,
111
112
  page: string,
112
113
  anchor: string,
113
- author: string,
114
+ author: Identity,
114
115
  body: string | null,
115
116
  origin: string
116
117
  ): WebhookEvent {
@@ -130,7 +131,8 @@ function webhookEvent(
130
131
  threadId,
131
132
  pageUrl: new URL(page, origin).toString(),
132
133
  selector,
133
- author,
134
+ author: author.name,
135
+ authorId: author.id,
134
136
  body,
135
137
  };
136
138
  }
@@ -179,6 +181,8 @@ async function body(request: Request): Promise<Record<string, unknown>> {
179
181
  ? ["user"]
180
182
  : path === "/project/sites"
181
183
  ? ["sites"]
184
+ : path === "/project/bots"
185
+ ? ["name"]
182
186
  : path === "/project/webhook"
183
187
  ? ["url", "secret", "events", "enabled"]
184
188
  : ["access", "confirm", "threadIds"]
@@ -308,6 +312,7 @@ async function authenticate(
308
312
  ?.match(/^Bearer (.{1,200})$/)?.[1];
309
313
  check(bearer, 401, "Enter your name to comment.");
310
314
  const { proxy, proxyAccessTokens, sessionMaxAge, allowGuests } = authOptions(env);
315
+ if (isBotToken(bearer)) return identity(await authenticateBotToken(env, bearer, project, access, request));
311
316
  if (isPersonalToken(bearer)) {
312
317
  check(
313
318
  !proxy || proxyAccessTokens,
@@ -1628,7 +1633,7 @@ async function route(
1628
1633
  id,
1629
1634
  page,
1630
1635
  JSON.stringify(anchor),
1631
- user.name,
1636
+ user,
1632
1637
  text,
1633
1638
  origin || url.origin
1634
1639
  ), ...(snapshotStatus ? { snapshotStatus } : {}), ...(data.share === false ? { share: false } : {}) }, firstCommentId),
@@ -1864,7 +1869,7 @@ async function route(
1864
1869
  ).bind(Number(data.resolved), data.resolved ? user.id : null, now, threadId),
1865
1870
  ...(firstComment ? [enqueueWebhook(env.DB, project, webhookEvent(
1866
1871
  "comment.resolved", project, repo, branch, threadId, thread.page,
1867
- thread.anchor, user.name, null, origin || url.origin
1872
+ thread.anchor, user, null, origin || url.origin
1868
1873
  ), firstComment.id)] : []),
1869
1874
  ]);
1870
1875
  ctx.waitUntil(drainWebhooks(env));
@@ -1893,7 +1898,7 @@ async function route(
1893
1898
  threadId,
1894
1899
  thread.page,
1895
1900
  thread.anchor,
1896
- user.name,
1901
+ user,
1897
1902
  text,
1898
1903
  origin || url.origin
1899
1904
  ), replyId),
@@ -0,0 +1,10 @@
1
+ CREATE TABLE project_bot_tokens (
2
+ id text PRIMARY KEY,
3
+ project text NOT NULL,
4
+ user_id text NOT NULL REFERENCES users(id),
5
+ token_hash text NOT NULL,
6
+ created_by text NOT NULL REFERENCES users(id),
7
+ created_at bigint NOT NULL,
8
+ revoked_at bigint
9
+ );
10
+ CREATE INDEX project_bot_tokens_project ON project_bot_tokens(project);
@@ -1,3 +1,4 @@
1
+ import { createBotToken } from "./bot-tokens";
1
2
  import { importProject } from "./import-project";
2
3
  import { projectSites, saveProjectSites } from "./project-sites";
3
4
  import { check, string } from "./validation";
@@ -23,6 +24,11 @@ export async function privateAccess(env: Env, project: string) {
23
24
  );
24
25
  }
25
26
  export async function requireMember(env: Env, project: string, user: Identity) {
27
+ if (user.id.startsWith("bot:")) {
28
+ const grant = await env.DB.prepare("SELECT id FROM project_bot_tokens WHERE user_id=? AND project=? AND revoked_at IS NULL").bind(user.id, project).first();
29
+ check(grant, 403, "This bot is not allowed for this project.");
30
+ return;
31
+ }
26
32
  check(
27
33
  user.verified && user.id.startsWith("google:"),
28
34
  403,
@@ -86,6 +92,17 @@ export async function manageProject(
86
92
  return Response.json({ ok: true });
87
93
  }
88
94
  await googleOwner(env, project, user);
95
+ if (path === "/project/bots" && request.method === "POST")
96
+ return Response.json(await createBotToken(env, project, user.id, await readBody()), { status: 201 });
97
+ if (path === "/project/bots" && request.method === "GET") {
98
+ const rows = await env.DB.prepare("SELECT id,user_id,created_at,revoked_at FROM project_bot_tokens WHERE project=? ORDER BY created_at DESC").bind(project).all();
99
+ return Response.json({ bots: rows.results });
100
+ }
101
+ const botId = /^\/project\/bots\/([a-f0-9-]{36})$/.exec(path)?.[1];
102
+ if (botId && request.method === "DELETE") {
103
+ await env.DB.prepare("UPDATE project_bot_tokens SET revoked_at=? WHERE id=? AND project=? AND revoked_at IS NULL").bind(Date.now(), botId, project).run();
104
+ return Response.json({ ok: true });
105
+ }
89
106
  if (path === "/project/webhook" && request.method === "GET") {
90
107
  const row = await env.DB.prepare(
91
108
  "SELECT webhook_url,webhook_secret,webhook_events,webhook_enabled FROM project_settings WHERE project=?"
@@ -18,6 +18,10 @@ export type WebhookEvent = {
18
18
  pageUrl: string;
19
19
  selector: string;
20
20
  author: string;
21
+ /** Stable identity for consumers to reject their own bot replies. */
22
+ authorId?: string;
23
+ /** The comment that emitted this event, not the thread's first comment. */
24
+ commentId?: string;
21
25
  body: string | null;
22
26
  snapshotStatus?: "pending" | "skipped";
23
27
  /** Present and false when the reviewer chose to keep this comment in Palette. */
@@ -221,7 +225,7 @@ export function enqueueWebhook(
221
225
  .bind(
222
226
  event.id,
223
227
  project,
224
- JSON.stringify(event),
228
+ JSON.stringify({ ...event, commentId }),
225
229
  Date.now(),
226
230
  commentId,
227
231
  project,