mcp-feedback 0.5.0 → 0.7.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.
Files changed (42) hide show
  1. package/README.md +139 -2
  2. package/agentdist.json +40 -0
  3. package/dist/cli.d.ts +5 -0
  4. package/dist/cli.js +26 -3
  5. package/dist/conformance-cases.js +15 -4
  6. package/dist/drizzle.js +1 -0
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +2 -2
  9. package/dist/ingest/cli.d.ts +8 -0
  10. package/dist/ingest/cli.js +270 -0
  11. package/dist/ingest/github.d.ts +40 -0
  12. package/dist/ingest/github.js +80 -0
  13. package/dist/ingest/handler.d.ts +84 -0
  14. package/dist/ingest/handler.js +447 -0
  15. package/dist/ingest/index.d.ts +3 -0
  16. package/dist/ingest/index.js +5 -0
  17. package/dist/ingest/protocol.d.ts +203 -0
  18. package/dist/ingest/protocol.js +78 -0
  19. package/dist/ingest/tokens.d.ts +84 -0
  20. package/dist/ingest/tokens.js +163 -0
  21. package/dist/install.d.ts +3 -0
  22. package/dist/install.js +27 -0
  23. package/dist/reader.js +6 -1
  24. package/dist/register.d.ts +36 -4
  25. package/dist/register.js +45 -21
  26. package/dist/remote.d.ts +66 -0
  27. package/dist/remote.js +399 -0
  28. package/dist/store.d.ts +17 -0
  29. package/dist/store.js +5 -0
  30. package/dist/stores/memory.js +3 -1
  31. package/dist/stores/sql.js +5 -0
  32. package/dist/tools.d.ts +8 -1
  33. package/dist/tools.js +28 -7
  34. package/dist/types.d.ts +4 -0
  35. package/package.json +15 -2
  36. package/skills/add-feedback-to-mcp-server/SKILL.md +179 -0
  37. package/skills/add-feedback-to-mcp-server/references/feedback-section.md +57 -0
  38. package/skills/add-feedback-to-mcp-server/references/remote-ingest.md +84 -0
  39. package/skills/read-feedback/SKILL.md +99 -0
  40. package/skills/read-feedback/references/connecting.md +84 -0
  41. package/skills/set-up-feedback-reading/SKILL.md +60 -0
  42. package/skills/set-up-feedback-reading/references/project-reference.md +48 -0
