starlight-annotations 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/index.d.ts +74 -0
- package/index.js +108 -0
- package/package.json +66 -4
- package/server-node.d.ts +10 -0
- package/server.d.ts +77 -0
- package/src/client/annotations.js +706 -0
- package/src/client/backend.js +67 -0
- package/src/client/i18n.js +237 -0
- package/src/client/styles.css +384 -0
- package/src/core.js +161 -0
- package/src/server/github.js +284 -0
- package/src/server/index.js +89 -0
- package/src/server/node.js +86 -0
package/src/core.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// starlight-annotations: the format and the rules, shared by the browser, the
|
|
2
|
+
// dev server and every storage.
|
|
3
|
+
//
|
|
4
|
+
// One JSON file per page: <dir>/<page>.json (dir defaults to "annotations"). An annotation follows the
|
|
5
|
+
// W3C Web Annotation model in a reduced form: the target is a TextQuoteSelector
|
|
6
|
+
// (the quoted text plus a little context on both sides), or for a long passage
|
|
7
|
+
// a RangeSelector made of a start quote and an end quote. Both survive small
|
|
8
|
+
// edits to the page. A reply has `replyTo` and no target.
|
|
9
|
+
|
|
10
|
+
export const ROUTE_PREFIX = '/_annotations';
|
|
11
|
+
export const FORMAT_VERSION = 1;
|
|
12
|
+
|
|
13
|
+
const MAX_BODY = 5000;
|
|
14
|
+
const MAX_EXACT = 2000;
|
|
15
|
+
const MAX_EDGE = 200;
|
|
16
|
+
const MAX_CONTEXT = 64;
|
|
17
|
+
|
|
18
|
+
export class AnnotationError extends Error {
|
|
19
|
+
constructor(status, message) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.status = status;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// "rfc/0002-user-data-model", "it/rfc/0002-user-data-model" or "index".
|
|
26
|
+
export function checkPage(value) {
|
|
27
|
+
const page = String(value ?? '');
|
|
28
|
+
if (!/^[a-z0-9][a-z0-9/_.-]{0,199}$/i.test(page) || page.includes('..') || page.includes('//') || page.endsWith('/')) {
|
|
29
|
+
throw new AnnotationError(400, 'Invalid page.');
|
|
30
|
+
}
|
|
31
|
+
return page;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function filePath(page, dir = 'annotations') {
|
|
35
|
+
const folder = String(dir).replace(/^\/+|\/+$/g, '');
|
|
36
|
+
return folder ? `${folder}/${checkPage(page)}.json` : `${checkPage(page)}.json`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function emptyDocument(page) {
|
|
40
|
+
return { version: FORMAT_VERSION, page, annotations: [] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function parseDocument(text, page) {
|
|
44
|
+
if (!text) return emptyDocument(page);
|
|
45
|
+
const doc = JSON.parse(text);
|
|
46
|
+
if (!Array.isArray(doc.annotations)) throw new AnnotationError(500, 'Corrupt annotation file.');
|
|
47
|
+
return doc;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function serializeDocument(doc) {
|
|
51
|
+
return `${JSON.stringify(doc, null, 2)}\n`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function text(value, max, field) {
|
|
55
|
+
if (typeof value !== 'string') throw new AnnotationError(400, `Missing ${field}.`);
|
|
56
|
+
const trimmed = value.trim();
|
|
57
|
+
if (!trimmed) throw new AnnotationError(400, `Empty ${field}.`);
|
|
58
|
+
if (trimmed.length > max) throw new AnnotationError(400, `${field} is too long.`);
|
|
59
|
+
return trimmed;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function context(value) {
|
|
63
|
+
return typeof value === 'string' ? value.slice(0, MAX_CONTEXT) : '';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A short selection keeps its whole text (TextQuoteSelector). A long one keeps
|
|
67
|
+
// only its first and last words (RangeSelector of two quotes): the file stays
|
|
68
|
+
// small, and an edit in the middle of the passage does not lose the note.
|
|
69
|
+
function selector(target) {
|
|
70
|
+
if (target?.type === 'RangeSelector') {
|
|
71
|
+
return {
|
|
72
|
+
type: 'RangeSelector',
|
|
73
|
+
startSelector: {
|
|
74
|
+
type: 'TextQuoteSelector',
|
|
75
|
+
exact: text(target.startSelector?.exact, MAX_EDGE, 'quote start'),
|
|
76
|
+
prefix: context(target.startSelector?.prefix),
|
|
77
|
+
},
|
|
78
|
+
endSelector: {
|
|
79
|
+
type: 'TextQuoteSelector',
|
|
80
|
+
exact: text(target.endSelector?.exact, MAX_EDGE, 'quote end'),
|
|
81
|
+
suffix: context(target.endSelector?.suffix),
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
type: 'TextQuoteSelector',
|
|
87
|
+
exact: text(target?.exact, MAX_EXACT, 'quote'),
|
|
88
|
+
prefix: context(target?.prefix),
|
|
89
|
+
suffix: context(target?.suffix),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// A change is one of:
|
|
94
|
+
// { action: 'create', target: { exact, prefix, suffix }, body }
|
|
95
|
+
// { action: 'reply', replyTo, body }
|
|
96
|
+
// { action: 'resolve', id, resolved }
|
|
97
|
+
// { action: 'delete', id }
|
|
98
|
+
// It returns the annotation it touched, and a commit message.
|
|
99
|
+
export function applyChange(doc, change, user, now = new Date()) {
|
|
100
|
+
const created = now.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
101
|
+
const author = { login: user.login, name: user.name || user.login };
|
|
102
|
+
const find = (id) => {
|
|
103
|
+
const found = doc.annotations.find((item) => item.id === id);
|
|
104
|
+
if (!found) throw new AnnotationError(404, 'Annotation not found.');
|
|
105
|
+
return found;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
switch (change?.action) {
|
|
109
|
+
case 'create': {
|
|
110
|
+
const annotation = {
|
|
111
|
+
id: crypto.randomUUID(),
|
|
112
|
+
created,
|
|
113
|
+
author,
|
|
114
|
+
target: { selector: selector(change.target) },
|
|
115
|
+
body: text(change.body, MAX_BODY, 'note'),
|
|
116
|
+
resolved: false,
|
|
117
|
+
};
|
|
118
|
+
doc.annotations.push(annotation);
|
|
119
|
+
return { annotation, message: `docs(annotations): note on ${doc.page}` };
|
|
120
|
+
}
|
|
121
|
+
case 'reply': {
|
|
122
|
+
// Threads are flat: `replyTo` is always the first note of the thread.
|
|
123
|
+
// `inReplyTo` optionally names the reply being answered, for the
|
|
124
|
+
// "in reply to" reference in the panel.
|
|
125
|
+
const parent = find(change.replyTo);
|
|
126
|
+
if (parent.replyTo) throw new AnnotationError(400, 'Reply to the first note of the thread.');
|
|
127
|
+
const annotation = { id: crypto.randomUUID(), created, author, replyTo: parent.id, body: text(change.body, MAX_BODY, 'reply') };
|
|
128
|
+
if (change.inReplyTo && change.inReplyTo !== parent.id) {
|
|
129
|
+
const answered = find(change.inReplyTo);
|
|
130
|
+
if (answered.replyTo !== parent.id) throw new AnnotationError(400, 'That reply belongs to another thread.');
|
|
131
|
+
annotation.inReplyTo = answered.id;
|
|
132
|
+
}
|
|
133
|
+
doc.annotations.push(annotation);
|
|
134
|
+
return { annotation, message: `docs(annotations): reply on ${doc.page}` };
|
|
135
|
+
}
|
|
136
|
+
case 'resolve': {
|
|
137
|
+
const annotation = find(change.id);
|
|
138
|
+
if (annotation.replyTo) throw new AnnotationError(400, 'Only a thread can be resolved.');
|
|
139
|
+
annotation.resolved = Boolean(change.resolved);
|
|
140
|
+
annotation.resolvedBy = annotation.resolved ? author : undefined;
|
|
141
|
+
annotation.resolvedAt = annotation.resolved ? created : undefined;
|
|
142
|
+
return { annotation, message: `docs(annotations): ${annotation.resolved ? 'resolve' : 'reopen'} note on ${doc.page}` };
|
|
143
|
+
}
|
|
144
|
+
case 'delete': {
|
|
145
|
+
const annotation = find(change.id);
|
|
146
|
+
if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can delete a note.');
|
|
147
|
+
// Deleting the first note of a thread deletes its replies too.
|
|
148
|
+
doc.annotations = doc.annotations.filter((item) => item.id !== annotation.id && item.replyTo !== annotation.id);
|
|
149
|
+
return { annotation, message: `docs(annotations): delete note on ${doc.page}` };
|
|
150
|
+
}
|
|
151
|
+
default:
|
|
152
|
+
throw new AnnotationError(400, 'Unknown action.');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function json(data, status = 200, headers = {}) {
|
|
157
|
+
return new Response(JSON.stringify(data), {
|
|
158
|
+
status,
|
|
159
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers },
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// GitHub storage and GitHub sign-in.
|
|
2
|
+
//
|
|
3
|
+
// Storage: one JSON file per page, committed through the Contents API to a
|
|
4
|
+
// branch of its own (default "annotations"), so notes never touch the default
|
|
5
|
+
// branch and never trigger a deploy. The branch is created from the default
|
|
6
|
+
// branch on the first save. Each commit has the reader as author (their
|
|
7
|
+
// noreply address), so `git log` and `git blame` show who wrote what.
|
|
8
|
+
//
|
|
9
|
+
// Sign-in: a GitHub OAuth app (or a GitHub App's user authorization). The
|
|
10
|
+
// reader's token is used once to learn their login and is then dropped; the
|
|
11
|
+
// session is an HMAC-signed cookie. `writers` decides who may write.
|
|
12
|
+
|
|
13
|
+
import { AnnotationError, filePath, parseDocument, serializeDocument } from '../core.js';
|
|
14
|
+
|
|
15
|
+
const GITHUB_API = 'https://api.github.com';
|
|
16
|
+
const SESSION_COOKIE = 'annot_session';
|
|
17
|
+
const STATE_COOKIE = 'annot_state';
|
|
18
|
+
const SESSION_AGE = 60 * 60 * 24 * 30;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Storage and sign-in together, which is what most sites want.
|
|
22
|
+
* @param {GitHubOptions} options
|
|
23
|
+
*/
|
|
24
|
+
export function github(options) {
|
|
25
|
+
return { storage: githubStorage(options), auth: githubAuth(options) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {{ repo: string, token: string, branch?: string, dir?: string, commitMessage?: (action: string, page: string) => string }} options
|
|
30
|
+
*/
|
|
31
|
+
export function githubStorage({ repo, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
|
|
32
|
+
required({ repo, token }, 'githubStorage');
|
|
33
|
+
|
|
34
|
+
const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
|
|
35
|
+
|
|
36
|
+
async function read(page) {
|
|
37
|
+
const file = await api(token, `${contentsPath(page)}?ref=${encodeURIComponent(branch)}`, { allow404: true });
|
|
38
|
+
if (!file) return { doc: parseDocument('', page), sha: undefined };
|
|
39
|
+
return { doc: parseDocument(new TextDecoder().decode(fromBase64(file.content)), page), sha: file.sha };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function createBranch() {
|
|
43
|
+
const info = await api(token, `/repos/${repo}`);
|
|
44
|
+
const head = await api(token, `/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
|
|
45
|
+
const response = await raw(token, `/repos/${repo}/git/refs`, {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: head.object.sha }),
|
|
48
|
+
});
|
|
49
|
+
// 422: it exists already (another save created it a moment ago).
|
|
50
|
+
if (!response.ok && response.status !== 422) throw new Error(`GitHub create branch ${response.status}: ${await response.text()}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
mode: 'github',
|
|
55
|
+
async load(page) {
|
|
56
|
+
return (await read(page)).doc;
|
|
57
|
+
},
|
|
58
|
+
async update(page, mutate, user) {
|
|
59
|
+
// Two readers saving on the same page: GitHub refuses the stale sha, so
|
|
60
|
+
// read again and apply the change on top.
|
|
61
|
+
let branchCreated = false;
|
|
62
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
63
|
+
const { doc, sha } = await read(page);
|
|
64
|
+
const { annotation, message } = mutate(doc);
|
|
65
|
+
const response = await raw(token, contentsPath(page), {
|
|
66
|
+
method: 'PUT',
|
|
67
|
+
body: JSON.stringify({
|
|
68
|
+
message: commitMessage ? commitMessage(message, page) : message,
|
|
69
|
+
content: toBase64(new TextEncoder().encode(serializeDocument(doc))),
|
|
70
|
+
sha,
|
|
71
|
+
branch,
|
|
72
|
+
author: user.id
|
|
73
|
+
? { name: user.name || user.login, email: `${user.id}+${user.login}@users.noreply.github.com` }
|
|
74
|
+
: undefined,
|
|
75
|
+
}),
|
|
76
|
+
});
|
|
77
|
+
if (response.ok) return { annotation, annotations: doc.annotations };
|
|
78
|
+
if (response.status === 404 || response.status === 422) {
|
|
79
|
+
const detail = await response.text();
|
|
80
|
+
// A missing branch answers 404 or 422 "Branch not found". Create it once.
|
|
81
|
+
if (!branchCreated && (response.status === 404 || /branch/i.test(detail))) {
|
|
82
|
+
await createBranch();
|
|
83
|
+
branchCreated = true;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`GitHub PUT ${response.status}: ${detail}`);
|
|
87
|
+
}
|
|
88
|
+
if (response.status === 409) continue;
|
|
89
|
+
throw new Error(`GitHub PUT ${response.status}: ${await response.text()}`);
|
|
90
|
+
}
|
|
91
|
+
throw new AnnotationError(409, 'Someone else is saving notes on this page. Try again.');
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @param {GitHubOptions} options
|
|
98
|
+
*/
|
|
99
|
+
export function githubAuth({ clientId, clientSecret, sessionSecret, repo, token, writers = 'collaborators', cookieSecure = true }) {
|
|
100
|
+
required({ clientId, clientSecret, sessionSecret }, 'githubAuth');
|
|
101
|
+
if (writers === 'collaborators') required({ repo, token }, 'githubAuth with writers "collaborators"');
|
|
102
|
+
|
|
103
|
+
const cookie = (name, value, maxAge, path = '/') =>
|
|
104
|
+
`${name}=${value}; HttpOnly;${cookieSecure ? ' Secure;' : ''} SameSite=Lax; Path=${path}; Max-Age=${maxAge}`;
|
|
105
|
+
|
|
106
|
+
async function mayWrite(profile) {
|
|
107
|
+
if (writers === 'anyone') return true;
|
|
108
|
+
if (Array.isArray(writers)) return writers.map((login) => login.toLowerCase()).includes(profile.login.toLowerCase());
|
|
109
|
+
if (typeof writers === 'function') return Boolean(await writers(profile));
|
|
110
|
+
const permission = await api(token, `/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, { allow404: true });
|
|
111
|
+
return Boolean(permission && permission.permission !== 'none');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function hmac(value) {
|
|
115
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
116
|
+
return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
mode: 'github',
|
|
121
|
+
|
|
122
|
+
async user(request) {
|
|
123
|
+
const value = readCookie(request, SESSION_COOKIE);
|
|
124
|
+
if (!value) return null;
|
|
125
|
+
const [body, signature] = value.split('.');
|
|
126
|
+
if (!body || !signature || !timingSafeEqual(signature, await hmac(body))) return null;
|
|
127
|
+
try {
|
|
128
|
+
const payload = JSON.parse(new TextDecoder().decode(fromBase64url(body)));
|
|
129
|
+
return payload.exp > Date.now() / 1000 ? payload : null;
|
|
130
|
+
} catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
async route(route, request, url, prefix) {
|
|
136
|
+
if (request.method !== 'GET') return null;
|
|
137
|
+
const callbackPath = `${prefix}/callback`;
|
|
138
|
+
const redirectUri = `${url.origin}${callbackPath}`;
|
|
139
|
+
|
|
140
|
+
if (route === '/login') {
|
|
141
|
+
const state = crypto.randomUUID();
|
|
142
|
+
const back = safeReturn(url.searchParams.get('return'));
|
|
143
|
+
const authorize = new URL('https://github.com/login/oauth/authorize');
|
|
144
|
+
authorize.searchParams.set('client_id', clientId);
|
|
145
|
+
authorize.searchParams.set('redirect_uri', redirectUri);
|
|
146
|
+
authorize.searchParams.set('state', state);
|
|
147
|
+
authorize.searchParams.set('allow_signup', 'false');
|
|
148
|
+
// No scope: the public profile is enough to know who the reader is.
|
|
149
|
+
return redirect(authorize.toString(), [cookie(STATE_COOKIE, `${state}.${encodeURIComponent(back)}`, 600, callbackPath)]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (route === '/callback') {
|
|
153
|
+
// "<uuid>.<return path>": the uuid has no dot, the path may.
|
|
154
|
+
const saved = readCookie(request, STATE_COOKIE) || '';
|
|
155
|
+
const dot = saved.indexOf('.');
|
|
156
|
+
const [state, back] = dot === -1 ? [saved, ''] : [saved.slice(0, dot), saved.slice(dot + 1)];
|
|
157
|
+
const clear = cookie(STATE_COOKIE, '', 0, callbackPath);
|
|
158
|
+
if (!state || state !== url.searchParams.get('state')) return text('The sign-in link expired. Try again.', 400, [clear]);
|
|
159
|
+
|
|
160
|
+
const exchange = await fetch('https://github.com/login/oauth/access_token', {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
163
|
+
body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, code: url.searchParams.get('code'), redirect_uri: redirectUri }),
|
|
164
|
+
});
|
|
165
|
+
const { access_token: userToken } = await exchange.json();
|
|
166
|
+
if (!userToken) return text('GitHub did not confirm the sign-in.', 400, [clear]);
|
|
167
|
+
|
|
168
|
+
const profile = await api(userToken, '/user');
|
|
169
|
+
if (!(await mayWrite(profile))) {
|
|
170
|
+
return text(`${profile.login} may not annotate these docs.`, 403, [clear]);
|
|
171
|
+
}
|
|
172
|
+
const body = base64url(
|
|
173
|
+
new TextEncoder().encode(
|
|
174
|
+
JSON.stringify({ login: profile.login, id: profile.id, name: profile.name || profile.login, exp: Math.floor(Date.now() / 1000) + SESSION_AGE }),
|
|
175
|
+
),
|
|
176
|
+
);
|
|
177
|
+
const session = `${body}.${await hmac(body)}`;
|
|
178
|
+
return redirect(safeReturn(decodeURIComponent(back || '/')), [clear, cookie(SESSION_COOKIE, session, SESSION_AGE)]);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (route === '/logout') {
|
|
182
|
+
return redirect(safeReturn(url.searchParams.get('return')), [cookie(SESSION_COOKIE, '', 0)]);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return null;
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ---- GitHub REST ----
|
|
191
|
+
|
|
192
|
+
function raw(token, path, init = {}) {
|
|
193
|
+
return fetch(`${GITHUB_API}${path}`, {
|
|
194
|
+
...init,
|
|
195
|
+
headers: {
|
|
196
|
+
Accept: 'application/vnd.github+json',
|
|
197
|
+
Authorization: `Bearer ${token}`,
|
|
198
|
+
'User-Agent': 'starlight-annotations',
|
|
199
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
200
|
+
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function api(token, path, { allow404 = false } = {}) {
|
|
206
|
+
const response = await raw(token, path);
|
|
207
|
+
if (allow404 && response.status === 404) return null;
|
|
208
|
+
if (!response.ok) throw new Error(`GitHub GET ${path} ${response.status}: ${await response.text()}`);
|
|
209
|
+
return response.json();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---- Helpers ----
|
|
213
|
+
|
|
214
|
+
function required(values, where) {
|
|
215
|
+
const missing = Object.entries(values)
|
|
216
|
+
.filter(([, value]) => !value)
|
|
217
|
+
.map(([key]) => key);
|
|
218
|
+
if (missing.length) throw new Error(`starlight-annotations: ${where} needs ${missing.join(', ')}.`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function safeReturn(value) {
|
|
222
|
+
const path = String(value || '/');
|
|
223
|
+
return path.startsWith('/') && !path.startsWith('//') ? path : '/';
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function readCookie(request, name) {
|
|
227
|
+
for (const part of (request.headers.get('Cookie') || '').split(';')) {
|
|
228
|
+
const [key, ...rest] = part.trim().split('=');
|
|
229
|
+
if (key === name) return rest.join('=');
|
|
230
|
+
}
|
|
231
|
+
return '';
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function redirect(location, cookies = []) {
|
|
235
|
+
const headers = new Headers({ Location: location, 'Cache-Control': 'no-store' });
|
|
236
|
+
for (const value of cookies) headers.append('Set-Cookie', value);
|
|
237
|
+
return new Response(null, { status: 303, headers });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function text(message, status, cookies = []) {
|
|
241
|
+
const headers = new Headers({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
242
|
+
for (const value of cookies) headers.append('Set-Cookie', value);
|
|
243
|
+
return new Response(message, { status, headers });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function toBase64(bytes) {
|
|
247
|
+
let binary = '';
|
|
248
|
+
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
249
|
+
return btoa(binary);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function fromBase64(value) {
|
|
253
|
+
return Uint8Array.from(atob(value.replace(/\s/g, '')), (char) => char.charCodeAt(0));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function base64url(bytes) {
|
|
257
|
+
return toBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function fromBase64url(value) {
|
|
261
|
+
const padded = value.replace(/-/g, '+').replace(/_/g, '/');
|
|
262
|
+
return fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function timingSafeEqual(left, right) {
|
|
266
|
+
const length = Math.max(left.length, right.length);
|
|
267
|
+
let diff = left.length === right.length ? 0 : 1;
|
|
268
|
+
for (let i = 0; i < length; i++) diff |= (left.charCodeAt(i) || 0) ^ (right.charCodeAt(i) || 0);
|
|
269
|
+
return diff === 0;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* @typedef {{
|
|
274
|
+
* repo: string,
|
|
275
|
+
* token: string,
|
|
276
|
+
* branch?: string,
|
|
277
|
+
* dir?: string,
|
|
278
|
+
* clientId: string,
|
|
279
|
+
* clientSecret: string,
|
|
280
|
+
* sessionSecret: string,
|
|
281
|
+
* writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string, id: number }) => boolean | Promise<boolean>),
|
|
282
|
+
* cookieSecure?: boolean,
|
|
283
|
+
* }} GitHubOptions
|
|
284
|
+
*/
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// The annotation API as a Web-standard handler: (Request) => Response | null.
|
|
2
|
+
// It runs anywhere that speaks fetch: Cloudflare Workers, Deno, Bun, Netlify
|
|
3
|
+
// and Vercel functions, Node 20+, or an Astro endpoint.
|
|
4
|
+
//
|
|
5
|
+
// const handle = createAnnotationsHandler(github({ repo, token, ... }));
|
|
6
|
+
// const response = await handle(request); // null when the path is not ours
|
|
7
|
+
//
|
|
8
|
+
// Routes, under `prefix` (default "/_annotations"):
|
|
9
|
+
// GET /api?page=<page> notes of a page, and who is signed in
|
|
10
|
+
// POST /api { page, change } applies one change
|
|
11
|
+
// GET /login /callback /logout handled by the auth, when it has them
|
|
12
|
+
|
|
13
|
+
import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json } from '../core.js';
|
|
14
|
+
|
|
15
|
+
export { github, githubAuth, githubStorage } from './github.js';
|
|
16
|
+
export { AnnotationError } from '../core.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{ storage: Storage, auth?: Auth, prefix?: string }} options
|
|
20
|
+
*/
|
|
21
|
+
export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX }) {
|
|
22
|
+
if (!storage) throw new Error('starlight-annotations: createAnnotationsHandler needs a storage.');
|
|
23
|
+
const root = prefix.replace(/\/$/, '');
|
|
24
|
+
|
|
25
|
+
return async function handleAnnotations(request) {
|
|
26
|
+
const url = new URL(request.url);
|
|
27
|
+
if (!url.pathname.startsWith(`${root}/`)) return null;
|
|
28
|
+
const route = url.pathname.slice(root.length);
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
if (auth?.route) {
|
|
32
|
+
const response = await auth.route(route, request, url, root);
|
|
33
|
+
if (response) return response;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (route === '/api' && request.method === 'GET') {
|
|
37
|
+
const page = checkPage(url.searchParams.get('page'));
|
|
38
|
+
const doc = await storage.load(page);
|
|
39
|
+
const user = auth ? await auth.user(request) : null;
|
|
40
|
+
return json({
|
|
41
|
+
annotations: doc.annotations,
|
|
42
|
+
user: user && { login: user.login, name: user.name },
|
|
43
|
+
mode: auth?.mode ?? storage.mode ?? 'api',
|
|
44
|
+
canSignIn: Boolean(auth?.route),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (route === '/api' && request.method === 'POST') {
|
|
49
|
+
const origin = request.headers.get('Origin');
|
|
50
|
+
if (origin && origin !== url.origin) return json({ error: 'Cross-site request refused.' }, 403);
|
|
51
|
+
const user = auth ? await auth.user(request) : null;
|
|
52
|
+
if (!user) return json({ error: 'Sign in first.' }, 401);
|
|
53
|
+
const { page, change } = await request.json();
|
|
54
|
+
const result = await storage.update(checkPage(page), (doc) => applyChange(doc, change, user), user);
|
|
55
|
+
return json(result);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return json({ error: 'Not found.' }, 404);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof AnnotationError) return json({ error: error.message }, error.status);
|
|
61
|
+
console.error('starlight-annotations', error);
|
|
62
|
+
return json({ error: 'The annotation service failed. Try again.' }, 502);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A fixed identity, for local development or a site behind its own login.
|
|
69
|
+
* @param {{ login: string, name?: string, id?: number }} user
|
|
70
|
+
*/
|
|
71
|
+
export function staticAuth(user) {
|
|
72
|
+
return { mode: 'local', user: async () => user };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @typedef {{ login: string, name?: string, id?: number }} User
|
|
77
|
+
* @typedef {{ version: number, page: string, annotations: object[] }} AnnotationDocument
|
|
78
|
+
* @typedef {{
|
|
79
|
+
* mode?: string,
|
|
80
|
+
* load(page: string): Promise<AnnotationDocument>,
|
|
81
|
+
* update(page: string, mutate: (doc: AnnotationDocument) => { annotation: object, message: string }, user: User):
|
|
82
|
+
* Promise<{ annotation: object, annotations: object[] }>,
|
|
83
|
+
* }} Storage
|
|
84
|
+
* @typedef {{
|
|
85
|
+
* mode?: string,
|
|
86
|
+
* user(request: Request): Promise<User | null>,
|
|
87
|
+
* route?(route: string, request: Request, url: URL, prefix: string): Promise<Response | null>,
|
|
88
|
+
* }} Auth
|
|
89
|
+
*/
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Node-only pieces: a storage on disk, and a bridge from Node's
|
|
2
|
+
// IncomingMessage/ServerResponse to the Web-standard handler (used by the dev
|
|
3
|
+
// server, and usable with Express, Fastify or plain node:http).
|
|
4
|
+
|
|
5
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { filePath, parseDocument, serializeDocument } from '../core.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Notes as JSON files in a folder. Good for development, or for a Node
|
|
11
|
+
* server whose folder is a Git checkout that something else commits.
|
|
12
|
+
* @param {{ dir: string }} options
|
|
13
|
+
*/
|
|
14
|
+
export function fsStorage({ dir }) {
|
|
15
|
+
const fileFor = (page) => path.join(dir, filePath(page, ''));
|
|
16
|
+
|
|
17
|
+
async function load(page) {
|
|
18
|
+
try {
|
|
19
|
+
return parseDocument(await readFile(fileFor(page), 'utf8'), page);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (error.code === 'ENOENT') return parseDocument('', page);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// One write at a time per file, so two quick saves do not lose each other.
|
|
27
|
+
const queues = new Map();
|
|
28
|
+
|
|
29
|
+
return {
|
|
30
|
+
mode: 'local',
|
|
31
|
+
load,
|
|
32
|
+
update(page, mutate) {
|
|
33
|
+
const run = async () => {
|
|
34
|
+
const doc = await load(page);
|
|
35
|
+
const { annotation } = mutate(doc);
|
|
36
|
+
const target = fileFor(page);
|
|
37
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
38
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
39
|
+
await writeFile(temporary, serializeDocument(doc));
|
|
40
|
+
await rename(temporary, target);
|
|
41
|
+
return { annotation, annotations: doc.annotations };
|
|
42
|
+
};
|
|
43
|
+
const next = (queues.get(page) ?? Promise.resolve()).then(run, run);
|
|
44
|
+
queues.set(page, next.catch(() => {}));
|
|
45
|
+
return next;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Wraps a Web handler as Node middleware: (req, res, next).
|
|
52
|
+
* @param {(request: Request) => Promise<Response | null>} handler
|
|
53
|
+
*/
|
|
54
|
+
export function toNodeMiddleware(handler) {
|
|
55
|
+
return async (req, res, next) => {
|
|
56
|
+
try {
|
|
57
|
+
const host = req.headers.host ?? 'localhost';
|
|
58
|
+
const url = new URL(req.url, `http://${host}`);
|
|
59
|
+
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
|
|
60
|
+
const request = new Request(url, {
|
|
61
|
+
method: req.method,
|
|
62
|
+
headers: Object.entries(req.headers).flatMap(([key, value]) =>
|
|
63
|
+
Array.isArray(value) ? value.map((item) => [key, item]) : value == null ? [] : [[key, value]],
|
|
64
|
+
),
|
|
65
|
+
body: hasBody ? await readBody(req) : undefined,
|
|
66
|
+
});
|
|
67
|
+
const response = await handler(request);
|
|
68
|
+
if (!response) return next?.();
|
|
69
|
+
res.statusCode = response.status;
|
|
70
|
+
response.headers.forEach((value, key) => {
|
|
71
|
+
if (key !== 'set-cookie') res.setHeader(key, value);
|
|
72
|
+
});
|
|
73
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
74
|
+
if (cookies.length) res.setHeader('set-cookie', cookies);
|
|
75
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
76
|
+
} catch (error) {
|
|
77
|
+
next ? next(error) : res.end();
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function readBody(req) {
|
|
83
|
+
const chunks = [];
|
|
84
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
85
|
+
return Buffer.concat(chunks);
|
|
86
|
+
}
|