@superforge/infra 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,9 +5,10 @@ runs on, as an app's server calls it: login for its people, its comments
5
5
  from the toolbar, Claude's login to its MCP, and which project its key is
6
6
  for. It's the one way an app reaches Infra: a typed client, the stand-in
7
7
  an app's tests and a fresh dev server use in its place, and the choice
8
- between them. Infra's own API, each call with its fields and errors, is
9
- its README in superforge's `source/infra/`, which the Superforge MCP's
10
- `read_infra_docs` hands an agent.
8
+ between them. Infra's own API reference, each call with its fields and
9
+ errors, isn't public: an agent reads it with the Superforge MCP's
10
+ `read_infra_docs`. Everything an app calls is below, and every request and
11
+ answer is a zod schema in `@superforge/infra/contract`.
11
12
 
12
13
  ```bash
13
14
  pnpm add @superforge/infra zod
@@ -29,14 +30,14 @@ const { infra } = chooseInfra({
29
30
  environment: process.env,
30
31
  checkout: process.cwd(),
31
32
  // The website's hosts, which the stand-in's project has
32
- domains: ["vmdsystem.com"]
33
+ domains: ["example.com"]
33
34
  })
34
35
 
35
36
  const started = await infra.startLogin({
36
37
  channel: "email",
37
38
  address: "ada@example.com",
38
39
  ip: visitor_ip,
39
- link_to: "https://vmdsystem.com/login"
40
+ link_to: "https://example.com/login"
40
41
  })
41
42
  if (!started.ok) {
42
43
  console.warn("Login didn't start", started.error)
@@ -67,14 +68,87 @@ while Infra itself is worked on: a build always calls Infra's own
67
68
  address, so no variable can send its secret key, or anyone's login,
68
69
  anywhere else.
69
70
 
71
+ A dev server that has `INFRA_SECRET_KEY`, or runs on Railway
72
+ (`RAILWAY_DEPLOYMENT_ID`), calls nothing either: it's a deployed server
73
+ built as a dev one, and the stand-in would show anyone the code.
74
+
75
+ `chooseInfra` takes `development`, `environment` (`process.env`),
76
+ `checkout` (the folder whose `.env` a dev server reads), `domains` (the
77
+ stand-in project's) and `paths`, and answers `{ infra, using }`, `using`
78
+ being `"secret key"`, `"test key"`, `"stand-in"` or `"nothing"`.
79
+
80
+ ### What `Infra` answers
81
+
82
+ Every method answers a result; every refusal but `unavailable` and
83
+ `invalid-token` is Infra's own, as its contract types it.
84
+
85
+ | Method | Answers | Refuses with |
86
+ | ------------------------------------------------------ | --------------------------------------------------------------------------------------- | ------------------------------------------------- |
87
+ | `project()` | the key's project, its mode and its domains | `unavailable` |
88
+ | `startLogin({ channel, address, ip, link_to? })` | the address, `with_link`, `expires_at`, and `test` (the code and link, with a test key) | `rate-limited`, `not-sent`, `unavailable` |
89
+ | `verifyLogin({ channel, address, code } \| { token })` | whose address it was | `wrong-code`, `no-code`, `no-link`, `unavailable` |
90
+ | `fileComment(comment)` | the comment's `id` and `created_at` | `invalid`, `too-large`, `unavailable` |
91
+ | `passOAuth(request, call, origin)` | the `Response` for one of Claude's OAuth calls | (a `Response`: OAuth's own errors) |
92
+ | `agentRequest(request_id)` | what the Allow page shows | `not-found`, `unavailable` |
93
+ | `allowAgent(request_id, { user_id, scopes })` | `{ redirect_to }`, back to Claude | `not-found`, `not-asked`, `unavailable` |
94
+ | `denyAgent(request_id)` | `{ redirect_to }`, back to Claude | `not-found`, `unavailable` |
95
+ | `agentConnections(user_id)` | their connections, oldest first | `unavailable` |
96
+ | `endAgentConnection(connection_id)` | `null` | `not-found`, `unavailable` |
97
+ | `endAgentConnections(user_id)` | how many it ended | `unavailable` |
98
+ | `checkAgentToken(token, { origin, resource })` | `{ user_id, scopes, connection_id }` | `invalid-token`, `unavailable` |
99
+
100
+ A request or connection ID that isn't Infra's shape (letters, digits, `_`
101
+ and `-`, at most 128) is refused `not-found` before any call, so a route
102
+ that passes on what it was sent can't reach another of Infra's addresses.
103
+
104
+ ### Claude's login
105
+
106
+ - **`requestOrigin(request.url)`**: where a request reached the app,
107
+ `https://<host>`, or `http://<host>` on this computer
108
+ (`LOOPBACK_HOSTNAMES` and names under `localhost`). Every token is
109
+ bound to it, as its issuer; give it to `passOAuth` and
110
+ `checkAgentToken`.
111
+ - **`passOAuth`** answers `metadata`, `authorize`, `token`, `register` and
112
+ `revoke`. A body over 16 KB is refused 413, never sent on.
113
+ - **`checkAgentToken`** checks the token with Infra's public keys, fetched
114
+ and cached, with no call to Infra while they're fresh. A token that's
115
+ run out, for another address, app, project or mode, or not Infra's is
116
+ `invalid-token`, with why in `message`; the app answers it 401. Infra's
117
+ keys out of reach is `unavailable`, so the app answers 503 and Claude
118
+ tries again rather than logging in again.
119
+ - **`APP_PATHS`** (`{ oauth: "/oauth", allow: "/connect" }`) is where the
120
+ app answers Claude's login; an app that keeps it elsewhere gives
121
+ `chooseInfra` its own `paths`.
122
+ - **`oauthMetadata`** is the server's metadata, which `passOAuth`
123
+ answers `metadata` with.
124
+
125
+ ### `infraClient`
126
+
127
+ `infraClient({ key, url?, send?, paths? })` is the real Infra, which
128
+ `chooseInfra` makes; an app calls it itself only to point a test at a fake
129
+ of Infra (`send` is `fetch`, or the test's own; `url` is `INFRA_URL`,
130
+ Infra's address, unless set).
131
+
70
132
  ### The stand-in, for tests
71
133
 
72
- `standInInfra()` is Infra's test mode in memory: login sends nothing and
73
- answers the code and the link, which verify as Infra's do (once each, for
74
- 15 minutes, a code for five tries); a comment is checked as Infra checks
75
- it and kept nowhere; Claude logs in to nothing, and `checkAgentToken` takes
76
- only the tokens `standInAgentToken()` mints. An app's tests use it, so they
77
- never reach Infra.
134
+ `standInInfra({ waiting?, logs?, domains? })` is Infra's test mode in
135
+ memory: login sends nothing and answers the code and the link, which
136
+ verify as Infra's do (once each, for 15 minutes, a code for five tries),
137
+ and links, as Infra's do, only to this computer and the project's
138
+ `domains`, over https; any other host gets `with_link: false`. A comment
139
+ is checked as Infra checks it and kept nowhere; Claude logs in to nothing,
140
+ and `checkAgentToken` takes only the tokens `standInAgentToken()` mints:
141
+ `standInAgentToken({ user_id, resource, scopes?, origin?, expires_in? })`,
142
+ `origin` being `http://localhost` and `expires_in` `"10m"` unless set. An
143
+ app's tests use it, so they never reach Infra.
144
+
145
+ ### The contract
146
+
147
+ `@superforge/infra/contract`, also exported from the package itself, is
148
+ Infra's contract with nothing of Node's, so a page can import it: every
149
+ call's request and answer as zod schemas (`login_start`, `started_login`,
150
+ `agent_request`…), the types made from them, and every reason a call is
151
+ refused, Infra's (`INFRA_ERRORS`) and the package's own (`CLIENT_ERRORS`).
78
152
 
