@aidenhq/sdk 0.3.0 → 0.4.1

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 (70) hide show
  1. package/README.md +15 -7
  2. package/dist/src/agent-paused.d.ts +7 -0
  3. package/dist/src/agent-paused.js +4 -0
  4. package/dist/src/attribution.d.ts +16 -0
  5. package/dist/src/attribution.js +21 -0
  6. package/dist/src/box-bundle.d.ts +9 -0
  7. package/dist/src/box-bundle.js +59 -0
  8. package/dist/src/caller.js +2 -1
  9. package/dist/src/checks.d.ts +101 -0
  10. package/dist/src/checks.js +151 -0
  11. package/dist/src/churn.d.ts +46 -0
  12. package/dist/src/churn.js +177 -0
  13. package/dist/src/closed-event.d.ts +36 -0
  14. package/dist/src/closed-event.js +17 -0
  15. package/dist/src/engine-io.d.ts +2 -0
  16. package/dist/src/engine-io.js +13 -8
  17. package/dist/src/executor.d.ts +46 -3
  18. package/dist/src/executor.js +23 -13
  19. package/dist/src/fence.d.ts +12 -0
  20. package/dist/src/fence.js +24 -1
  21. package/dist/src/for-others.d.ts +3 -0
  22. package/dist/src/for-others.js +7 -0
  23. package/dist/src/instance-details.d.ts +10 -0
  24. package/dist/src/instance-details.js +63 -0
  25. package/dist/src/instance-paths.d.ts +3 -0
  26. package/dist/src/instance-paths.js +7 -0
  27. package/dist/src/judge.d.ts +54 -20
  28. package/dist/src/judge.js +57 -75
  29. package/dist/src/kernel-client.d.ts +45 -0
  30. package/dist/src/kernel-client.js +103 -0
  31. package/dist/src/kit.js +19 -4
  32. package/dist/src/maintained-repos.d.ts +58 -0
  33. package/dist/src/maintained-repos.js +136 -0
  34. package/dist/src/model-text.d.ts +29 -0
  35. package/dist/src/model-text.js +361 -0
  36. package/dist/src/owner-day.d.ts +12 -0
  37. package/dist/src/owner-day.js +39 -0
  38. package/dist/src/paperclip.d.ts +34 -0
  39. package/dist/src/paperclip.js +64 -0
  40. package/dist/src/pass-rule.d.ts +10 -0
  41. package/dist/src/pass-rule.js +24 -0
  42. package/dist/src/pin-owner.d.ts +2 -0
  43. package/dist/src/pin-owner.js +1 -0
  44. package/dist/src/progress.js +7 -2
  45. package/dist/src/provider.d.ts +83 -0
  46. package/dist/src/provider.js +31 -0
  47. package/dist/src/quality.d.ts +74 -0
  48. package/dist/src/quality.js +131 -0
  49. package/dist/src/repeat.d.ts +19 -0
  50. package/dist/src/repeat.js +38 -0
  51. package/dist/src/responses.d.ts +64 -0
  52. package/dist/src/responses.js +198 -0
  53. package/dist/src/reviewer.d.ts +79 -34
  54. package/dist/src/reviewer.js +198 -22
  55. package/dist/src/source-store.d.ts +13 -3
  56. package/dist/src/source-store.js +14 -9
  57. package/dist/src/task-state-types.d.ts +77 -0
  58. package/dist/src/task-state-types.js +4 -0
  59. package/dist/src/tiers.d.ts +88 -0
  60. package/dist/src/tiers.js +156 -0
  61. package/dist/src/tools-client.d.ts +60 -0
  62. package/dist/src/tools-client.js +192 -0
  63. package/dist/src/types.d.ts +28 -2
  64. package/dist/src/vendor/needs.d.ts +35 -0
  65. package/dist/src/vendor/needs.js +43 -0
  66. package/dist/src/vendor/oauth.d.ts +82 -2
  67. package/dist/src/vendor/oauth.js +282 -32
  68. package/dist/src/vendor/proxy.d.ts +31 -6
  69. package/dist/src/vendor/proxy.js +376 -49
  70. package/package.json +11 -10
@@ -5,6 +5,8 @@ export interface AuthStatus {
5
5
  detail?: string;
6
6
  /** The scopes the vendor granted at the last sign-in. */
7
7
  scope?: string;
8
+ /** Signs in by a pasted value (a service token), never a browser sign-in: the board's Connect asks for it while not ok. */
9
+ paste?: boolean;
8
10
  }
9
11
  export declare class AuthError extends Error {
10
12
  }
@@ -12,23 +14,61 @@ export declare class SignInError extends Error {
12
14
  }
13
15
  /** The board's sign-in: which scopes the owner may pick (and the ones pre-selected), then the round trip. */
