starlight-annotations 0.5.0 â 0.6.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.js +13 -3
- package/package.json +1 -1
- package/server.d.ts +65 -2
- package/src/client/annotations.js +5 -1
- package/src/core.js +11 -2
- package/src/overview.astro +11 -4
- 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 +130 -0
- package/src/server/oauth.js +53 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# starlight-annotations
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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 }`.
|
|
8
|
+
- 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`.
|
|
9
|
+
|
|
10
|
+
## 0.5.1
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 4ff776c: Adds the overview page for every locale of a multilingual site (`/it/annotations/` next to `/annotations/`), in that locale's language, and makes the notes panel link to the one in the reader's language. A sidebar link to `/annotations/` no longer leads to a missing page on localized pages, since Starlight adds the locale to it.
|
|
15
|
+
|
|
3
16
|
## 0.5.0
|
|
4
17
|
|
|
5
18
|
### Minor 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.js
CHANGED
|
@@ -18,10 +18,16 @@ export default function starlightAnnotations(options = {}) {
|
|
|
18
18
|
// Starlight links customCss on every page, in dev and in the build.
|
|
19
19
|
// (CSS imported by an injected script is bundled but not linked.)
|
|
20
20
|
updateConfig({ customCss: [...(starlightConfig.customCss ?? []), 'starlight-annotations/styles.css'] });
|
|
21
|
-
// The overview page
|
|
21
|
+
// The overview page exists once per locale (/annotations/, /it/annotations/âĶ),
|
|
22
|
+
// because Starlight prefixes sidebar links with the reader's locale.
|
|
22
23
|
const locales = starlightConfig.locales ?? {};
|
|
23
24
|
const lang = locales[starlightConfig.defaultLocale ?? 'root']?.lang ?? locales.root?.lang ?? starlightConfig.defaultLocale ?? 'en';
|
|
24
|
-
|
|
25
|
+
const prefixed = Object.fromEntries(
|
|
26
|
+
Object.entries(locales)
|
|
27
|
+
.filter(([key]) => key !== 'root')
|
|
28
|
+
.map(([key, locale]) => [key, locale?.lang ?? key]),
|
|
29
|
+
);
|
|
30
|
+
addIntegration(annotationsIntegration({ ...config, lang, locales: prefixed }));
|
|
25
31
|
},
|
|
26
32
|
},
|
|
27
33
|
};
|
|
@@ -79,7 +85,11 @@ function annotationsIntegration(config) {
|
|
|
79
85
|
});
|
|
80
86
|
injectScript('page', `import 'starlight-annotations/client';`);
|
|
81
87
|
if (config.overview) {
|
|
82
|
-
injectRoute({
|
|
88
|
+
injectRoute({
|
|
89
|
+
pattern: `/[...locale]/${config.overview}`,
|
|
90
|
+
entrypoint: fileURLToPath(new URL('./src/overview.astro', import.meta.url)),
|
|
91
|
+
prerender: true,
|
|
92
|
+
});
|
|
83
93
|
}
|
|
84
94
|
},
|
|
85
95
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "starlight-annotations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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' | '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.
|
|
@@ -247,7 +247,11 @@ async function start(root) {
|
|
|
247
247
|
const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count);
|
|
248
248
|
const body = h('div', { class: 'annot-body' });
|
|
249
249
|
// The page with every note on the site, when the plugin adds it.
|
|
250
|
-
|
|
250
|
+
// In the reader's locale, like the rest of the page.
|
|
251
|
+
const locale = page.split('/')[0];
|
|
252
|
+
const overviewUrl = config.overview
|
|
253
|
+
? `${BASE}/${config.locales && locale in config.locales ? `${locale}/` : ''}${config.overview}/`
|
|
254
|
+
: null;
|
|
251
255
|
const resolvedBox = h('input', {
|
|
252
256
|
type: 'checkbox',
|
|
253
257
|
onchange: (event) => {
|
package/src/core.js
CHANGED
|
@@ -111,6 +111,8 @@ function selector(target) {
|
|
|
111
111
|
export function applyChange(doc, change, user, now = new Date()) {
|
|
112
112
|
const created = now.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
113
113
|
const author = { login: user.login, name: user.name || user.login };
|
|
114
|
+
// The writer's sealed email, kept on the notes they write (not on resolves).
|
|
115
|
+
const writer = user.contact ? { ...author, contact: user.contact } : author;
|
|
114
116
|
const find = (id) => {
|
|
115
117
|
const found = doc.annotations.find((item) => item.id === id);
|
|
116
118
|
if (!found) throw new AnnotationError(404, 'Annotation not found.');
|
|
@@ -122,7 +124,7 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
122
124
|
const annotation = {
|
|
123
125
|
id: crypto.randomUUID(),
|
|
124
126
|
created,
|
|
125
|
-
author,
|
|
127
|
+
author: writer,
|
|
126
128
|
target: { selector: selector(change.target) },
|
|
127
129
|
body: text(change.body, MAX_BODY, 'note'),
|
|
128
130
|
resolved: false,
|
|
@@ -136,7 +138,7 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
136
138
|
// "in reply to" reference in the panel.
|
|
137
139
|
const parent = find(change.replyTo);
|
|
138
140
|
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') };
|
|
141
|
+
const annotation = { id: crypto.randomUUID(), created, author: writer, replyTo: parent.id, body: text(change.body, MAX_BODY, 'reply') };
|
|
140
142
|
if (change.inReplyTo && change.inReplyTo !== parent.id) {
|
|
141
143
|
const answered = find(change.inReplyTo);
|
|
142
144
|
if (answered.replyTo !== parent.id) throw new AnnotationError(400, 'That reply belongs to another thread.');
|
|
@@ -165,6 +167,13 @@ export function applyChange(doc, change, user, now = new Date()) {
|
|
|
165
167
|
}
|
|
166
168
|
}
|
|
167
169
|
|
|
170
|
+
// Notes as the browser gets them: without the sealed emails.
|
|
171
|
+
export function withoutContact(annotation) {
|
|
172
|
+
if (!annotation?.author?.contact) return annotation;
|
|
173
|
+
const { contact, ...author } = annotation.author;
|
|
174
|
+
return { ...annotation, author };
|
|
175
|
+
}
|
|
176
|
+
|
|
168
177
|
export function json(data, status = 200, headers = {}) {
|
|
169
178
|
return new Response(JSON.stringify(data), {
|
|
170
179
|
status,
|
package/src/overview.astro
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
---
|
|
2
|
-
// The overview page, added by the plugin at `/<overview
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// The overview page, added by the plugin at `/<overview>/` and once per
|
|
3
|
+
// locale (`/it/<overview>/`), so links from a localized sidebar or panel
|
|
4
|
+
// land in the reader's language. Every locale lists every note of the site.
|
|
5
|
+
// The list itself is drawn in the browser (client/overview.js), from the
|
|
6
|
+
// same API as the notes panel; here only the page titles are known.
|
|
5
7
|
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
|
|
6
8
|
import { getCollection } from 'astro:content';
|
|
7
9
|
import config from 'virtual:starlight-annotations/config';
|
|
8
10
|
import { strings } from './client/i18n.js';
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
export function getStaticPaths() {
|
|
13
|
+
return [{ params: { locale: undefined } }, ...Object.keys(config.locales ?? {}).map((locale) => ({ params: { locale } }))];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const { locale } = Astro.params;
|
|
17
|
+
const T = strings(locale ? config.locales[locale] : config.lang, config.translations);
|
|
11
18
|
const docs = await getCollection('docs');
|
|
12
19
|
const titles = Object.fromEntries(docs.map((entry) => [entry.id, entry.data.title]));
|
|
13
20
|
---
|
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,130 @@
|
|
|
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
|
+
const ACTIONS = ['create', 'reply', 'resolve', 'reopen', 'delete'];
|
|
11
|
+
|
|
12
|
+
// "@ada" and "@ada-l" in a message, not inside an email address or code span.
|
|
13
|
+
const MENTION = /(?<![\w`.@/])@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})(?![\w-])/gi;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The event passed to `onChange`, built from a saved change.
|
|
17
|
+
* @returns {import('../../server').AnnotationEvent}
|
|
18
|
+
*/
|
|
19
|
+
export function changeEvent({ change, result, page, user, url }) {
|
|
20
|
+
const { annotation, annotations } = result;
|
|
21
|
+
const action = change.action === 'resolve' ? (annotation.resolved ? 'resolve' : 'reopen') : change.action;
|
|
22
|
+
const byId = new Map(annotations.map((item) => [item.id, item]));
|
|
23
|
+
// A deleted thread is gone from `annotations`: it is its own thread.
|
|
24
|
+
const thread = annotation.replyTo ? (byId.get(annotation.replyTo) ?? null) : annotation;
|
|
25
|
+
const inReplyTo = annotation.inReplyTo ? (byId.get(annotation.inReplyTo) ?? null) : annotation.replyTo ? thread : null;
|
|
26
|
+
const messages = thread ? [thread, ...annotations.filter((item) => item.replyTo === thread.id)] : [annotation];
|
|
27
|
+
const others = (logins) => [...new Set(logins)].filter((login) => login && login.toLowerCase() !== user.login.toLowerCase());
|
|
28
|
+
const written = action === 'create' || action === 'reply';
|
|
29
|
+
return {
|
|
30
|
+
action,
|
|
31
|
+
page,
|
|
32
|
+
url,
|
|
33
|
+
user: { login: user.login, name: user.name || user.login },
|
|
34
|
+
annotation,
|
|
35
|
+
thread,
|
|
36
|
+
inReplyTo,
|
|
37
|
+
threadAuthor: null, // Filled in by the handler: it can open sealed emails.
|
|
38
|
+
participants: others(messages.map((item) => item.author?.login)),
|
|
39
|
+
mentions: written ? others([...annotation.body.matchAll(MENTION)].map((match) => match[1])) : [],
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The quoted passage of a thread, cut in the middle when it is long. */
|
|
44
|
+
export function quoteOf(thread) {
|
|
45
|
+
const selector = thread?.target?.selector;
|
|
46
|
+
if (!selector) return '';
|
|
47
|
+
const squash = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
48
|
+
if (selector.type === 'RangeSelector') return `${squash(selector.startSelector.exact)} âĶ ${squash(selector.endSelector.exact)}`;
|
|
49
|
+
const exact = squash(selector.exact);
|
|
50
|
+
return exact.length > 200 ? `${exact.slice(0, 120)} âĶ ${exact.slice(-60)}` : exact;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Plain text for any channel: a title line, the quote and the message.
|
|
55
|
+
* @param {import('../../server').AnnotationEvent} event
|
|
56
|
+
*/
|
|
57
|
+
export function describeChange(event) {
|
|
58
|
+
const who = event.user.name;
|
|
59
|
+
const title = {
|
|
60
|
+
create: `${who} added a note on ${event.page}`,
|
|
61
|
+
reply: `${who} replied on ${event.page}`,
|
|
62
|
+
resolve: `${who} resolved a note on ${event.page}`,
|
|
63
|
+
reopen: `${who} reopened a note on ${event.page}`,
|
|
64
|
+
delete: `${who} deleted a note on ${event.page}`,
|
|
65
|
+
}[event.action];
|
|
66
|
+
const quote = quoteOf(event.thread);
|
|
67
|
+
const body = event.action === 'create' || event.action === 'reply' ? cut(event.annotation.body, 600) : '';
|
|
68
|
+
const text = [title, quote && `> ${quote}`, body, event.url].filter(Boolean).join('\n\n');
|
|
69
|
+
return { title, quote, body, text };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Posts each change to a Slack incoming webhook.
|
|
74
|
+
* @param {string} webhookUrl
|
|
75
|
+
* @param {{ actions?: string[] }} [options] Which actions to post. Default: all.
|
|
76
|
+
*/
|
|
77
|
+
export function slackWebhook(webhookUrl, { actions = ACTIONS } = {}) {
|
|
78
|
+
if (!webhookUrl) throw new Error('starlight-annotations: slackWebhook needs a webhook URL.');
|
|
79
|
+
return async (event) => {
|
|
80
|
+
if (!actions.includes(event.action)) return;
|
|
81
|
+
const { title, quote, body } = describeChange(event);
|
|
82
|
+
const escape = (value) => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
83
|
+
const lines = [
|
|
84
|
+
event.url ? `*<${event.url}|${escape(title)}>*` : `*${escape(title)}*`,
|
|
85
|
+
quote && `> _${escape(quote)}_`,
|
|
86
|
+
body && escape(body),
|
|
87
|
+
];
|
|
88
|
+
await post(webhookUrl, { text: lines.filter(Boolean).join('\n') }, 'Slack');
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Posts each change to a Microsoft Teams channel through a Workflows webhook
|
|
94
|
+
* ("Post to a channel when a webhook request is received").
|
|
95
|
+
* @param {string} webhookUrl
|
|
96
|
+
* @param {{ actions?: string[] }} [options] Which actions to post. Default: all.
|
|
97
|
+
*/
|
|
98
|
+
export function teamsWebhook(webhookUrl, { actions = ACTIONS } = {}) {
|
|
99
|
+
if (!webhookUrl) throw new Error('starlight-annotations: teamsWebhook needs a webhook URL.');
|
|
100
|
+
return async (event) => {
|
|
101
|
+
if (!actions.includes(event.action)) return;
|
|
102
|
+
const { title, quote, body } = describeChange(event);
|
|
103
|
+
const card = {
|
|
104
|
+
$schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
|
|
105
|
+
type: 'AdaptiveCard',
|
|
106
|
+
version: '1.4',
|
|
107
|
+
body: [
|
|
108
|
+
{ type: 'TextBlock', text: title, weight: 'Bolder', wrap: true },
|
|
109
|
+
quote && { type: 'TextBlock', text: quote, isSubtle: true, wrap: true },
|
|
110
|
+
body && { type: 'TextBlock', text: body, wrap: true },
|
|
111
|
+
].filter(Boolean),
|
|
112
|
+
actions: event.url ? [{ type: 'Action.OpenUrl', title: 'Open the note', url: event.url }] : [],
|
|
113
|
+
};
|
|
114
|
+
await post(
|
|
115
|
+
webhookUrl,
|
|
116
|
+
{ type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', contentUrl: null, content: card }] },
|
|
117
|
+
'Teams',
|
|
118
|
+
);
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function post(url, payload, label) {
|
|
123
|
+
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
|
|
124
|
+
if (!response.ok) throw new Error(`${label} webhook ${response.status}: ${await response.text()}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function cut(value, max) {
|
|
128
|
+
const text = String(value ?? '').trim();
|
|
129
|
+
return text.length > max ? `${text.slice(0, max).trimEnd()}âĶ` : text;
|
|
130
|
+
}
|
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)}`;
|