starlight-annotations 0.1.2 → 0.3.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 +33 -0
- package/README.md +8 -2
- package/package.json +9 -4
- package/server.d.ts +91 -1
- package/src/client/annotations.js +2 -1
- package/src/client/backend.js +2 -1
- package/src/server/git-storage.js +51 -0
- package/src/server/gitea.js +104 -0
- package/src/server/github.js +74 -255
- package/src/server/gitlab.js +109 -0
- package/src/server/index.js +26 -7
- package/src/server/oauth.js +167 -0
- package/src/server/util.js +84 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# starlight-annotations
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 05c032c: Checks write access again while a session lasts, not only at sign-in. Before saving a note, and when a signed-in reader loads a page, the server asks the provider again whether they may still write (`writers`), reusing the answer for `recheck` seconds (default 60). If their access was removed, the save is refused and they are signed out, instead of keeping write access until their 30-day session ends. Set `recheck: false` to check only at sign-in, as before. Custom auths can implement the same with an optional `allowed(user)`.
|
|
8
|
+
|
|
9
|
+
## 0.2.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- ccdae74: Adds GitLab and Gitea/Forgejo storage and sign-in, next to GitHub: `gitlab({ host, project, … })` for gitlab.com and self-managed GitLab, and `gitea({ host, repo, … })` (also exported as `forgejo`) for Gitea, Forgejo and Codeberg. Both are experimental: they are tested against simulated APIs. The OAuth flow, session and retry logic are now shared by all providers; GitHub behaves as before.
|
|
14
|
+
|
|
15
|
+
## 0.1.2
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 8c153d2: `writers: 'collaborators'` (the default) now accepts only people with write, maintain or admin access to the repository. Read and triage access are refused; on a public repository GitHub reports read access for anyone, so before this fix any GitHub user could sign in and annotate.
|
|
20
|
+
|
|
21
|
+
## 0.1.1
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- 7ebce53: Loads the Markdown parser only when a page has notes or a reader starts writing one. The script added to every page drops from about 100 kB to 27 kB.
|
|
26
|
+
- 943a525: Fixes the annotation UI having no styles in production builds: the stylesheet is now added to Starlight's `customCss`, which is linked on every page. In 0.1.0 the Notes button and panel appeared unstyled at the end of the page.
|
|
27
|
+
- 1d6c768: Points the npm homepage to the documentation site, and adds badges, feature icons and more search keywords to the package page.
|
|
28
|
+
|
|
29
|
+
## 0.1.0
|
|
30
|
+
|
|
31
|
+
### Minor Changes
|
|
32
|
+
|
|
33
|
+
- 859bd1b: First release. Readers select text on a Starlight page and leave Markdown notes with replies; notes are stored as one JSON file per page on an `annotations` branch of a GitHub repository, through OAuth sign-in and a Web-standard handler, or in the reader's browser with `backend: 'browser'`.
|
package/README.md
CHANGED
|
@@ -7,13 +7,13 @@
|
|
|
7
7
|
|
|
8
8
|
Let readers highlight text and leave notes on your [Starlight](https://starlight.astro.build) docs. Notes are JSON files committed to your Git repository, not stored by a third-party service.
|
|
9
9
|
|
|
10
|
-
**📖 [Documentation](https://alessandroros.github.io/starlight-annotations/) · ✨ [Live demo](https://alessandroros.github.io/starlight-annotations/guides/demo/)**
|
|
10
|
+
**📖 [Documentation](https://alessandroros.github.io/starlight-annotations/) · ✨ [Live demo](https://alessandroros.github.io/starlight-annotations/guides/demo/) · 📋 [Changelog](https://alessandroros.github.io/starlight-annotations/changelog/)**
|
|
11
11
|
|
|
12
12
|
## Features
|
|
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,8 +67,14 @@ 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
|
|
|
74
|
+
## 📋 Versions
|
|
75
|
+
|
|
76
|
+
The package follows semantic versioning. While it is `0.x`, a minor version may change behavior or options: check the [changelog](https://alessandroros.github.io/starlight-annotations/changelog/) before upgrading.
|
|
77
|
+
|
|
72
78
|
## 📄 License
|
|
73
79
|
|
|
74
80
|
MIT © Alessandro Rosa
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "starlight-annotations",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "🖍️ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository.",
|
|
3
|
+
"version": "0.3.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
|
".": {
|
|
@@ -48,7 +52,8 @@
|
|
|
48
52
|
"index.d.ts",
|
|
49
53
|
"server.d.ts",
|
|
50
54
|
"server-node.d.ts",
|
|
51
|
-
"src"
|
|
55
|
+
"src",
|
|
56
|
+
"CHANGELOG.md"
|
|
52
57
|
],
|
|
53
58
|
"scripts": {
|
|
54
59
|
"test": "vitest run"
|
package/server.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export interface Auth {
|
|
|
24
24
|
mode?: string;
|
|
25
25
|
user(request: Request): Promise<User | null>;
|
|
26
26
|
route?(route: string, request: Request, url: URL, prefix: string): Promise<Response | null>;
|
|
27
|
+
/** Whether a signed-in user may still write. Called before every save and on page loads. */
|
|
28
|
+
allowed?(user: User): Promise<boolean>;
|
|
29
|
+
/** The message for a user who may no longer write. */
|
|
30
|
+
noAccess?(login: string): string;
|
|
31
|
+
/** A `Set-Cookie` value that ends the session, sent with a refusal. */
|
|
32
|
+
clearSession?: string;
|
|
27
33
|
}
|
|
28
34
|
|
|
29
35
|
export interface HandlerOptions {
|
|
@@ -61,13 +67,97 @@ export interface GitHubAuthOptions {
|
|
|
61
67
|
writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
|
|
62
68
|
repo?: string;
|
|
63
69
|
token?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Seconds between checks that a signed-in user may still write, on saves and page loads.
|
|
72
|
+
* `false` checks only at sign-in. Default 60.
|
|
73
|
+
*/
|
|
74
|
+
recheck?: number | false;
|
|
64
75
|
/** Set to false only for plain-http local testing. Default true. */
|
|
65
76
|
cookieSecure?: boolean;
|
|
66
77
|
}
|
|
67
78
|
|
|
79
|
+
export type GitHubOptions = GitHubStorageOptions & GitHubAuthOptions;
|
|
80
|
+
|
|
68
81
|
export function githubStorage(options: GitHubStorageOptions): Storage;
|
|
69
82
|
export function githubAuth(options: GitHubAuthOptions): Auth;
|
|
70
|
-
export function github(options:
|
|
83
|
+
export function github(options: GitHubOptions): { storage: Storage; auth: Auth };
|
|
84
|
+
|
|
85
|
+
interface CommonStorageOptions {
|
|
86
|
+
/** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
|
|
87
|
+
branch?: string;
|
|
88
|
+
/** Folder for the notes in the branch. Default `"annotations"`. */
|
|
89
|
+
dir?: string;
|
|
90
|
+
/** Rewrite the commit message, e.g. to fit your commit convention. */
|
|
91
|
+
commitMessage?: (message: string, page: string) => string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface CommonAuthOptions {
|
|
95
|
+
/** OAuth application id and secret. */
|
|
96
|
+
clientId: string;
|
|
97
|
+
clientSecret: string;
|
|
98
|
+
/** A long random string that signs the session cookie. */
|
|
99
|
+
sessionSecret: string;
|
|
100
|
+
/**
|
|
101
|
+
* Who may write. `"collaborators"` (default) checks the reader's role on the repository with
|
|
102
|
+
* `token`. `"anyone"` accepts every signed-in user.
|
|
103
|
+
*/
|
|
104
|
+
writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
|
|
105
|
+
/**
|
|
106
|
+
* Seconds between checks that a signed-in user may still write, on saves and page loads.
|
|
107
|
+
* `false` checks only at sign-in. Default 60.
|
|
108
|
+
*/
|
|
109
|
+
recheck?: number | false;
|
|
110
|
+
/** Set to false only for plain-http local testing. Default true. */
|
|
111
|
+
cookieSecure?: boolean;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface GitLabStorageOptions extends CommonStorageOptions {
|
|
115
|
+
/** Your GitLab, e.g. `"https://gitlab.example.com"`. Default `"https://gitlab.com"`. */
|
|
116
|
+
host?: string;
|
|
117
|
+
/** Project path (`"group/project"`) or numeric id. */
|
|
118
|
+
project: string | number;
|
|
119
|
+
/** Project, group or personal access token with the `api` scope and the Developer role. */
|
|
120
|
+
token: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** `"collaborators"` means project members with the Developer role or higher. */
|
|
124
|
+
export interface GitLabAuthOptions extends CommonAuthOptions {
|
|
125
|
+
host?: string;
|
|
126
|
+
project?: string | number;
|
|
127
|
+
token?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type GitLabOptions = GitLabStorageOptions & GitLabAuthOptions;
|
|
131
|
+
|
|
132
|
+
/** Experimental: tested against a simulated GitLab API. */
|
|
133
|
+
export function gitlabStorage(options: GitLabStorageOptions): Storage;
|
|
134
|
+
export function gitlabAuth(options: GitLabAuthOptions): Auth;
|
|
135
|
+
export function gitlab(options: GitLabOptions): { storage: Storage; auth: Auth };
|
|
136
|
+
|
|
137
|
+
export interface GiteaStorageOptions extends CommonStorageOptions {
|
|
138
|
+
/** Your Gitea or Forgejo server, e.g. `"https://codeberg.org"`. */
|
|
139
|
+
host: string;
|
|
140
|
+
/** `owner/name` of the repository. */
|
|
141
|
+
repo: string;
|
|
142
|
+
/** Access token with `write:repository` on the repository. */
|
|
143
|
+
token: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `"collaborators"` means people with write, admin or owner permission on the repository. */
|
|
147
|
+
export interface GiteaAuthOptions extends CommonAuthOptions {
|
|
148
|
+
host: string;
|
|
149
|
+
repo?: string;
|
|
150
|
+
token?: string;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export type GiteaOptions = GiteaStorageOptions & GiteaAuthOptions;
|
|
154
|
+
|
|
155
|
+
/** Experimental: tested against a simulated Gitea API. Works with Forgejo and Codeberg. */
|
|
156
|
+
export function giteaStorage(options: GiteaStorageOptions): Storage;
|
|
157
|
+
export function giteaAuth(options: GiteaAuthOptions): Auth;
|
|
158
|
+
export function gitea(options: GiteaOptions): { storage: Storage; auth: Auth };
|
|
159
|
+
/** The same as `gitea`: Forgejo speaks the Gitea API. */
|
|
160
|
+
export const forgejo: typeof gitea;
|
|
71
161
|
|
|
72
162
|
/** A fixed identity: for local development, or a site behind its own login. */
|
|
73
163
|
export function staticAuth(user: User): Auth;
|
|
@@ -373,7 +373,8 @@ async function start(root) {
|
|
|
373
373
|
const data = await backend.send(page, change);
|
|
374
374
|
if (!data.ok) {
|
|
375
375
|
state.error = data.error;
|
|
376
|
-
|
|
376
|
+
// Not signed in, or the session ended because access was removed.
|
|
377
|
+
if (data.status === 401 || data.signedOut) state.user = null;
|
|
377
378
|
render();
|
|
378
379
|
return null;
|
|
379
380
|
}
|
package/src/client/backend.js
CHANGED
|
@@ -31,7 +31,8 @@ function apiBackend(config, base) {
|
|
|
31
31
|
body: JSON.stringify({ page, change }),
|
|
32
32
|
});
|
|
33
33
|
const data = await response.json().catch(() => ({}));
|
|
34
|
-
if (!response.ok)
|
|
34
|
+
if (!response.ok)
|
|
35
|
+
return { ok: false, status: response.status, signedOut: Boolean(data.signedOut), error: data.error || `Error ${response.status}` };
|
|
35
36
|
return { ok: true, ...data };
|
|
36
37
|
},
|
|
37
38
|
loginUrl: () => `${api}/login?return=${here()}`,
|
|
@@ -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 };
|
package/src/server/github.js
CHANGED
|
@@ -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
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
|
|
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
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
|
-
|
|
104
|
-
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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
|
+
}
|
package/src/server/index.js
CHANGED
|
@@ -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
|
/**
|
|
@@ -21,6 +24,7 @@ export { AnnotationError } from '../core.js';
|
|
|
21
24
|
export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX }) {
|
|
22
25
|
if (!storage) throw new Error('starlight-annotations: createAnnotationsHandler needs a storage.');
|
|
23
26
|
const root = prefix.replace(/\/$/, '');
|
|
27
|
+
const stillAllowed = async (user) => (auth?.allowed ? auth.allowed(user) : true);
|
|
24
28
|
|
|
25
29
|
return async function handleAnnotations(request) {
|
|
26
30
|
const url = new URL(request.url);
|
|
@@ -36,13 +40,21 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
|
|
|
36
40
|
if (route === '/api' && request.method === 'GET') {
|
|
37
41
|
const page = checkPage(url.searchParams.get('page'));
|
|
38
42
|
const doc = await storage.load(page);
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
let user = auth ? await auth.user(request) : null;
|
|
44
|
+
// Reading never fails on the access check: if the provider does not
|
|
45
|
+
// answer, the reader stays signed in and the next write asks again.
|
|
46
|
+
const revoked = user && (await stillAllowed(user).catch(() => true)) === false;
|
|
47
|
+
if (revoked) user = null;
|
|
48
|
+
return json(
|
|
49
|
+
{
|
|
50
|
+
annotations: doc.annotations,
|
|
51
|
+
user: user && { login: user.login, name: user.name },
|
|
52
|
+
mode: auth?.mode ?? storage.mode ?? 'api',
|
|
53
|
+
canSignIn: Boolean(auth?.route),
|
|
54
|
+
},
|
|
55
|
+
200,
|
|
56
|
+
revoked && auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {},
|
|
57
|
+
);
|
|
46
58
|
}
|
|
47
59
|
|
|
48
60
|
if (route === '/api' && request.method === 'POST') {
|
|
@@ -50,6 +62,10 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
|
|
|
50
62
|
if (origin && origin !== url.origin) return json({ error: 'Cross-site request refused.' }, 403);
|
|
51
63
|
const user = auth ? await auth.user(request) : null;
|
|
52
64
|
if (!user) return json({ error: 'Sign in first.' }, 401);
|
|
65
|
+
if (!(await stillAllowed(user))) {
|
|
66
|
+
const error = auth.noAccess ? auth.noAccess(user.login) : 'You may no longer annotate these docs.';
|
|
67
|
+
return json({ error, signedOut: true }, 403, auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {});
|
|
68
|
+
}
|
|
53
69
|
const { page, change } = await request.json();
|
|
54
70
|
const result = await storage.update(checkPage(page), (doc) => applyChange(doc, change, user), user);
|
|
55
71
|
return json(result);
|
|
@@ -85,5 +101,8 @@ export function staticAuth(user) {
|
|
|
85
101
|
* mode?: string,
|
|
86
102
|
* user(request: Request): Promise<User | null>,
|
|
87
103
|
* route?(route: string, request: Request, url: URL, prefix: string): Promise<Response | null>,
|
|
104
|
+
* allowed?(user: User): Promise<boolean>,
|
|
105
|
+
* noAccess?(login: string): string,
|
|
106
|
+
* clearSession?: string,
|
|
88
107
|
* }} Auth
|
|
89
108
|
*/
|
|
@@ -0,0 +1,167 @@
|
|
|
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, at sign-in and
|
|
7
|
+
// again while the session lasts (every `recheck` seconds), so removing
|
|
8
|
+
// someone's access to the repository also ends their session.
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
base64url,
|
|
12
|
+
fromBase64url,
|
|
13
|
+
readCookie,
|
|
14
|
+
redirect,
|
|
15
|
+
required,
|
|
16
|
+
safeReturn,
|
|
17
|
+
text,
|
|
18
|
+
timingSafeEqual,
|
|
19
|
+
} from './util.js';
|
|
20
|
+
|
|
21
|
+
const SESSION_COOKIE = 'annot_session';
|
|
22
|
+
const STATE_COOKIE = 'annot_state';
|
|
23
|
+
const SESSION_AGE = 60 * 60 * 24 * 30;
|
|
24
|
+
const RECHECK = 60;
|
|
25
|
+
const CACHE_SIZE = 500;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {{
|
|
29
|
+
* mode: string,
|
|
30
|
+
* where: string,
|
|
31
|
+
* authorizeUrl: string,
|
|
32
|
+
* tokenUrl: string,
|
|
33
|
+
* scope?: string,
|
|
34
|
+
* clientId: string,
|
|
35
|
+
* clientSecret: string,
|
|
36
|
+
* sessionSecret: string,
|
|
37
|
+
* cookieSecure?: boolean,
|
|
38
|
+
* recheck?: number | false,
|
|
39
|
+
* writers?: 'collaborators' | 'anyone' | string[] | ((profile: object) => boolean | Promise<boolean>),
|
|
40
|
+
* profile: (userToken: string) => Promise<{ login: string, id: number, name?: string }>,
|
|
41
|
+
* canWrite: (profile: { login: string, id: number }) => Promise<boolean>,
|
|
42
|
+
* noAccess: (login: string) => string,
|
|
43
|
+
* }} options
|
|
44
|
+
*/
|
|
45
|
+
export function oauthAuth(options) {
|
|
46
|
+
const { mode, where, authorizeUrl, tokenUrl, scope, clientId, clientSecret, sessionSecret, cookieSecure = true } = options;
|
|
47
|
+
const writers = options.writers ?? 'collaborators';
|
|
48
|
+
const recheck = options.recheck ?? RECHECK;
|
|
49
|
+
required({ clientId, clientSecret, sessionSecret }, where);
|
|
50
|
+
|
|
51
|
+
const cookie = (name, value, maxAge, path = '/') =>
|
|
52
|
+
`${name}=${value}; HttpOnly;${cookieSecure ? ' Secure;' : ''} SameSite=Lax; Path=${path}; Max-Age=${maxAge}`;
|
|
53
|
+
|
|
54
|
+
async function mayWrite(profile) {
|
|
55
|
+
if (writers === 'anyone') return true;
|
|
56
|
+
if (Array.isArray(writers)) return writers.map((login) => login.toLowerCase()).includes(profile.login.toLowerCase());
|
|
57
|
+
if (typeof writers === 'function') return Boolean(await writers(profile));
|
|
58
|
+
return options.canWrite(profile);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Answers of `mayWrite` for signed-in users, kept `recheck` seconds. It
|
|
62
|
+
// lives in memory, per server instance: a cold start just asks again.
|
|
63
|
+
const answers = new Map();
|
|
64
|
+
function remember(user, allowed) {
|
|
65
|
+
if (!recheck) return;
|
|
66
|
+
const key = `${user.id}:${user.login}`;
|
|
67
|
+
answers.delete(key);
|
|
68
|
+
answers.set(key, { allowed, until: Date.now() + recheck * 1000 });
|
|
69
|
+
if (answers.size > CACHE_SIZE) answers.delete(answers.keys().next().value);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function hmac(value) {
|
|
73
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
74
|
+
return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
mode,
|
|
79
|
+
clearSession: cookie(SESSION_COOKIE, '', 0),
|
|
80
|
+
|
|
81
|
+
/** Whether a signed-in user may still write. Asks the provider at most every `recheck` seconds. */
|
|
82
|
+
async allowed(user) {
|
|
83
|
+
if (recheck === false) return true;
|
|
84
|
+
const saved = answers.get(`${user.id}:${user.login}`);
|
|
85
|
+
if (saved && saved.until > Date.now()) return saved.allowed;
|
|
86
|
+
const allowed = await mayWrite(user);
|
|
87
|
+
remember(user, allowed);
|
|
88
|
+
return allowed;
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
noAccess: options.noAccess,
|
|
92
|
+
|
|
93
|
+
async user(request) {
|
|
94
|
+
const value = readCookie(request, SESSION_COOKIE);
|
|
95
|
+
if (!value) return null;
|
|
96
|
+
const [body, signature] = value.split('.');
|
|
97
|
+
if (!body || !signature || !timingSafeEqual(signature, await hmac(body))) return null;
|
|
98
|
+
try {
|
|
99
|
+
const payload = JSON.parse(new TextDecoder().decode(fromBase64url(body)));
|
|
100
|
+
return payload.exp > Date.now() / 1000 ? payload : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
async route(route, request, url, prefix) {
|
|
107
|
+
if (request.method !== 'GET') return null;
|
|
108
|
+
const callbackPath = `${prefix}/callback`;
|
|
109
|
+
const redirectUri = `${url.origin}${callbackPath}`;
|
|
110
|
+
|
|
111
|
+
if (route === '/login') {
|
|
112
|
+
const state = crypto.randomUUID();
|
|
113
|
+
const back = safeReturn(url.searchParams.get('return'));
|
|
114
|
+
const authorize = new URL(authorizeUrl);
|
|
115
|
+
authorize.searchParams.set('client_id', clientId);
|
|
116
|
+
authorize.searchParams.set('redirect_uri', redirectUri);
|
|
117
|
+
authorize.searchParams.set('response_type', 'code');
|
|
118
|
+
authorize.searchParams.set('state', state);
|
|
119
|
+
if (scope) authorize.searchParams.set('scope', scope);
|
|
120
|
+
if (mode === 'github') authorize.searchParams.set('allow_signup', 'false');
|
|
121
|
+
return redirect(authorize.toString(), [cookie(STATE_COOKIE, `${state}.${encodeURIComponent(back)}`, 600, callbackPath)]);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (route === '/callback') {
|
|
125
|
+
// "<uuid>.<return path>": the uuid has no dot, the path may.
|
|
126
|
+
const saved = readCookie(request, STATE_COOKIE) || '';
|
|
127
|
+
const dot = saved.indexOf('.');
|
|
128
|
+
const [state, back] = dot === -1 ? [saved, ''] : [saved.slice(0, dot), saved.slice(dot + 1)];
|
|
129
|
+
const clear = cookie(STATE_COOKIE, '', 0, callbackPath);
|
|
130
|
+
if (!state || state !== url.searchParams.get('state')) return text('The sign-in link expired. Try again.', 400, [clear]);
|
|
131
|
+
|
|
132
|
+
const exchange = await fetch(tokenUrl, {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
135
|
+
body: JSON.stringify({
|
|
136
|
+
client_id: clientId,
|
|
137
|
+
client_secret: clientSecret,
|
|
138
|
+
code: url.searchParams.get('code'),
|
|
139
|
+
grant_type: 'authorization_code',
|
|
140
|
+
redirect_uri: redirectUri,
|
|
141
|
+
}),
|
|
142
|
+
});
|
|
143
|
+
const { access_token: userToken } = await exchange.json().catch(() => ({}));
|
|
144
|
+
if (!userToken) return text('The sign-in was not confirmed. Try again.', 400, [clear]);
|
|
145
|
+
|
|
146
|
+
const profile = await options.profile(userToken);
|
|
147
|
+
const allowed = await mayWrite(profile);
|
|
148
|
+
remember(profile, allowed);
|
|
149
|
+
if (!allowed) return text(options.noAccess(profile.login), 403, [clear]);
|
|
150
|
+
|
|
151
|
+
const body = base64url(
|
|
152
|
+
new TextEncoder().encode(
|
|
153
|
+
JSON.stringify({ login: profile.login, id: profile.id, name: profile.name || profile.login, exp: Math.floor(Date.now() / 1000) + SESSION_AGE }),
|
|
154
|
+
),
|
|
155
|
+
);
|
|
156
|
+
const session = `${body}.${await hmac(body)}`;
|
|
157
|
+
return redirect(safeReturn(decodeURIComponent(back || '/')), [clear, cookie(SESSION_COOKIE, session, SESSION_AGE)]);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (route === '/logout') {
|
|
161
|
+
return redirect(safeReturn(url.searchParams.get('return')), [cookie(SESSION_COOKIE, '', 0)]);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return null;
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -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
|
+
}
|