starlight-annotations 0.3.0 → 0.4.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 +6 -0
- package/package.json +1 -1
- package/server.d.ts +19 -3
- package/src/server/github-app.js +100 -0
- package/src/server/github.js +35 -11
- package/src/server/index.js +1 -0
- package/src/server/util.js +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# starlight-annotations
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2a7a36c: Adds GitHub App support: `github({ app: { appId, privateKey } })` instead of `token`. The server mints installation tokens limited to the notes repository, valid for an hour and renewed before they expire, and the app's client ID and secret also handle sign-in, so one app replaces the OAuth app and the personal access token. It suits organizations: the app belongs to no one, needs no token approval and does not expire. Commits show the app as committer and the reader as author. `token` keeps working as before; `githubAppToken()` is exported for other uses of the same app.
|
|
8
|
+
|
|
3
9
|
## 0.3.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "starlight-annotations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "🖍️ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository on GitHub, GitLab, Gitea or Forgejo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Alessandro Rosa",
|
package/server.d.ts
CHANGED
|
@@ -45,8 +45,10 @@ export function createAnnotationsHandler(options: HandlerOptions): (request: Req
|
|
|
45
45
|
export interface GitHubStorageOptions {
|
|
46
46
|
/** `owner/name` of the repository that stores the notes. */
|
|
47
47
|
repo: string;
|
|
48
|
-
/** Token with Contents read/write (and Metadata read) on `repo`. */
|
|
49
|
-
token
|
|
48
|
+
/** Token with Contents read/write (and Metadata read) on `repo`. Or use `app`. */
|
|
49
|
+
token?: string | (() => Promise<string>);
|
|
50
|
+
/** A GitHub App installed on `repo`, instead of `token`. */
|
|
51
|
+
app?: GitHubAppOptions;
|
|
50
52
|
/** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
|
|
51
53
|
branch?: string;
|
|
52
54
|
/** Folder for the notes in the branch. Default `"annotations"`. */
|
|
@@ -55,7 +57,20 @@ export interface GitHubStorageOptions {
|
|
|
55
57
|
commitMessage?: (message: string, page: string) => string;
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
export interface GitHubAppOptions {
|
|
61
|
+
/** The App ID, on the app's General page. */
|
|
62
|
+
appId: string | number;
|
|
63
|
+
/** The app's private key: the `.pem` file, PKCS#1 or PKCS#8. Line breaks may be written as `\n`. */
|
|
64
|
+
privateKey: string;
|
|
65
|
+
/** The installation on `repo`. Looked up when omitted. */
|
|
66
|
+
installationId?: string | number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Installation tokens of a GitHub App, limited to `repo` and renewed before they expire. */
|
|
70
|
+
export function githubAppToken(options: GitHubAppOptions & { repo: string }): () => Promise<string>;
|
|
71
|
+
|
|
58
72
|
export interface GitHubAuthOptions {
|
|
73
|
+
/** The OAuth app's client ID, or the GitHub App's. */
|
|
59
74
|
clientId: string;
|
|
60
75
|
clientSecret: string;
|
|
61
76
|
/** A long random string that signs the session cookie. */
|
|
@@ -66,7 +81,8 @@ export interface GitHubAuthOptions {
|
|
|
66
81
|
*/
|
|
67
82
|
writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
|
|
68
83
|
repo?: string;
|
|
69
|
-
token?: string;
|
|
84
|
+
token?: string | (() => Promise<string>);
|
|
85
|
+
app?: GitHubAppOptions;
|
|
70
86
|
/**
|
|
71
87
|
* Seconds between checks that a signed-in user may still write, on saves and page loads.
|
|
72
88
|
* `false` checks only at sign-in. Default 60.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Server credentials from a GitHub App instead of a personal access token.
|
|
2
|
+
//
|
|
3
|
+
// The server signs a short JWT with the app's private key, finds the app's
|
|
4
|
+
// installation on `repo`, and exchanges the JWT for an installation token
|
|
5
|
+
// limited to that one repository. The token lasts an hour; it is kept in
|
|
6
|
+
// memory and renewed five minutes before it expires.
|
|
7
|
+
//
|
|
8
|
+
// Unlike a personal token, an app belongs to no one: it survives people
|
|
9
|
+
// leaving, needs no approval as a personal token in an organization, and
|
|
10
|
+
// its commits show the app as committer (the reader stays the author).
|
|
11
|
+
|
|
12
|
+
import { base64url, fromBase64, required, restClient } from './util.js';
|
|
13
|
+
|
|
14
|
+
const API = 'https://api.github.com';
|
|
15
|
+
const HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
|
16
|
+
const RENEW_BEFORE = 5 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A function that returns a valid installation token for `repo`.
|
|
20
|
+
* @param {{ appId: string | number, privateKey: string, installationId?: string | number, repo: string }} options
|
|
21
|
+
* @returns {() => Promise<string>}
|
|
22
|
+
*/
|
|
23
|
+
export function githubAppToken({ appId, privateKey, installationId, repo }) {
|
|
24
|
+
required({ appId, privateKey, repo }, 'githubAppToken');
|
|
25
|
+
const name = repo.split('/')[1];
|
|
26
|
+
let key;
|
|
27
|
+
let installation = installationId;
|
|
28
|
+
let current;
|
|
29
|
+
let pending;
|
|
30
|
+
|
|
31
|
+
async function appJwt() {
|
|
32
|
+
key ??= await crypto.subtle.importKey('pkcs8', pkcs8(privateKey), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']);
|
|
33
|
+
const now = Math.floor(Date.now() / 1000);
|
|
34
|
+
// 60 s in the past for clock drift; GitHub accepts at most 10 minutes.
|
|
35
|
+
const part = (value) => base64url(new TextEncoder().encode(JSON.stringify(value)));
|
|
36
|
+
const unsigned = `${part({ alg: 'RS256', typ: 'JWT' })}.${part({ iat: now - 60, exp: now + 540, iss: String(appId) })}`;
|
|
37
|
+
const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(unsigned));
|
|
38
|
+
return `${unsigned}.${base64url(new Uint8Array(signature))}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function mint() {
|
|
42
|
+
const api = restClient({ base: API, headers: { ...HEADERS, Authorization: `Bearer ${await appJwt()}` }, label: 'GitHub App' });
|
|
43
|
+
if (!installation) {
|
|
44
|
+
const found = await api.get(`/repos/${repo}/installation`, { allow404: true });
|
|
45
|
+
if (!found) throw new Error(`starlight-annotations: the GitHub App ${appId} is not installed on ${repo}.`);
|
|
46
|
+
installation = found.id;
|
|
47
|
+
}
|
|
48
|
+
const response = await api.raw(`/app/installations/${installation}/access_tokens`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
body: JSON.stringify({ repositories: [name] }),
|
|
51
|
+
});
|
|
52
|
+
if (!response.ok) throw new Error(`GitHub App token ${response.status}: ${await response.text()}`);
|
|
53
|
+
const { token, expires_at: expiresAt } = await response.json();
|
|
54
|
+
return { token, expires: Date.parse(expiresAt) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return async function installationToken() {
|
|
58
|
+
if (current && current.expires - Date.now() > RENEW_BEFORE) return current.token;
|
|
59
|
+
// Requests that arrive together share one renewal.
|
|
60
|
+
const renewal = (pending ??= mint()
|
|
61
|
+
.then((fresh) => (current = fresh))
|
|
62
|
+
.finally(() => (pending = undefined)));
|
|
63
|
+
return (await renewal).token;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// GitHub downloads keys as PKCS#1 ("BEGIN RSA PRIVATE KEY"); Web Crypto
|
|
68
|
+
// imports PKCS#8 ("BEGIN PRIVATE KEY"). Both are accepted, also with the
|
|
69
|
+
// line breaks written as "\n", as they often are in environment variables.
|
|
70
|
+
export function pkcs8(pem) {
|
|
71
|
+
const text = String(pem).replace(/\\n/g, '\n').trim();
|
|
72
|
+
const der = fromBase64(text.replace(/-----(BEGIN|END)[^-]*-----/g, '').replace(/\s/g, ''));
|
|
73
|
+
if (text.includes('BEGIN PRIVATE KEY')) return der;
|
|
74
|
+
if (text.includes('BEGIN RSA PRIVATE KEY')) {
|
|
75
|
+
// PrivateKeyInfo { version 0, AlgorithmIdentifier { rsaEncryption, NULL }, OCTET STRING { the PKCS#1 key } }
|
|
76
|
+
const rsaEncryption = Uint8Array.of(0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00);
|
|
77
|
+
return node(0x30, concat(Uint8Array.of(0x02, 0x01, 0x00), rsaEncryption, node(0x04, der)));
|
|
78
|
+
}
|
|
79
|
+
throw new Error('starlight-annotations: the GitHub App private key must be a PEM ("BEGIN RSA PRIVATE KEY" or "BEGIN PRIVATE KEY").');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function node(tag, content) {
|
|
83
|
+
const length = [];
|
|
84
|
+
if (content.length < 0x80) length.push(content.length);
|
|
85
|
+
else {
|
|
86
|
+
for (let n = content.length; n > 0; n >>= 8) length.unshift(n & 0xff);
|
|
87
|
+
length.unshift(0x80 | length.length);
|
|
88
|
+
}
|
|
89
|
+
return concat(Uint8Array.of(tag, ...length), content);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function concat(...parts) {
|
|
93
|
+
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
94
|
+
let offset = 0;
|
|
95
|
+
for (const part of parts) {
|
|
96
|
+
out.set(part, offset);
|
|
97
|
+
offset += part.length;
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
package/src/server/github.js
CHANGED
|
@@ -6,33 +6,53 @@
|
|
|
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
|
-
// annotate, unless `writers`
|
|
9
|
+
// Sign-in: a GitHub OAuth app, or the client id and secret of a GitHub App.
|
|
10
|
+
// Only people with write access to `repo` may annotate, unless `writers`
|
|
11
|
+
// says otherwise.
|
|
12
|
+
//
|
|
13
|
+
// Server credentials: a token, or `app` ({ appId, privateKey }) for a GitHub
|
|
14
|
+
// App installed on `repo` (see github-app.js).
|
|
11
15
|
|
|
12
16
|
import { filePath } from '../core.js';
|
|
17
|
+
import { githubAppToken } from './github-app.js';
|
|
13
18
|
import { gitStorage } from './git-storage.js';
|
|
14
19
|
import { oauthAuth } from './oauth.js';
|
|
15
20
|
import { decodeText, encodeText, required, restClient } from './util.js';
|
|
16
21
|
|
|
22
|
+
// `token` is a string, or a function that returns one (a GitHub App).
|
|
17
23
|
const client = (token) =>
|
|
18
24
|
restClient({
|
|
19
25
|
base: 'https://api.github.com',
|
|
20
|
-
headers:
|
|
26
|
+
headers: async () => ({
|
|
27
|
+
Authorization: `Bearer ${typeof token === 'function' ? await token() : token}`,
|
|
28
|
+
Accept: 'application/vnd.github+json',
|
|
29
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
30
|
+
}),
|
|
21
31
|
label: 'GitHub',
|
|
22
32
|
});
|
|
23
33
|
|
|
34
|
+
// The server credential: `token` as given, or installation tokens of `app`.
|
|
35
|
+
function serverToken({ repo, token, app }, where) {
|
|
36
|
+
if (token) return token;
|
|
37
|
+
if (app) return githubAppToken({ ...app, repo });
|
|
38
|
+
throw new Error(`starlight-annotations: ${where} needs token or app.`);
|
|
39
|
+
}
|
|
40
|
+
|
|
24
41
|
/**
|
|
25
|
-
* Storage and sign-in together, which is what most sites want.
|
|
42
|
+
* Storage and sign-in together, which is what most sites want. With `app`,
|
|
43
|
+
* both share one installation token.
|
|
26
44
|
* @param {import('../../server').GitHubOptions} options
|
|
27
45
|
*/
|
|
28
46
|
export function github(options) {
|
|
29
|
-
|
|
47
|
+
const token = options.token || options.app ? serverToken(options, 'github') : undefined;
|
|
48
|
+
const shared = { ...options, token, app: undefined };
|
|
49
|
+
return { storage: githubStorage(shared), auth: githubAuth(shared) };
|
|
30
50
|
}
|
|
31
51
|
|
|
32
52
|
/** @param {import('../../server').GitHubStorageOptions} options */
|
|
33
|
-
export function githubStorage({ repo, token, branch = 'annotations', dir = 'annotations', commitMessage }) {
|
|
34
|
-
required({ repo
|
|
35
|
-
const api = client(token);
|
|
53
|
+
export function githubStorage({ repo, token, app, branch = 'annotations', dir = 'annotations', commitMessage }) {
|
|
54
|
+
required({ repo }, 'githubStorage');
|
|
55
|
+
const api = client(serverToken({ repo, token, app }, 'githubStorage'));
|
|
36
56
|
const contentsPath = (page) => `/repos/${repo}/contents/${filePath(page, dir).split('/').map(encodeURIComponent).join('/')}`;
|
|
37
57
|
|
|
38
58
|
return gitStorage({
|
|
@@ -78,8 +98,12 @@ export function githubStorage({ repo, token, branch = 'annotations', dir = 'anno
|
|
|
78
98
|
}
|
|
79
99
|
|
|
80
100
|
/** @param {import('../../server').GitHubAuthOptions} options */
|
|
81
|
-
export function githubAuth({ repo, token, writers = 'collaborators', ...options }) {
|
|
82
|
-
|
|
101
|
+
export function githubAuth({ repo, token, app, writers = 'collaborators', ...options }) {
|
|
102
|
+
let server;
|
|
103
|
+
if (writers === 'collaborators') {
|
|
104
|
+
required({ repo }, 'githubAuth with writers "collaborators"');
|
|
105
|
+
server = serverToken({ repo, token, app }, 'githubAuth with writers "collaborators"');
|
|
106
|
+
}
|
|
83
107
|
return oauthAuth({
|
|
84
108
|
...options,
|
|
85
109
|
writers,
|
|
@@ -96,7 +120,7 @@ export function githubAuth({ repo, token, writers = 'collaborators', ...options
|
|
|
96
120
|
// counts as write, triage as read. On a public repository GitHub answers
|
|
97
121
|
// "read" for anyone, so read access is not enough.
|
|
98
122
|
async canWrite(profile) {
|
|
99
|
-
const permission = await client(
|
|
123
|
+
const permission = await client(server).get(`/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, {
|
|
100
124
|
allow404: true,
|
|
101
125
|
});
|
|
102
126
|
return permission?.permission === 'admin' || permission?.permission === 'write';
|
package/src/server/index.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import { AnnotationError, ROUTE_PREFIX, applyChange, checkPage, json } from '../core.js';
|
|
15
15
|
|
|
16
16
|
export { github, githubAuth, githubStorage } from './github.js';
|
|
17
|
+
export { githubAppToken } from './github-app.js';
|
|
17
18
|
export { gitlab, gitlabAuth, gitlabStorage } from './gitlab.js';
|
|
18
19
|
export { forgejo, gitea, giteaAuth, giteaStorage } from './gitea.js';
|
|
19
20
|
export { AnnotationError } from '../core.js';
|
package/src/server/util.js
CHANGED
|
@@ -63,14 +63,15 @@ export function timingSafeEqual(left, right) {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
// A small REST client: JSON in and out, `null` for an allowed 404.
|
|
66
|
+
// `headers` may be a function, for credentials that change (GitHub App).
|
|
66
67
|
export function restClient({ base, headers, label }) {
|
|
67
|
-
const raw = (path, init = {}) =>
|
|
68
|
+
const raw = async (path, init = {}) =>
|
|
68
69
|
fetch(`${base}${path}`, {
|
|
69
70
|
...init,
|
|
70
71
|
headers: {
|
|
71
72
|
Accept: 'application/json',
|
|
72
73
|
'User-Agent': 'starlight-annotations',
|
|
73
|
-
...headers,
|
|
74
|
+
...(typeof headers === 'function' ? await headers() : headers),
|
|
74
75
|
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
|
75
76
|
},
|
|
76
77
|
});
|