starlight-annotations 0.1.2 → 0.2.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/README.md CHANGED
@@ -13,7 +13,7 @@ Let readers highlight text and leave notes on your [Starlight](https://starlight
13
13
 
14
14
  - 💎 **Select, note, discuss.** Markdown notes with a formatting toolbar, replies, "in reply to" references, resolve and reopen.
15
15
  - 📌 **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.
16
- - 🗂ïļ **Your repo, your data.** One file per page on a branch of its own; every note is a commit by its author.
16
+ - 🗂ïļ **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).
17
17
  - 🌍 **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.
18
18
  - ðŸŠķ **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.
19
19
  - 🌐 **Multilingual.** English, Italian, German, French and Spanish built in; the UI follows the page language.
@@ -67,6 +67,8 @@ export default {
67
67
 
68
68
  See [Store notes on GitHub](https://alessandroros.github.io/starlight-annotations/guides/github/) for the OAuth app and the token, and [other hosts](https://alessandroros.github.io/starlight-annotations/guides/other-hosts/) for Netlify, Vercel, Node and Astro endpoints.
69
69
 
70
+ On GitLab or Gitea/Forgejo, use `gitlab({ host, project, â€Ķ })` or `gitea({ host, repo, â€Ķ })` instead of `github(â€Ķ)`: see [GitLab](https://alessandroros.github.io/starlight-annotations/guides/gitlab/) and [Gitea, Forgejo and Codeberg](https://alessandroros.github.io/starlight-annotations/guides/gitea/).
71
+
70
72
  No server? `starlightAnnotations({ backend: 'browser' })` keeps notes in each reader's browser.
71
73
 
72
74
  ## 📄 License
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.1.2",
4
- "description": "🖍ïļ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository.",
3
+ "version": "0.2.0",
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",
7
7
  "type": "module",
@@ -24,7 +24,11 @@
24
24
  "highlight",
25
25
  "notes",
26
26
  "feedback",
27
- "docs-review"
27
+ "docs-review",
28
+ "gitlab",
29
+ "gitea",
30
+ "forgejo",
31
+ "codeberg"
28
32
  ],
29
33
  "exports": {
30
34
  ".": {
package/server.d.ts CHANGED
@@ -65,9 +65,83 @@ export interface GitHubAuthOptions {
65
65
  cookieSecure?: boolean;
66
66
  }
67
67
 
68
+ export type GitHubOptions = GitHubStorageOptions & GitHubAuthOptions;
69
+
68
70
  export function githubStorage(options: GitHubStorageOptions): Storage;
69
71
  export function githubAuth(options: GitHubAuthOptions): Auth;
70
- export function github(options: GitHubStorageOptions & GitHubAuthOptions): { storage: Storage; auth: Auth };
72
+ export function github(options: GitHubOptions): { storage: Storage; auth: Auth };
73
+
74
+ interface CommonStorageOptions {
75
+ /** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
76
+ branch?: string;
77
+ /** Folder for the notes in the branch. Default `"annotations"`. */
78
+ dir?: string;
79
+ /** Rewrite the commit message, e.g. to fit your commit convention. */
80
+ commitMessage?: (message: string, page: string) => string;
81
+ }
82
+
83
+ interface CommonAuthOptions {
84
+ /** OAuth application id and secret. */
85
+ clientId: string;
86
+ clientSecret: string;
87
+ /** A long random string that signs the session cookie. */
88
+ sessionSecret: string;
89
+ /**
90
+ * Who may write. `"collaborators"` (default) checks the reader's role on the repository with
91
+ * `token`. `"anyone"` accepts every signed-in user.
92
+ */
93
+ writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
94
+ /** Set to false only for plain-http local testing. Default true. */
95
+ cookieSecure?: boolean;
96
+ }
97
+
98
+ export interface GitLabStorageOptions extends CommonStorageOptions {
99
+ /** Your GitLab, e.g. `"https://gitlab.example.com"`. Default `"https://gitlab.com"`. */
100
+ host?: string;
101
+ /** Project path (`"group/project"`) or numeric id. */
102
+ project: string | number;
103
+ /** Project, group or personal access token with the `api` scope and the Developer role. */
104
+ token: string;
105
+ }
106
+
107
+ /** `"collaborators"` means project members with the Developer role or higher. */
108
+ export interface GitLabAuthOptions extends CommonAuthOptions {
109
+ host?: string;
110
+ project?: string | number;
111
+ token?: string;
112
+ }
113
+
114
+ export type GitLabOptions = GitLabStorageOptions & GitLabAuthOptions;
115
+
116
+ /** Experimental: tested against a simulated GitLab API. */
117
+ export function gitlabStorage(options: GitLabStorageOptions): Storage;
118
+ export function gitlabAuth(options: GitLabAuthOptions): Auth;
119
+ export function gitlab(options: GitLabOptions): { storage: Storage; auth: Auth };
120
+
121
+ export interface GiteaStorageOptions extends CommonStorageOptions {
122
+ /** Your Gitea or Forgejo server, e.g. `"https://codeberg.org"`. */
123
+ host: string;
124
+ /** `owner/name` of the repository. */
125
+ repo: string;
126
+ /** Access token with `write:repository` on the repository. */
127
+ token: string;
128
+ }
129
+
130
+ /** `"collaborators"` means people with write, admin or owner permission on the repository. */
131
+ export interface GiteaAuthOptions extends CommonAuthOptions {
132
+ host: string;
133
+ repo?: string;
134
+ token?: string;
135
+ }
136
+
137
+ export type GiteaOptions = GiteaStorageOptions & GiteaAuthOptions;
138
+
139
+ /** Experimental: tested against a simulated Gitea API. Works with Forgejo and Codeberg. */
140
+ export function giteaStorage(options: GiteaStorageOptions): Storage;
141
+ export function giteaAuth(options: GiteaAuthOptions): Auth;
142
+ export function gitea(options: GiteaOptions): { storage: Storage; auth: Auth };
143
+ /** The same as `gitea`: Forgejo speaks the Gitea API. */
144
+ export const forgejo: typeof gitea;
71
145
 
72
146
  /** A fixed identity: for local development, or a site behind its own login. */
73
147
  export function staticAuth(user: User): Auth;
@@ -0,0 +1,51 @@
1
+ // The part every Git host storage shares: read the page file, apply the
2
+ // change, write it back; on a concurrent save read again and retry; when the
3
+ // notes branch does not exist yet, create it once and retry.
4
+
5
+ import { AnnotationError, parseDocument, serializeDocument } from '../core.js';
6
+
7
+ /**
8
+ * @param {{
9
+ * mode: string,
10
+ * commitMessage?: (message: string, page: string) => string,
11
+ * read: (page: string) => Promise<{ text: string, version?: string } | null>,
12
+ * write: (page: string, text: string, version: string | undefined, message: string, user: object) =>
13
+ * Promise<'ok' | 'conflict' | 'missing-branch'>,
14
+ * createBranch: () => Promise<void>,
15
+ * }} host
16
+ */
17
+ export function gitStorage(host) {
18
+ async function read(page) {
19
+ const file = await host.read(page);
20
+ return { doc: parseDocument(file?.text ?? '', page), version: file?.version };
21
+ }
22
+
23
+ return {
24
+ mode: host.mode,
25
+ async load(page) {
26
+ return (await read(page)).doc;
27
+ },
28
+ async update(page, mutate, user) {
29
+ let branchCreated = false;
30
+ for (let attempt = 0; attempt < 4; attempt++) {
31
+ const { doc, version } = await read(page);
32
+ const { annotation, message } = mutate(doc);
33
+ const outcome = await host.write(
34
+ page,
35
+ serializeDocument(doc),
36
+ version,
37
+ host.commitMessage ? host.commitMessage(message, page) : message,
38
+ user,
39
+ );
40
+ if (outcome === 'ok') return { annotation, annotations: doc.annotations };
41
+ if (outcome === 'missing-branch') {
42
+ if (branchCreated) throw new Error(`${host.mode}: the notes branch is still missing after creating it.`);
43
+ await host.createBranch();
44
+ branchCreated = true;
45
+ }
46
+ // 'conflict': someone saved a moment ago; read again and apply on top.
47
+ }
48
+ throw new AnnotationError(409, 'Someone else is saving notes on this page. Try again.');
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,104 @@
1
+ // Gitea and Forgejo storage and sign-in: self-hosted servers, and Codeberg
2
+ // (https://codeberg.org), which runs Forgejo.
3
+ //
4
+ // Storage: the Contents API, on a branch of its own (default "annotations"),
5
+ // created from the default branch on the first save. Commits carry the
6
+ // reader as author.
7
+ //
8
+ // Sign-in: an OAuth2 application on the server. Only people with write
9
+ // access to the repository may annotate, unless `writers` says otherwise.
10
+
11
+ import { filePath } from '../core.js';
12
+ import { gitStorage } from './git-storage.js';
13
+ import { oauthAuth } from './oauth.js';
14
+ import { decodeText, encodeText, required, restClient } from './util.js';
15
+
16
+ const hostOf = (url) => url.replace(/\/+$/, '');
17
+
18
+ const client = (host, authorization) => restClient({ base: `${hostOf(host)}/api/v1`, headers: { Authorization: authorization }, label: 'Gitea' });
19
+
20
+ /**
21
+ * Storage and sign-in together.
22
+ * @param {import('../../server').GiteaOptions} options
23
+ */
24
+ export function gitea(options) {
25
+ return { storage: giteaStorage(options), auth: giteaAuth(options) };
26
+ }
27
+
28
+ /** @param {import('../../server').GiteaStorageOptions} options */
29
+ export function giteaStorage({ host, repo, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
30
+ required({ host, repo, token }, 'giteaStorage');
31
+ const api = client(host, `token ${token}`);
32
+ const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
33
+ const hostname = new URL(hostOf(host)).hostname;
34
+
35
+ return gitStorage({
36
+ mode: 'gitea',
37
+ commitMessage,
38
+
39
+ async read(page) {
40
+ const file = await api.get(`${contentsPath(page)}?ref=${encodeURIComponent(branch)}`, { allow404: true });
41
+ return file && { text: decodeText(file.content), version: file.sha };
42
+ },
43
+
44
+ async write(page, content, sha, message, user) {
45
+ const response = await api.raw(contentsPath(page), {
46
+ method: sha ? 'PUT' : 'POST',
47
+ body: JSON.stringify({
48
+ message,
49
+ content: encodeText(content),
50
+ sha,
51
+ branch,
52
+ ...(user.id ? { author: { name: user.name || user.login, email: `${user.login}@noreply.${hostname}` } } : {}),
53
+ }),
54
+ });
55
+ if (response.ok) return 'ok';
56
+ const detail = await response.text();
57
+ if ((response.status === 404 || response.status === 422) && /branch/i.test(detail)) return 'missing-branch';
58
+ // Stale sha, or the file was created by another save meanwhile.
59
+ if (response.status === 409 || response.status === 422) return 'conflict';
60
+ throw new Error(`Gitea ${sha ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
61
+ },
62
+
63
+ async createBranch() {
64
+ const info = await api.get(`/repos/${repo}`);
65
+ const response = await api.raw(`/repos/${repo}/branches`, {
66
+ method: 'POST',
67
+ body: JSON.stringify({ new_branch_name: branch, old_branch_name: info.default_branch }),
68
+ });
69
+ // 409: it exists already.
70
+ if (!response.ok && response.status !== 409) throw new Error(`Gitea create branch ${response.status}: ${await response.text()}`);
71
+ },
72
+ });
73
+ }
74
+
75
+ /** @param {import('../../server').GiteaAuthOptions} options */
76
+ export function giteaAuth({ host, repo, token, writers = 'collaborators', ...options }) {
77
+ required({ host }, 'giteaAuth');
78
+ if (writers === 'collaborators') required({ repo, token }, 'giteaAuth with writers "collaborators"');
79
+ const base = hostOf(host);
80
+ return oauthAuth({
81
+ ...options,
82
+ writers,
83
+ mode: 'gitea',
84
+ where: 'giteaAuth',
85
+ authorizeUrl: `${base}/login/oauth/authorize`,
86
+ tokenUrl: `${base}/login/oauth/access_token`,
87
+ scope: 'read:user',
88
+ async profile(userToken) {
89
+ const user = await client(host, `Bearer ${userToken}`).get('/user');
90
+ return { login: user.login, id: user.id, name: user.full_name };
91
+ },
92
+ async canWrite(profile) {
93
+ const permission = await client(host, `token ${token}`).get(
94
+ `/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`,
95
+ { allow404: true },
96
+ );
97
+ return ['owner', 'admin', 'write'].includes(permission?.permission);
98
+ },
99
+ noAccess: (login) => `${login} may not annotate these docs.`,
100
+ });
101
+ }
102
+
103
+ /** Forgejo speaks the same API as Gitea. */
104
+ export { gitea as forgejo };
@@ -6,282 +6,101 @@
6
6
  // branch on the first save. Each commit has the reader as author (their
7
7
  // noreply address), so `git log` and `git blame` show who wrote what.
8
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;
9
+ // Sign-in: a GitHub OAuth app. Only people with write access to `repo` may
10
+ // annotate, unless `writers` says otherwise.
11
+
12
+ import { filePath } from '../core.js';
13
+ import { gitStorage } from './git-storage.js';
14
+ import { oauthAuth } from './oauth.js';
15
+ import { decodeText, encodeText, required, restClient } from './util.js';
16
+
17
+ const client = (token) =>
18
+ restClient({
19
+ base: 'https://api.github.com',
20
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
21
+ label: 'GitHub',
22
+ });
19
23
 
20
24
  /**
21
25
  * Storage and sign-in together, which is what most sites want.
22
- * @param {GitHubOptions} options
26
+ * @param {import('../../server').GitHubOptions} options
23
27
  */
24
28
  export function github(options) {
25
29
  return { storage: githubStorage(options), auth: githubAuth(options) };
26
30
  }
27
31
 
28
- /**
29
- * @param {{ repo: string, token: string, branch?: string, dir?: string, commitMessage?: (action: string, page: string) => string }} options
30
- */
32
+ /** @param {import('../../server').GitHubStorageOptions} options */
31
33
  export function githubStorage({ repo, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
32
34
  required({ repo, token }, 'githubStorage');
33
-
35
+ const api = client(token);
34
36
  const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
35
37
 
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
- }
38
+ return gitStorage({
39
+ mode: 'github',
40
+ commitMessage,
41
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
- }
42
+ async read(page) {
43
+ const file = await api.get(`${contentsPath(page)}?ref=${encodeURIComponent(branch)}`, { allow404: true });
44
+ return file && { text: decodeText(file.content), version: file.sha };
45
+ },
52
46
 
53
- return {
54
- mode: 'github',
55
- async load(page) {
56
- return (await read(page)).doc;
47
+ async write(page, content, sha, message, user) {
48
+ const response = await api.raw(contentsPath(page), {
49
+ method: 'PUT',
50
+ body: JSON.stringify({
51
+ message,
52
+ content: encodeText(content),
53
+ sha,
54
+ branch,
55
+ author: user.id ? { name: user.name || user.login, email: `${user.id}+${user.login}@users.noreply.github.com` } : undefined,
56
+ }),
57
+ });
58
+ if (response.ok) return 'ok';
59
+ const detail = await response.text();
60
+ // A missing branch answers 404, or 422 "Branch â€Ķ not found".
61
+ if (response.status === 404 || (response.status === 422 && /branch/i.test(detail))) return 'missing-branch';
62
+ // 409: stale sha. 422 "sha wasn't supplied": the file was created meanwhile.
63
+ if (response.status === 409 || response.status === 422) return 'conflict';
64
+ throw new Error(`GitHub PUT ${response.status}: ${detail}`);
57
65
  },
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.');
66
+
67
+ async createBranch() {
68
+ const info = await api.get(`/repos/${repo}`);
69
+ const head = await api.get(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
70
+ const response = await api.raw(`/repos/${repo}/git/refs`, {
71
+ method: 'POST',
72
+ body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: head.object.sha }),
73
+ });
74
+ // 422: it exists already (another save created it a moment ago).
75
+ if (!response.ok && response.status !== 422) throw new Error(`GitHub create branch ${response.status}: ${await response.text()}`);
92
76
  },
93
- };
77
+ });
94
78
  }
95
79
 
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');
80
+ /** @param {import('../../server').GitHubAuthOptions} options */
81
+ export function githubAuth({ repo, token, writers = 'collaborators', ...options }) {
101
82
  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
- // Only people who can push to the repository. `permission` is the legacy
111
- // level: maintain counts as write, triage as read. On a public repository
112
- // GitHub answers "read" for anyone, so read access is not enough.
113
- const permission = await api(token, `/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, { allow404: true });
114
- return permission?.permission === 'admin' || permission?.permission === 'write';
115
- }
116
-
117
- async function hmac(value) {
118
- const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
119
- return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
120
- }
121
-
122
- return {
83
+ return oauthAuth({
84
+ ...options,
85
+ writers,
123
86
  mode: 'github',
124
-
125
- async user(request) {
126
- const value = readCookie(request, SESSION_COOKIE);
127
- if (!value) return null;
128
- const [body, signature] = value.split('.');
129
- if (!body || !signature || !timingSafeEqual(signature, await hmac(body))) return null;
130
- try {
131
- const payload = JSON.parse(new TextDecoder().decode(fromBase64url(body)));
132
- return payload.exp > Date.now() / 1000 ? payload : null;
133
- } catch {
134
- return null;
135
- }
87
+ where: 'githubAuth',
88
+ authorizeUrl: 'https://github.com/login/oauth/authorize',
89
+ tokenUrl: 'https://github.com/login/oauth/access_token',
90
+ // No scope: the public profile is enough to know who the reader is.
91
+ async profile(userToken) {
92
+ const user = await client(userToken).get('/user');
93
+ return { login: user.login, id: user.id, name: user.name };
136
94
  },
137
-
138
- async route(route, request, url, prefix) {
139
- if (request.method !== 'GET') return null;
140
- const callbackPath = `${prefix}/callback`;
141
- const redirectUri = `${url.origin}${callbackPath}`;
142
-
143
- if (route === '/login') {
144
- const state = crypto.randomUUID();
145
- const back = safeReturn(url.searchParams.get('return'));
146
- const authorize = new URL('https://github.com/login/oauth/authorize');
147
- authorize.searchParams.set('client_id', clientId);
148
- authorize.searchParams.set('redirect_uri', redirectUri);
149
- authorize.searchParams.set('state', state);
150
- authorize.searchParams.set('allow_signup', 'false');
151
- // No scope: the public profile is enough to know who the reader is.
152
- return redirect(authorize.toString(), [cookie(STATE_COOKIE, `${state}.${encodeURIComponent(back)}`, 600, callbackPath)]);
153
- }
154
-
155
- if (route === '/callback') {
156
- // "<uuid>.<return path>": the uuid has no dot, the path may.
157
- const saved = readCookie(request, STATE_COOKIE) || '';
158
- const dot = saved.indexOf('.');
159
- const [state, back] = dot === -1 ? [saved, ''] : [saved.slice(0, dot), saved.slice(dot + 1)];
160
- const clear = cookie(STATE_COOKIE, '', 0, callbackPath);
161
- if (!state || state !== url.searchParams.get('state')) return text('The sign-in link expired. Try again.', 400, [clear]);
162
-
163
- const exchange = await fetch('https://github.com/login/oauth/access_token', {
164
- method: 'POST',
165
- headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
166
- body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, code: url.searchParams.get('code'), redirect_uri: redirectUri }),
167
- });
168
- const { access_token: userToken } = await exchange.json();
169
- if (!userToken) return text('GitHub did not confirm the sign-in.', 400, [clear]);
170
-
171
- const profile = await api(userToken, '/user');
172
- if (!(await mayWrite(profile))) {
173
- return text(`${profile.login} may not annotate these docs.`, 403, [clear]);
174
- }
175
- const body = base64url(
176
- new TextEncoder().encode(
177
- JSON.stringify({ login: profile.login, id: profile.id, name: profile.name || profile.login, exp: Math.floor(Date.now() / 1000) + SESSION_AGE }),
178
- ),
179
- );
180
- const session = `${body}.${await hmac(body)}`;
181
- return redirect(safeReturn(decodeURIComponent(back || '/')), [clear, cookie(SESSION_COOKIE, session, SESSION_AGE)]);
182
- }
183
-
184
- if (route === '/logout') {
185
- return redirect(safeReturn(url.searchParams.get('return')), [cookie(SESSION_COOKIE, '', 0)]);
186
- }
187
-
188
- return null;
189
- },
190
- };
191
- }
192
-
193
- // ---- GitHub REST ----
194
-
195
- function raw(token, path, init = {}) {
196
- return fetch(`${GITHUB_API}${path}`, {
197
- ...init,
198
- headers: {
199
- Accept: 'application/vnd.github+json',
200
- Authorization: `Bearer ${token}`,
201
- 'User-Agent': 'starlight-annotations',
202
- 'X-GitHub-Api-Version': '2022-11-28',
203
- ...(init.body ? { 'Content-Type': 'application/json' } : {}),
95
+ // Only people who can push. `permission` is the legacy level: maintain
96
+ // counts as write, triage as read. On a public repository GitHub answers
97
+ // "read" for anyone, so read access is not enough.
98
+ async canWrite(profile) {
99
+ const permission = await client(token).get(`/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, {
100
+ allow404: true,
101
+ });
102
+ return permission?.permission === 'admin' || permission?.permission === 'write';
204
103
  },
104
+ noAccess: (login) => `${login} may not annotate these docs.`,
205
105
  });
206
106
  }
207
-
208
- async function api(token, path, { allow404 = false } = {}) {
209
- const response = await raw(token, path);
210
- if (allow404 && response.status === 404) return null;
211
- if (!response.ok) throw new Error(`GitHub GET ${path} ${response.status}: ${await response.text()}`);
212
- return response.json();
213
- }
214
-
215
- // ---- Helpers ----
216
-
217
- function required(values, where) {
218
- const missing = Object.entries(values)
219
- .filter(([, value]) => !value)
220
- .map(([key]) => key);
221
- if (missing.length) throw new Error(`starlight-annotations: ${where} needs ${missing.join(', ')}.`);
222
- }
223
-
224
- function safeReturn(value) {
225
- const path = String(value || '/');
226
- return path.startsWith('/') && !path.startsWith('//') ? path : '/';
227
- }
228
-
229
- function readCookie(request, name) {
230
- for (const part of (request.headers.get('Cookie') || '').split(';')) {
231
- const [key, ...rest] = part.trim().split('=');
232
- if (key === name) return rest.join('=');
233
- }
234
- return '';
235
- }
236
-
237
- function redirect(location, cookies = []) {
238
- const headers = new Headers({ Location: location, 'Cache-Control': 'no-store' });
239
- for (const value of cookies) headers.append('Set-Cookie', value);
240
- return new Response(null, { status: 303, headers });
241
- }
242
-
243
- function text(message, status, cookies = []) {
244
- const headers = new Headers({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
245
- for (const value of cookies) headers.append('Set-Cookie', value);
246
- return new Response(message, { status, headers });
247
- }
248
-
249
- function toBase64(bytes) {
250
- let binary = '';
251
- for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
252
- return btoa(binary);
253
- }
254
-
255
- function fromBase64(value) {
256
- return Uint8Array.from(atob(value.replace(/\s/g, '')), (char) => char.charCodeAt(0));
257
- }
258
-
259
- function base64url(bytes) {
260
- return toBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
261
- }
262
-
263
- function fromBase64url(value) {
264
- const padded = value.replace(/-/g, '+').replace(/_/g, '/');
265
- return fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4));
266
- }
267
-
268
- function timingSafeEqual(left, right) {
269
- const length = Math.max(left.length, right.length);
270
- let diff = left.length === right.length ? 0 : 1;
271
- for (let i = 0; i < length; i++) diff |= (left.charCodeAt(i) || 0) ^ (right.charCodeAt(i) || 0);
272
- return diff === 0;
273
- }
274
-
275
- /**
276
- * @typedef {{
277
- * repo: string,
278
- * token: string,
279
- * branch?: string,
280
- * dir?: string,
281
- * clientId: string,
282
- * clientSecret: string,
283
- * sessionSecret: string,
284
- * writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string, id: number }) => boolean | Promise<boolean>),
285
- * cookieSecure?: boolean,
286
- * }} GitHubOptions
287
- */
@@ -0,0 +1,109 @@
1
+ // GitLab storage and sign-in, for gitlab.com and self-managed GitLab.
2
+ //
3
+ // Storage: the Repository Files API, on a branch of its own (default
4
+ // "annotations"), created from the default branch on the first save. Commits
5
+ // carry the reader as author. Concurrent saves are caught with
6
+ // `last_commit_id`.
7
+ //
8
+ // Sign-in: a GitLab OAuth application with the `read_user` scope. Only
9
+ // project members with the Developer role or higher may annotate, unless
10
+ // `writers` says otherwise.
11
+
12
+ import { filePath } from '../core.js';
13
+ import { gitStorage } from './git-storage.js';
14
+ import { oauthAuth } from './oauth.js';
15
+ import { decodeText, encodeText, required, restClient } from './util.js';
16
+
17
+ const DEVELOPER = 30;
18
+
19
+ function hostOf(url = 'https://gitlab.com') {
20
+ return url.replace(/\/+$/, '');
21
+ }
22
+
23
+ const client = (host, token) =>
24
+ restClient({ base: `${hostOf(host)}/api/v4`, headers: { Authorization: `Bearer ${token}` }, label: 'GitLab' });
25
+
26
+ /**
27
+ * Storage and sign-in together.
28
+ * @param {import('../../server').GitLabOptions} options
29
+ */
30
+ export function gitlab(options) {
31
+ return { storage: gitlabStorage(options), auth: gitlabAuth(options) };
32
+ }
33
+
34
+ /** @param {import('../../server').GitLabStorageOptions} options */
35
+ export function gitlabStorage({ host, project, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
36
+ required({ project, token }, 'gitlabStorage');
37
+ const api = client(host, token);
38
+ const id = encodeURIComponent(project);
39
+ const filesPath = (page) => `/projects/${id}/repository/files/${encodeURIComponent(filePath(page, dir))}`;
40
+ const hostname = new URL(hostOf(host)).hostname;
41
+
42
+ return gitStorage({
43
+ mode: 'gitlab',
44
+ commitMessage,
45
+
46
+ async read(page) {
47
+ const file = await api.get(`${filesPath(page)}?ref=${encodeURIComponent(branch)}`, { allow404: true });
48
+ return file && { text: decodeText(file.content), version: file.last_commit_id };
49
+ },
50
+
51
+ async write(page, content, lastCommitId, message, user) {
52
+ const response = await api.raw(filesPath(page), {
53
+ method: lastCommitId ? 'PUT' : 'POST',
54
+ body: JSON.stringify({
55
+ branch,
56
+ content: encodeText(content),
57
+ encoding: 'base64',
58
+ commit_message: message,
59
+ last_commit_id: lastCommitId,
60
+ ...(user.id ? { author_name: user.name || user.login, author_email: `${user.id}-${user.login}@users.noreply.${hostname}` } : {}),
61
+ }),
62
+ });
63
+ if (response.ok) return 'ok';
64
+ const detail = await response.text();
65
+ if ((response.status === 400 || response.status === 404) && /branch/i.test(detail)) return 'missing-branch';
66
+ // "has changed since you started editing it", or "already exists" when
67
+ // another save created the file a moment ago.
68
+ if (response.status === 400 && /changed|already exists/i.test(detail)) return 'conflict';
69
+ throw new Error(`GitLab ${lastCommitId ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
70
+ },
71
+
72
+ async createBranch() {
73
+ const info = await api.get(`/projects/${id}`);
74
+ const response = await api.raw(
75
+ `/projects/${id}/repository/branches?branch=${encodeURIComponent(branch)}&ref=${encodeURIComponent(info.default_branch)}`,
76
+ { method: 'POST' },
77
+ );
78
+ if (!response.ok) {
79
+ const detail = await response.text();
80
+ if (!(response.status === 400 && /already exists/i.test(detail))) throw new Error(`GitLab create branch ${response.status}: ${detail}`);
81
+ }
82
+ },
83
+ });
84
+ }
85
+
86
+ /** @param {import('../../server').GitLabAuthOptions} options */
87
+ export function gitlabAuth({ host, project, token, writers = 'collaborators', ...options }) {
88
+ if (writers === 'collaborators') required({ project, token }, 'gitlabAuth with writers "collaborators"');
89
+ const base = hostOf(host);
90
+ return oauthAuth({
91
+ ...options,
92
+ writers,
93
+ mode: 'gitlab',
94
+ where: 'gitlabAuth',
95
+ authorizeUrl: `${base}/oauth/authorize`,
96
+ tokenUrl: `${base}/oauth/token`,
97
+ scope: 'read_user',
98
+ async profile(userToken) {
99
+ const user = await client(host, userToken).get('/user');
100
+ return { login: user.username, id: user.id, name: user.name };
101
+ },
102
+ // Developer (30) and above can push to unprotected branches.
103
+ async canWrite(profile) {
104
+ const member = await client(host, token).get(`/projects/${encodeURIComponent(project)}/members/all/${profile.id}`, { allow404: true });
105
+ return Boolean(member && member.access_level >= DEVELOPER);
106
+ },
107
+ noAccess: (login) => `${login} may not annotate these docs: a Developer role or higher on the project is needed.`,
108
+ });
109
+ }
@@ -1,4 +1,5 @@
1
1
  // The annotation API as a Web-standard handler: (Request) => Response | null.
2
+ // Storage and sign-in for GitHub, GitLab, and Gitea/Forgejo (Codeberg).
2
3
  // It runs anywhere that speaks fetch: Cloudflare Workers, Deno, Bun, Netlify
3
4
  // and Vercel functions, Node 20+, or an Astro endpoint.
4
5
  //
@@ -13,6 +14,8 @@
13
14
  import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json } from '../core.js';
14
15
 
15
16
  export { github, githubAuth, githubStorage } from './github.js';
17
+ export { gitlab, gitlabAuth, gitlabStorage } from './gitlab.js';
18
+ export { forgejo, gitea, giteaAuth, giteaStorage } from './gitea.js';
16
19
  export { AnnotationError } from '../core.js';
17
20
 
18
21
  /**
@@ -0,0 +1,135 @@
1
+ // Sign-in with an OAuth 2 provider (GitHub, GitLab, Gitea/Forgejo), shared by
2
+ // every provider module.
3
+ //
4
+ // The reader's access token is used once, at the callback, to read who they
5
+ // are, and is then dropped. The session is an HMAC-signed cookie, so the
6
+ // server keeps no state. `writers` decides who may write.
7
+
8
+ import {
9
+ base64url,
10
+ fromBase64url,
11
+ readCookie,
12
+ redirect,
13
+ required,
14
+ safeReturn,
15
+ text,
16
+ timingSafeEqual,
17
+ } from './util.js';
18
+
19
+ const SESSION_COOKIE = 'annot_session';
20
+ const STATE_COOKIE = 'annot_state';
21
+ const SESSION_AGE = 60 * 60 * 24 * 30;
22
+
23
+ /**
24
+ * @param {{
25
+ * mode: string,
26
+ * where: string,
27
+ * authorizeUrl: string,
28
+ * tokenUrl: string,
29
+ * scope?: string,
30
+ * clientId: string,
31
+ * clientSecret: string,
32
+ * sessionSecret: string,
33
+ * cookieSecure?: boolean,
34
+ * writers?: 'collaborators' | 'anyone' | string[] | ((profile: object) => boolean | Promise<boolean>),
35
+ * profile: (userToken: string) => Promise<{ login: string, id: number, name?: string }>,
36
+ * canWrite: (profile: { login: string, id: number }) => Promise<boolean>,
37
+ * noAccess: (login: string) => string,
38
+ * }} options
39
+ */
40
+ export function oauthAuth(options) {
41
+ const { mode, where, authorizeUrl, tokenUrl, scope, clientId, clientSecret, sessionSecret, cookieSecure = true } = options;
42
+ const writers = options.writers ?? 'collaborators';
43
+ required({ clientId, clientSecret, sessionSecret }, where);
44
+
45
+ const cookie = (name, value, maxAge, path = '/') =>
46
+ `${name}=${value}; HttpOnly;${cookieSecure ? ' Secure;' : ''} SameSite=Lax; Path=${path}; Max-Age=${maxAge}`;
47
+
48
+ async function mayWrite(profile) {
49
+ if (writers === 'anyone') return true;
50
+ if (Array.isArray(writers)) return writers.map((login) => login.toLowerCase()).includes(profile.login.toLowerCase());
51
+ if (typeof writers === 'function') return Boolean(await writers(profile));
52
+ return options.canWrite(profile);
53
+ }
54
+
55
+ async function hmac(value) {
56
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
57
+ return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
58
+ }
59
+
60
+ return {
61
+ mode,
62
+
63
+ async user(request) {
64
+ const value = readCookie(request, SESSION_COOKIE);
65
+ if (!value) return null;
66
+ const [body, signature] = value.split('.');
67
+ if (!body || !signature || !timingSafeEqual(signature, await hmac(body))) return null;
68
+ try {
69
+ const payload = JSON.parse(new TextDecoder().decode(fromBase64url(body)));
70
+ return payload.exp > Date.now() / 1000 ? payload : null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ },
75
+
76
+ async route(route, request, url, prefix) {
77
+ if (request.method !== 'GET') return null;
78
+ const callbackPath = `${prefix}/callback`;
79
+ const redirectUri = `${url.origin}${callbackPath}`;
80
+
81
+ if (route === '/login') {
82
+ const state = crypto.randomUUID();
83
+ const back = safeReturn(url.searchParams.get('return'));
84
+ const authorize = new URL(authorizeUrl);
85
+ authorize.searchParams.set('client_id', clientId);
86
+ authorize.searchParams.set('redirect_uri', redirectUri);
87
+ authorize.searchParams.set('response_type', 'code');
88
+ authorize.searchParams.set('state', state);
89
+ if (scope) authorize.searchParams.set('scope', scope);
90
+ if (mode === 'github') authorize.searchParams.set('allow_signup', 'false');
91
+ return redirect(authorize.toString(), [cookie(STATE_COOKIE, `${state}.${encodeURIComponent(back)}`, 600, callbackPath)]);
92
+ }
93
+
94
+ if (route === '/callback') {
95
+ // "<uuid>.<return path>": the uuid has no dot, the path may.
96
+ const saved = readCookie(request, STATE_COOKIE) || '';
97
+ const dot = saved.indexOf('.');
98
+ const [state, back] = dot === -1 ? [saved, ''] : [saved.slice(0, dot), saved.slice(dot + 1)];
99
+ const clear = cookie(STATE_COOKIE, '', 0, callbackPath);
100
+ if (!state || state !== url.searchParams.get('state')) return text('The sign-in link expired. Try again.', 400, [clear]);
101
+
102
+ const exchange = await fetch(tokenUrl, {
103
+ method: 'POST',
104
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
105
+ body: JSON.stringify({
106
+ client_id: clientId,
107
+ client_secret: clientSecret,
108
+ code: url.searchParams.get('code'),
109
+ grant_type: 'authorization_code',
110
+ redirect_uri: redirectUri,
111
+ }),
112
+ });
113
+ const { access_token: userToken } = await exchange.json().catch(() => ({}));
114
+ if (!userToken) return text('The sign-in was not confirmed. Try again.', 400, [clear]);
115
+
116
+ const profile = await options.profile(userToken);
117
+ if (!(await mayWrite(profile))) return text(options.noAccess(profile.login), 403, [clear]);
118
+
119
+ const body = base64url(
120
+ new TextEncoder().encode(
121
+ JSON.stringify({ login: profile.login, id: profile.id, name: profile.name || profile.login, exp: Math.floor(Date.now() / 1000) + SESSION_AGE }),
122
+ ),
123
+ );
124
+ const session = `${body}.${await hmac(body)}`;
125
+ return redirect(safeReturn(decodeURIComponent(back || '/')), [clear, cookie(SESSION_COOKIE, session, SESSION_AGE)]);
126
+ }
127
+
128
+ if (route === '/logout') {
129
+ return redirect(safeReturn(url.searchParams.get('return')), [cookie(SESSION_COOKIE, '', 0)]);
130
+ }
131
+
132
+ return null;
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,84 @@
1
+ // Small helpers shared by the server modules. Web APIs only, so they run on
2
+ // Workers, Deno, Bun and Node 20+.
3
+
4
+ export function required(values, where) {
5
+ const missing = Object.entries(values)
6
+ .filter(([, value]) => !value)
7
+ .map(([key]) => key);
8
+ if (missing.length) throw new Error(`starlight-annotations: ${where} needs ${missing.join(', ')}.`);
9
+ }
10
+
11
+ export function safeReturn(value) {
12
+ const path = String(value || '/');
13
+ return path.startsWith('/') && !path.startsWith('//') ? path : '/';
14
+ }
15
+
16
+ export function readCookie(request, name) {
17
+ for (const part of (request.headers.get('Cookie') || '').split(';')) {
18
+ const [key, ...rest] = part.trim().split('=');
19
+ if (key === name) return rest.join('=');
20
+ }
21
+ return '';
22
+ }
23
+
24
+ export function redirect(location, cookies = []) {
25
+ const headers = new Headers({ Location: location, 'Cache-Control': 'no-store' });
26
+ for (const value of cookies) headers.append('Set-Cookie', value);
27
+ return new Response(null, { status: 303, headers });
28
+ }
29
+
30
+ export function text(message, status, cookies = []) {
31
+ const headers = new Headers({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
32
+ for (const value of cookies) headers.append('Set-Cookie', value);
33
+ return new Response(message, { status, headers });
34
+ }
35
+
36
+ export function toBase64(bytes) {
37
+ let binary = '';
38
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
39
+ return btoa(binary);
40
+ }
41
+
42
+ export function fromBase64(value) {
43
+ return Uint8Array.from(atob(value.replace(/\s/g, '')), (char) => char.charCodeAt(0));
44
+ }
45
+
46
+ export const encodeText = (value) => toBase64(new TextEncoder().encode(value));
47
+ export const decodeText = (value) => new TextDecoder().decode(fromBase64(value));
48
+
49
+ export function base64url(bytes) {
50
+ return toBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
51
+ }
52
+
53
+ export function fromBase64url(value) {
54
+ const padded = value.replace(/-/g, '+').replace(/_/g, '/');
55
+ return fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4));
56
+ }
57
+
58
+ export function timingSafeEqual(left, right) {
59
+ const length = Math.max(left.length, right.length);
60
+ let diff = left.length === right.length ? 0 : 1;
61
+ for (let i = 0; i < length; i++) diff |= (left.charCodeAt(i) || 0) ^ (right.charCodeAt(i) || 0);
62
+ return diff === 0;
63
+ }
64
+
65
+ // A small REST client: JSON in and out, `null` for an allowed 404.
66
+ export function restClient({ base, headers, label }) {
67
+ const raw = (path, init = {}) =>
68
+ fetch(`${base}${path}`, {
69
+ ...init,
70
+ headers: {
71
+ Accept: 'application/json',
72
+ 'User-Agent': 'starlight-annotations',
73
+ ...headers,
74
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
75
+ },
76
+ });
77
+ const get = async (path, { allow404 = false } = {}) => {
78
+ const response = await raw(path);
79
+ if (allow404 && response.status === 404) return null;
80
+ if (!response.ok) throw new Error(`${label} GET ${path} ${response.status}: ${await response.text()}`);
81
+ return response.json();
82
+ };
83
+ return { raw, get };
84
+ }