starlight-annotations 0.2.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 ADDED
@@ -0,0 +1,39 @@
1
+ # starlight-annotations
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
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 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)`.
14
+
15
+ ## 0.2.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 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.
20
+
21
+ ## 0.1.2
22
+
23
+ ### Patch Changes
24
+
25
+ - 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.
26
+
27
+ ## 0.1.1
28
+
29
+ ### Patch Changes
30
+
31
+ - 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.
32
+ - 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.
33
+ - 1d6c768: Points the npm homepage to the documentation site, and adds badges, feature icons and more search keywords to the package page.
34
+
35
+ ## 0.1.0
36
+
37
+ ### Minor Changes
38
+
39
+ - 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,7 +7,7 @@
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
 
@@ -71,6 +71,10 @@ On GitLab or Gitea/Forgejo, use `gitlab({ host, project, … })` or `gitea({ hos
71
71
 
72
72
  No server? `starlightAnnotations({ backend: 'browser' })` keeps notes in each reader's browser.
73
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
+
74
78
  ## 📄 License
75
79
 
76
80
  MIT © Alessandro Rosa
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.2.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",
@@ -52,7 +52,8 @@
52
52
  "index.d.ts",
53
53
  "server.d.ts",
54
54
  "server-node.d.ts",
55
- "src"
55
+ "src",
56
+ "CHANGELOG.md"
56
57
  ],
57
58
  "scripts": {
58
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 {
@@ -39,8 +45,10 @@ export function createAnnotationsHandler(options: HandlerOptions): (request: Req
39
45
  export interface GitHubStorageOptions {
40
46
  /** `owner/name` of the repository that stores the notes. */
41
47
  repo: string;
42
- /** Token with Contents read/write (and Metadata read) on `repo`. */
43
- token: string;
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;
44
52
  /** Branch for the notes. Created from the default branch on the first save. Default `"annotations"`. */
45
53
  branch?: string;
46
54
  /** Folder for the notes in the branch. Default `"annotations"`. */
@@ -49,7 +57,20 @@ export interface GitHubStorageOptions {
49
57
  commitMessage?: (message: string, page: string) => string;
50
58
  }
51
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
+
52
72
  export interface GitHubAuthOptions {
73
+ /** The OAuth app's client ID, or the GitHub App's. */
53
74
  clientId: string;
54
75
  clientSecret: string;
55
76
  /** A long random string that signs the session cookie. */
@@ -60,7 +81,13 @@ export interface GitHubAuthOptions {
60
81
  */
61
82
  writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
62
83
  repo?: string;
63
- token?: string;
84
+ token?: string | (() => Promise<string>);
85
+ app?: GitHubAppOptions;
86
+ /**
87
+ * Seconds between checks that a signed-in user may still write, on saves and page loads.
88
+ * `false` checks only at sign-in. Default 60.
89
+ */
90
+ recheck?: number | false;
64
91
  /** Set to false only for plain-http local testing. Default true. */
65
92
  cookieSecure?: boolean;
66
93
  }
@@ -91,6 +118,11 @@ interface CommonAuthOptions {
91
118
  * `token`. `"anyone"` accepts every signed-in user.
92
119
  */
93
120
  writers?: 'collaborators' | 'anyone' | string[] | ((profile: { login: string; id: number }) => boolean | Promise<boolean>);
121
+ /**
122
+ * Seconds between checks that a signed-in user may still write, on saves and page loads.
123
+ * `false` checks only at sign-in. Default 60.
124
+ */
125
+ recheck?: number | false;
94
126
  /** Set to false only for plain-http local testing. Default true. */
95
127
  cookieSecure?: boolean;
96
128
  }
@@ -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
- if (data.status === 401) state.user = null;
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
  }
@@ -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) return { ok: false, status: response.status, error: data.error || `Error ${response.status}` };
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,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
+ }
@@ -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. Only people with write access to `repo` may
10
- // annotate, unless `writers` says otherwise.
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: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
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
- return { storage: githubStorage(options), auth: githubAuth(options) };
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, token }, 'githubStorage');
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
- if (writers === 'collaborators') required({ repo, token }, 'githubAuth with writers "collaborators"');
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(token).get(`/repos/${repo}/collaborators/${encodeURIComponent(profile.login)}/permission`, {
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';
@@ -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';
@@ -24,6 +25,7 @@ export { AnnotationError } from '../core.js';
24
25
  export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX }) {
25
26
  if (!storage) throw new Error('starlight-annotations: createAnnotationsHandler needs a storage.');
26
27
  const root = prefix.replace(/\/$/, '');
28
+ const stillAllowed = async (user) => (auth?.allowed ? auth.allowed(user) : true);
27
29
 
28
30
  return async function handleAnnotations(request) {
29
31
  const url = new URL(request.url);
@@ -39,13 +41,21 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
39
41
  if (route === '/api' && request.method === 'GET') {
40
42
  const page = checkPage(url.searchParams.get('page'));
41
43
  const doc = await storage.load(page);
42
- const user = auth ? await auth.user(request) : null;
43
- return json({
44
- annotations: doc.annotations,
45
- user: user && { login: user.login, name: user.name },
46
- mode: auth?.mode ?? storage.mode ?? 'api',
47
- canSignIn: Boolean(auth?.route),
48
- });
44
+ let user = auth ? await auth.user(request) : null;
45
+ // Reading never fails on the access check: if the provider does not
46
+ // answer, the reader stays signed in and the next write asks again.
47
+ const revoked = user && (await stillAllowed(user).catch(() => true)) === false;
48
+ if (revoked) user = null;
49
+ return json(
50
+ {
51
+ annotations: doc.annotations,
52
+ user: user && { login: user.login, name: user.name },
53
+ mode: auth?.mode ?? storage.mode ?? 'api',
54
+ canSignIn: Boolean(auth?.route),
55
+ },
56
+ 200,
57
+ revoked && auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {},
58
+ );
49
59
  }
50
60
 
51
61
  if (route === '/api' && request.method === 'POST') {
@@ -53,6 +63,10 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
53
63
  if (origin && origin !== url.origin) return json({ error: 'Cross-site request refused.' }, 403);
54
64
  const user = auth ? await auth.user(request) : null;
55
65
  if (!user) return json({ error: 'Sign in first.' }, 401);
66
+ if (!(await stillAllowed(user))) {
67
+ const error = auth.noAccess ? auth.noAccess(user.login) : 'You may no longer annotate these docs.';
68
+ return json({ error, signedOut: true }, 403, auth.clearSession ? { 'Set-Cookie': auth.clearSession } : {});
69
+ }
56
70
  const { page, change } = await request.json();
57
71
  const result = await storage.update(checkPage(page), (doc) => applyChange(doc, change, user), user);
58
72
  return json(result);
@@ -88,5 +102,8 @@ export function staticAuth(user) {
88
102
  * mode?: string,
89
103
  * user(request: Request): Promise<User | null>,
90
104
  * route?(route: string, request: Request, url: URL, prefix: string): Promise<Response | null>,
105
+ * allowed?(user: User): Promise<boolean>,
106
+ * noAccess?(login: string): string,
107
+ * clearSession?: string,
91
108
  * }} Auth
92
109
  */
@@ -3,7 +3,9 @@
3
3
  //
4
4
  // The reader's access token is used once, at the callback, to read who they
5
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.
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.
7
9
 
8
10
  import {
9
11
  base64url,
@@ -19,6 +21,8 @@ import {
19
21
  const SESSION_COOKIE = 'annot_session';
20
22
  const STATE_COOKIE = 'annot_state';
21
23
  const SESSION_AGE = 60 * 60 * 24 * 30;
24
+ const RECHECK = 60;
25
+ const CACHE_SIZE = 500;
22
26
 
23
27
  /**
24
28
  * @param {{
@@ -31,6 +35,7 @@ const SESSION_AGE = 60 * 60 * 24 * 30;
31
35
  * clientSecret: string,
32
36
  * sessionSecret: string,
33
37
  * cookieSecure?: boolean,
38
+ * recheck?: number | false,
34
39
  * writers?: 'collaborators' | 'anyone' | string[] | ((profile: object) => boolean | Promise<boolean>),
35
40
  * profile: (userToken: string) => Promise<{ login: string, id: number, name?: string }>,
36
41
  * canWrite: (profile: { login: string, id: number }) => Promise<boolean>,
@@ -40,6 +45,7 @@ const SESSION_AGE = 60 * 60 * 24 * 30;
40
45
  export function oauthAuth(options) {
41
46
  const { mode, where, authorizeUrl, tokenUrl, scope, clientId, clientSecret, sessionSecret, cookieSecure = true } = options;
42
47
  const writers = options.writers ?? 'collaborators';
48
+ const recheck = options.recheck ?? RECHECK;
43
49
  required({ clientId, clientSecret, sessionSecret }, where);
44
50
 
45
51
  const cookie = (name, value, maxAge, path = '/') =>
@@ -52,6 +58,17 @@ export function oauthAuth(options) {
52
58
  return options.canWrite(profile);
53
59
  }
54
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
+
55
72
  async function hmac(value) {
56
73
  const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(sessionSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
57
74
  return base64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value))));
@@ -59,6 +76,19 @@ export function oauthAuth(options) {
59
76
 
60
77
  return {
61
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,
62
92
 
63
93
  async user(request) {
64
94
  const value = readCookie(request, SESSION_COOKIE);
@@ -114,7 +144,9 @@ export function oauthAuth(options) {
114
144
  if (!userToken) return text('The sign-in was not confirmed. Try again.', 400, [clear]);
115
145
 
116
146
  const profile = await options.profile(userToken);
117
- if (!(await mayWrite(profile))) return text(options.noAccess(profile.login), 403, [clear]);
147
+ const allowed = await mayWrite(profile);
148
+ remember(profile, allowed);
149
+ if (!allowed) return text(options.noAccess(profile.login), 403, [clear]);
118
150
 
119
151
  const body = base64url(
120
152
  new TextEncoder().encode(
@@ -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
  });