starlight-annotations 0.5.1 â 0.7.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/CHANGELOG.md +13 -0
- package/README.md +1 -0
- package/index.d.ts +6 -0
- package/package.json +1 -1
- package/server.d.ts +65 -2
- package/src/client/anchoring.js +70 -0
- package/src/client/annotations.js +92 -73
- package/src/client/i18n.js +30 -0
- package/src/client/overview.js +42 -8
- package/src/client/styles.css +18 -0
- package/src/core.js +30 -2
- package/src/server/gitea.js +1 -1
- package/src/server/github.js +14 -3
- package/src/server/gitlab.js +1 -1
- package/src/server/index.js +77 -7
- package/src/server/notify.js +133 -0
- package/src/server/oauth.js +53 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# starlight-annotations
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 25427bd: Authors can edit their notes and replies, which then show "edited". A note whose text is gone from the page can be attached to another passage with **Attach to other text**. The overview page marks these notes **Text changed** and filters them. The server has two new actions, `edit` and `anchor`, which `onChange` receives too; the Slack and Teams senders skip them unless asked.
|
|
8
|
+
|
|
9
|
+
## 0.6.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- f1ec199: Adds `emails: true` to the GitHub, GitLab and Gitea auths, to email the author of a note when someone else answers or resolves it. The reader's email is read at sign-in (`user:email` on a GitHub OAuth app; the "Email addresses" account permission on a GitHub App) and stored on their notes encrypted with a key derived from the session secret, never in clear in the repository or in API responses. `onChange` events gain `threadAuthor: { login, name, email }`.
|
|
14
|
+
- 3121a8f: Adds notifications: `createAnnotationsHandler({ ..., onChange })` calls a listener (or a list) after every saved change, with the action (`create`, `reply`, `resolve`, `reopen`, `delete`), the page, a link that opens the note, who made the change, the note and its thread, and the logins of the other participants and of `@mentions`. `slackWebhook(url)` and `teamsWebhook(url)` post to a Slack or Microsoft Teams channel, and `describeChange(event)` gives plain text for email or anything else. A failing listener never fails the save; pass the platform context (`handler(request, ctx)`) and it runs after the response with `waitUntil`.
|
|
15
|
+
|
|
3
16
|
## 0.5.1
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ Let readers highlight text and leave notes on your [Starlight](https://starlight
|
|
|
15
15
|
- ðïļ **All notes on one page.** An overview of every note on the site, filtered by status, author or text, each one a click away from its passage.
|
|
16
16
|
- ð **Anchored to the text.** W3C Web Annotation selectors: notes find their place again after edits, and long passages are stored by their start and end.
|
|
17
17
|
- ðïļ **Your repo, your data.** One file per page on a branch of its own; every note is a commit by its author. Works with **GitHub**, **GitLab** (gitlab.com or self-managed) and **Gitea / Forgejo** (including Codeberg).
|
|
18
|
+
- ð **Notifications.** Post new notes and replies to Slack, Microsoft Teams or email with one `onChange` option.
|
|
18
19
|
- ð **Runs anywhere.** The API is one Web-standard handler for Cloudflare Workers, Netlify, Vercel, Deno or Node. Or keep personal notes in the browser, with no server.
|
|
19
20
|
- ðŠķ **Light and safe.** Highlights use the CSS Custom Highlight API, so the page markup is never rewritten. Notes cannot inject HTML, and the Markdown parser loads only when it is needed.
|
|
20
21
|
- ð **Multilingual.** English, Italian, German, French and Spanish built in; the UI follows the page language.
|
package/index.d.ts
CHANGED
|
@@ -59,6 +59,12 @@ export type AnnotationStrings = {
|
|
|
59
59
|
showing: string;
|
|
60
60
|
author: string;
|
|
61
61
|
seeAll: string;
|
|
62
|
+
edit: string;
|
|
63
|
+
edited: string;
|
|
64
|
+
move: string;
|
|
65
|
+
moveHint: string;
|
|
66
|
+
moveHere: string;
|
|
67
|
+
textChanged: string;
|
|
62
68
|
};
|
|
63
69
|
|
|
64
70
|
export interface StarlightAnnotationsOptions {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "starlight-annotations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "ðïļ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository on GitHub, GitLab, Gitea or Forgejo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Alessandro Rosa",
|
package/server.d.ts
CHANGED
|
@@ -32,17 +32,70 @@ export interface Auth {
|
|
|
32
32
|
noAccess?(login: string): string;
|
|
33
33
|
/** A `Set-Cookie` value that ends the session, sent with a refusal. */
|
|
34
34
|
clearSession?: string;
|
|
35
|
+
/** Seals an email for a notes file (with `emails`). */
|
|
36
|
+
sealContact?(email: string): Promise<string>;
|
|
37
|
+
/** Opens a sealed email, or `null`. */
|
|
38
|
+
openContact?(sealed: string): Promise<string | null>;
|
|
35
39
|
}
|
|
36
40
|
|
|
41
|
+
export type AnnotationAction = 'create' | 'reply' | 'resolve' | 'reopen' | 'edit' | 'anchor' | 'delete';
|
|
42
|
+
|
|
43
|
+
/** What `onChange` receives after every saved change. */
|
|
44
|
+
export interface AnnotationEvent {
|
|
45
|
+
action: AnnotationAction;
|
|
46
|
+
/** The page key, e.g. `"rfc/0002-user-data-model"` or `"it/guides/demo"`. */
|
|
47
|
+
page: string;
|
|
48
|
+
/** A link that opens the note on its page (the page alone after a thread is deleted). */
|
|
49
|
+
url: string;
|
|
50
|
+
/** Who made the change. */
|
|
51
|
+
user: { login: string; name: string };
|
|
52
|
+
/** The note created, answered, resolved, reopened or deleted. */
|
|
53
|
+
annotation: Record<string, any>;
|
|
54
|
+
/** The first note of the thread, with the quoted passage. */
|
|
55
|
+
thread: Record<string, any> | null;
|
|
56
|
+
/** For a reply: the message it answers. */
|
|
57
|
+
inReplyTo: Record<string, any> | null;
|
|
58
|
+
/** Logins of everyone else who wrote in the thread. */
|
|
59
|
+
participants: string[];
|
|
60
|
+
/** Logins mentioned with `@login` in a new note or reply, except the writer. */
|
|
61
|
+
mentions: string[];
|
|
62
|
+
/** Who opened the thread, when it is not `user`. `email` needs `emails: true` in the auth. */
|
|
63
|
+
threadAuthor: { login: string; name: string; email: string | null } | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type OnChange = (event: AnnotationEvent) => void | Promise<void>;
|
|
67
|
+
|
|
37
68
|
export interface HandlerOptions {
|
|
38
69
|
storage: Storage;
|
|
39
70
|
auth?: Auth;
|
|
40
71
|
/** Path the handler answers on, including the site base. Default `"/_annotations"`. */
|
|
41
72
|
prefix?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Called after every saved change, e.g. to post to Slack or Teams. A failing listener is
|
|
75
|
+
* logged and never fails the save. Pass the platform context (`waitUntil`) to the handler
|
|
76
|
+
* so the response does not wait for it.
|
|
77
|
+
*/
|
|
78
|
+
onChange?: OnChange | OnChange[];
|
|
79
|
+
/** The address of a page, for `event.url`. Default: the page the reader saved from. */
|
|
80
|
+
pageUrl?: (page: string, request: Request) => string;
|
|
42
81
|
}
|
|
43
82
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
83
|
+
/**
|
|
84
|
+
* A Web-standard handler. Resolves to `null` when the path is not under `prefix`. `context` is the
|
|
85
|
+
* platform's (Cloudflare `ctx`, Vercel, Netlify): with `waitUntil`, notifications run after the response.
|
|
86
|
+
*/
|
|
87
|
+
export function createAnnotationsHandler(
|
|
88
|
+
options: HandlerOptions,
|
|
89
|
+
): (request: Request, context?: { waitUntil(promise: Promise<unknown>): void }) => Promise<Response | null>;
|
|
90
|
+
|
|
91
|
+
/** Plain text for any channel: `title`, `quote`, `body`, and all of them with the link as `text`. */
|
|
92
|
+
export function describeChange(event: AnnotationEvent): { title: string; quote: string; body: string; text: string };
|
|
93
|
+
|
|
94
|
+
/** An `onChange` that posts to a Slack incoming webhook. */
|
|
95
|
+
export function slackWebhook(webhookUrl: string, options?: { actions?: AnnotationAction[] }): OnChange;
|
|
96
|
+
|
|
97
|
+
/** An `onChange` that posts an Adaptive Card to a Microsoft Teams Workflows webhook. */
|
|
98
|
+
export function teamsWebhook(webhookUrl: string, options?: { actions?: AnnotationAction[] }): OnChange;
|
|
46
99
|
|
|
47
100
|
export interface GitHubStorageOptions {
|
|
48
101
|
/** `owner/name` of the repository that stores the notes. */
|
|
@@ -85,6 +138,11 @@ export interface GitHubAuthOptions {
|
|
|
85
138
|
repo?: string;
|
|
86
139
|
token?: string | (() => Promise<string>);
|
|
87
140
|
app?: GitHubAppOptions;
|
|
141
|
+
/**
|
|
142
|
+
* Read the reader's email at sign-in and store it, encrypted with the session secret, on their
|
|
143
|
+
* notes, so `onChange` can email the author of a note (`event.threadAuthor.email`). Default false.
|
|
144
|
+
*/
|
|
145
|
+
emails?: boolean;
|
|
88
146
|
/**
|
|
89
147
|
* Seconds between checks that a signed-in user may still write, on saves and page loads.
|
|
90
148
|
* `false` checks only at sign-in. Default 60.
|
|
@@ -120,6 +178,11 @@ interface CommonAuthOptions {
|
|
|
120
178
|
* `token`. `"anyone"` accepts every signed-in user.
|
|
121
179
|
*/
|
|
122
180
|
writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
|
|
181
|
+
/**
|
|
182
|
+
* Read the reader's email at sign-in and store it, encrypted with the session secret, on their
|
|
183
|
+
* notes, so `onChange` can email the author of a note (`event.threadAuthor.email`). Default false.
|
|
184
|
+
*/
|
|
185
|
+
emails?: boolean;
|
|
123
186
|
/**
|
|
124
187
|
* Seconds between checks that a signed-in user may still write, on saves and page loads.
|
|
125
188
|
* `false` checks only at sign-in. Default 60.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Finding a stored quote in a page's text. Shared by the page panel and the
|
|
2
|
+
// overview, which checks pages it fetched for notes whose text has changed.
|
|
3
|
+
|
|
4
|
+
// Text the reader does not see as content: diagrams (rendered late), heading
|
|
5
|
+
// anchor links ("Section titled âĶ"), buttons, and the selectors you add.
|
|
6
|
+
export function skipSelector(exclude = []) {
|
|
7
|
+
return ['pre.mermaid', 'svg', 'script', 'style', 'button', '.sl-anchor-link', '.annot-ui', ...exclude].join(', ');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// The text of `root` as one string, with each text node's offset. `skip`
|
|
11
|
+
// names the elements whose text the reader does not see as content.
|
|
12
|
+
export function buildIndex(root, skip) {
|
|
13
|
+
const nodes = [];
|
|
14
|
+
const byNode = new Map();
|
|
15
|
+
let text = '';
|
|
16
|
+
const walker = (root.ownerDocument ?? document).createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
17
|
+
acceptNode: (node) =>
|
|
18
|
+
node.parentElement && !node.parentElement.closest(skip) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
|
|
19
|
+
});
|
|
20
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
21
|
+
const entry = { node, start: text.length };
|
|
22
|
+
nodes.push(entry);
|
|
23
|
+
byNode.set(node, entry);
|
|
24
|
+
text += node.data;
|
|
25
|
+
}
|
|
26
|
+
return { text, nodes, byNode };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function shared(a, b, fromEnd) {
|
|
30
|
+
let n = 0;
|
|
31
|
+
const max = Math.min(a.length, b.length);
|
|
32
|
+
while (n < max && (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
|
|
33
|
+
return n;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Finds a quote in the page, at or after `from`. Among several matches, the
|
|
37
|
+
// one whose surrounding text agrees best with the stored context wins; on a
|
|
38
|
+
// tie, the first one.
|
|
39
|
+
function anchorQuote(index, { exact, prefix = '', suffix = '' }, from = 0) {
|
|
40
|
+
const text = index.text;
|
|
41
|
+
const matches = [];
|
|
42
|
+
for (let at = text.indexOf(exact, from); at !== -1; at = text.indexOf(exact, at + 1)) matches.push([at, at + exact.length]);
|
|
43
|
+
if (matches.length === 0) {
|
|
44
|
+
// Whitespace may differ after an edit or a rebuild.
|
|
45
|
+
const pattern = exact.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
|
46
|
+
if (!pattern) return null;
|
|
47
|
+
for (const match of text.matchAll(new RegExp(pattern, 'g'))) {
|
|
48
|
+
if (match.index >= from) matches.push([match.index, match.index + match[0].length]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let best = null;
|
|
52
|
+
let bestScore = -1;
|
|
53
|
+
for (const [start, end] of matches) {
|
|
54
|
+
const score =
|
|
55
|
+
shared(text.slice(Math.max(0, start - prefix.length), start), prefix, true) +
|
|
56
|
+
shared(text.slice(end, end + suffix.length), suffix, false);
|
|
57
|
+
if (score > bestScore) [best, bestScore] = [[start, end], score];
|
|
58
|
+
}
|
|
59
|
+
return best;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A long passage is stored as its start and its end: find the start, then
|
|
63
|
+
// the end after it.
|
|
64
|
+
export function anchor(index, selector) {
|
|
65
|
+
if (selector.type !== 'RangeSelector') return anchorQuote(index, selector);
|
|
66
|
+
const start = anchorQuote(index, selector.startSelector);
|
|
67
|
+
if (!start) return null;
|
|
68
|
+
const end = anchorQuote(index, selector.endSelector, start[1]);
|
|
69
|
+
return end ? [start[0], end[1]] : null;
|
|
70
|
+
}
|
|
@@ -8,13 +8,12 @@
|
|
|
8
8
|
// note cannot inject markup into the page.
|
|
9
9
|
import config from 'virtual:starlight-annotations/config';
|
|
10
10
|
import { createBackend } from './backend.js';
|
|
11
|
+
import { anchor, buildIndex as indexText, skipSelector } from './anchoring.js';
|
|
11
12
|
import { strings } from './i18n.js';
|
|
12
13
|
import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
|
|
13
14
|
|
|
14
15
|
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
|
|
15
|
-
|
|
16
|
-
// anchor links ("Section titled âĶ"), buttons, and the selectors you add.
|
|
17
|
-
const SKIP = ['pre.mermaid', 'svg', 'script', 'style', 'button', '.sl-anchor-link', '.annot-ui', ...config.exclude].join(', ');
|
|
16
|
+
const SKIP = skipSelector(config.exclude);
|
|
18
17
|
const CONTEXT = 32;
|
|
19
18
|
const T = strings(document.documentElement.lang, config.translations);
|
|
20
19
|
const backend = createBackend(config, BASE, T);
|
|
@@ -108,24 +107,10 @@ function pageKey() {
|
|
|
108
107
|
return path || 'index';
|
|
109
108
|
}
|
|
110
109
|
|
|
111
|
-
// ---- Text index: the page text
|
|
110
|
+
// ---- Text index: offsets in the page text, mapped back to DOM nodes ----
|
|
111
|
+
|
|
112
|
+
const buildIndex = (root) => indexText(root, SKIP);
|
|
112
113
|
|
|
113
|
-
function buildIndex(root) {
|
|
114
|
-
const nodes = [];
|
|
115
|
-
const byNode = new Map();
|
|
116
|
-
let text = '';
|
|
117
|
-
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
118
|
-
acceptNode: (node) =>
|
|
119
|
-
node.parentElement && !node.parentElement.closest(SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
|
|
120
|
-
});
|
|
121
|
-
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
122
|
-
const entry = { node, start: text.length };
|
|
123
|
-
nodes.push(entry);
|
|
124
|
-
byNode.set(node, entry);
|
|
125
|
-
text += node.data;
|
|
126
|
-
}
|
|
127
|
-
return { text, nodes, byNode };
|
|
128
|
-
}
|
|
129
114
|
|
|
130
115
|
function offsetOf(index, container, offset) {
|
|
131
116
|
const entry = container.nodeType === Node.TEXT_NODE && index.byNode.get(container);
|
|
@@ -152,48 +137,8 @@ function rangeFor(index, start, end) {
|
|
|
152
137
|
return range;
|
|
153
138
|
}
|
|
154
139
|
|
|
155
|
-
function shared(a, b, fromEnd) {
|
|
156
|
-
let n = 0;
|
|
157
|
-
const max = Math.min(a.length, b.length);
|
|
158
|
-
while (n < max && (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
|
|
159
|
-
return n;
|
|
160
|
-
}
|
|
161
140
|
|
|
162
|
-
// Finds a quote in the page, at or after `from`. Among several matches, the
|
|
163
|
-
// one whose surrounding text agrees best with the stored context wins; on a
|
|
164
|
-
// tie, the first one.
|
|
165
|
-
function anchorQuote(index, { exact, prefix = '', suffix = '' }, from = 0) {
|
|
166
|
-
const text = index.text;
|
|
167
|
-
const matches = [];
|
|
168
|
-
for (let at = text.indexOf(exact, from); at !== -1; at = text.indexOf(exact, at + 1)) matches.push([at, at + exact.length]);
|
|
169
|
-
if (matches.length === 0) {
|
|
170
|
-
// Whitespace may differ after an edit or a rebuild.
|
|
171
|
-
const pattern = exact.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
|
172
|
-
if (!pattern) return null;
|
|
173
|
-
for (const match of text.matchAll(new RegExp(pattern, 'g'))) {
|
|
174
|
-
if (match.index >= from) matches.push([match.index, match.index + match[0].length]);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
let best = null;
|
|
178
|
-
let bestScore = -1;
|
|
179
|
-
for (const [start, end] of matches) {
|
|
180
|
-
const score =
|
|
181
|
-
shared(text.slice(Math.max(0, start - prefix.length), start), prefix, true) +
|
|
182
|
-
shared(text.slice(end, end + suffix.length), suffix, false);
|
|
183
|
-
if (score > bestScore) [best, bestScore] = [[start, end], score];
|
|
184
|
-
}
|
|
185
|
-
return best;
|
|
186
|
-
}
|
|
187
141
|
|
|
188
|
-
// A long passage is stored as its start and its end: find the start, then
|
|
189
|
-
// the end after it.
|
|
190
|
-
function anchor(index, selector) {
|
|
191
|
-
if (selector.type !== 'RangeSelector') return anchorQuote(index, selector);
|
|
192
|
-
const start = anchorQuote(index, selector.startSelector);
|
|
193
|
-
if (!start) return null;
|
|
194
|
-
const end = anchorQuote(index, selector.endSelector, start[1]);
|
|
195
|
-
return end ? [start[0], end[1]] : null;
|
|
196
|
-
}
|
|
197
142
|
|
|
198
143
|
// Selections longer than LONG keep only their first and last EDGE characters.
|
|
199
144
|
const LONG = config.longQuote;
|
|
@@ -227,6 +172,8 @@ async function start(root) {
|
|
|
227
172
|
pending: null, // the selector of the selection being annotated
|
|
228
173
|
showResolved: false,
|
|
229
174
|
active: null,
|
|
175
|
+
editing: null, // the id of the message being edited
|
|
176
|
+
moving: null, // the id of the thread being attached to new text
|
|
230
177
|
error: '',
|
|
231
178
|
};
|
|
232
179
|
const supportsHighlights = 'highlights' in CSS && typeof Highlight === 'function';
|
|
@@ -346,11 +293,15 @@ async function start(root) {
|
|
|
346
293
|
dateStyle: 'medium',
|
|
347
294
|
timeStyle: 'short',
|
|
348
295
|
});
|
|
349
|
-
|
|
296
|
+
const edited = item.edited
|
|
297
|
+
? h('span', { class: 'annot-edited', title: new Date(item.edited).toLocaleString(document.documentElement.lang || undefined) }, ` · ${T.edited}`)
|
|
298
|
+
: null;
|
|
299
|
+
return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when, edited);
|
|
350
300
|
}
|
|
351
301
|
|
|
352
|
-
function editor(placeholder, onSave, onCancel) {
|
|
302
|
+
function editor(placeholder, onSave, onCancel, initial = '') {
|
|
353
303
|
const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
|
|
304
|
+
area.value = initial;
|
|
354
305
|
const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
|
|
355
306
|
const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
|
|
356
307
|
const tools = h(
|
|
@@ -486,10 +437,49 @@ async function start(root) {
|
|
|
486
437
|
);
|
|
487
438
|
}
|
|
488
439
|
|
|
489
|
-
const
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
440
|
+
const own = (item) => state.user && item.author.login === state.user.login;
|
|
441
|
+
const ownActions = (item, question) =>
|
|
442
|
+
own(item)
|
|
443
|
+
? [
|
|
444
|
+
h('button', { type: 'button', onclick: () => startEditing(item.id) }, T.edit),
|
|
445
|
+
h('button', { type: 'button', class: 'annot-danger', onclick: () => confirm(question) && send({ action: 'delete', id: item.id }) }, T.delete),
|
|
446
|
+
]
|
|
447
|
+
: [];
|
|
448
|
+
|
|
449
|
+
// The message, or an editor on it while its author edits it.
|
|
450
|
+
function text(item) {
|
|
451
|
+
if (state.editing !== item.id || !own(item)) return renderMarkdown(h('div', { class: 'annot-text annot-md' }), item.body);
|
|
452
|
+
return editor(
|
|
453
|
+
item.replyTo ? T.replyPlaceholder : T.placeholder,
|
|
454
|
+
async (value) => {
|
|
455
|
+
if (value.trim() === item.body) {
|
|
456
|
+
stopEditing();
|
|
457
|
+
return true;
|
|
458
|
+
}
|
|
459
|
+
const saved = await send({ action: 'edit', id: item.id, body: value });
|
|
460
|
+
if (!saved) return false;
|
|
461
|
+
stopEditing();
|
|
462
|
+
return true;
|
|
463
|
+
},
|
|
464
|
+
stopEditing,
|
|
465
|
+
item.body,
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// A thread whose text is gone: attach it to the passage it is about now.
|
|
470
|
+
function moveBox() {
|
|
471
|
+
if (anchored || !state.user) return [];
|
|
472
|
+
if (state.moving !== thread.id)
|
|
473
|
+
return [h('div', { class: 'annot-actions' }, h('button', { type: 'button', onclick: () => startMoving(thread.id) }, T.move))];
|
|
474
|
+
return [
|
|
475
|
+
h(
|
|
476
|
+
'div',
|
|
477
|
+
{ class: 'annot-move', role: 'status' },
|
|
478
|
+
h('p', {}, T.moveHint),
|
|
479
|
+
h('button', { type: 'button', onclick: () => startMoving(null) }, T.cancel),
|
|
480
|
+
),
|
|
481
|
+
];
|
|
482
|
+
}
|
|
493
483
|
|
|
494
484
|
card.append(
|
|
495
485
|
h(
|
|
@@ -498,34 +488,35 @@ async function start(root) {
|
|
|
498
488
|
quote(thread.target.selector),
|
|
499
489
|
),
|
|
500
490
|
...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
|
|
501
|
-
|
|
491
|
+
...moveBox(),
|
|
492
|
+
h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), text(thread)),
|
|
502
493
|
...repliesOf(thread.id).map((reply) =>
|
|
503
494
|
h(
|
|
504
495
|
'div',
|
|
505
496
|
{ class: 'annot-reply annot-message', 'data-msg': reply.id },
|
|
506
497
|
reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
|
|
507
498
|
meta(reply),
|
|
508
|
-
|
|
509
|
-
state.user
|
|
499
|
+
text(reply),
|
|
500
|
+
state.user && state.editing !== reply.id
|
|
510
501
|
? h(
|
|
511
502
|
'div',
|
|
512
503
|
{ class: 'annot-actions annot-reply-actions' },
|
|
513
504
|
h('button', { type: 'button', onclick: () => openReply(reply) }, T.reply),
|
|
514
|
-
|
|
505
|
+
...ownActions(reply, T.confirmDeleteReply),
|
|
515
506
|
)
|
|
516
507
|
: null,
|
|
517
508
|
),
|
|
518
509
|
),
|
|
519
510
|
replyBox,
|
|
520
511
|
);
|
|
521
|
-
if (state.user) {
|
|
512
|
+
if (state.user && state.editing !== thread.id) {
|
|
522
513
|
card.append(
|
|
523
514
|
h(
|
|
524
515
|
'div',
|
|
525
516
|
{ class: 'annot-actions' },
|
|
526
517
|
h('button', { type: 'button', onclick: () => openReply(null) }, T.reply),
|
|
527
518
|
h('button', { type: 'button', onclick: () => send({ action: 'resolve', id: thread.id, resolved: !thread.resolved }) }, thread.resolved ? T.reopen : T.resolve),
|
|
528
|
-
|
|
519
|
+
...ownActions(thread, T.confirmDelete),
|
|
529
520
|
),
|
|
530
521
|
);
|
|
531
522
|
}
|
|
@@ -576,6 +567,23 @@ async function start(root) {
|
|
|
576
567
|
body.replaceChildren(...parts.filter(Boolean));
|
|
577
568
|
}
|
|
578
569
|
|
|
570
|
+
function startEditing(id) {
|
|
571
|
+
loadMarkdown();
|
|
572
|
+
state.editing = id;
|
|
573
|
+
render();
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function stopEditing() {
|
|
577
|
+
state.editing = null;
|
|
578
|
+
render();
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function startMoving(id) {
|
|
582
|
+
state.moving = id;
|
|
583
|
+
if (id) state.pending = null;
|
|
584
|
+
render();
|
|
585
|
+
}
|
|
586
|
+
|
|
579
587
|
function focusThread(id, scroll) {
|
|
580
588
|
state.active = id;
|
|
581
589
|
paint();
|
|
@@ -615,13 +623,24 @@ async function start(root) {
|
|
|
615
623
|
return;
|
|
616
624
|
}
|
|
617
625
|
const rect = selected.range.getBoundingClientRect();
|
|
626
|
+
selectButton.textContent = state.moving ? T.moveHere : T.annotate;
|
|
618
627
|
selectButton.hidden = false;
|
|
619
628
|
selectButton.style.top = `${window.scrollY + rect.bottom + 6}px`;
|
|
620
629
|
selectButton.style.left = `${Math.min(window.scrollX + rect.right - selectButton.offsetWidth, window.scrollX + document.documentElement.clientWidth - selectButton.offsetWidth - 8)}px`;
|
|
621
630
|
}
|
|
622
631
|
|
|
623
|
-
function compose() {
|
|
632
|
+
async function compose() {
|
|
624
633
|
if (!selected) return;
|
|
634
|
+
if (state.moving) {
|
|
635
|
+
const id = state.moving;
|
|
636
|
+
selectButton.hidden = true;
|
|
637
|
+
window.getSelection()?.removeAllRanges();
|
|
638
|
+
const moved = await send({ action: 'anchor', id, target: selected.selector });
|
|
639
|
+
if (!moved) return;
|
|
640
|
+
state.moving = null;
|
|
641
|
+
focusThread(id, false);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
625
644
|
loadMarkdown();
|
|
626
645
|
state.pending = selected.selector;
|
|
627
646
|
selectButton.hidden = true;
|
package/src/client/i18n.js
CHANGED
|
@@ -60,6 +60,12 @@ const en = {
|
|
|
60
60
|
showing: 'Status',
|
|
61
61
|
author: 'Author',
|
|
62
62
|
seeAll: 'See the notes on other pages.',
|
|
63
|
+
edit: 'Edit',
|
|
64
|
+
edited: 'edited',
|
|
65
|
+
move: 'Attach to other text',
|
|
66
|
+
moveHint: 'Select the passage this note is about now, then press âAttach hereâ.',
|
|
67
|
+
moveHere: 'Attach here',
|
|
68
|
+
textChanged: 'Text changed',
|
|
63
69
|
};
|
|
64
70
|
|
|
65
71
|
const it = {
|
|
@@ -121,6 +127,12 @@ const it = {
|
|
|
121
127
|
showing: 'Stato',
|
|
122
128
|
author: 'Autore',
|
|
123
129
|
seeAll: 'Guarda le note delle altre pagine.',
|
|
130
|
+
edit: 'Modifica',
|
|
131
|
+
edited: 'modificata',
|
|
132
|
+
move: 'Collega ad altro testo',
|
|
133
|
+
moveHint: 'Seleziona il passaggio a cui si riferisce ora la nota, poi premi âCollega quiâ.',
|
|
134
|
+
moveHere: 'Collega qui',
|
|
135
|
+
textChanged: 'Testo cambiato',
|
|
124
136
|
};
|
|
125
137
|
|
|
126
138
|
const de = {
|
|
@@ -182,6 +194,12 @@ const de = {
|
|
|
182
194
|
showing: 'Status',
|
|
183
195
|
author: 'Autor',
|
|
184
196
|
seeAll: 'Notizen auf anderen Seiten ansehen.',
|
|
197
|
+
edit: 'Bearbeiten',
|
|
198
|
+
edited: 'bearbeitet',
|
|
199
|
+
move: 'Mit anderem Text verknÞpfen',
|
|
200
|
+
moveHint: 'Markiere die Stelle, um die es in dieser Notiz jetzt geht, und klicke auf âHier verknÞpfenâ.',
|
|
201
|
+
moveHere: 'Hier verknÞpfen',
|
|
202
|
+
textChanged: 'Text geÃĪndert',
|
|
185
203
|
};
|
|
186
204
|
|
|
187
205
|
const fr = {
|
|
@@ -243,6 +261,12 @@ const fr = {
|
|
|
243
261
|
showing: 'Statut',
|
|
244
262
|
author: 'Auteur',
|
|
245
263
|
seeAll: 'Voir les notes des autres pages.',
|
|
264
|
+
edit: 'Modifier',
|
|
265
|
+
edited: 'modifiÃĐe',
|
|
266
|
+
move: 'Rattacher à un autre texte',
|
|
267
|
+
moveHint: 'SÃĐlectionnez le passage dont parle maintenant la note, puis cliquez sur ÂŦ Rattacher ici Âŧ.',
|
|
268
|
+
moveHere: 'Rattacher ici',
|
|
269
|
+
textChanged: 'Texte modifiÃĐ',
|
|
246
270
|
};
|
|
247
271
|
|
|
248
272
|
const es = {
|
|
@@ -304,6 +328,12 @@ const es = {
|
|
|
304
328
|
showing: 'Estado',
|
|
305
329
|
author: 'Autor',
|
|
306
330
|
seeAll: 'Ver las notas de otras pÃĄginas.',
|
|
331
|
+
edit: 'Editar',
|
|
332
|
+
edited: 'editada',
|
|
333
|
+
move: 'Vincular a otro texto',
|
|
334
|
+
moveHint: 'Selecciona el pasaje al que se refiere ahora la nota y pulsa ÂŦVincular aquÃÂŧ.',
|
|
335
|
+
moveHere: 'Vincular aquÃ',
|
|
336
|
+
textChanged: 'Texto cambiado',
|
|
307
337
|
};
|
|
308
338
|
|
|
309
339
|
export const builtIn = { en, it, de, fr, es };
|
package/src/client/overview.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The overview page: every note on the site, grouped by page, with filters.
|
|
2
2
|
// Read-only: a note opens on its page, where it can be answered or resolved.
|
|
3
3
|
import config from 'virtual:starlight-annotations/config';
|
|
4
|
+
import { anchor, buildIndex, skipSelector } from './anchoring.js';
|
|
4
5
|
import { createBackend } from './backend.js';
|
|
5
6
|
import { strings } from './i18n.js';
|
|
6
7
|
import { h, quoteText, renderMarkdown } from './shared.js';
|
|
@@ -43,16 +44,20 @@ async function start(container) {
|
|
|
43
44
|
// Filters live in the address, so a filtered view can be shared.
|
|
44
45
|
const params = new URLSearchParams(location.search);
|
|
45
46
|
const state = {
|
|
46
|
-
status: ['open', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
|
|
47
|
+
status: ['open', 'changed', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
|
|
47
48
|
author: params.get('author') ?? '',
|
|
48
49
|
text: params.get('q') ?? '',
|
|
49
50
|
};
|
|
50
51
|
|
|
52
|
+
const changed = new Set(); // ids of open threads whose text is gone
|
|
51
53
|
const counts = {
|
|
52
54
|
open: threads.filter((entry) => !entry.thread.resolved).length,
|
|
55
|
+
changed: 0, // known once the pages are checked
|
|
53
56
|
resolved: threads.filter((entry) => entry.thread.resolved).length,
|
|
54
57
|
all: threads.length,
|
|
55
58
|
};
|
|
59
|
+
const labels = { open: T.statusOpen, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
|
|
60
|
+
const option = (value) => `${labels[value]} (${counts[value]})`;
|
|
56
61
|
const authors = new Map();
|
|
57
62
|
for (const { thread, replies } of threads)
|
|
58
63
|
for (const item of [thread, ...replies]) authors.set(item.author.login, item.author.name || item.author.login);
|
|
@@ -60,13 +65,7 @@ async function start(container) {
|
|
|
60
65
|
const status = h(
|
|
61
66
|
'select',
|
|
62
67
|
{ onchange: (event) => update({ status: event.target.value }) },
|
|
63
|
-
['open', 'resolved', 'all'].map((value) =>
|
|
64
|
-
h(
|
|
65
|
-
'option',
|
|
66
|
-
{ value, selected: state.status === value },
|
|
67
|
-
`${{ open: T.statusOpen, resolved: T.statusResolved, all: T.statusAll }[value]} (${counts[value]})`,
|
|
68
|
-
),
|
|
69
|
-
),
|
|
68
|
+
['open', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
|
|
70
69
|
);
|
|
71
70
|
const author = h(
|
|
72
71
|
'select',
|
|
@@ -109,6 +108,7 @@ async function start(container) {
|
|
|
109
108
|
function matches({ thread, replies }) {
|
|
110
109
|
if (state.status === 'open' && thread.resolved) return false;
|
|
111
110
|
if (state.status === 'resolved' && !thread.resolved) return false;
|
|
111
|
+
if (state.status === 'changed' && (thread.resolved || !changed.has(thread.id))) return false;
|
|
112
112
|
const messages = [thread, ...replies];
|
|
113
113
|
if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
|
|
114
114
|
const text = state.text.trim().toLowerCase();
|
|
@@ -130,6 +130,7 @@ async function start(container) {
|
|
|
130
130
|
' · ',
|
|
131
131
|
when,
|
|
132
132
|
thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
|
|
133
|
+
!thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
|
|
133
134
|
),
|
|
134
135
|
renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
|
|
135
136
|
h(
|
|
@@ -169,4 +170,37 @@ async function start(container) {
|
|
|
169
170
|
}
|
|
170
171
|
|
|
171
172
|
render();
|
|
173
|
+
|
|
174
|
+
// Open notes whose quoted text is no longer on their page: fetch each page
|
|
175
|
+
// and look for the quotes, as the page itself does.
|
|
176
|
+
const skip = skipSelector(config.exclude);
|
|
177
|
+
const open = [...new Set(threads.filter((entry) => !entry.thread.resolved).map((entry) => entry.page))];
|
|
178
|
+
await mapLimit(open, 4, async (page) => {
|
|
179
|
+
const root = await fetchContent(pageUrl(page));
|
|
180
|
+
if (!root) return; // Not a page we can read: say nothing.
|
|
181
|
+
const index = buildIndex(root, skip);
|
|
182
|
+
for (const entry of threads)
|
|
183
|
+
if (entry.page === page && !entry.thread.resolved && !anchor(index, entry.thread.target.selector)) changed.add(entry.thread.id);
|
|
184
|
+
});
|
|
185
|
+
counts.changed = changed.size;
|
|
186
|
+
status.querySelector('option[value="changed"]').textContent = option('changed');
|
|
187
|
+
render();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function fetchContent(url) {
|
|
191
|
+
try {
|
|
192
|
+
const response = await fetch(url, { credentials: 'same-origin' });
|
|
193
|
+
if (!response.ok) return null;
|
|
194
|
+
const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
|
|
195
|
+
return doc.querySelector(config.content);
|
|
196
|
+
} catch {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function mapLimit(items, limit, run) {
|
|
202
|
+
const queue = [...items];
|
|
203
|
+
await Promise.all(Array.from({ length: Math.min(limit, queue.length) }, async () => {
|
|
204
|
+
while (queue.length) await run(queue.shift());
|
|
205
|
+
}));
|
|
172
206
|
}
|
package/src/client/styles.css
CHANGED
|
@@ -161,6 +161,24 @@
|
|
|
161
161
|
background: var(--sl-color-gray-5);
|
|
162
162
|
font-size: var(--sl-text-xs);
|
|
163
163
|
}
|
|
164
|
+
.annot-badge.annot-changed {
|
|
165
|
+
margin-left: 0.4rem;
|
|
166
|
+
background: var(--sl-color-orange-low);
|
|
167
|
+
color: var(--sl-color-orange-high);
|
|
168
|
+
}
|
|
169
|
+
.annot-move {
|
|
170
|
+
display: flex;
|
|
171
|
+
flex-direction: column;
|
|
172
|
+
align-items: flex-start;
|
|
173
|
+
gap: 0.4rem;
|
|
174
|
+
padding: 0.5rem 0.6rem;
|
|
175
|
+
border: 1px dashed var(--sl-color-accent);
|
|
176
|
+
border-radius: 0.4rem;
|
|
177
|
+
font-size: var(--sl-text-sm);
|
|
178
|
+
}
|
|
179
|
+
.annot-move p {
|
|
180
|
+
margin: 0;
|
|
181
|
+
}
|
|
164
182
|
.annot-meta {
|
|
165
183
|
color: var(--sl-color-gray-3);
|
|
166
184
|
font-size: var(--sl-text-xs);
|
package/src/core.js
CHANGED
|
@@ -106,11 +106,15 @@ function selector(target) {
|
|
|
106
106
|
// { action: 'create', target: { exact, prefix, suffix }, body }
|
|
107
107
|
// { action: 'reply', replyTo, body }
|
|
108
108
|
// { action: 'resolve', id, resolved }
|
|
109
|
+
// { action: 'edit', id, body } the author changes their message
|
|
110
|
+
// { action: 'anchor', id, target } a thread moves to another passage
|
|
109
111
|
// { action: 'delete', id }
|
|
110
112
|
// It returns the annotation it touched, and a commit message.
|
|
111
113
|
export function applyChange(doc, change, user, now = new Date()) {
|
|
112
114
|
const created = now.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
113
115
|
const author = { login: user.login, name: user.name || user.login };
|
|
116
|
+
// The writer's sealed email, kept on the notes they write (not on resolves).
|
|
117
|
+
const writer = user.contact ? { ...author, contact: user.contact } : author;
|
|
114
118
|
const find = (id) => {
|
|
115
119
|
const found = doc.annotations.find((item) => item.id === id);
|
|
116
120
|
if (!found) throw new AnnotationError(404, 'Annotation not found.');
|
|
@@ -122,7 +126,7 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
122
126
|
const annotation = {
|
|
123
127
|
id: crypto.randomUUID(),
|
|
124
128
|
created,
|
|
125
|
-
author,
|
|
129
|
+
author: writer,
|
|
126
130
|
target: { selector: selector(change.target) },
|
|
127
131
|
body: text(change.body, MAX_BODY, 'note'),
|
|
128
132
|
resolved: false,
|
|
@@ -136,7 +140,7 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
136
140
|
// "in reply to" reference in the panel.
|
|
137
141
|
const parent = find(change.replyTo);
|
|
138
142
|
if (parent.replyTo) throw new AnnotationError(400, 'Reply to the first note of the thread.');
|
|
139
|
-
const annotation = { id: crypto.randomUUID(), created, author, replyTo: parent.id, body: text(change.body, MAX_BODY, 'reply') };
|
|
143
|
+
const annotation = { id: crypto.randomUUID(), created, author: writer, replyTo: parent.id, body: text(change.body, MAX_BODY, 'reply') };
|
|
140
144
|
if (change.inReplyTo && change.inReplyTo !== parent.id) {
|
|
141
145
|
const answered = find(change.inReplyTo);
|
|
142
146
|
if (answered.replyTo !== parent.id) throw new AnnotationError(400, 'That reply belongs to another thread.');
|
|
@@ -153,6 +157,23 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
153
157
|
annotation.resolvedAt = annotation.resolved ? created : undefined;
|
|
154
158
|
return { annotation, message: `docs(annotations): ${annotation.resolved ? 'resolve' : 'reopen'} note on ${doc.page}` };
|
|
155
159
|
}
|
|
160
|
+
case 'edit': {
|
|
161
|
+
const annotation = find(change.id);
|
|
162
|
+
if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can edit a note.');
|
|
163
|
+
annotation.body = text(change.body, MAX_BODY, annotation.replyTo ? 'reply' : 'note');
|
|
164
|
+
annotation.edited = created;
|
|
165
|
+
return { annotation, message: `docs(annotations): edit note on ${doc.page}` };
|
|
166
|
+
}
|
|
167
|
+
case 'anchor': {
|
|
168
|
+
// When the page changed and the quote is gone, anyone who can write
|
|
169
|
+
// attaches the thread to the passage it is now about.
|
|
170
|
+
const annotation = find(change.id);
|
|
171
|
+
if (annotation.replyTo) throw new AnnotationError(400, 'Only a thread can be moved.');
|
|
172
|
+
annotation.target = { selector: selector(change.target) };
|
|
173
|
+
annotation.movedBy = author;
|
|
174
|
+
annotation.movedAt = created;
|
|
175
|
+
return { annotation, message: `docs(annotations): move note on ${doc.page}` };
|
|
176
|
+
}
|
|
156
177
|
case 'delete': {
|
|
157
178
|
const annotation = find(change.id);
|
|
158
179
|
if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can delete a note.');
|
|
@@ -165,6 +186,13 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
165
186
|
}
|
|
166
187
|
}
|
|
167
188
|
|
|
189
|
+
// Notes as the browser gets them: without the sealed emails.
|
|
190
|
+
export function withoutContact(annotation) {
|
|
191
|
+
if (!annotation?.author?.contact) return annotation;
|
|
192
|
+
const { contact, ...author } = annotation.author;
|
|
193
|
+
return { ...annotation, author };
|
|
194
|
+
}
|
|
195
|
+
|
|
168
196
|
export function json(data, status = 200, headers = {}) {
|
|
169
197
|
return new Response(JSON.stringify(data), {
|
|
170
198
|
status,
|
package/src/server/gitea.js
CHANGED
|
@@ -101,7 +101,7 @@ export function giteaAuth({ host, repo, token, writers = 'collaborators', ...opt
|
|
|
101
101
|
scope: 'read:user',
|
|
102
102
|
async profile(userToken) {
|
|
103
103
|
const user = await client(host, `Bearer ${userToken}`).get('/user');
|
|
104
|
-
return { login: user.login, id: user.id, name: user.full_name };
|
|
104
|
+
return { login: user.login, id: user.id, name: user.full_name, email: user.email || null };
|
|
105
105
|
},
|
|
106
106
|
async canWrite(profile) {
|
|
107
107
|
const permission = await client(host, `token ${token}`).get(
|
package/src/server/github.js
CHANGED
|
@@ -119,9 +119,20 @@ export function githubAuth({ repo, token, app, writers = 'collaborators', ...opt
|
|
|
119
119
|
authorizeUrl: 'https://github.com/login/oauth/authorize',
|
|
120
120
|
tokenUrl: 'https://github.com/login/oauth/access_token',
|
|
121
121
|
// No scope: the public profile is enough to know who the reader is.
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
122
|
+
// With `emails`, `user:email` (an OAuth app; a GitHub App needs the
|
|
123
|
+
// account permission "Email addresses: Read-only" instead).
|
|
124
|
+
scope: options.emails ? 'user:email' : undefined,
|
|
125
|
+
async profile(userToken, { emails }) {
|
|
126
|
+
const api = client(userToken);
|
|
127
|
+
const user = await api.get('/user');
|
|
128
|
+
let email = null;
|
|
129
|
+
if (emails) {
|
|
130
|
+
// The primary verified address; without the permission, the public one.
|
|
131
|
+
const response = await api.raw('/user/emails');
|
|
132
|
+
const list = response.ok ? await response.json() : [];
|
|
133
|
+
email = list.find((entry) => entry.primary && entry.verified)?.email ?? user.email ?? null;
|
|
134
|
+
}
|
|
135
|
+
return { login: user.login, id: user.id, name: user.name, email };
|
|
125
136
|
},
|
|
126
137
|
// Only people who can push. `permission` is the legacy level: maintain
|
|
127
138
|
// counts as write, triage as read. On a public repository GitHub answers
|
package/src/server/gitlab.js
CHANGED
|
@@ -111,7 +111,7 @@ export function gitlabAuth({ host, project, token, writers = 'collaborators', ..
|
|
|
111
111
|
scope: 'read_user',
|
|
112
112
|
async profile(userToken) {
|
|
113
113
|
const user = await client(host, userToken).get('/user');
|
|
114
|
-
return { login: user.username, id: user.id, name: user.name };
|
|
114
|
+
return { login: user.username, id: user.id, name: user.name, email: user.email || user.public_email || null };
|
|
115
115
|
},
|
|
116
116
|
// Developer (30) and above can push to unprotected branches.
|
|
117
117
|
async canWrite(profile) {
|
package/src/server/index.js
CHANGED
|
@@ -12,23 +12,77 @@
|
|
|
12
12
|
// POST /api { page, change } applies one change
|
|
13
13
|
// GET /login /callback /logout handled by the auth, when it has them
|
|
14
14
|
|
|
15
|
-
import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json } from '../core.js';
|
|
15
|
+
import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json, withoutContact } from '../core.js';
|
|
16
|
+
import { changeEvent } from './notify.js';
|
|
16
17
|
|
|
17
18
|
export { github, githubAuth, githubStorage } from './github.js';
|
|
18
19
|
export { githubAppToken } from './github-app.js';
|
|
19
20
|
export { gitlab, gitlabAuth, gitlabStorage } from './gitlab.js';
|
|
20
21
|
export { forgejo, gitea, giteaAuth, giteaStorage } from './gitea.js';
|
|
21
22
|
export { AnnotationError } from '../core.js';
|
|
23
|
+
export { describeChange, slackWebhook, teamsWebhook } from './notify.js';
|
|
22
24
|
|
|
23
25
|
/**
|
|
24
|
-
* @param {{
|
|
26
|
+
* @param {{
|
|
27
|
+
* storage: Storage,
|
|
28
|
+
* auth?: Auth,
|
|
29
|
+
* prefix?: string,
|
|
30
|
+
* onChange?: OnChange | OnChange[],
|
|
31
|
+
* pageUrl?: (page: string, request: Request) => string,
|
|
32
|
+
* }} options
|
|
25
33
|
*/
|
|
26
|
-
export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX }) {
|
|
34
|
+
export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX, onChange, pageUrl }) {
|
|
27
35
|
if (!storage) throw new Error('starlight-annotations: createAnnotationsHandler needs a storage.');
|
|
28
36
|
const root = prefix.replace(/\/$/, '');
|
|
29
37
|
const stillAllowed = async (user) => (auth?.allowed ? auth.allowed(user) : true);
|
|
38
|
+
const listeners = [onChange].flat().filter(Boolean);
|
|
30
39
|
|
|
31
|
-
|
|
40
|
+
// After a save: tell every listener. A failing listener is logged and never
|
|
41
|
+
// fails the save. With `context.waitUntil` (Cloudflare Workers, Vercel,
|
|
42
|
+
// Netlify) the response does not wait for them.
|
|
43
|
+
function notify(event, context) {
|
|
44
|
+
if (!listeners.length) return undefined;
|
|
45
|
+
const task = Promise.all(
|
|
46
|
+
listeners.map((listener) =>
|
|
47
|
+
Promise.resolve()
|
|
48
|
+
.then(() => listener(event))
|
|
49
|
+
.catch((error) => console.error('starlight-annotations: onChange failed', error)),
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
if (typeof context?.waitUntil === 'function') {
|
|
53
|
+
context.waitUntil(task);
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
return task;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Where a note can be opened: the page the reader was on (the Referer of a
|
|
60
|
+
// same-origin save), else `pageUrl(page)`, else a guess without the base.
|
|
61
|
+
function linkTo(page, request, url, id) {
|
|
62
|
+
let base = pageUrl?.(page, request);
|
|
63
|
+
if (!base) {
|
|
64
|
+
try {
|
|
65
|
+
const referer = new URL(request.headers.get('Referer') ?? '');
|
|
66
|
+
if (referer.origin === url.origin) base = `${referer.origin}${referer.pathname}`;
|
|
67
|
+
} catch {
|
|
68
|
+
// No Referer, or not a URL.
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
base ??= `${url.origin}/${page === 'index' ? '' : `${page.replace(/\/index$/, '')}/`}`;
|
|
72
|
+
return id ? `${base}#annotation-${encodeURIComponent(id)}` : base;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Who opened the thread, when it is someone else, with their email when
|
|
76
|
+
// their note carries one and the auth can open it.
|
|
77
|
+
async function threadAuthor({ annotation, annotations }, user) {
|
|
78
|
+
const thread = annotation.replyTo ? annotations.find((item) => item.id === annotation.replyTo) : annotation;
|
|
79
|
+
const owner = thread?.author;
|
|
80
|
+
if (!owner || owner.login.toLowerCase() === user.login.toLowerCase()) return null;
|
|
81
|
+
const email = owner.contact && auth?.openContact ? await auth.openContact(owner.contact) : null;
|
|
82
|
+
return { login: owner.login, name: owner.name, email };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return async function handleAnnotations(request, context) {
|
|
32
86
|
const url = new URL(request.url);
|
|
33
87
|
if (!url.pathname.startsWith(`${root}/`)) return null;
|
|
34
88
|
const route = url.pathname.slice(root.length);
|
|
@@ -49,7 +103,7 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
|
|
|
49
103
|
if (revoked) user = null;
|
|
50
104
|
return json(
|
|
51
105
|
{
|
|
52
|
-
annotations: doc.annotations,
|
|
106
|
+
annotations: doc.annotations.map(withoutContact),
|
|
53
107
|
user: user && { login: user.login, name: user.name },
|
|
54
108
|
mode: auth?.mode ?? storage.mode ?? 'api',
|
|
55
109
|
canSignIn: Boolean(auth?.route),
|
|
@@ -61,7 +115,9 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
|
|
|
61
115
|
|
|
62
116
|
if (route === '/api/all' && request.method === 'GET') {
|
|
63
117
|
if (!storage.list) return json({ error: 'This storage cannot list pages.' }, 501);
|
|
64
|
-
const pages = (await storage.list())
|
|
118
|
+
const pages = (await storage.list())
|
|
119
|
+
.filter((entry) => entry.annotations.length > 0)
|
|
120
|
+
.map((entry) => ({ ...entry, annotations: entry.annotations.map(withoutContact) }));
|
|
65
121
|
pages.sort((a, b) => a.page.localeCompare(b.page));
|
|
66
122
|
return json({ pages, mode: auth?.mode ?? storage.mode ?? 'api' });
|
|
67
123
|
}
|
|
@@ -76,7 +132,18 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
|
|
|
76
132
|
return json({ error, signedOut: true }, 403, auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {});
|
|
77
133
|
}
|
|
78
134
|
const { page, change } = await request.json();
|
|
79
|
-
|
|
135
|
+
// With `emails`, new notes carry the writer's email, sealed.
|
|
136
|
+
const writer = auth?.sealContact && user.email ? { ...user, contact: await auth.sealContact(user.email) } : user;
|
|
137
|
+
const saved = await storage.update(checkPage(page), (doc) => applyChange(doc, change, writer), writer);
|
|
138
|
+
const result = { ...saved, annotation: withoutContact(saved.annotation), annotations: saved.annotations.map(withoutContact) };
|
|
139
|
+
if (listeners.length) {
|
|
140
|
+
const deleted = change.action === 'delete';
|
|
141
|
+
const target = deleted ? (result.annotation.replyTo ?? null) : result.annotation.id;
|
|
142
|
+
const exists = target && result.annotations.some((item) => item.id === target);
|
|
143
|
+
const event = changeEvent({ change, result, page, user, url: linkTo(page, request, url, exists ? target : null) });
|
|
144
|
+
event.threadAuthor = await threadAuthor(saved, user);
|
|
145
|
+
await notify(event, context);
|
|
146
|
+
}
|
|
80
147
|
return json(result);
|
|
81
148
|
}
|
|
82
149
|
|
|
@@ -114,5 +181,8 @@ export function staticAuth(user) {
|
|
|
114
181
|
* allowed?(user: User): Promise<boolean>,
|
|
115
182
|
* noAccess?(login: string): string,
|
|
116
183
|
* clearSession?: string,
|
|
184
|
+
* sealContact?(email: string): Promise<string>,
|
|
185
|
+
* openContact?(sealed: string): Promise<string | null>,
|
|
117
186
|
* }} Auth
|
|
187
|
+
* @typedef {(event: import('../../server').AnnotationEvent) => void | Promise<void>} OnChange
|
|
118
188
|
*/
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Notifications: what the handler tells `onChange` after every saved change,
|
|
2
|
+
// and ready-made senders for Slack and Microsoft Teams.
|
|
3
|
+
//
|
|
4
|
+
// createAnnotationsHandler({ ...github(options), onChange: slackWebhook(env.SLACK_WEBHOOK_URL) })
|
|
5
|
+
//
|
|
6
|
+
// The plugin knows readers by their login and name only, not their email, so
|
|
7
|
+
// these post to a channel. `event.participants` and `event.mentions` (logins)
|
|
8
|
+
// let you reach people too, with your own login -> address map.
|
|
9
|
+
|
|
10
|
+
// What the Slack and Teams senders post by default: not edits and moves.
|
|
11
|
+
const ACTIONS = ['create', 'reply', 'resolve', 'reopen', 'delete'];
|
|
12
|
+
|
|
13
|
+
// "@ada" and "@ada-l" in a message, not inside an email address or code span.
|
|
14
|
+
const MENTION = /(?<![\w`.@/])@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})(?![\w-])/gi;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The event passed to `onChange`, built from a saved change.
|
|
18
|
+
* @returns {import('../../server').AnnotationEvent}
|
|
19
|
+
*/
|
|
20
|
+
export function changeEvent({ change, result, page, user, url }) {
|
|
21
|
+
const { annotation, annotations } = result;
|
|
22
|
+
const action = change.action === 'resolve' ? (annotation.resolved ? 'resolve' : 'reopen') : change.action;
|
|
23
|
+
const byId = new Map(annotations.map((item) => [item.id, item]));
|
|
24
|
+
// A deleted thread is gone from `annotations`: it is its own thread.
|
|
25
|
+
const thread = annotation.replyTo ? (byId.get(annotation.replyTo) ?? null) : annotation;
|
|
26
|
+
const inReplyTo = annotation.inReplyTo ? (byId.get(annotation.inReplyTo) ?? null) : annotation.replyTo ? thread : null;
|
|
27
|
+
const messages = thread ? [thread, ...annotations.filter((item) => item.replyTo === thread.id)] : [annotation];
|
|
28
|
+
const others = (logins) => [...new Set(logins)].filter((login) => login && login.toLowerCase() !== user.login.toLowerCase());
|
|
29
|
+
const written = action === 'create' || action === 'reply';
|
|
30
|
+
return {
|
|
31
|
+
action,
|
|
32
|
+
page,
|
|
33
|
+
url,
|
|
34
|
+
user: { login: user.login, name: user.name || user.login },
|
|
35
|
+
annotation,
|
|
36
|
+
thread,
|
|
37
|
+
inReplyTo,
|
|
38
|
+
threadAuthor: null, // Filled in by the handler: it can open sealed emails.
|
|
39
|
+
participants: others(messages.map((item) => item.author?.login)),
|
|
40
|
+
mentions: written ? others([...annotation.body.matchAll(MENTION)].map((match) => match[1])) : [],
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The quoted passage of a thread, cut in the middle when it is long. */
|
|
45
|
+
export function quoteOf(thread) {
|
|
46
|
+
const selector = thread?.target?.selector;
|
|
47
|
+
if (!selector) return '';
|
|
48
|
+
const squash = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
49
|
+
if (selector.type === 'RangeSelector') return `${squash(selector.startSelector.exact)} âĶ ${squash(selector.endSelector.exact)}`;
|
|
50
|
+
const exact = squash(selector.exact);
|
|
51
|
+
return exact.length > 200 ? `${exact.slice(0, 120)} âĶ ${exact.slice(-60)}` : exact;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Plain text for any channel: a title line, the quote and the message.
|
|
56
|
+
* @param {import('../../server').AnnotationEvent} event
|
|
57
|
+
*/
|
|
58
|
+
export function describeChange(event) {
|
|
59
|
+
const who = event.user.name;
|
|
60
|
+
const title = {
|
|
61
|
+
create: `${who} added a note on ${event.page}`,
|
|
62
|
+
reply: `${who} replied on ${event.page}`,
|
|
63
|
+
resolve: `${who} resolved a note on ${event.page}`,
|
|
64
|
+
reopen: `${who} reopened a note on ${event.page}`,
|
|
65
|
+
edit: `${who} edited a note on ${event.page}`,
|
|
66
|
+
anchor: `${who} moved a note on ${event.page}`,
|
|
67
|
+
delete: `${who} deleted a note on ${event.page}`,
|
|
68
|
+
}[event.action];
|
|
69
|
+
const quote = quoteOf(event.thread);
|
|
70
|
+
const body = ['create', 'reply', 'edit'].includes(event.action) ? cut(event.annotation.body, 600) : '';
|
|
71
|
+
const text = [title, quote && `> ${quote}`, body, event.url].filter(Boolean).join('\n\n');
|
|
72
|
+
return { title, quote, body, text };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Posts each change to a Slack incoming webhook.
|
|
77
|
+
* @param {string} webhookUrl
|
|
78
|
+
* @param {{ actions?: string[] }} [options] Which actions to post. Default: all but edit and anchor.
|
|
79
|
+
*/
|
|
80
|
+
export function slackWebhook(webhookUrl, { actions = ACTIONS } = {}) {
|
|
81
|
+
if (!webhookUrl) throw new Error('starlight-annotations: slackWebhook needs a webhook URL.');
|
|
82
|
+
return async (event) => {
|
|
83
|
+
if (!actions.includes(event.action)) return;
|
|
84
|
+
const { title, quote, body } = describeChange(event);
|
|
85
|
+
const escape = (value) => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
86
|
+
const lines = [
|
|
87
|
+
event.url ? `*<${event.url}|${escape(title)}>*` : `*${escape(title)}*`,
|
|
88
|
+
quote && `> _${escape(quote)}_`,
|
|
89
|
+
body && escape(body),
|
|
90
|
+
];
|
|
91
|
+
await post(webhookUrl, { text: lines.filter(Boolean).join('\n') }, 'Slack');
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Posts each change to a Microsoft Teams channel through a Workflows webhook
|
|
97
|
+
* ("Post to a channel when a webhook request is received").
|
|
98
|
+
* @param {string} webhookUrl
|
|
99
|
+
* @param {{ actions?: string[] }} [options] Which actions to post. Default: all but edit and anchor.
|
|
100
|
+
*/
|
|
101
|
+
export function teamsWebhook(webhookUrl, { actions = ACTIONS } = {}) {
|
|
102
|
+
if (!webhookUrl) throw new Error('starlight-annotations: teamsWebhook needs a webhook URL.');
|
|
103
|
+
return async (event) => {
|
|
104
|
+
if (!actions.includes(event.action)) return;
|
|
105
|
+
const { title, quote, body } = describeChange(event);
|
|
106
|
+
const card = {
|
|
107
|
+
$schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
|
|
108
|
+
type: 'AdaptiveCard',
|
|
109
|
+
version: '1.4',
|
|
110
|
+
body: [
|
|
111
|
+
{ type: 'TextBlock', text: title, weight: 'Bolder', wrap: true },
|
|
112
|
+
quote && { type: 'TextBlock', text: quote, isSubtle: true, wrap: true },
|
|
113
|
+
body && { type: 'TextBlock', text: body, wrap: true },
|
|
114
|
+
].filter(Boolean),
|
|
115
|
+
actions: event.url ? [{ type: 'Action.OpenUrl', title: 'Open the note', url: event.url }] : [],
|
|
116
|
+
};
|
|
117
|
+
await post(
|
|
118
|
+
webhookUrl,
|
|
119
|
+
{ type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', contentUrl: null, content: card }] },
|
|
120
|
+
'Teams',
|
|
121
|
+
);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function post(url, payload, label) {
|
|
126
|
+
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
|
|
127
|
+
if (!response.ok) throw new Error(`${label} webhook ${response.status}: ${await response.text()}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function cut(value, max) {
|
|
131
|
+
const text = String(value ?? '').trim();
|
|
132
|
+
return text.length > max ? `${text.slice(0, max).trimEnd()}âĶ` : text;
|
|
133
|
+
}
|
package/src/server/oauth.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// every provider module.
|
|
3
3
|
//
|
|
4
4
|
// The reader's access token is used once, at the callback, to read who they
|
|
5
|
-
// are, and is then dropped. The session
|
|
5
|
+
// are (and, with `emails`, their email), and is then dropped. The session
|
|
6
|
+
// is an HMAC-signed cookie, so the
|
|
6
7
|
// server keeps no state. `writers` decides who may write, at sign-in and
|
|
7
8
|
// again while the session lasts (every `recheck` seconds), so removing
|
|
8
9
|
// someone's access to the repository also ends their session.
|
|
@@ -37,7 +38,8 @@ const CACHE_SIZE = 500;
|
|
|
37
38
|
* cookieSecure?: boolean,
|
|
38
39
|
* recheck?: number | false,
|
|
39
40
|
* writers?: 'collaborators' | 'anyone' | string[] | ((profile: object) => boolean | Promise<boolean>),
|
|
40
|
-
*
|
|
41
|
+
* emails?: boolean,
|
|
42
|
+
* profile: (userToken: string, options: { emails: boolean }) => Promise<{ login: string, id: number, name?: string, email?: string | null }>,
|
|
41
43
|
* canWrite: (profile: { login: string, id: number }) => Promise<boolean>,
|
|
42
44
|
* noAccess: (login: string) => string,
|
|
43
45
|
* }} options
|
|
@@ -46,6 +48,7 @@ export function oauthAuth(options) {
|
|
|
46
48
|
const { mode, where, authorizeUrl, tokenUrl, scope, clientId, clientSecret, sessionSecret, cookieSecure = true } = options;
|
|
47
49
|
const writers = options.writers ?? 'collaborators';
|
|
48
50
|
const recheck = options.recheck ?? RECHECK;
|
|
51
|
+
const emails = Boolean(options.emails);
|
|
49
52
|
required({ clientId, clientSecret, sessionSecret }, where);
|
|
50
53
|
|
|
51
54
|
const cookie = (name, value, maxAge, path = '/') =>
|
|
@@ -69,6 +72,25 @@ export function oauthAuth(options) {
|
|
|
69
72
|
if (answers.size > CACHE_SIZE) answers.delete(answers.keys().next().value);
|
|
70
73
|
}
|
|
71
74
|
|
|
75
|
+
// A reader's email, sealed with AES-GCM under a key derived from the
|
|
76
|
+
// session secret, so it can sit in a notes file without being readable
|
|
77
|
+
// there. Changing the session secret makes old seals unreadable (null).
|
|
78
|
+
let contactKey;
|
|
79
|
+
function sealingKey() {
|
|
80
|
+
contactKey ??= crypto.subtle
|
|
81
|
+
.importKey('raw', new TextEncoder().encode(sessionSecret), 'HKDF', false, ['deriveKey'])
|
|
82
|
+
.then((base) =>
|
|
83
|
+
crypto.subtle.deriveKey(
|
|
84
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('starlight-annotations'), info: new TextEncoder().encode('contact v1') },
|
|
85
|
+
base,
|
|
86
|
+
{ name: 'AES-GCM', length: 256 },
|
|
87
|
+
false,
|
|
88
|
+
['encrypt', 'decrypt'],
|
|
89
|
+
),
|
|
90
|
+
);
|
|
91
|
+
return contactKey;
|
|
92
|
+
}
|
|
93
|
+
|
|
72
94
|
async function hmac(value) {
|
|
73
95
|
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
74
96
|
return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
|
|
@@ -78,6 +100,27 @@ export function oauthAuth(options) {
|
|
|
78
100
|
mode,
|
|
79
101
|
clearSession: cookie(SESSION_COOKIE, '', 0),
|
|
80
102
|
|
|
103
|
+
...(emails && {
|
|
104
|
+
async sealContact(email) {
|
|
105
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
106
|
+
const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await sealingKey(), new TextEncoder().encode(email));
|
|
107
|
+
return `v1.${base64url(iv)}.${base64url(new Uint8Array(sealed))}`;
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
|
|
111
|
+
// Opening also works with `emails` off, so turning it off later does not
|
|
112
|
+
// silence the notes written meanwhile.
|
|
113
|
+
async openContact(sealed) {
|
|
114
|
+
const [version, iv, data] = String(sealed ?? '').split('.');
|
|
115
|
+
if (version !== 'v1' || !iv || !data) return null;
|
|
116
|
+
try {
|
|
117
|
+
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromBase64url(iv) }, await sealingKey(), fromBase64url(data));
|
|
118
|
+
return new TextDecoder().decode(plain);
|
|
119
|
+
} catch {
|
|
120
|
+
return null; // Another session secret, or tampered with.
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
|
|
81
124
|
/** Whether a signed-in user may still write. Asks the provider at most every `recheck` seconds. */
|
|
82
125
|
async allowed(user) {
|
|
83
126
|
if (recheck === false) return true;
|
|
@@ -143,14 +186,20 @@ export function oauthAuth(options) {
|
|
|
143
186
|
const { access_token: userToken } = await exchange.json().catch(() => ({}));
|
|
144
187
|
if (!userToken) return text('The sign-in was not confirmed. Try again.', 400, [clear]);
|
|
145
188
|
|
|
146
|
-
const profile = await options.profile(userToken);
|
|
189
|
+
const profile = await options.profile(userToken, { emails });
|
|
147
190
|
const allowed = await mayWrite(profile);
|
|
148
191
|
remember(profile, allowed);
|
|
149
192
|
if (!allowed) return text(options.noAccess(profile.login), 403, [clear]);
|
|
150
193
|
|
|
151
194
|
const body = base64url(
|
|
152
195
|
new TextEncoder().encode(
|
|
153
|
-
JSON.stringify({
|
|
196
|
+
JSON.stringify({
|
|
197
|
+
login: profile.login,
|
|
198
|
+
id: profile.id,
|
|
199
|
+
name: profile.name || profile.login,
|
|
200
|
+
...(emails && profile.email ? { email: profile.email } : {}),
|
|
201
|
+
exp: Math.floor(Date.now() / 1000) + SESSION_AGE,
|
|
202
|
+
}),
|
|
154
203
|
),
|
|
155
204
|
);
|
|
156
205
|
const session = `${body}.${await hmac(body)}`;
|