14
16
  export interface SignInFlow {
15
- scopes(): Promise<{
17
+ /** `target`: the account or new client a sign-in is for, whose own scopes are pre-selected (a connection with several). */
18
+ scopes(target?: SignInTarget): Promise<{
16
19
  supported: string[];
17
20
  recommended: string[];
18
21
  }>;
19
- start(redirectUri: string, scopes?: string[]): Promise<{
22
+ /** `target`: for a connection with several accounts, the one to reconnect, or the client a new one signs in with. */
23
+ start(redirectUri: string, scopes?: string[], target?: SignInTarget): Promise<{
20
24
  url: string;
21
25
  }>;
22
26
  finish(state: string, code: string): Promise<void>;
23
27
  }
28
+ /** Which account a sign-in is for, on a connection with several (Slack's workspaces): one to reconnect, or the client a new one uses. */
29
+ export interface SignInTarget {
30
+ account?: string;
31
+ client_id?: string;
32
+ }
33
+ /** A device sign-in (RFC 8628) as the board shows it: the code to type on the vendor's page, and how it is going. */
34
+ export interface DeviceStart {
35
+ user_code: string;
36
+ verification_uri: string;
37
+ verification_uri_complete?: string;
38
+ expires_in: number;
39
+ interval: number;
40
+ }
41
+ export interface DeviceState {
42
+ state: "idle" | "pending" | "ok" | "expired" | "denied" | "cancelled" | "failed";
43
+ detail?: string;
44
+ }
45
+ /**
46
+ * A sign-in for a server without a browser (GitHub, like `gh`): start asks the vendor for a code, and this service polls for the
47
+ * token itself until it lands, the code expires or the board cancels. One at a time: a new start cancels the one before.
48
+ */
49
+ export interface DeviceFlow {
50
+ start(onSignedIn?: () => void): Promise<DeviceStart>;
51
+ state(): DeviceState;
52
+ cancel(): void;
53
+ }
24
54
  /** What the proxy needs from a sign-in: the headers for an upstream request, a refresh after a refusal, and its state. */
25
55
  export interface Auth {
26
56
  headers(): Promise<Record<string, string>>;
27
57
  refresh(): Promise<void>;
28
58
  status(): AuthStatus;
59
+ /** Verifies the sign-in with the vendor before its status is read (a token's cheap authenticated read, kept briefly). */
60
+ check?(): Promise<void>;
61
+ /** Whether the vendor refuses the current token right now (its own cheap authenticated read): a 401 or a refused refresh proves nothing alone. Absent: the connection can't tell. */
62
+ refused?(): Promise<boolean>;
63
+ /** How many sign-ins this connection has completed: a refresh keeps it, a new sign-in (a different account or grant) bumps it, so a
64
+ * caller can tell a token the same sign-in refreshed from one a different sign-in replaced. Absent: the connection can't tell. */
65
+ signInCount?(): number;
29
66
  mark(state: "ok" | "expired", detail?: string): void;
30
67
  signedIn(): boolean;
31
68
  signIn?: SignInFlow;
69
+ device?: DeviceFlow;
70
+ /** Signs one account out (a connection with several): the board's per-account Disconnect. */
71
+ disconnect?(account?: string): Promise<void>;
32
72
  }
33
73
  /** A connection that signs in to nothing (a local server), with fixed headers. */
34
74
  export declare function staticAuth(headers?: Record<string, string>): Auth;
@@ -65,8 +105,35 @@ export interface OAuthOptions {
65
105
  resource?: false;
66
106
  /** A vendor's token answer in the standard shape (Slack nests the user token under authed_user). */
67
107
  tokenAnswer?: (json: Record<string, unknown>) => Record<string, unknown>;
108
+ /**
109
+ * Sign in by device code (RFC 8628) instead of a redirect: `endpoint` is the vendor's device authorization endpoint, the token
110
+ * endpoint is `endpoints.token` (else discovered). An empty `client_id` is a sign-in not configured yet.
111
+ */
112
+ device?: {
113
+ endpoint: string;
114
+ client_id: string;
115
+ scopes?: string[];
116
+ };
68
117
  fetchImpl?: typeof fetch;
118
+ /** Whether the vendor still answers this access token (false only when it refuses it). With it, a refused refresh or a stray 401 never marks a working token expired, and an expired mark heals itself once the token answers. */
119
+ accepts?: (accessToken: string) => Promise<boolean>;
120
+ /** How often an expired mark re-asks `accepts` (default 30 s). */
121
+ healMs?: number;
122
+ /** How a device sign-in waits between polls (tests: no wait). */
123
+ wait?: (ms: number) => Promise<void>;
124
+ /** Where the token lives (default: token.json in `stateDir`): a connection with several accounts keeps one per account. */
125
+ store?: TokenStore;
126
+ }
127
+ /**
128
+ * Where a sign-in's token is kept. `read` answers the same object until `write` replaces it, so a refresh can tell that a
129
+ * new sign-in saved a token meanwhile; a `write` that throws (a sign-in for another account) saves nothing.
130
+ */
131
+ export interface TokenStore {
132
+ read(): StoredToken | undefined;
133
+ write(t: StoredToken): void;
69
134
  }
135
+ /** token.json (0600), written atomically; a file removed from outside reads as signed out. */
136
+ export declare function fileStore(path: string): TokenStore;
70
137
  /** token.json: the pair plus the client it belongs to. Extra fields a vendor answered (Slack's user_id) are kept. */
71
138
  export interface StoredToken {
72
139
  access_token: string;
@@ -77,9 +144,22 @@ export interface StoredToken {
77
144
  client_secret?: string;
78
145
  token_endpoint?: string;
79
146
  resource?: string;
147
+ /** The whole MCP address it was issued for (query included). */
148
+ endpoint?: string;
149
+ /** The authorization server that issued it. */
150
+ issuer?: string;
151
+ /** sha256 of the extra headers it was issued under (Grafana Cloud's stack); absent without any. */
152
+ tenant?: string;
80
153
  [extra: string]: unknown;
81
154
  }
82
155
  /** A redirect this sign-in may send: a loopback callback (a tunnel), or a callback on the board's https origin. */
83
156
  export declare function redirectAllowed(redirectUri: string, boardUrl?: string): boolean;
157
+ /** A private, loopback, link-local or shared address: never a vendor's sign-in server. */
158
+ export declare function privateAddress(ip: string): boolean;
159
+ /**
160
+ * fetch for the OAuth calls (discovery names hosts the vendor chose): https only, each connection's address checked as the socket
161
+ * opens (TLS still verifies the name), and no redirect followed.
162
+ */
163
+ export declare const publicFetch: typeof fetch;
84
164
  /** The owner's OAuth sign-in to a vendor's MCP server. */
85
165
  export declare function oauth(o: OAuthOptions): Auth;
@@ -2,9 +2,20 @@
2
2
  // the board (its Connect sends the browser here and back to the board's callback, at its https address or on loopback), with the scopes the owner picks
3
3
  // there. The client is registered dynamically (RFC 7591) or is one the owner made in the vendor (HubSpot, Slack). Only this
4
4
  // service sees the tokens: the pair lives in /state/token.json (0600), refreshed here, rotated pairs written back atomically.
5
+ // A saved token is bound to what it was issued for: the whole MCP address (`endpoint`, query included: a tenant may live
6
+ // there), the RFC 8707 `resource`, the extra headers that pick a tenant (`tenant`, a hash) and its issuer. A changed address or
7
+ // tenant reads as signed out ("Connect again"), so a token never reaches an endpoint it wasn't issued for; a token saved before
8
+ // binding keeps working while its resource matches and no tenant header applies. A refresh answer never rewrites those
9
+ // fields or where the next refresh goes. Discovery takes only https endpoints (http on loopback, for tests), metadata whose
10
+ // issuer names itself and a resource on the MCP server's origin; no request here follows a redirect or reaches a private
11
+ // network address.
5
12
  //
6
- // Vendor connections import it as @aidenhq/sdk/vendor/oauth.
13
+ // Every module imports it from npm (@aidenhq/sdk/vendor/oauth) at an exact pin: a change here needs a version bump in package.json,
14
+ // which is what publishes it.
7
15
  import { createHash, randomBytes } from "node:crypto";
16
+ import { lookup } from "node:dns";
17
+ import { request } from "node:https";
18
+ import { isIP } from "node:net";
8
19
  import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
20
  import { dirname, join } from "node:path";
10
21
  export class AuthError extends Error {
@@ -14,7 +25,25 @@ export class SignInError extends Error {
14
25
  /** A connection that signs in to nothing (a local server), with fixed headers. */
15
26
  export function staticAuth(headers = {}) {
16
27
  const since = new Date().toISOString();
17
- return { headers: async () => headers, refresh: async () => { }, status: () => ({ state: "none", since }), mark: () => { }, signedIn: () => true };
28
+ return { headers: async () => headers, refresh: async () => { }, status: () => ({ state: "none", since }), mark: () => { }, signedIn: () => true, signInCount: () => 0 };
29
+ }
30
+ /** token.json (0600), written atomically; a file removed from outside reads as signed out. */
31
+ export function fileStore(path) {
32
+ let token;
33
+ return {
34
+ read() {
35
+ if (!existsSync(path))
36
+ return (token = undefined);
37
+ return (token ??= JSON.parse(readFileSync(path, "utf8")));
38
+ },
39
+ write(t) {
40
+ const tmp = join(dirname(path), `.token.${process.pid}.tmp`);
41
+ writeFileSync(tmp, JSON.stringify(t, null, 2), { mode: 0o600 });
42
+ chmodSync(tmp, 0o600);
43
+ renameSync(tmp, path);
44
+ token = t;
45
+ },
46
+ };
18
47
  }
19
48
  const LOOPBACK = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\/[\w/-]*$/;
20
49
  /** A redirect this sign-in may send: a loopback callback (a tunnel), or a callback on the board's https origin. */
@@ -27,20 +56,102 @@ export function redirectAllowed(redirectUri, boardUrl = process.env.BOARD_URL ??
27
56
  return /^\/[\w/-]*$/.test(redirectUri.slice(board.origin.length));
28
57
  }
29
58
  const strings = (v) => (Array.isArray(v) ? v.filter((s) => typeof s === "string") : undefined);
59
+ /** An endpoint discovery may hand a credential to: https, or http on loopback (a local test server). */
60
+ const secure = (u) => typeof u === "string" && URL.canParse(u) && (new URL(u).protocol === "https:" || (new URL(u).protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(new URL(u).hostname)));
61
+ const sameIssuer = (a, b) => a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
62
+ /** A private, loopback, link-local or shared address: never a vendor's sign-in server. */
63
+ export function privateAddress(ip) {
64
+ // An IPv4-mapped IPv6 address in either form (::ffff:10.0.0.5, or ::ffff:a00:5 as URL writes it) is its IPv4 address.
65
+ const m = /^(?:0{0,4}:){0,4}:?ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip);
66
+ const v4 = m ? [parseInt(m[1], 16) >> 8, parseInt(m[1], 16) & 255, parseInt(m[2], 16) >> 8, parseInt(m[2], 16) & 255].join(".") : ip.replace(/^::ffff:/i, "");
67
+ if (isIP(v4) === 4) {
68
+ const [a, b] = v4.split(".").map(Number);
69
+ return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
70
+ }
71
+ const x = ip.toLowerCase();
72
+ return x === "::" || x === "::1" || /^f[cd]/.test(x) || /^fe[89ab]/.test(x) || x.startsWith("ff");
73
+ }
74
+ /** The address a connection is opened to: refused when private, at connect time (a second DNS answer can't slip past it). */
75
+ const publicLookup = (host, opts, done) => lookup(host, { ...opts, all: true }, (err, addrs) => {
76
+ if (err)
77
+ return done(err, "", 0);
78
+ const list = addrs;
79
+ const bad = list.find((a) => privateAddress(a.address));
80
+ if (bad || !list.length)
81
+ return done(new SignInError(`refused ${host}: it resolves to a private network address`), "", 0);
82
+ return opts.all ? done(null, list) : done(null, list[0].address, list[0].family);
83
+ });
84
+ /**
85
+ * fetch for the OAuth calls (discovery names hosts the vendor chose): https only, each connection's address checked as the socket
86
+ * opens (TLS still verifies the name), and no redirect followed.
87
+ */
88
+ export const publicFetch = (input, init) => new Promise((resolve, reject) => {
89
+ const url = new URL(String(input instanceof Request ? input.url : input));
90
+ if (url.protocol !== "https:" || (isIP(url.hostname.replace(/^\[|\]$/g, "")) && privateAddress(url.hostname.replace(/^\[|\]$/g, ""))))
91
+ return reject(new SignInError(`refused ${url.host}: only public https addresses`));
92
+ const body = init?.body == null ? undefined : String(init.body);
93
+ const headers = { ...init?.headers, ...(init?.body instanceof URLSearchParams ? { "content-type": "application/x-www-form-urlencoded" } : {}), ...(body ? { "content-length": String(Buffer.byteLength(body)) } : {}) };
94
+ const req = request(url, { method: init?.method ?? "GET", headers, lookup: publicLookup, signal: init?.signal ?? undefined }, (res) => {
95
+ if ((res.statusCode ?? 0) >= 300 && (res.statusCode ?? 0) < 400) {
96
+ res.resume();
97
+ return reject(new TypeError(`${url.host} answered a redirect`));
98
+ }
99
+ const chunks = [];
100
+ res.on("data", (c) => chunks.push(c));
101
+ res.on("end", () => resolve(new Response(Buffer.concat(chunks), { status: res.statusCode ?? 502, headers: Object.entries(res.headers).flatMap(([k, v]) => (v == null ? [] : [[k, String(v)]])) })));
102
+ res.on("error", reject);
103
+ });
104
+ req.on("error", reject);
105
+ req.end(body);
106
+ });
30
107
  /** The owner's OAuth sign-in to a vendor's MCP server. */
31
108
  export function oauth(o) {
32
- const fetchImpl = o.fetchImpl ?? fetch;
33
- const tokenPath = join(o.stateDir, "token.json");
109
+ const fetchImpl = o.fetchImpl ?? publicFetch;
110
+ const store = o.store ?? fileStore(join(o.stateDir, "token.json"));
34
111
  const clientPath = join(o.stateDir, "client.json");
35
112
  // The resource a token is for (RFC 8707): the MCP endpoint without its query (Atlassian's ?tools=all).
36
- const resourceOf = () => { if (o.resource === false)
113
+ // No address yet (a cleared setting): no resource, and the connection reads as not set up rather than failing.
114
+ const resourceOf = () => { if (o.resource === false || !URL.canParse(o.mcpUrl))
37
115
  return undefined; const u = new URL(o.mcpUrl); return u.origin + u.pathname; };
116
+ // The tenant a token is for: the extra headers sent with it (Grafana Cloud's x-grafana-url), hashed; none without any.
117
+ const tenantOf = () => (o.headers && Object.keys(o.headers).length ? createHash("sha256").update(JSON.stringify(Object.entries(o.headers).map(([k, v]) => [k.toLowerCase(), v]).sort())).digest("hex") : undefined);
118
+ // The saved token while it is bound to this connection's resource and tenant, exactly. A token saved before binding keeps
119
+ // working only where its identity is on record: every sign-in saved its resource, so it matches, and the connection picks no
120
+ // tenant. One saved without the tenant a connection now sends (Grafana Cloud's stack) can't be verified: Connect again.
121
+ let unbound = false;
122
+ const current = () => {
123
+ const t = store.read();
124
+ // No address (a cleared setting): nothing is connected, whatever is still on disk.
125
+ if (!t || !URL.canParse(o.mcpUrl))
126
+ return (unbound = false), undefined;
127
+ const resource = resourceOf();
128
+ unbound = Boolean((t.endpoint !== undefined && t.endpoint !== o.mcpUrl) || (resource && t.resource !== resource) || t.tenant !== tenantOf());
129
+ return unbound ? undefined : t;
130
+ };
131
+ /** What a saved token is bound to: written by a sign-in, never by a vendor's answer. */
132
+ const binding = () => { const resource = resourceOf(), tenant = tenantOf(); return { endpoint: o.mcpUrl, ...(resource ? { resource } : {}), ...(tenant ? { tenant } : {}) }; };
133
+ const BOUND = ["endpoint", "resource", "tenant", "issuer", "token_endpoint", "client_id", "client_secret"];
134
+ const strip = (x) => Object.fromEntries(Object.entries(x).filter(([k]) => !BOUND.includes(k)));
135
+ const changed = () => `${o.name}'s address changed since it was connected: Connect again`;
38
136
  const pending = new Map();
39
- let token;
40
137
  let refreshing;
41
- let status = { state: "unknown", since: new Date().toISOString() };
138
+ // A stored token that nothing has refused is signed in: "unknown" after every restart read as "Needs setup" on the board.
139
+ const usable = () => {
140
+ try {
141
+ const t = current();
142
+ return Boolean(t?.access_token) && (Boolean(t.refresh_token) || !t.expires_at || t.expires_at > Date.now());
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ };
148
+ let status = { state: usable() ? "ok" : "unknown", since: new Date().toISOString() };
149
+ // A completed sign-in, not a refresh: a caller holding a token from before can tell the two apart (proxy.ts, client.ts).
150
+ let signedInCount = 0;
151
+ // JSON asked for explicitly: GitHub's OAuth endpoints answer form-encoded otherwise.
152
+ // Never a redirect: a credential (a code, a refresh token, a client secret) must not follow one to another host.
42
153
  const json = async (url, init) => {
43
- const res = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(15_000) });
154
+ const res = await fetchImpl(url, { ...init, redirect: "error", headers: { accept: "application/json", ...init?.headers }, signal: AbortSignal.timeout(15_000) });
44
155
  return { ok: res.ok, status: res.status, body: (await res.json().catch(() => ({}))) };
45
156
  };
46
157
  /** A token answer as StoredToken fields; a refusal throws its error. */
@@ -60,42 +171,70 @@ export function oauth(o) {
60
171
  scope: typeof a.scope === "string" ? a.scope : undefined,
61
172
  };
62
173
  }
174
+ /** The vendor refuses the current token: true when `accepts` says so, or can't be asked (the old rule); a vendor that errors isn't a refusal. */
175
+ async function refused() {
176
+ if (!o.accepts)
177
+ return true;
178
+ try {
179
+ return !(await o.accepts(load().access_token));
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ }
185
+ // An expired mark is a claim about the token: while it stands, ask the vendor again, and a token that answers is signed in
186
+ // (no container restart). A reconnect marks ok itself.
187
+ let healer;
63
188
  function mark(state, detail) {
189
+ if (state === "ok" && healer) {
190
+ clearInterval(healer);
191
+ healer = undefined;
192
+ }
64
193
  if (status.state === state && status.detail === detail)
65
194
  return;
66
195
  status = { state, since: new Date().toISOString(), ...(detail ? { detail } : {}) };
67
- }
68
- function load() {
69
- if (!token) {
70
- if (!existsSync(tokenPath))
71
- throw new AuthError(`${o.name} isn't connected yet (Connect on the board)`);
72
- token = JSON.parse(readFileSync(tokenPath, "utf8"));
196
+ if (state === "expired" && o.accepts && !healer) {
197
+ // Only a confirmed answer heals: a timeout or a vendor 5xx (accepts throws) leaves the mark.
198
+ healer = setInterval(() => void Promise.resolve().then(() => o.accepts(load().access_token)).then((ok) => { if (ok && status.state === "expired")
199
+ mark("ok"); }, () => undefined), o.healMs ?? 30_000);
200
+ healer.unref?.();
73
201
  }
74
- return token;
75
202
  }
76
- function save(t) {
77
- const tmp = join(dirname(tokenPath), `.token.${process.pid}.tmp`);
78
- writeFileSync(tmp, JSON.stringify(t, null, 2), { mode: 0o600 });
79
- chmodSync(tmp, 0o600);
80
- renameSync(tmp, tokenPath);
81
- token = t;
203
+ function load() {
204
+ const t = current();
205
+ if (!t)
206
+ throw new AuthError(unbound ? changed() : `${o.name} isn't connected yet (Connect on the board)`);
207
+ return t;
82
208
  }
209
+ const save = (t) => store.write(t);
210
+ /** The token saved now (a new sign-in may have replaced the one a refresh started from). */
211
+ const token = () => current();
83
212
  async function doRefresh() {
84
213
  const t = load();
85
214
  const endpoint = t.token_endpoint ?? o.endpoints?.token;
86
215
  const clientId = t.client_id ?? o.client?.()?.id;
87
216
  if (!t.refresh_token || !endpoint || !clientId) {
88
- mark("expired", "the sign-in has no refresh token");
217
+ const gone = await refused();
218
+ if (token() !== t)
219
+ return token();
220
+ if (gone)
221
+ mark("expired", "the sign-in has no refresh token");
89
222
  throw new AuthError(`${o.name} token expired and can't be refreshed (Reconnect on the board)`);
90
223
  }
224
+ // A refresh token goes only to an https token endpoint (one saved before this check included).
225
+ if (!secure(endpoint))
226
+ throw new AuthError(`${o.name}'s saved token endpoint isn't https (Reconnect on the board)`);
91
227
  const body = new URLSearchParams({ grant_type: "refresh_token", refresh_token: t.refresh_token, client_id: clientId });
92
228
  const secret = t.client_secret ?? o.client?.()?.secret;
93
229
  if (secret)
94
230
  body.set("client_secret", secret);
95
231
  if (t.resource)
96
232
  body.set("resource", t.resource);
97
- const res = await fetchImpl(endpoint, { method: "POST", body, signal: AbortSignal.timeout(15_000) });
233
+ const res = await fetchImpl(endpoint, { method: "POST", body, redirect: "error", headers: { accept: "application/json" }, signal: AbortSignal.timeout(15_000) });
98
234
  const answer = (await res.json().catch(() => ({})));
235
+ // A reconnect saved a newer grant while this refresh was in flight: its answer, good or bad, is stale.
236
+ if (token() !== t)
237
+ return token();
99
238
  let next;
100
239
  try {
101
240
  if (!res.ok && typeof answer.error !== "string")
@@ -104,12 +243,21 @@ export function oauth(o) {
104
243
  }
105
244
  catch (err) {
106
245
  // A refusal (invalid_grant and the like) needs the owner; a 5xx is the vendor's problem and may pass.
107
- if (res.status < 500)
108
- mark("expired", String(err.message));
246
+ // A refused refresh on a token the vendor still answers (a rotated refresh token reused after a restart) is not an expiry.
247
+ if (res.status < 500) {
248
+ const gone = await refused();
249
+ // A reconnect saved a newer grant while the probe was in flight: its verdict is on the old token.
250
+ if (token() !== t)
251
+ return token();
252
+ if (gone)
253
+ mark("expired", String(err.message));
254
+ }
109
255
  throw err;
110
256
  }
111
- save({ ...t, ...next, refresh_token: next.refresh_token ?? t.refresh_token });
112
- return token;
257
+ // The answer updates the token, never what it is bound to or where the next refresh goes.
258
+ const fresh = Object.fromEntries(Object.entries(next).filter(([k]) => !BOUND.includes(k)));
259
+ save({ ...t, ...fresh, refresh_token: next.refresh_token ?? t.refresh_token, scope: next.scope ?? t.scope });
260
+ return token();
113
261
  }
114
262
  const refresh = () => (refreshing ??= doRefresh().finally(() => (refreshing = undefined)));
115
263
  /** The vendor's endpoints and the scopes it lists: the server's 401 names its resource metadata (the MCP way), else the well-known paths. */
@@ -121,17 +269,26 @@ export function oauth(o) {
121
269
  const path = mcp.pathname.replace(/\/$/, "");
122
270
  const probe = await fetchImpl(o.mcpUrl, {
123
271
  method: "POST",
272
+ redirect: "error",
124
273
  headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...o.headers },
125
274
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
126
275
  signal: AbortSignal.timeout(15_000),
127
276
  }).catch(() => undefined);
128
277
  const named = /resource_metadata="([^"]+)"/.exec(probe?.headers.get("www-authenticate") ?? "")?.[1];
278
+ if (named && !secure(named))
279
+ throw new SignInError(`${o.name}'s resource metadata isn't on https (${named.slice(0, 100)})`);
129
280
  let issuer = mcp.origin;
130
281
  let resourceScopes;
131
282
  for (const u of [...(named ? [named] : []), `${mcp.origin}/.well-known/oauth-protected-resource${path}`, `${mcp.origin}/.well-known/oauth-protected-resource`]) {
132
283
  const r = await json(u).catch(() => undefined);
133
284
  const servers = r?.ok ? strings(r.body.authorization_servers) : undefined;
134
285
  if (servers?.[0]) {
286
+ // The metadata is for this server: a resource on another origin would point its sign-in somewhere else.
287
+ const said = r.body.resource;
288
+ if (o.resource !== false && typeof said === "string" && (!URL.canParse(said) || new URL(said).origin !== mcp.origin))
289
+ throw new SignInError(`${o.name}'s resource metadata names another resource (${said.slice(0, 100)})`);
290
+ if (!secure(servers[0]))
291
+ throw new SignInError(`${o.name}'s sign-in server isn't on https (${servers[0].slice(0, 100)})`);
135
292
  issuer = servers[0].replace(/\/$/, "");
136
293
  resourceScopes = strings(r.body.scopes_supported);
137
294
  break;
@@ -142,6 +299,12 @@ export function oauth(o) {
142
299
  for (const u of [`${is.origin}/.well-known/oauth-authorization-server${isPath}`, `${is.origin}${isPath}/.well-known/openid-configuration`, `${is.origin}/.well-known/oauth-authorization-server`]) {
143
300
  const r = await json(u).catch(() => undefined);
144
301
  if (r?.ok && typeof r.body.authorization_endpoint === "string" && typeof r.body.token_endpoint === "string") {
302
+ // RFC 8414 §3.3: the metadata names the issuer it was asked for, and every endpoint takes the code or a token over https.
303
+ if (typeof r.body.issuer !== "string" || !sameIssuer(r.body.issuer, issuer))
304
+ throw new SignInError(`${o.name}'s sign-in server doesn't name its issuer ${issuer.slice(0, 100)} (it said ${String(r.body.issuer ?? "nothing").slice(0, 100)})`);
305
+ for (const e of [r.body.authorization_endpoint, r.body.token_endpoint, ...(r.body.registration_endpoint === undefined ? [] : [r.body.registration_endpoint])])
306
+ if (!secure(e))
307
+ throw new SignInError(`${o.name}'s sign-in endpoints must be https (got ${String(e).slice(0, 100)})`);
145
308
  const offered = strings(r.body.scopes_supported) ?? [];
146
309
  return {
147
310
  authorize: r.body.authorization_endpoint,
@@ -244,22 +407,106 @@ export function oauth(o) {
244
407
  catch (err) {
245
408
  throw new SignInError(`${o.name} refused the sign-in: ${String(err.message).slice(0, 200)}`);
246
409
  }
247
- save({ ...parsed, client_id: p.client.id, ...(p.client.secret ? { client_secret: p.client.secret } : {}), token_endpoint: p.ep.token, ...(resource ? { resource } : {}) });
410
+ save({ ...strip(parsed), client_id: p.client.id, ...(p.client.secret ? { client_secret: p.client.secret } : {}), token_endpoint: p.ep.token, issuer: p.ep.issuer, ...binding() });
411
+ signedInCount += 1;
248
412
  mark("ok");
249
413
  },
250
414
  };
415
+ // The device sign-in: one run at a time; its device_code never leaves this service.
416
+ const wait = o.wait ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
417
+ let run;
418
+ let runs = 0;
419
+ const vendorWords = (b) => String(b.error_description ?? b.error ?? "").slice(0, 200);
420
+ const device = o.device && {
421
+ async start(onSignedIn) {
422
+ const d = o.device;
423
+ if (!d.client_id)
424
+ throw new SignInError(`${o.name}'s sign-in isn't configured yet: it has no client ID`);
425
+ const ep = o.endpoints ? undefined : await discover();
426
+ const tokenUrl = o.endpoints?.token ?? ep.token;
427
+ const issuer = ep?.issuer ?? new URL(o.endpoints.authorize).origin;
428
+ const body = new URLSearchParams({ client_id: d.client_id, ...(d.scopes?.length ? { scope: d.scopes.join(o.scopes?.separator ?? " ") } : {}) });
429
+ const r = await json(d.endpoint, { method: "POST", body });
430
+ const b = r.body;
431
+ const uri = b.verification_uri ?? b.verification_url;
432
+ if (!r.ok || typeof b.device_code !== "string" || typeof b.user_code !== "string" || typeof uri !== "string")
433
+ throw new SignInError(`${o.name} refused to start the sign-in: ${vendorWords(b) || `it answered ${r.status}`}`);
434
+ const expiresIn = Number(b.expires_in) > 0 ? Number(b.expires_in) : 900;
435
+ const deviceCode = b.device_code;
436
+ const me = { id: ++runs, state: { state: "pending" } };
437
+ run = me;
438
+ const expires = Date.now() + expiresIn * 1000;
439
+ let interval = Number(b.interval) > 0 ? Number(b.interval) : 5;
440
+ const end = (state) => { if (run === me)
441
+ run.state = state; };
442
+ void (async () => {
443
+ while (run === me && me.state.state === "pending") {
444
+ await wait(interval * 1000);
445
+ if (run !== me || me.state.state !== "pending")
446
+ return;
447
+ if (Date.now() >= expires)
448
+ return end({ state: "expired", detail: "the code expired before it was entered" });
449
+ const p = await json(tokenUrl, { method: "POST", body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: deviceCode, client_id: d.client_id }) }).catch(() => undefined);
450
+ if (!p || p.status >= 500)
451
+ continue; // the vendor's hiccup: ask again
452
+ const err = typeof p.body.error === "string" ? p.body.error : "";
453
+ if (err === "authorization_pending")
454
+ continue;
455
+ if (err === "slow_down") {
456
+ interval += 5;
457
+ continue;
458
+ }
459
+ if (err === "expired_token")
460
+ return end({ state: "expired", detail: "the code expired before it was entered" });
461
+ if (err === "access_denied")
462
+ return end({ state: "denied", detail: `access was denied on ${o.name}'s page` });
463
+ try {
464
+ if (err || !p.ok)
465
+ throw new AuthError(vendorWords(p.body) || `${o.name} answered ${p.status}`);
466
+ const parsed = parse(p.body);
467
+ if (run !== me || me.state.state !== "pending")
468
+ return; // cancelled while the answer was on its way: nothing saved
469
+ save({ ...strip(parsed), client_id: d.client_id, token_endpoint: tokenUrl, issuer, ...binding() });
470
+ signedInCount += 1;
471
+ mark("ok");
472
+ end({ state: "ok" });
473
+ onSignedIn?.();
474
+ }
475
+ catch (e) {
476
+ return end({ state: "failed", detail: `${o.name} refused the sign-in: ${String(e.message).slice(0, 200)}` });
477
+ }
478
+ }
479
+ })();
480
+ return { user_code: b.user_code, verification_uri: uri, ...(typeof b.verification_uri_complete === "string" ? { verification_uri_complete: b.verification_uri_complete } : {}), expires_in: expiresIn, interval };
481
+ },
482
+ state: () => run?.state ?? { state: "idle" },
483
+ cancel() {
484
+ if (run?.state.state === "pending")
485
+ run.state = { state: "cancelled" };
486
+ },
487
+ };
251
488
  return {
252
489
  async headers() {
253
490
  const t = load();
254
- const access = !t.expires_at || t.expires_at - 120_000 > Date.now() ? t.access_token : (await refresh()).access_token;
491
+ let access = t.access_token;
492
+ if (t.expires_at && t.expires_at - 120_000 <= Date.now()) {
493
+ try {
494
+ access = (await refresh()).access_token;
495
+ }
496
+ catch (err) {
497
+ // A refused refresh is no reason to drop a token that has not run out and still answers.
498
+ if (status.state === "expired" || t.expires_at <= Date.now())
499
+ throw err;
500
+ }
501
+ }
255
502
  return { ...o.headers, authorization: `Bearer ${access}` };
256
503
  },
257
504
  async refresh() {
258
505
  await refresh();
259
506
  },
260
507
  status() {
261
- if (!existsSync(tokenPath))
262
- return { state: "missing", since: status.since };
508
+ if (!current())
509
+ return { state: "missing", since: status.since, ...(unbound ? { detail: changed() } : o.device && !o.device.client_id ? { detail: `${o.name}'s sign-in isn't configured yet: it has no client ID` } : {}) };
263
510
  const scope = (() => { try {
264
511
  return load().scope;
265
512
  }
@@ -269,7 +516,10 @@ export function oauth(o) {
269
516
  return { ...status, ...(scope ? { scope } : {}) };
270
517
  },
271
518
  mark,
272
- signedIn: () => existsSync(tokenPath),
519
+ ...(o.accepts ? { refused } : {}),
520
+ signedIn: () => Boolean(current()),
273
521
  signIn,
522
+ signInCount: () => signedInCount,
523
+ ...(device ? { device } : {}),
274
524
  };
275
525
  }
@@ -5,8 +5,12 @@ import type { Logger } from "pino";
5
5
  import { type Auth } from "./oauth.js";
6
6
  /** A connection's own logic, where it has any. */
7
7
  export interface Hooks {
8
- /** After each connect (Jira: find the configured site); a throw fails the connect. */
9
- connected?(client: Client, tools: Tool[]): Promise<void>;
8
+ /**
9
+ * After each connect (Jira: find the configured site); a throw fails the connect. It returns a commit function when its work
10
+ * publishes state other calls read (Jira's cloudId): the proxy runs it only if this connect becomes the session, so a connect a
11
+ * sign-in or reset superseded never writes its state over the winner's. Work that publishes nothing may return nothing.
12
+ */
13
+ connected?(client: Client, tools: Tool[]): Promise<void | (() => void)>;
10
14
  /** The tools as agents see them (a pinned argument dropped from the schema, a lead line in a description). */
11
15
  tools?(tools: Tool[]): Tool[];
12
16
  /**
@@ -16,12 +20,19 @@ export interface Hooks {
16
20
  args?(name: string, args: Record<string, unknown>, tool: Tool): Record<string, unknown>;
17
21
  /** Tools never listed or called (a real security rule; most connections have none). */
18
22
  deny?: RegExp;
19
- /** A tool's answer as it goes back (ClickHouse: cut to a size). */
20
- result?(result: CallToolResult): CallToolResult;
23
+ /** A tool's answer as it goes back (ClickHouse: cut to a size; Primer: the digest fenced as untrusted). */
24
+ result?(result: CallToolResult, name: string): CallToolResult;
21
25
  /** Whether the upstream says a tool only reads. Default: it marks it readOnlyHint. */
22
26
  isRead?(tool: Tool): boolean;
23
27
  /** A problem that makes the connection unusable though signed in (Jira: the site isn't reachable). */
24
28
  health?(): string | undefined;
29
+ /** More of the sign-in's state for the board (GitHub: scopes, per-org problems, the rate limit), merged into /auth/status. */
30
+ status?(): Record<string, unknown>;
31
+ /**
32
+ * Serves a call itself instead of this proxy's own session (Slack: one session per workspace, each its own proxy). Admission is
33
+ * done by then (bearer, caller, deny); the hook applies the read rule (`readOnly`) and answers every failure as a result.
34
+ */
35
+ call?(name: string, args: Record<string, unknown>, readOnly: boolean): Promise<CallToolResult>;
25
36
  }
26
37
  export interface ProxyOptions {
27
38
  /** The vendor's name in messages ("Glean"). */
@@ -46,12 +57,26 @@ export interface ProxyOptions {
46
57
  callTimeoutMs?: number;
47
58
  /** Remembers the tool list here (tools.json), for stand-ins while not connected. */
48
59
  stateDir?: string;
60
+ /**
61
+ * How long a call waits on a connect another call (or a reset) started before it opens a session of its own; default 20 s, the
62
+ * board's budget for one handshake. Without the bound, one stalled handshake would hold up every call after it.
63
+ */
64
+ resetWaitMs?: number;
49
65
  hooks?: Hooks;
50
66
  /** More routes on the same port (a write kind's executor); true when it answered. */
51
67
  routes?(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
52
68
  }
53
69
  export type VendorProxy = HttpServer & {
54
- /** One tool call from this service's own code (a warehouse sync, an executor), through the same sign-in and hooks. */
55
- call(name: string, args: Record<string, unknown>): Promise<CallToolResult>;
70
+ /** One tool call from this service's own code (a warehouse sync, an executor), through the same sign-in and hooks; `readOnly`: the read endpoint's rule. */
71
+ call(name: string, args: Record<string, unknown>, readOnly?: boolean): Promise<CallToolResult>;
72
+ /** A new sign-in saved elsewhere (another proxy's Connect): the session opened with the old one is retired. */
73
+ signedIn(): Promise<void>;
74
+ /** The tools this proxy's current session advertises (the connection's view applied); undefined when it couldn't list them. */
75
+ list(): Promise<Tool[] | undefined>;
76
+ /**
77
+ * Drops the session without opening another: the sign-out whose grant is already gone, or a check that failed, so the next call
78
+ * (or Connect) opens a session from the sign-in that is there now. Nothing waits on an upstream handshake.
79
+ */
80
+ forget(): void;
56
81
  };
57
82
  export declare function createVendorProxy(o: ProxyOptions): VendorProxy;