79
153
  ## When something goes wrong
80
154
 
@@ -82,7 +156,7 @@ Every refusal is Infra's own `error`, as it answered it, in the shape a
82
156
  template's API answers too: `reason`, for code to branch on, `message`,
83
157
  what went wrong and what fixes it in plain words, and any fields the call
84
158
  adds, like `retry_after`. Infra's contract has every reason
85
- (`INFRA_ERRORS`). When the package couldn't ask Infra, it says why in
159
+ (`INFRA_ERRORS`, and the package's own, `CLIENT_ERRORS`). When the package couldn't ask Infra, it says why in
86
160
  the same shape:
87
161
 
88
162
  ```ts
@@ -125,18 +199,14 @@ dependency (Dependabot opens a PR a month), never by copying code.
125
199
 
126
200
  CI signs in to npm with trusted publishing: npm trusts this repository's
127
201
  `ci.yml` to publish the package (the package's settings on npmjs.com,
128
- "Trusted publisher"), so no npm token is kept anywhere. npm only lets a
129
- package that exists trust a workflow, so the package was made by hand
130
- first: a staged 0.1.0 from a checkout signed in with `npm login`, which
131
- was never approved, since 0.1.1 replaced it. 0.1.1 was the first CI
132
- published.
133
-
134
- From v1 on, Infra keeps answering every version apps are on, the way
135
- Stripe does: one implementation, of the latest contract, and an adapter
136
- for each breaking change, which turns an older client's request into
137
- today's and today's answer back into the one it knows, by the version in
138
- `Infra-Client`. Until v1, Infra keeps none: an app takes the latest
139
- release.
202
+ "Trusted publisher"), so no npm token is kept anywhere. A PR's
203
+ `release-version` check refuses one whose version isn't the one right
204
+ after `main`'s, with its line in `CHANGELOG.md`.
205
+
206
+ Infra changes its API additively: it adds fields and calls, and never
207
+ renames or drops one an app's release calls, so a release keeps working
208
+ until the app takes the next. Until 1.0.0 it keeps no older shapes: an app
209
+ takes the latest release.
140
210
 
141
211
  ## Working on it
142
212
 
@@ -1,10 +1,10 @@
1
1
  import { type JWTVerifyGetKey } from "jose";
2
2
  import { type AppPaths, type KeyMode, type OAuthCall } from "./contract/index.js";
3
- import type { AgentToken } from "./infra.js";
3
+ import type { AgentToken, AgentTokenRefused, InfraUnavailable } from "./infra.js";
4
4
  import type { AsyncOperationResult } from "./results.js";
5
5
  /**
6
- * Where a request reached the app: `https://vmdsystem.com`, or plain http
7
- * on this computer, as a dev server is. Behind Railway's proxy a request's
6
+ * Where a request reached the app: `https://example.com`, or plain http
7
+ * on this computer (`LOOPBACK_HOSTNAMES`), as a dev server is. Behind Railway's proxy a request's
8
8
  * own address says http though the browser's said https, so only the host
9
9
  * counts. Every token Claude holds is bound to it, as its issuer.
10
10
  */
@@ -36,6 +36,12 @@ export declare function oauthMetadata({ origin, paths, infra_url }: {
36
36
  client_id_metadata_document_supported: boolean;
37
37
  authorization_response_iss_parameter_supported: boolean;
38
38
  };
39
+ /**
40
+ * The most bytes a body Claude sends to the token, register and revoke
41
+ * calls may be: each is a few hundred, and they're the app's only calls
42
+ * that take a body from anyone, unauthenticated, and send it on to Infra
43
+ */
44
+ export declare const OAUTH_BODY_LIMIT: number;
39
45
  /**
40
46
  * Answers one of Claude's OAuth calls to the app (`call`), its request
41
47
  * unread:
@@ -62,8 +68,11 @@ export declare function passOAuth({ url, key, send, paths, request, call, origin
62
68
  * looping: why, as `error_description`, which Claude shows
63
69
  */
64
70
  export declare function unavailableOAuth(message: string): Response;
65
- /** Where a token's signature is checked: Infra's published public keys */
66
- export declare function infraKeys(url: string): JWTVerifyGetKey;
71
+ /**
72
+ * Where a token's signature is checked: Infra's published public keys,
73
+ * fetched with `send`
74
+ */
75
+ export declare function infraKeys(url: string, send?: typeof fetch): JWTVerifyGetKey;
67
76
  /**
68
77
  * Checks a token Claude brings, as Infra's README says to: Infra signed
69
78
  * it, for this app's `origin`, for `resource`, the address it was brought
@@ -74,4 +83,4 @@ export declare function checkToken(keys: JWTVerifyGetKey, token: string, expecte
74
83
  resource: string;
75
84
  project: string;
76
85
  mode: KeyMode;
77
- }): AsyncOperationResult<AgentToken, "invalid-token">;
86
+ }): AsyncOperationResult<AgentToken, AgentTokenRefused | InfraUnavailable>;
package/output/agents.js CHANGED
@@ -1,6 +1,6 @@
1
- import { createRemoteJWKSet, jwtVerify } from "jose";
2
- import { AGENT_SCOPES, APP_ORIGIN_HEADER, agent_authorized, agent_claims, authorize_refused, CLIENT_HEADER, infra_failure } from "./contract/index.js";
3
- import { SECOND } from "./primitives.js";
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from "jose";
2
+ import { AGENT_SCOPES, APP_ORIGIN_HEADER, agent_authorized, agent_claims, authorize_refused, CLIENT_HEADER, infra_failure, isLoopbackHost } from "./contract/index.js";
3
+ import { CALL_TIMEOUT, SECOND } from "./primitives.js";
4
4
  import { CLIENT } from "./version.js";
5
5
  // Claude logging in to an app's own MCP, through Infra: Infra is the OAuth
6
6
  // server, and the app only checks the tokens it signs, with Infra's public
@@ -8,16 +8,14 @@ import { CLIENT } from "./version.js";
8
8
  // the client does: where the app was reached, the server's metadata, the
9
9
  // OAuth calls Claude makes, passed on to Infra, and checking a token.
10
10
  /**
11
- * Where a request reached the app: `https://vmdsystem.com`, or plain http
12
- * on this computer, as a dev server is. Behind Railway's proxy a request's
11
+ * Where a request reached the app: `https://example.com`, or plain http
12
+ * on this computer (`LOOPBACK_HOSTNAMES`), as a dev server is. Behind Railway's proxy a request's
13
13
  * own address says http though the browser's said https, so only the host
14
14
  * counts. Every token Claude holds is bound to it, as its issuer.
15
15
  */
16
16
  export function requestOrigin(request_url) {
17
17
  const { host, hostname } = new URL(request_url);
18
- const local = ["localhost", "127.0.0.1", "[::1]"].includes(hostname) ||
19
- hostname.endsWith(".localhost");
20
- return local ? `http://${host}` : `https://${host}`;
18
+ return isLoopbackHost(hostname) ? `http://${host}` : `https://${host}`;
21
19
  }
22
20
  /**
23
21
  * The OAuth server's metadata (RFC 8414), which Claude reads at the app's
@@ -49,6 +47,12 @@ export function oauthMetadata({ origin, paths, infra_url }) {
49
47
  // What a call passed on may carry, of the request Claude or the browser
50
48
  // sent: what the body is, and what Claude accepts back
51
49
  const PASSED_HEADERS = ["accept", "content-type"];
50
+ /**
51
+ * The most bytes a body Claude sends to the token, register and revoke
52
+ * calls may be: each is a few hundred, and they're the app's only calls
53
+ * that take a body from anyone, unauthenticated, and send it on to Infra
54
+ */
55
+ export const OAUTH_BODY_LIMIT = 16 * 1024;
52
56
  /**
53
57
  * Answers one of Claude's OAuth calls to the app (`call`), its request
54
58
  * unread:
@@ -78,9 +82,18 @@ export async function passOAuth({ url, key, send, paths, request, call, origin }
78
82
  headers.set(name, value);
79
83
  }
80
84
  }
81
- const body = request.method === "GET" || request.method === "HEAD"
82
- ? undefined
83
- : await request.text();
85
+ let body;
86
+ if (request.method !== "GET" && request.method !== "HEAD") {
87
+ const read = await limitedText(request, OAUTH_BODY_LIMIT);
88
+ if (read === null) {
89
+ console.warn("Claude's OAuth call is over its limit", { call });
90
+ return Response.json({
91
+ error: "invalid_request",
92
+ error_description: `This call's body is over ${OAUTH_BODY_LIMIT} bytes, the most it takes.`
93
+ }, { status: 413, headers: { "Cache-Control": "no-store" } });
94
+ }
95
+ body = read;
96
+ }
84
97
  const path = `/agents/oauth/${call}`;
85
98
  let answer;
86
99
  try {
@@ -89,7 +102,7 @@ export async function passOAuth({ url, key, send, paths, request, call, origin }
89
102
  headers,
90
103
  body,
91
104
  redirect: "manual",
92
- signal: AbortSignal.timeout(15 * SECOND)
105
+ signal: AbortSignal.timeout(CALL_TIMEOUT)
93
106
  });
94
107
  }
95
108
  catch (error) {
@@ -121,7 +134,7 @@ async function authorized(answer, origin, paths) {
121
134
  return null;
122
135
  });
123
136
  const made = agent_authorized.safeParse(json);
124
- if (answer.status === 200 && made.success) {
137
+ if (answer.status >= 200 && answer.status < 300 && made.success) {
125
138
  const to = "request" in made.data
126
139
  ? `${origin}${paths.allow}/${made.data.request.id}`
127
140
  : made.data.redirect_to;
@@ -152,6 +165,42 @@ async function authorized(answer, origin, paths) {
152
165
  ? failed.data.error.message
153
166
  : `Infra answered Claude's authorize request with ${answer.status}, in a shape this version of @superforge/infra can't read.`);
154
167
  }
168
+ /**
169
+ * A request's body as text, or null once it's over `limit` bytes: by its
170
+ * `Content-Length` when it says one, then while it's read, so a body that
171
+ * lies about its length is stopped too, and never held whole
172
+ */
173
+ async function limitedText(request, limit) {
174
+ const length = Number(request.headers.get("content-length") ?? "0");
175
+ if (length > limit) {
176
+ return null;
177
+ }
178
+ if (request.body === null) {
179
+ return "";
180
+ }
181
+ const reader = request.body.getReader();
182
+ const chunks = [];
183
+ let size = 0;
184
+ for (;;) {
185
+ const { done, value } = await reader.read();
186
+ if (done) {
187
+ break;
188
+ }
189
+ size += value.byteLength;
190
+ if (size > limit) {
191
+ await reader.cancel();
192
+ return null;
193
+ }
194
+ chunks.push(value);
195
+ }
196
+ const whole = new Uint8Array(size);
197
+ let at = 0;
198
+ for (const chunk of chunks) {
199
+ whole.set(chunk, at);
200
+ at += chunk.byteLength;
201
+ }
202
+ return new TextDecoder().decode(whole);
203
+ }
155
204
  /**
156
205
  * What one of Claude's OAuth calls answers when Infra can't be asked, as
157
206
  * RFC 6749 has it, so Claude says why login isn't working rather than
@@ -160,10 +209,20 @@ async function authorized(answer, origin, paths) {
160
209
  export function unavailableOAuth(message) {
161
210
  return Response.json({ error: "temporarily_unavailable", error_description: message }, { status: 503, headers: { "Cache-Control": "no-store" } });
162
211
  }
163
- /** Where a token's signature is checked: Infra's published public keys */
164
- export function infraKeys(url) {
165
- return createRemoteJWKSet(new URL("/.well-known/jwks.json", new URL(url).origin), { timeoutDuration: 10 * SECOND, cooldownDuration: 30 * SECOND });
212
+ /**
213
+ * Where a token's signature is checked: Infra's published public keys,
214
+ * fetched with `send`
215
+ */
216
+ export function infraKeys(url, send = fetch) {
217
+ return createRemoteJWKSet(new URL("/.well-known/jwks.json", new URL(url).origin), {
218
+ timeoutDuration: 10 * SECOND,
219
+ cooldownDuration: 30 * SECOND,
220
+ [customFetch]: send
221
+ });
166
222
  }
223
+ // How much a token's times may be off, for an app server whose clock is a
224
+ // few seconds from Infra's
225
+ const CLOCK_TOLERANCE_SECONDS = 5;
167
226
  /**
168
227
  * Checks a token Claude brings, as Infra's README says to: Infra signed
169
228
  * it, for this app's `origin`, for `resource`, the address it was brought
@@ -174,7 +233,10 @@ export async function checkToken(keys, token, expected) {
174
233
  const { payload } = await jwtVerify(token, keys, {
175
234
  issuer: expected.origin,
176
235
  audience: expected.resource,
177
- algorithms: ["ES256"]
236
+ algorithms: ["ES256"],
237
+ typ: "at+jwt",
238
+ requiredClaims: ["exp"],
239
+ clockTolerance: CLOCK_TOLERANCE_SECONDS
178
240
  });
179
241
  const claims = agent_claims.safeParse(payload);
180
242
  if (!claims.success ||
@@ -183,7 +245,7 @@ export async function checkToken(keys, token, expected) {
183
245
  console.warn("Agent token not for this app", {
184
246
  origin: expected.origin
185
247
  });
186
- return { ok: false, error: "invalid-token" };
248
+ return invalidToken("Claude's token is for another project or key mode than this app's key, so it can't be used here. Claude logs in again.");
187
249
  }
188
250
  else {
189
251
  const said = claims.data.scope.split(" ");
@@ -198,7 +260,56 @@ export async function checkToken(keys, token, expected) {
198
260
  }
199
261
  }
200
262
  catch (error) {
263
+ if (keySetFailed(error)) {
264
+ console.error("Infra's public keys couldn't be fetched", {
265
+ origin: expected.origin,
266
+ error
267
+ });
268
+ return {
269
+ ok: false,
270
+ error: {
271
+ reason: "unavailable",
272
+ message: "Infra's public keys couldn't be fetched, so Claude's token can't be checked. Infra may be down; trying again in a few minutes may work."
273
+ }
274
+ };
275
+ }
201
276
  console.info("Agent token refused", { origin: expected.origin, error });
202
- return { ok: false, error: "invalid-token" };
277
+ return invalidToken(whyRefused(error));
278
+ }
279
+ }
280
+ function invalidToken(message) {
281
+ return { ok: false, error: { reason: "invalid-token", message } };
282
+ }
283
+ // Whether checking a token failed on fetching Infra's keys, rather than on
284
+ // the token: a timeout, no answer, an answer that isn't 200, or one that
285
+ // isn't a key set. Infra being down then isn't the token's fault.
286
+ function keySetFailed(error) {
287
+ return (error instanceof errors.JWKSTimeout ||
288
+ error instanceof errors.JWKSInvalid ||
289
+ error instanceof TypeError ||
290
+ (error instanceof DOMException && error.name === "AbortError") ||
291
+ (error instanceof errors.JOSEError &&
292
+ error.code === "ERR_JOSE_GENERIC" &&
293
+ (error.message.startsWith("Expected 200 OK") ||
294
+ error.message.startsWith("Failed to parse the JSON Web Key Set"))));
295
+ }
296
+ // Why a token was refused, in words, by what jose found
297
+ function whyRefused(error) {
298
+ if (error instanceof errors.JWTExpired) {
299
+ return "Claude's token has run out. Claude refreshes it, or logs in again.";
300
+ }
301
+ else if (error instanceof errors.JWTClaimValidationFailed) {
302
+ if (error.claim === "aud") {
303
+ return "Claude's token is for another address than the one it was brought to.";
304
+ }
305
+ else if (error.claim === "iss") {
306
+ return "Claude's token was made for another app, or for this app at another address.";
307
+ }
308
+ else {
309
+ return `Claude's token's ${error.claim} claim isn't what Infra signs.`;
310
+ }
311
+ }
312
+ else {
313
+ return "Claude's token isn't one Infra signed. Claude logs in again.";
203
314
  }
204
315
  }
package/output/choose.js CHANGED
@@ -4,7 +4,7 @@ import { parseEnv } from "node:util";
4
4
  import { z } from "zod";
5
5
  import { unavailableOAuth } from "./agents.js";
6
6
  import { INFRA_URL, infraClient } from "./client.js";
7
- import { APP_PATHS } from "./contract/index.js";
7
+ import { APP_PATHS, KEY_BODY, KEY_PREFIXES } from "./contract/index.js";
8
8
  import { standInInfra } from "./stand-in.js";
9
9
  // Which Infra the server calls, by what it runs as and the keys it has:
10
10
  //
@@ -20,9 +20,17 @@ import { standInInfra } from "./stand-in.js";
20
20
  // takes a secret key, so it can't email real people. An app's tests use
21
21
  // the stand-in themselves. When there's nothing to call, every call
22
22
  // answers unavailable with why, which an app shows its team.
23
- // A key's shape: its prefix, then 32 letters and digits
24
- const SECRET_KEY = /^sf_secret_[0-9A-Za-z]{32}$/;
25
- const TEST_KEY = /^sf_test_[0-9A-Za-z]{32}$/;
23
+ //
24
+ // A dev server that has a secret key, or runs on Railway, calls nothing
25
+ // either: it's a deployed server built as a dev one (NODE_ENV=development
26
+ // on its service), and the stand-in would show anyone the code to log in
27
+ // as anyone.
28
+ // A key's shape: its prefix, then what Infra makes (KEY_BODY)
29
+ const SECRET_KEY = new RegExp(`^${KEY_PREFIXES.live}${KEY_BODY}$`);
30
+ const TEST_KEY = new RegExp(`^${KEY_PREFIXES.test}${KEY_BODY}$`);
31
+ // What Railway sets on a deployment alone, never in a checkout (`railway
32
+ // run` brings a service's variables, not this)
33
+ const DEPLOYED_MARKERS = ["RAILWAY_DEPLOYMENT_ID"];
26
34
  // What the server reads to reach Infra, by the variables' names: the
27
35
  // secret key Railway holds, and a checkout's test key. A dev server reads
28
36
  // them from the checkout's `.env` too (`checkoutVariables`), under whatever
@@ -69,6 +77,12 @@ export function chooseInfra({ development, environment, checkout, domains = [],
69
77
  return { infra: unavailableInfra(message), using: "nothing" };
70
78
  }
71
79
  }
80
+ const deployed = DEPLOYED_MARKERS.find((name) => (environment[name] ?? "").trim() !== "");
81
+ if (INFRA_SECRET_KEY !== undefined || deployed !== undefined) {
82
+ const message = `No one can log in: this server runs as a dev server, though ${deployed === undefined ? "it has INFRA_SECRET_KEY" : `it's deployed (${deployed} is set)`}, so it won't use the stand-in, which shows anyone the code. A deployed app is built for production: take NODE_ENV=development off the app's service in Railway. On this computer, take INFRA_SECRET_KEY out of the checkout's .env and the shell, and use INFRA_TEST_KEY.`;
83
+ console.error("Login is down", { message });
84
+ return { infra: unavailableInfra(message), using: "nothing" };
85
+ }
72
86
  // Without a slash at the end, since each call's path starts with one
73
87
  const url = (parsed.data.INFRA_URL ?? INFRA_URL).replace(/\/+$/, "");
74
88
  const test_key = parsed.data.INFRA_TEST_KEY;
@@ -179,7 +193,7 @@ function noSecretKey(set) {
179
193
  return `No one can log in: INFRA_SECRET_KEY holds a test key (sf_test_…), which never emails anyone, so a deployed app can't use it. ${fix}`;
180
194
  }
181
195
  else {
182
- return `No one can log in: INFRA_SECRET_KEY isn't a secret key (sf_secret_ and 32 letters and digits), so something may be missing from it or added to it. ${fix}`;
196
+ return `No one can log in: INFRA_SECRET_KEY isn't a secret key (sf_secret_ and 32 or more letters and digits), so something may be missing from it or added to it. ${fix}`;
183
197
  }
184
198
  }
185
199
  // Infra when it can't be reached at all: every call answers unavailable,
package/output/client.js CHANGED
@@ -1,12 +1,9 @@
1
1
  import { checkToken, infraKeys, passOAuth } from "./agents.js";
2
- import { APP_PATHS, agent_connections, agent_ended, agent_redirect, agent_refused, agent_request, CLIENT_HEADER, comment_refused, infra_failure, infra_project, kept_comment, start_refused, started_login, verified_login, verify_refused } from "./contract/index.js";
3
- import { SECOND } from "./primitives.js";
2
+ import { AGENT_ID, APP_PATHS, agent_connections, agent_ended, agent_redirect, agent_refused, agent_request, CLIENT_HEADER, comment_refused, infra_failure, infra_project, kept_comment, start_refused, started_login, verified_login, verify_refused } from "./contract/index.js";
3
+ import { CALL_TIMEOUT } from "./primitives.js";
4
4
  import { CLIENT } from "./version.js";
5
5
  /** Infra's API, which a project's keys call */
6
6
  export const INFRA_URL = "https://infra.superforge.studio/v1";
7
- // How long a call waits for Infra's answer. Starting a login waits on
8
- // Infra sending the email, which takes a second or two.
9
- const TIMEOUT = 15 * SECOND;
10
7
  /**
11
8
  * Infra, called over HTTP with a project's key: a secret key in a build, a
12
9
  * test key in a dev server. No call is retried, since none is safe to send
@@ -35,7 +32,7 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
35
32
  method,
36
33
  headers,
37
34
  body: body === undefined ? undefined : JSON.stringify(body),
38
- signal: AbortSignal.timeout(TIMEOUT)
35
+ signal: AbortSignal.timeout(CALL_TIMEOUT)
39
36
  }).catch((error) => {
40
37
  console.error("Infra didn't answer", { call, url, error });
41
38
  return null;
@@ -68,16 +65,16 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
68
65
  }
69
66
  return { ok: true, data: { status: response.status, json } };
70
67
  }
71
- // An answer read with `schema` when it's `status`, else as one of the
72
- // call's `refused`, else as one the client can't act on: unavailable,
73
- // in Infra's own words
68
+ // An answer read with `schema` when it's a success (any 2xx, so Infra
69
+ // can say 200 or 201 as it likes), else as one of the call's `refused`,
70
+ // else as one the client can't act on: unavailable, in Infra's own words
74
71
  async function answered(asked, call, expected, refused) {
75
72
  const answer = await asked;
76
73
  if (!answer.ok) {
77
74
  return answer;
78
75
  }
79
76
  const { status, json } = answer.data;
80
- if (status === expected.status) {
77
+ if (status >= 200 && status < 300) {
81
78
  const parsed = expected.schema.safeParse(json);
82
79
  return parsed.success
83
80
  ? { ok: true, data: parsed.data }
@@ -94,12 +91,11 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
94
91
  // Claude's login (agents.ts): Infra's public keys, fetched once and
95
92
  // again for a key they don't have, and which project and mode the key
96
93
  // is, which every token must be for, asked once
97
- const keys = infraKeys(url);
94
+ const keys = infraKeys(url, send);
98
95
  let project;
99
96
  function projectOf() {
100
97
  const call = "/project";
101
98
  return answered(ask("GET", call), call, {
102
- status: 200,
103
99
  schema: infra_project
104
100
  });
105
101
  }
@@ -109,15 +105,15 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
109
105
  },
110
106
  startLogin(request) {
111
107
  const call = "/login/start";
112
- return answered(ask("POST", call, request), call, { status: 200, schema: started_login }, start_refused);
108
+ return answered(ask("POST", call, request), call, { schema: started_login }, start_refused);
113
109
  },
114
110
  verifyLogin(proof) {
115
111
  const call = "/login/verify";
116
- return answered(ask("POST", call, proof), call, { status: 200, schema: verified_login }, verify_refused);
112
+ return answered(ask("POST", call, proof), call, { schema: verified_login }, verify_refused);
117
113
  },
118
114
  async fileComment(comment) {
119
115
  const call = "/board/comments";
120
- const filed = await answered(ask("POST", call, comment), call, { status: 201, schema: kept_comment }, comment_refused);
116
+ const filed = await answered(ask("POST", call, comment), call, { schema: kept_comment }, comment_refused);
121
117
  if (!filed.ok && filed.error.reason !== "unavailable") {
122
118
  // What the app sent is wrong, which only a change to it
123
119
  // fixes
@@ -132,22 +128,30 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
132
128
  return passOAuth({ url, key, send, paths, request, call, origin });
133
129
  },
134
130
  async agentRequest(request_id) {
135
- const call = `/agents/requests/${request_id}`;
136
- const asked = await answered(ask("GET", call), call, { status: 200, schema: agent_request }, agent_refused);
131
+ if (!AGENT_ID.test(request_id)) {
132
+ return notAnId("request", request_id);
133
+ }
134
+ const call = `/agents/requests/${encodeURIComponent(request_id)}`;
135
+ const asked = await answered(ask("GET", call), call, { schema: agent_request }, agent_refused);
137
136
  return asked.ok ? { ok: true, data: asked.data.request } : asked;
138
137
  },
139
- allowAgent(request_id, allowed) {
140
- const call = `/agents/requests/${request_id}/allow`;
141
- return answered(ask("POST", call, allowed), call, { status: 200, schema: agent_redirect }, agent_refused);
138
+ async allowAgent(request_id, allowed) {
139
+ if (!AGENT_ID.test(request_id)) {
140
+ return notAnId("request", request_id);
141
+ }
142
+ const call = `/agents/requests/${encodeURIComponent(request_id)}/allow`;
143
+ return answered(ask("POST", call, allowed), call, { schema: agent_redirect }, agent_refused);
142
144
  },
143
- denyAgent(request_id) {
144
- const call = `/agents/requests/${request_id}/deny`;
145
- return answered(ask("POST", call, {}), call, { status: 200, schema: agent_redirect }, agent_refused);
145
+ async denyAgent(request_id) {
146
+ if (!AGENT_ID.test(request_id)) {
147
+ return notAnId("request", request_id);
148
+ }
149
+ const call = `/agents/requests/${encodeURIComponent(request_id)}/deny`;
150
+ return answered(ask("POST", call, {}), call, { schema: agent_redirect }, agent_refused);
146
151
  },
147
152
  async agentConnections(user_id) {
148
153
  const call = `/agents/connections?${new URLSearchParams({ user_id })}`;
149
154
  const listed = await answered(ask("GET", call), call, {
150
- status: 200,
151
155
  schema: agent_connections
152
156
  });
153
157
  return listed.ok
@@ -155,14 +159,16 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
155
159
  : listed;
156
160
  },
157
161
  async endAgentConnection(connection_id) {
158
- const call = `/agents/connections/${connection_id}`;
159
- const ended = await answered(ask("DELETE", call), call, { status: 200, schema: agent_ended }, agent_refused);
162
+ if (!AGENT_ID.test(connection_id)) {
163
+ return notAnId("connection", connection_id);
164
+ }
165
+ const call = `/agents/connections/${encodeURIComponent(connection_id)}`;
166
+ const ended = await answered(ask("DELETE", call), call, { schema: agent_ended }, agent_refused);
160
167
  return ended.ok ? { ok: true, data: null } : ended;
161
168
  },
162
169
  async endAgentConnections(user_id) {
163
170
  const call = `/agents/connections?${new URLSearchParams({ user_id })}`;
164
171
  const ended = await answered(ask("DELETE", call), call, {
165
- status: 200,
166
172
  schema: agent_ended
167
173
  });
168
174
  return ended.ok ? { ok: true, data: ended.data.ended } : ended;
@@ -187,6 +193,19 @@ export function infraClient({ key, url = INFRA_URL, send = fetch, paths = APP_PA
187
193
  }
188
194
  };
189
195
  }
196
+ // An ID that can't be one of Infra's, refused before any call, so a route
197
+ // that passes on what it was sent can't make the path reach another of
198
+ // Infra's addresses: what Infra would answer, since it has none such
199
+ function notAnId(kind, id) {
200
+ console.warn("Not an ID Infra makes", { kind, length: id.length });
201
+ return {
202
+ ok: false,
203
+ error: {
204
+ reason: "not-found",
205
+ message: `There's no ${kind} with this ID: Infra's IDs are letters, digits, _ and -, at most 128 of them.`
206
+ }
207
+ };
208
+ }
190
209
  // Infra couldn't be asked, and why
191
210
  function unavailable(message) {
192
211
  return { ok: false, error: { reason: "unavailable", message } };
@@ -8,7 +8,7 @@ export declare const agent_scope: z.ZodEnum<{
8
8
  export type AgentScope = z.infer<typeof agent_scope>;
9
9
  /**
10
10
  * The header the app's server sends Claude's OAuth calls on with: where
11
- * Claude reached the app, `https://vmdsystem.com`, its tokens' issuer.
11
+ * Claude reached the app, `https://example.com`, its tokens' issuer.
12
12
  * Only a header can carry it, since the call's body and query are Claude's.
13
13
  */
14
14
  export declare const APP_ORIGIN_HEADER = "App-Origin";
@@ -24,6 +24,12 @@ export type AppPaths = {
24
24
  allow: string;
25
25
  };
26
26
  export declare const APP_PATHS: AppPaths;
27
+ /**
28
+ * An ID Infra makes for a request or a connection, as the app puts it in a
29
+ * path: letters, digits, `_` and `-`, so it can't reach another address
30
+ */
31
+ export declare const AGENT_ID: RegExp;
32
+ export declare const agent_id: z.ZodString;
27
33
  /** The OAuth calls Claude makes, which the app passes on */
28
34
  export declare const OAUTH_CALLS: readonly ["authorize", "token", "register", "revoke"];
29
35
  export type OAuthCall = (typeof OAUTH_CALLS)[number];
@@ -34,7 +40,7 @@ export type OAuthCall = (typeof OAUTH_CALLS)[number];
34
40
  */
35
41
  export declare const agent_authorized: z.ZodUnion<readonly [z.ZodObject<{
36
42
  request: z.ZodObject<{
37
- id: z.ZodUUID;
43
+ id: z.ZodString;
38
44
  }, z.core.$strip>;
39
45
  }, z.core.$strip>, z.ZodObject<{
40
46
  redirect_to: z.ZodURL;
@@ -14,11 +14,17 @@ export const AGENT_SCOPES = ["read", "act"];
14
14
  export const agent_scope = z.enum(AGENT_SCOPES);
15
15
  /**
16
16
  * The header the app's server sends Claude's OAuth calls on with: where
17
- * Claude reached the app, `https://vmdsystem.com`, its tokens' issuer.
17
+ * Claude reached the app, `https://example.com`, its tokens' issuer.
18
18
  * Only a header can carry it, since the call's body and query are Claude's.
19
19
  */
20
20
  export const APP_ORIGIN_HEADER = "App-Origin";
21
21
  export const APP_PATHS = { oauth: "/oauth", allow: "/connect" };
22
+ /**
23
+ * An ID Infra makes for a request or a connection, as the app puts it in a
24
+ * path: letters, digits, `_` and `-`, so it can't reach another address
25
+ */
26
+ export const AGENT_ID = /^[\w-]{1,128}$/;
27
+ export const agent_id = z.string().regex(AGENT_ID);
22
28
  /** The OAuth calls Claude makes, which the app passes on */
23
29
  export const OAUTH_CALLS = ["authorize", "token", "register", "revoke"];
24
30
  /**
@@ -27,8 +33,8 @@ export const OAUTH_CALLS = ["authorize", "token", "register", "revoke"];
27
33
  * goes back to Claude with an error
28
34
  */
29
35
  export const agent_authorized = z.union([
30
- z.object({ request: z.object({ id: z.uuid() }) }),
31
- z.object({ redirect_to: z.url() })
36
+ z.object({ request: z.object({ id: agent_id }) }),
37
+ z.object({ redirect_to: z.url({ protocol: /^https?$/ }) })
32
38
  ]);
33
39
  /** Why authorize sends nothing back to Claude: answered as plain words */
34
40
  export const authorize_refused = z.union([
@@ -45,7 +51,9 @@ export const agent_request = z.object({
45
51
  // The address Claude asked to use, which its tokens are good for:
46
52
  // the app's MCP
47
53
  resource: z.string(),
48
- expires_at: z.iso.datetime().transform((value) => new Date(value))
54
+ expires_at: z.iso
55
+ .datetime({ offset: true })
56
+ .transform((value) => new Date(value))
49
57
  })
50
58
  });
51
59
  /** `POST /v1/agents/requests/:request_id/allow`: who allowed what */
@@ -54,7 +62,9 @@ export const agent_allow = z.object({
54
62
  scopes: z.array(agent_scope).min(1)
55
63
  });
56
64
  /** What allowing or denying answers: where the browser goes back to Claude */
57
- export const agent_redirect = z.object({ redirect_to: z.url() });
65
+ export const agent_redirect = z.object({
66
+ redirect_to: z.url({ protocol: /^https?$/ })
67
+ });
58
68
  /** `GET` and `DELETE /v1/agents/connections?user_id=…`: whose */
59
69
  export const connections_query = z.object({ user_id });
60
70
  /** One of Claude's connections, as the app's Connected list shows it */
@@ -65,8 +75,12 @@ export const agent_connection = z.object({
65
75
  scopes: z.array(agent_scope),
66
76
  resource: z.string(),
67
77
  // When Claude last refreshed it, to within about ten minutes
68
- last_used_at: z.iso.datetime().transform((value) => new Date(value)),
69
- created_at: z.iso.datetime().transform((value) => new Date(value))
78
+ last_used_at: z.iso
79
+ .datetime({ offset: true })
80
+ .transform((value) => new Date(value)),
81
+ created_at: z.iso
82
+ .datetime({ offset: true })
83
+ .transform((value) => new Date(value))
70
84
  });
71
85
  /** `GET /v1/agents/connections?user_id=…`: theirs, oldest first */
72
86
  export const agent_connections = z.object({
@@ -55,7 +55,9 @@ export const kept_comment = z
55
55
  .object({
56
56
  comment: z.object({
57
57
  id: z.string(),
58
- created_at: z.iso.datetime().transform((value) => new Date(value))
58
+ created_at: z.iso
59
+ .datetime({ offset: true })
60
+ .transform((value) => new Date(value))
59
61
  })
60
62
  })
61
63
  .transform(({ comment }) => comment);
@@ -20,6 +20,16 @@ export declare const INFRA_ERRORS: {
20
20
  };
21
21
  /** A reason Infra refuses a call with */
22
22
  export type InfraErrorReason = keyof typeof INFRA_ERRORS;
23
+ /**
24
+ * The reasons the package itself answers with, never Infra: beside
25
+ * `INFRA_ERRORS`, so the two lists hold every reason an app sees
26
+ */
27
+ export declare const CLIENT_ERRORS: {
28
+ readonly unavailable: "Infra couldn't be asked: no key in a build, a key it refused, no answer, or an answer outside the contract; `message` says which";
29
+ readonly "invalid-token": "A token Claude brought isn't one Infra signed for this app, address, project and mode, or it ran out; `message` says which";
30
+ };
31
+ /** A reason the package answers with */
32
+ export type ClientErrorReason = keyof typeof CLIENT_ERRORS;
23
33
  /** What didn't fit, for `invalid`: a dotted path, and why */
24
34
  export declare const infra_issue: z.ZodObject<{
25
35
  path: z.ZodString;
@@ -31,6 +31,14 @@ export const INFRA_ERRORS = {
31
31
  "unknown-client": "Who's asking to connect isn't Claude, by its return address",
32
32
  "unknown-origin": "The app's origin isn't one its key may log Claude in at"
33
33
  };
34
+ /**
35
+ * The reasons the package itself answers with, never Infra: beside
36
+ * `INFRA_ERRORS`, so the two lists hold every reason an app sees
37
+ */
38
+ export const CLIENT_ERRORS = {
39
+ unavailable: "Infra couldn't be asked: no key in a build, a key it refused, no answer, or an answer outside the contract; `message` says which",
40
+ "invalid-token": "A token Claude brought isn't one Infra signed for this app, address, project and mode, or it ran out; `message` says which"
41
+ };
34
42
  /** What didn't fit, for `invalid`: a dotted path, and why */
35
43
  export const infra_issue = z.object({ path: z.string(), message: z.string() });
36
44
  /** Any refusal of Infra's, read for its reason and its words */
@@ -20,7 +20,7 @@ export declare const login_token: z.ZodString;
20
20
  /** The person's IP address, which Infra's limits count by network */
21
21
  export declare const visitor_ip: z.ZodUnion<readonly [z.ZodIPv4, z.ZodIPv6]>;
22
22
  /**
23
- * The page a login link opens, like `https://vmdsystem.com/login`: Infra
23
+ * The page a login link opens, like `https://example.com/login`: Infra
24
24
  * adds `#<token>`, and links only to the project's domains and localhost
25
25
  */
26
26
  export declare const link_to: z.ZodURL;
@@ -29,7 +29,7 @@ export const login_token = z.string().regex(/^[\w-]{43}$/);
29
29
  /** The person's IP address, which Infra's limits count by network */
30
30
  export const visitor_ip = z.union([z.ipv4(), z.ipv6()]);
31
31
  /**
32
- * The page a login link opens, like `https://vmdsystem.com/login`: Infra
32
+ * The page a login link opens, like `https://example.com/login`: Infra
33
33
  * adds `#<token>`, and links only to the project's domains and localhost
34
34
  */
35
35
  export const link_to = z
@@ -56,7 +56,9 @@ export const started_login = z.object({
56
56
  // Whether the message holds a link as well as the code
57
57
  with_link: z.boolean(),
58
58
  // When the code and the link stop working
59
- expires_at: z.iso.datetime().transform((value) => new Date(value)),
59
+ expires_at: z.iso
60
+ .datetime({ offset: true })
61
+ .transform((value) => new Date(value)),
60
62
  // With a test key, which sends nothing: what the message would have
61
63
  // held, for a dev server to show on the page. Null with a secret key.
62
64
  test: z.object({ code: z.string(), link: z.string().nullable() }).nullable()
@@ -9,11 +9,27 @@ export declare const key_mode: z.ZodEnum<{
9
9
  }>;
10
10
  export type KeyMode = z.infer<typeof key_mode>;
11
11
  /**
12
- * Each mode's key's prefix, then 32 letters and digits. The prefix lets a
12
+ * Each mode's key's prefix, then 32 to 128 letters, digits and
13
+ * underscores (`KEY_BODY`). The prefix lets a
13
14
  * leak scanner spot one, and tells a test key from a secret one at a
14
15
  * glance.
15
16
  */
16
17
  export declare const KEY_PREFIXES: Record<KeyMode, string>;
18
+ /**
19
+ * What follows a key's prefix. Infra makes 32 letters and digits today; a
20
+ * longer key, or one with a checksum after an underscore, still fits, so
21
+ * Infra can change how it makes them without every app refusing the new
22
+ * ones.
23
+ */
24
+ export declare const KEY_BODY = "[0-9A-Za-z_]{32,128}";
25
+ /**
26
+ * The hostnames that are this computer: a dev server's, which a test key
27
+ * logs Claude in at and a login link always goes to, over plain http.
28
+ * Names under `localhost` (`app.localhost`) are too (`isLoopbackHost`).
29
+ */
30
+ export declare const LOOPBACK_HOSTNAMES: readonly ["localhost", "127.0.0.1", "[::1]"];
31
+ /** Whether `hostname`, as a URL's `hostname` has it, is this computer */
32
+ export declare function isLoopbackHost(hostname: string): boolean;
17
33
  /**
18
34
  * `GET /v1/project`: which project the key is for, its mode, and its
19
35
  * domains, the only hosts besides localhost a login link goes to and
@@ -33,6 +49,6 @@ export declare const infra_project: z.ZodObject<{
33
49
  export type InfraProject = z.output<typeof infra_project>;
34
50
  /**
35
51
  * The header every call carries, saying which release of @superforge/infra
36
- * made it (`@superforge/infra/0.3.0`), which Infra logs and keeps per key
52
+ * made it (`@superforge/infra/<version>`), which Infra logs and keeps per key
37
53
  */
38
54
  export declare const CLIENT_HEADER = "Infra-Client";
@@ -8,7 +8,8 @@ export const PROJECT_ID_PREFIX = "sf_project_";
8
8
  export const KEY_MODES = ["live", "test"];
9
9
  export const key_mode = z.enum(KEY_MODES);
10
10
  /**
11
- * Each mode's key's prefix, then 32 letters and digits. The prefix lets a
11
+ * Each mode's key's prefix, then 32 to 128 letters, digits and
12
+ * underscores (`KEY_BODY`). The prefix lets a
12
13
  * leak scanner spot one, and tells a test key from a secret one at a
13
14
  * glance.
14
15
  */
@@ -16,6 +17,25 @@ export const KEY_PREFIXES = {
16
17
  live: "sf_secret_",
17
18
  test: "sf_test_"
18
19
  };
20
+ /**
21
+ * What follows a key's prefix. Infra makes 32 letters and digits today; a
22
+ * longer key, or one with a checksum after an underscore, still fits, so
23
+ * Infra can change how it makes them without every app refusing the new
24
+ * ones.
25
+ */
26
+ export const KEY_BODY = "[0-9A-Za-z_]{32,128}";
27
+ /**
28
+ * The hostnames that are this computer: a dev server's, which a test key
29
+ * logs Claude in at and a login link always goes to, over plain http.
30
+ * Names under `localhost` (`app.localhost`) are too (`isLoopbackHost`).
31
+ */
32
+ export const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
33
+ /** Whether `hostname`, as a URL's `hostname` has it, is this computer */
34
+ export function isLoopbackHost(hostname) {
35
+ const name = hostname.toLowerCase();
36
+ return (LOOPBACK_HOSTNAMES.includes(name) ||
37
+ name.endsWith(".localhost"));
38
+ }
19
39
  /**
20
40
  * `GET /v1/project`: which project the key is for, its mode, and its
21
41
  * domains, the only hosts besides localhost a login link goes to and
@@ -31,6 +51,6 @@ export const infra_project = z.object({
31
51
  });
32
52
  /**
33
53
  * The header every call carries, saying which release of @superforge/infra
34
- * made it (`@superforge/infra/0.3.0`), which Infra logs and keeps per key
54
+ * made it (`@superforge/infra/<version>`), which Infra logs and keeps per key
35
55
  */
36
56
  export const CLIENT_HEADER = "Infra-Client";
package/output/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { oauthMetadata, requestOrigin } from "./agents.js";
2
2
  export { chooseInfra, type InfraChoice } from "./choose.js";
3
3
  export { INFRA_URL, infraClient } from "./client.js";
4
4
  export * from "./contract/index.js";
5
- export type { AgentToken, Infra, InfraUnavailable } from "./infra.js";
5
+ export type { AgentToken, AgentTokenRefused, Infra, InfraUnavailable } from "./infra.js";
6
6
  export type { AsyncOperationResult, OperationResult } from "./results.js";
7
7
  export { standInAgentToken, standInInfra, type WaitingLogin } from "./stand-in.js";
8
8
  export { PACKAGE_VERSION } from "./version.js";
package/output/infra.d.ts CHANGED
@@ -60,7 +60,16 @@ export type Infra = {
60
60
  checkAgentToken(token: string, expected: {
61
61
  origin: string;
62
62
  resource: string;
63
- }): AsyncOperationResult<AgentToken, "invalid-token" | InfraUnavailable>;
63
+ }): AsyncOperationResult<AgentToken, AgentTokenRefused | InfraUnavailable>;
64
+ };
65
+ /**
66
+ * A token Claude brought that the app mustn't take, and why in words:
67
+ * it ran out, it's for another address or app, or Infra didn't sign it.
68
+ * The app answers it 401, so Claude logs in again.
69
+ */
70
+ export type AgentTokenRefused = {
71
+ reason: "invalid-token";
72
+ message: string;
64
73
  };
65
74
  /** What the app learns from a token Claude brings, once it's checked */
66
75
  export type AgentToken = {
@@ -1,5 +1,10 @@
1
1
  /** A second, a minute, in milliseconds */
2
2
  export declare const SECOND = 1000;
3
3
  export declare const MINUTE: number;
4
+ /**
5
+ * How long a call waits for Infra's answer. Starting a login waits on
6
+ * Infra sending the email, which takes a second or two.
7
+ */
8
+ export declare const CALL_TIMEOUT: number;
4
9
  /** 32 random bytes in base64url: a login link's token, as Infra makes one */
5
10
  export declare function randomToken(): string;
@@ -3,6 +3,11 @@
3
3
  /** A second, a minute, in milliseconds */
4
4
  export const SECOND = 1000;
5
5
  export const MINUTE = 60 * SECOND;
6
+ /**
7
+ * How long a call waits for Infra's answer. Starting a login waits on
8
+ * Infra sending the email, which takes a second or two.
9
+ */
10
+ export const CALL_TIMEOUT = 15 * SECOND;
6
11
  /** 32 random bytes in base64url: a login link's token, as Infra makes one */
7
12
  export function randomToken() {
8
13
  const bytes = crypto.getRandomValues(new Uint8Array(32));
@@ -19,7 +19,10 @@ export type WaitingLogin = {
19
19
  * it's given, an app's website's. An app's tests always use it, so they
20
20
  * never reach Infra, and so does a dev server with no test key
21
21
  * (choose.ts). A build never does: anyone could log in as anyone, since
22
- * the page shows the code. Its refusals say what Infra's say.
22
+ * the page shows the code. Its refusals have Infra's reasons, though not
23
+ * always its words, which aren't contract. Like Infra, it links only to
24
+ * this computer and the project's `domains`, over https, and answers
25
+ * `with_link: false` for any other host.
23
26
  *
24
27
  * `waiting` is where it keeps what it sent, by address: its own, or one
25
28
  * that outlives a dev server's reloads. With `logs`, as a dev server has
@@ -1,7 +1,7 @@
1
1
  import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from "jose";
2
2
  import { z } from "zod";
3
3
  import { checkToken, unavailableOAuth } from "./agents.js";
4
- import { COMMENT_BODY_LIMIT, filed_comment, login_start, login_verify } from "./contract/index.js";
4
+ import { COMMENT_BODY_LIMIT, filed_comment, isLoopbackHost, login_start, login_verify } from "./contract/index.js";
5
5
  import { MINUTE, randomToken } from "./primitives.js";
6
6
  // How Infra treats a code: it works for 15 minutes and five tries, and a
7
7
  // new one for the same address replaces it, link and all
@@ -18,7 +18,10 @@ const ATTEMPTS = 5;
18
18
  * it's given, an app's website's. An app's tests always use it, so they
19
19
  * never reach Infra, and so does a dev server with no test key
20
20
  * (choose.ts). A build never does: anyone could log in as anyone, since
21
- * the page shows the code. Its refusals say what Infra's say.
21
+ * the page shows the code. Its refusals have Infra's reasons, though not
22
+ * always its words, which aren't contract. Like Infra, it links only to
23
+ * this computer and the project's `domains`, over https, and answers
24
+ * `with_link: false` for any other host.
22
25
  *
23
26
  * `waiting` is where it keeps what it sent, by address: its own, or one
24
27
  * that outlives a dev server's reloads. With `logs`, as a dev server has
@@ -45,6 +48,7 @@ export function standInInfra({ waiting = new Map(), logs = false, domains = [] }
45
48
  return misfit(parsed.error);
46
49
  }
47
50
  const { channel, address, link_to } = parsed.data;
51
+ const page = link_to === undefined ? null : linkPage(link_to, domains);
48
52
  const sent = {
49
53
  address,
50
54
  code: randomCode(),
@@ -58,13 +62,11 @@ export function standInInfra({ waiting = new Map(), logs = false, domains = [] }
58
62
  data: {
59
63
  channel,
60
64
  address,
61
- with_link: link_to !== undefined,
65
+ with_link: page !== null,
62
66
  expires_at: new Date(sent.expires_at),
63
67
  test: {
64
68
  code: sent.code,
65
- link: link_to === undefined
66
- ? null
67
- : `${link_to}#${sent.token}`
69
+ link: page === null ? null : `${page}#${sent.token}`
68
70
  }
69
71
  }
70
72
  };
@@ -196,6 +198,19 @@ export function standInInfra({ waiting = new Map(), logs = false, domains = [] }
196
198
  }
197
199
  };
198
200
  }
201
+ // The page a login link opens, by Infra's rule: as it is on this computer,
202
+ // over https on its hostname when that's one of the project's domains,
203
+ // whatever scheme or port the app said, and null on any other host, which
204
+ // gets the code alone
205
+ function linkPage(link_to, domains) {
206
+ const url = new URL(link_to);
207
+ const page = `${url.pathname}${url.search}`;
208
+ if (isLoopbackHost(url.hostname)) {
209
+ return `${url.origin}${page}`;
210
+ }
211
+ const domain = domains.find((each) => each.toLowerCase() === url.hostname.toLowerCase());
212
+ return domain === undefined ? null : `https://${url.hostname}${page}`;
213
+ }
199
214
  // A request that doesn't fit Infra's contract: Infra answers it 400
200
215
  // `invalid`, which the client reads as unavailable, since it's a bug in
201
216
  // the app, with the fields that didn't fit
@@ -1,4 +1,4 @@
1
1
  /** The package's version, as package.json says it */
2
- export declare const PACKAGE_VERSION = "0.3.0";
3
- /** What it says: the package and its version, `@superforge/infra/0.3.0` */
4
- export declare const CLIENT = "@superforge/infra/0.3.0";
2
+ export declare const PACKAGE_VERSION = "0.4.0";
3
+ /** What it says: the package and its version, `@superforge/infra/<version>` */
4
+ export declare const CLIENT = "@superforge/infra/0.4.0";
package/output/version.js CHANGED
@@ -5,6 +5,6 @@
5
5
  // package away from its package.json; a test checks the two agree, so a
6
6
  // release that bumps one and not the other fails `pnpm check`.
7
7
  /** The package's version, as package.json says it */
8
- export const PACKAGE_VERSION = "0.3.0";
9
- /** What it says: the package and its version, `@superforge/infra/0.3.0` */
8
+ export const PACKAGE_VERSION = "0.4.0";
9
+ /** What it says: the package and its version, `@superforge/infra/<version>` */
10
10
  export const CLIENT = `@superforge/infra/${PACKAGE_VERSION}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superforge/infra",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Superforge Infra, the backend services Foundation and Skylevel apps run on, as an app's server calls it",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,6 +12,8 @@
12
12
  "engines": {
13
13
  "node": ">=22"
14
14
  },
15
+ "main": "./output/index.js",
16
+ "types": "./output/index.d.ts",
15
17
  "exports": {
16
18
  ".": {
17
19
  "types": "./output/index.d.ts",
@@ -23,8 +25,7 @@
23
25
  }
24
26
  },
25
27
  "files": [
26
- "output",
27
- "!output/tests"
28
+ "output"
28
29
  ],
29
30
  "sideEffects": false,
30
31
  "scripts": {
@@ -36,7 +37,7 @@
36
37
  "prepublishOnly": "pnpm check"
37
38
  },
38
39
  "dependencies": {
39
- "jose": "6.2.15"
40
+ "jose": "^6.2.15"
40
41
  },
41
42
  "peerDependencies": {
42
43
  "zod": "^4.6.7"