@@ -0,0 +1,270 @@
1
+ // `mcp-feedback ingest ...`: make keys, issue tokens, and run a hub for one project.
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { createRequire } from "node:module";
6
+ import { parseArgs } from "node:util";
7
+ import { FeedbackInputError } from "../reader.js";
8
+ import { createIngestHandler, toNodeListener } from "./handler.js";
9
+ import { generateKeyPair, issueToken, isValidProjectName } from "./tokens.js";
10
+ export const INGEST_USAGE = `mcp-feedback ingest: run a hub that collects feedback from installed copies of a server
11
+
12
+ Usage: mcp-feedback ingest <command> [options]
13
+
14
+ Commands:
15
+ keygen --out <file> Make a signing key. Writes it (private) to <file>; prints the public half
16
+ issue-key --project <p> Print a project key: ships in the server package, can only enrol
17
+ issue-token --project <p> --subject <s> [--days <n>]
18
+ Print a token for a person or team you know (default 90 days)
19
+ serve (--db <path> | --postgres <url>) [--project <p>...] [--port <n>] [--host <h>]
20
+ Run the hub (POST /v1/enroll, POST /v1/feedback). Every project
21
+ your key issued a project key for goes into one store, under its
22
+ own name; --project, repeated, accepts only those listed.
23
+ With MCP_FEEDBACK_READER_TOKEN set (32+ characters), also serves
24
+ the reader tools for all projects at POST /mcp, behind that token
25
+
26
+ Options (serve reads each from the environment variable shown when the flag is not given):
27
+ --key <file> The signing key MCP_FEEDBACK_INGEST_KEY (a path, or the key file's JSON)
28
+ --issuer <url> The hub's public URL; tokens are MCP_FEEDBACK_INGEST_ISSUER
29
+ only valid there
30
+ --db <path> SQLite file MCP_FEEDBACK_DB
31
+ --postgres <url> Postgres connection URL MCP_FEEDBACK_POSTGRES_URL, then DATABASE_URL
32
+ --table <name> Table, default mcp_feedback MCP_FEEDBACK_TABLE
33
+ --project <p> Accept only these projects (repeat) MCP_FEEDBACK_INGEST_PROJECTS (comma-separated)
34
+ --port <n> Default 8787 PORT
35
+ --host <h> Default 127.0.0.1 MCP_FEEDBACK_INGEST_HOST
36
+ --trust-proxy Client address from X-Forwarded-For MCP_FEEDBACK_INGEST_TRUST_PROXY=1
37
+ --revoked <file> Refuse tokens whose jti or subject is MCP_FEEDBACK_INGEST_REVOKED (comma-separated)
38
+ a line of this file (read at start)
39
+ Reader endpoint at /mcp MCP_FEEDBACK_READER_TOKEN (32+ characters)
40
+ HMAC key for token fingerprints MCP_FEEDBACK_FINGERPRINT_KEY
41
+ GitHub sign-in: OAuth app client id MCP_FEEDBACK_GITHUB_CLIENT_ID (device flow enabled)
42
+ ... only members of these orgs MCP_FEEDBACK_GITHUB_ORGS (comma-separated)
43
+ ... only these GitHub logins MCP_FEEDBACK_GITHUB_USERS (comma-separated)
44
+ --kid <id> With keygen: the key's id (default: generated)
45
+
46
+ serve also answers GET /healthz, for container health checks.
47
+ `;
48
+ function loadKey(values, env) {
49
+ const source = values.key ?? env.MCP_FEEDBACK_INGEST_KEY;
50
+ if (!source)
51
+ throw new FeedbackInputError("No signing key. Pass --key <file> or set MCP_FEEDBACK_INGEST_KEY.");
52
+ const text = source.trimStart().startsWith("{") ? source : readFileSync(source, "utf8");
53
+ try {
54
+ const key = JSON.parse(text);
55
+ if (typeof key.kid === "string" && typeof key.privateKey === "string" && typeof key.publicKey === "string")
56
+ return key;
57
+ }
58
+ catch {
59
+ // Falls through to the message below.
60
+ }
61
+ throw new FeedbackInputError("The signing key is not a file written by mcp-feedback ingest keygen.");
62
+ }
63
+ function required(values, name, envValue) {
64
+ const value = values[name] ?? envValue;
65
+ if (!value)
66
+ throw new FeedbackInputError(`--${name} is required.`);
67
+ return value;
68
+ }
69
+ function checkProject(name) {
70
+ if (!isValidProjectName(name))
71
+ throw new FeedbackInputError("--project is lowercase letters, digits, ., _ or -, at most 64.");
72
+ return name;
73
+ }
74
+ /** issue-key and issue-token take exactly one project. */
75
+ function project(values) {
76
+ const names = values.project ?? [];
77
+ if (names.length !== 1)
78
+ throw new FeedbackInputError("Give exactly one --project.");
79
+ return checkProject(names[0]);
80
+ }
81
+ const { version } = createRequire(import.meta.url)("../../package.json");
82
+ const list = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
83
+ const digest = (value) => createHash("sha256").update(value).digest();
84
+ const sameSecret = (given, expected) => timingSafeEqual(digest(given), digest(expected));
85
+ /** The reader tools over the hub's store, as a stateless Streamable HTTP MCP endpoint behind one token. */
86
+ function readerEndpoint(store, token, onError) {
87
+ return async (req, res) => {
88
+ if (req.method !== "POST") {
89
+ res.writeHead(405, { allow: "POST" }).end();
90
+ return;
91
+ }
92
+ if (!sameSecret(req.headers.authorization ?? "", `Bearer ${token}`)) {
93
+ res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));
94
+ return;
95
+ }
96
+ const [{ McpServer }, { StreamableHTTPServerTransport }, { registerFeedbackReader }] = await Promise.all([
97
+ import("@modelcontextprotocol/sdk/server/mcp.js"),
98
+ import("@modelcontextprotocol/sdk/server/streamableHttp.js"),
99
+ import("../register.js"),
100
+ ]);
101
+ // The SDK hands req.auth to the tools; its clientId is what triage records as triaged_by.
102
+ req.auth = { token, clientId: "hub-maintainer", scopes: [] };
103
+ const server = new McpServer({ name: "mcp-feedback-hub", version });
104
+ registerFeedbackReader(server, { store, onError: (error) => onError(error) });
105
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
106
+ res.on("close", () => {
107
+ void transport.close();
108
+ void server.close();
109
+ });
110
+ await server.connect(transport);
111
+ await transport.handleRequest(req, res);
112
+ };
113
+ }
114
+ async function openHubStore(values, env) {
115
+ const table = values.table ?? env.MCP_FEEDBACK_TABLE;
116
+ const db = values.db ?? env.MCP_FEEDBACK_DB;
117
+ // DATABASE_URL is what most hosts name the database they attach; the hub is its only user.
118
+ const postgres = values.postgres ?? env.MCP_FEEDBACK_POSTGRES_URL ?? env.DATABASE_URL;
119
+ if (db && postgres)
120
+ throw new FeedbackInputError("Configure one of --db (MCP_FEEDBACK_DB) or --postgres (MCP_FEEDBACK_POSTGRES_URL, DATABASE_URL).");
121
+ if (db) {
122
+ const { sqliteStore } = await import("../stores/sqlite.js");
123
+ return sqliteStore({ path: db, table });
124
+ }
125
+ if (postgres) {
126
+ const { default: pg } = await import("pg");
127
+ const pool = new pg.Pool({ connectionString: postgres });
128
+ const { postgresStore } = await import("../stores/postgres.js");
129
+ // Unlike the reader commands, the hub creates its table if it is missing.
130
+ return { ...postgresStore({ client: pool, table }), close: () => pool.end() };
131
+ }
132
+ throw new FeedbackInputError("serve needs a store: --db <path> (MCP_FEEDBACK_DB) or --postgres <url> (MCP_FEEDBACK_POSTGRES_URL or DATABASE_URL).");
133
+ }
134
+ export async function runIngestCli(argv, io) {
135
+ let parsed;
136
+ try {
137
+ parsed = parseArgs({
138
+ args: argv,
139
+ allowPositionals: true,
140
+ options: {
141
+ out: { type: "string" },
142
+ kid: { type: "string" },
143
+ key: { type: "string" },
144
+ issuer: { type: "string" },
145
+ project: { type: "string", multiple: true },
146
+ subject: { type: "string" },
147
+ days: { type: "string" },
148
+ db: { type: "string" },
149
+ postgres: { type: "string" },
150
+ table: { type: "string" },
151
+ port: { type: "string" },
152
+ host: { type: "string" },
153
+ revoked: { type: "string" },
154
+ "trust-proxy": { type: "boolean" },
155
+ help: { type: "boolean", short: "h" },
156
+ },
157
+ });
158
+ }
159
+ catch (error) {
160
+ throw new FeedbackInputError(error.message);
161
+ }
162
+ const { values, positionals } = parsed;
163
+ const [command, ...rest] = positionals;
164
+ if (values.help || !command) {
165
+ io.out(INGEST_USAGE);
166
+ return command || values.help ? 0 : 2;
167
+ }
168
+ if (rest.length)
169
+ throw new FeedbackInputError(`ingest ${command} takes no positional arguments.`);
170
+ const issuer = () => required(values, "issuer", io.env.MCP_FEEDBACK_INGEST_ISSUER);
171
+ const signer = () => {
172
+ const key = loadKey(values, io.env);
173
+ return { kid: key.kid, privateKey: key.privateKey };
174
+ };
175
+ switch (command) {
176
+ case "keygen": {
177
+ const out = required(values, "out");
178
+ if (existsSync(out))
179
+ throw new FeedbackInputError(`${out} already exists; keygen never overwrites a key.`);
180
+ const key = generateKeyPair(values.kid);
181
+ writeFileSync(out, `${JSON.stringify(key, null, 2)}\n`, { mode: 0o600, flag: "wx" });
182
+ io.err(`Wrote the signing key (kid ${key.kid}) to ${out}. Keep it private; it is never printed again.`);
183
+ io.out(key.publicKey.trimEnd());
184
+ return 0;
185
+ }
186
+ case "issue-key": {
187
+ io.out(issueToken({ issuer: issuer(), project: project(values), tier: "project" }, signer()).token);
188
+ return 0;
189
+ }
190
+ case "issue-token": {
191
+ const days = values.days === undefined ? 90 : Number(values.days);
192
+ if (!Number.isInteger(days) || days < 1 || days > 3650)
193
+ throw new FeedbackInputError("--days must be a whole number from 1 to 3650.");
194
+ const subject = required(values, "subject");
195
+ const { token, claims } = issueToken({ issuer: issuer(), project: project(values), tier: "issued", subject, ttlSeconds: days * 86400 }, signer());
196
+ io.err(`Token for ${subject}, valid until ${new Date(claims.exp * 1000).toISOString()} (jti ${claims.jti}, for revoking it).`);
197
+ io.out(token);
198
+ return 0;
199
+ }
200
+ case "serve": {
201
+ const key = loadKey(values, io.env);
202
+ const env = io.env;
203
+ const listed = (values.project ?? (env.MCP_FEEDBACK_INGEST_PROJECTS ?? "").split(","))
204
+ .map((name) => name.trim())
205
+ .filter(Boolean)
206
+ .map(checkProject);
207
+ const readerToken = io.env.MCP_FEEDBACK_READER_TOKEN;
208
+ if (readerToken !== undefined && readerToken.length < 32) {
209
+ throw new FeedbackInputError("MCP_FEEDBACK_READER_TOKEN must be at least 32 characters.");
210
+ }
211
+ const port = Number(values.port ?? env.PORT ?? 8787);
212
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
213
+ throw new FeedbackInputError("--port must be a port number.");
214
+ const revoked = new Set((values.revoked ? readFileSync(values.revoked, "utf8").split("\n") : (env.MCP_FEEDBACK_INGEST_REVOKED ?? "").split(","))
215
+ .map((line) => line.trim())
216
+ .filter(Boolean));
217
+ const trustProxy = values["trust-proxy"] === true || /^(1|true|yes)$/i.test(env.MCP_FEEDBACK_INGEST_TRUST_PROXY ?? "");
218
+ const store = await openHubStore(values, env);
219
+ // Opens the store (and creates its table) now, so a bad connection fails at start, not on the first report.
220
+ await store.stats({ since: new Date().toISOString() });
221
+ const logError = (error) => io.err(`mcp-feedback ingest: ${error instanceof Error ? error.message : String(error)}`);
222
+ const handler = createIngestHandler({
223
+ issuer: issuer(),
224
+ keyring: { keys: [{ kid: key.kid, publicKey: key.publicKey }], signer: { kid: key.kid, privateKey: key.privateKey } },
225
+ store,
226
+ ...(listed.length ? { projects: Object.fromEntries(listed.map((name) => [name, {}])) } : {}),
227
+ isRevoked: (claims) => revoked.has(claims.jti) || revoked.has(claims.sub),
228
+ tokenFingerprintKey: env.MCP_FEEDBACK_FINGERPRINT_KEY,
229
+ ...(env.MCP_FEEDBACK_GITHUB_CLIENT_ID
230
+ ? {
231
+ github: {
232
+ clientId: env.MCP_FEEDBACK_GITHUB_CLIENT_ID,
233
+ allowedOrgs: list(env.MCP_FEEDBACK_GITHUB_ORGS),
234
+ allowedUsers: list(env.MCP_FEEDBACK_GITHUB_USERS),
235
+ },
236
+ }
237
+ : {}),
238
+ onError: logError,
239
+ });
240
+ const ingest = toNodeListener(handler, { trustProxy });
241
+ const reader = readerToken ? readerEndpoint(store, readerToken, logError) : undefined;
242
+ const server = createServer((req, res) => {
243
+ const path = (req.url ?? "/").split("?")[0];
244
+ if (path === "/healthz" && req.method === "GET")
245
+ res.writeHead(200, { "content-type": "application/json" }).end('{"ok":true}');
246
+ else if (reader && path === "/mcp")
247
+ void reader(req, res).catch(logError);
248
+ else
249
+ void ingest(req, res);
250
+ });
251
+ const host = values.host ?? env.MCP_FEEDBACK_INGEST_HOST ?? "127.0.0.1";
252
+ await new Promise((resolve) => server.listen(port, host, resolve));
253
+ const address = server.address();
254
+ const bound = typeof address === "object" && address ? address.port : port;
255
+ const which = listed.length ? listed.join(", ") : "every project the key signed";
256
+ io.err(`mcp-feedback ingest: collecting feedback for ${which} on http://${host}:${bound} (POST /v1/enroll, /v1/feedback)`);
257
+ io.err(reader ? `mcp-feedback ingest: reader tools for all projects at http://${host}:${bound}/mcp` : "mcp-feedback ingest: no reader endpoint (MCP_FEEDBACK_READER_TOKEN is not set)");
258
+ io.err(env.MCP_FEEDBACK_GITHUB_CLIENT_ID ? "mcp-feedback ingest: GitHub sign-in on" : "mcp-feedback ingest: GitHub sign-in off (MCP_FEEDBACK_GITHUB_CLIENT_ID is not set)");
259
+ await new Promise((resolve) => {
260
+ process.once("SIGINT", resolve);
261
+ process.once("SIGTERM", resolve);
262
+ });
263
+ await new Promise((resolve) => server.close(() => resolve()));
264
+ await store.close?.();
265
+ return 0;
266
+ }
267
+ default:
268
+ throw new FeedbackInputError(`Unknown ingest command: ${command}. Run mcp-feedback ingest --help.`);
269
+ }
270
+ }
@@ -0,0 +1,40 @@
1
+ export interface GitHubSignInOptions {
2
+ /** The client id of a GitHub OAuth app with "Enable Device Flow" turned on. No secret is needed. */
3
+ clientId: string;
4
+ /** Accept only members of these organisations (asks GitHub for read:org). */
5
+ allowedOrgs?: string[];
6
+ /** Accept only these GitHub logins. */
7
+ allowedUsers?: string[];
8
+ /** How long a sign-in lasts before it must be renewed. Default 180 days. */
9
+ userTokenTtlSeconds?: number;
10
+ /** For tests. */
11
+ fetch?: typeof fetch;
12
+ /** For GitHub Enterprise Server: e.g. `https://github.example.com` and `https://github.example.com/api/v3`. */
13
+ webUrl?: string;
14
+ apiUrl?: string;
15
+ }
16
+ export interface DeviceCode {
17
+ device_code: string;
18
+ user_code: string;
19
+ verification_uri: string;
20
+ expires_in: number;
21
+ interval: number;
22
+ }
23
+ export type DevicePoll = {
24
+ status: "pending";
25
+ interval?: number;
26
+ } | {
27
+ status: "denied";
28
+ } | {
29
+ status: "expired";
30
+ } | {
31
+ status: "complete";
32
+ accessToken: string;
33
+ };
34
+ /** A failure talking to GitHub, or a configuration GitHub refused. */
35
+ export declare class GitHubError extends Error {
36
+ }
37
+ export declare function startDeviceFlow(options: GitHubSignInOptions): Promise<DeviceCode>;
38
+ export declare function pollDeviceFlow(options: GitHubSignInOptions, deviceCode: string): Promise<DevicePoll>;
39
+ /** Who signed in, checked against the allow lists. Resolves the login, or throws a GitHubError saying why not. */
40
+ export declare function signedInUser(options: GitHubSignInOptions, accessToken: string): Promise<string>;
@@ -0,0 +1,80 @@
1
+ // GitHub's OAuth device flow, run by the hub on an installation's behalf. The hub talks to GitHub;
2
+ // the installation only relays a code to its user. GitHub's access token never leaves the hub, and
3
+ // the hub drops it once it has read who signed in.
4
+ /** A failure talking to GitHub, or a configuration GitHub refused. */
5
+ export class GitHubError extends Error {
6
+ }
7
+ const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
8
+ function urls(options) {
9
+ return { web: (options.webUrl ?? "https://github.com").replace(/\/+$/, ""), api: (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "") };
10
+ }
11
+ async function postForm(options, path, body) {
12
+ const response = await (options.fetch ?? fetch)(urls(options).web + path, {
13
+ method: "POST",
14
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded", "user-agent": "mcp-feedback-hub" },
15
+ body: new URLSearchParams(body).toString(),
16
+ signal: AbortSignal.timeout(10_000),
17
+ });
18
+ if (response.status === 404 && path === "/login/device/code") {
19
+ throw new GitHubError("GitHub does not know this OAuth app's client id. Check MCP_FEEDBACK_GITHUB_CLIENT_ID and that the app has device flow enabled.");
20
+ }
21
+ if (!response.ok)
22
+ throw new GitHubError(`GitHub answered ${response.status}.`);
23
+ return (await response.json());
24
+ }
25
+ async function api(options, accessToken, path) {
26
+ const response = await (options.fetch ?? fetch)(urls(options).api + path, {
27
+ headers: { accept: "application/vnd.github+json", authorization: `Bearer ${accessToken}`, "user-agent": "mcp-feedback-hub" },
28
+ signal: AbortSignal.timeout(10_000),
29
+ });
30
+ if (!response.ok)
31
+ throw new GitHubError(`GitHub answered ${response.status} for ${path}.`);
32
+ return response.json();
33
+ }
34
+ export async function startDeviceFlow(options) {
35
+ const scope = options.allowedOrgs?.length ? "read:org" : "";
36
+ const body = await postForm(options, "/login/device/code", { client_id: options.clientId, scope });
37
+ if (typeof body.error === "string")
38
+ throw new GitHubError(`GitHub refused to start a sign-in: ${body.error}. Check that the OAuth app has device flow enabled.`);
39
+ const code = body;
40
+ if (typeof code.device_code !== "string" || typeof code.user_code !== "string" || typeof code.verification_uri !== "string") {
41
+ throw new GitHubError("GitHub gave an unexpected answer to the sign-in request.");
42
+ }
43
+ return { ...code, interval: Number(code.interval) || 5, expires_in: Number(code.expires_in) || 900 };
44
+ }
45
+ export async function pollDeviceFlow(options, deviceCode) {
46
+ const body = await postForm(options, "/login/oauth/access_token", { client_id: options.clientId, device_code: deviceCode, grant_type: DEVICE_GRANT });
47
+ if (typeof body.access_token === "string")
48
+ return { status: "complete", accessToken: body.access_token };
49
+ switch (body.error) {
50
+ case "authorization_pending":
51
+ return { status: "pending" };
52
+ case "slow_down":
53
+ return { status: "pending", interval: Number(body.interval) || undefined };
54
+ case "access_denied":
55
+ return { status: "denied" };
56
+ case "expired_token":
57
+ case "incorrect_device_code":
58
+ case "token_expired":
59
+ return { status: "expired" };
60
+ default:
61
+ throw new GitHubError(`GitHub refused the sign-in: ${String(body.error ?? "no reason given")}.`);
62
+ }
63
+ }
64
+ /** Who signed in, checked against the allow lists. Resolves the login, or throws a GitHubError saying why not. */
65
+ export async function signedInUser(options, accessToken) {
66
+ const user = (await api(options, accessToken, "/user"));
67
+ if (typeof user.login !== "string" || !user.login)
68
+ throw new GitHubError("GitHub did not say who signed in.");
69
+ const login = user.login;
70
+ if (options.allowedUsers?.length && !options.allowedUsers.some((allowed) => allowed.toLowerCase() === login.toLowerCase())) {
71
+ throw new GitHubError(`GitHub user ${login} is not one this hub accepts.`);
72
+ }
73
+ if (options.allowedOrgs?.length) {
74
+ const orgs = (await api(options, accessToken, "/user/orgs?per_page=100")).map((org) => String(org.login).toLowerCase());
75
+ if (!options.allowedOrgs.some((allowed) => orgs.includes(allowed.toLowerCase()))) {
76
+ throw new GitHubError(`GitHub user ${login} is not a member of an organisation this hub accepts.`);
77
+ }
78
+ }
79
+ return login;
80
+ }
@@ -0,0 +1,84 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type FeedbackLimits } from "../register.js";
3
+ import type { FeedbackStore } from "../store.js";
4
+ import type { FeedbackRecord } from "../types.js";
5
+ import { type GitHubSignInOptions } from "./github.js";
6
+ import { type Keyring, type TokenClaims } from "./tokens.js";
7
+ export interface IngestQuotas {
8
+ /** Reports one installation may file in 24 hours. */
9
+ perInstallPerDay: number;
10
+ /** Reports one holder of an issued token may file in 24 hours. */
11
+ perIssuedSubjectPerDay: number;
12
+ /** Reports a project accepts in 24 hours, from everyone together. */
13
+ perProjectPerDay: number;
14
+ /** Enrolments one network address may make in an hour. Kept in this process's memory only. */
15
+ enrollPerAddressPerHour: number;
16
+ }
17
+ export declare const DEFAULT_INGEST_QUOTAS: IngestQuotas;
18
+ export interface IngestProject {
19
+ /** Write this project somewhere other than the hub's shared store, e.g. a table its server already reads. */
20
+ store?: FeedbackStore;
21
+ quotas?: Partial<IngestQuotas>;
22
+ }
23
+ export interface IngestOptions {
24
+ /** This hub's identity, usually its public URL. Tokens must name it as `iss`. */
25
+ issuer: string;
26
+ /** The keys whose tokens are accepted, and the key install tokens are signed with. */
27
+ keyring: Keyring;
28
+ /**
29
+ * Where feedback is written. One store holds every project: each record's `server.name` is the
30
+ * project its token names, so readers can take one project (the `server` filter) or all of them.
31
+ * Required unless every project in `projects` has a store of its own.
32
+ */
33
+ store?: FeedbackStore;
34
+ /**
35
+ * Leave out to accept every project the keyring signed tokens for: a new server needs only a
36
+ * project key, no change here. Give it to accept only the projects listed, or to set a project's
37
+ * own store or quotas.
38
+ */
39
+ projects?: Record<string, IngestProject>;
40
+ quotas?: Partial<IngestQuotas>;
41
+ limits?: Partial<FeedbackLimits>;
42
+ /** How long an install token, and a signed-in person's per-project token, lasts. Default 30 days; installations renew them. */
43
+ installTokenTtlSeconds?: number;
44
+ /**
45
+ * Let people sign in with GitHub, so their reports carry `github:<login>` instead of an anonymous
46
+ * installation id. Needs a GitHub OAuth app with device flow enabled, and a signing key.
47
+ */
48
+ github?: GitHubSignInOptions;
49
+ /** Return true to refuse a token, e.g. by its `jti` or its `sub`. Checked on every request. */
50
+ isRevoked?: (claims: TokenClaims) => boolean | Promise<boolean>;
51
+ /**
52
+ * Return false to refuse an enrolment, for limits that must hold across processes. The built-in
53
+ * per-address limit still applies.
54
+ */
55
+ allowEnrollment?: (request: {
56
+ project: string;
57
+ clientAddress: string | null;
58
+ }) => boolean | Promise<boolean>;
59
+ /** Last chance to scrub a record before it is stored. */
60
+ redact?: (record: FeedbackRecord) => FeedbackRecord | Promise<FeedbackRecord>;
61
+ /** Secret for HMAC token fingerprints, as in registerFeedback. */
62
+ tokenFingerprintKey?: string;
63
+ /** Mount point, e.g. `"/ingest"`. The routes are `<basePath>/v1/enroll` and `<basePath>/v1/feedback`. */
64
+ basePath?: string;
65
+ /** Called with unexpected errors, for the host's logger. */
66
+ onError?: (error: unknown) => void;
67
+ }
68
+ /** What a host knows about a request that a web Request does not carry. */
69
+ export interface IngestRequestInfo {
70
+ clientAddress?: string | null;
71
+ }
72
+ export type IngestHandler = (request: Request, info?: IngestRequestInfo) => Promise<Response>;
73
+ export declare function createIngestHandler(options: IngestOptions): IngestHandler;
74
+ /**
75
+ * Adapts the handler to node:http and Express. Mount it before any body parser.
76
+ *
77
+ * The client address (for the enrolment limit) is, in order: `clientAddress(req)` if given; the
78
+ * first X-Forwarded-For entry with `trustProxy`, which is only safe behind a proxy that overwrites
79
+ * that header; Express's `req.ip`, which follows the app's own `trust proxy` setting; the socket.
80
+ */
81
+ export declare function toNodeListener(handler: IngestHandler, options?: {
82
+ trustProxy?: boolean;
83
+ clientAddress?: (req: IncomingMessage) => string | null | undefined;
84
+ }): (req: IncomingMessage, res: ServerResponse) => Promise<void>;