@superforge/infra 0.3.0 → 0.5.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,15 +5,16 @@ 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.
11
11
 
12
12
  ```bash
13
- pnpm add @superforge/infra zod
13
+ pnpm add @superforge/infra
14
14
  ```
15
15
 
16
- It needs Node 22 or later, and zod 4, which an app has already.
16
+ It needs Node 22 or later. It brings its own zod 4, so an app can be on any
17
+ zod, and move to the next one without waiting for the package.
17
18
 
18
19
  ## Using it
19
20
 
@@ -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,99 @@ 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
+ - **`AGENT_SCOPES`** (`["read", "act"]`) is what someone lets Claude do.
123
+ An app that checks scopes with zod builds its own list from it,
124
+ `z.enum(AGENT_SCOPES)`, with its own zod.
125
+
126
+ ### `infraClient`
127
+
128
+ `infraClient({ key, url?, send?, paths? })` is the real Infra, which
129
+ `chooseInfra` makes; an app calls it itself only to point a test at a fake
130
+ of Infra (`send` is `fetch`, or the test's own; `url` is Infra's own
131
+ address unless set).
132
+
70
133
  ### The stand-in, for tests
71
134
 
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.
135
+ `standInInfra({ domains? })` is Infra's test mode in
136
+ memory: login sends nothing and answers the code and the link, which
137
+ verify as Infra's do (once each, for 15 minutes, a code for five tries),
138
+ and links, as Infra's do, only to this computer and the project's
139
+ `domains`, over https; any other host gets `with_link: false`. A comment
140
+ is checked as Infra checks it and kept nowhere; Claude logs in to nothing,
141
+ and `checkAgentToken` takes only the tokens `standInAgentToken()` mints:
142
+ `standInAgentToken({ user_id, resource, scopes?, origin?, expires_in? })`,
143
+ `origin` being `http://localhost` and `expires_in` `"10m"` unless set. An
144
+ app's tests use it, so they never reach Infra.
145
+
146
+ ### The contract
147
+
148
+ `@superforge/infra/contract` is Infra's contract with nothing of Node's, so
149
+ a page can import it: the constants and types every call is made of, every
150
+ reason a call is refused, Infra's (`INFRA_ERRORS`) and the package's own
151
+ (`CLIENT_ERRORS`), and the zod schemas of what Infra is sent (`login_start`,
152
+ `login_verify`, `filed_comment`, `agent_allow`, `connections_query`), which
153
+ Infra checks with, with the two answers Infra's own server ties itself to
154
+ (`started_login`, `verified_login`). The package itself exports the same
155
+ constants and types, and no schema.
156
+
157
+ A schema here is made with the package's own zod: parse with it as it is,
158
+ and never put it inside a schema of the app's own, which may be another
159
+ zod's and then fails. Build the app's own from the constants instead.
160
+
161
+ Every name either entry exports is a promise: from 1.0.0 on, taking one
162
+ away is a major. So they export only what an app or Infra's server uses;
163
+ the rest is the package's own.
78
164
 
79
165
  ## When something goes wrong
80
166
 
@@ -82,7 +168,7 @@ Every refusal is Infra's own `error`, as it answered it, in the shape a
82
168
  template's API answers too: `reason`, for code to branch on, `message`,
83
169
  what went wrong and what fixes it in plain words, and any fields the call
84
170
  adds, like `retry_after`. Infra's contract has every reason
85
- (`INFRA_ERRORS`). When the package couldn't ask Infra, it says why in
171
+ (`INFRA_ERRORS`, and the package's own, `CLIENT_ERRORS`). When the package couldn't ask Infra, it says why in
86
172
  the same shape:
87
173
 
88
174
  ```ts
@@ -107,11 +193,14 @@ should only learn that login isn't working.
107
193
 
108
194
  ## What every call tells Infra
109
195
 
110
- Every call, Claude's OAuth calls passed through included, carries
111
- `Infra-Client: @superforge/infra/<version>`, so Infra knows which version
112
- each app is on, and can say when one's out of date (`PACKAGE_VERSION` and
113
- `CLIENT_HEADER` are exported). The version is written in
114
- `source/version.ts`, which a test checks against `package.json`.
196
+ Every call, Claude's OAuth calls passed through and the fetch of Infra's
197
+ public keys included, carries `Infra-Client: @superforge/infra/<version>`
198
+ (`CLIENT_HEADER`, in the contract), so Infra knows which version each app
199
+ is on. That release is the version Infra answers the call as: once Infra
200
+ changes an answer, a release from before the change still gets the shape
201
+ it reads. A call that names no release, like one from a terminal, is
202
+ answered as the oldest release Infra still answers. The version is written
203
+ in `source/version.ts`, which a test checks against `package.json`.
115
204
 
116
205
  ## Releases
117
206
 
@@ -125,18 +214,21 @@ dependency (Dependabot opens a PR a month), never by copying code.
125
214
 
126
215
  CI signs in to npm with trusted publishing: npm trusts this repository's
127
216
  `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.
217
+ "Trusted publisher"), so no npm token is kept anywhere. A PR's
218
+ `release-version` check refuses one whose version isn't the one right
219
+ after `main`'s, with its line in `CHANGELOG.md`.
220
+
221
+ Infra changes its API additively: it adds fields and calls, and never
222
+ renames or drops one an app's release calls, so a release keeps working
223
+ until the app takes the next. Until 1.0.0 it keeps no older shapes: an app
224
+ takes the latest release.
225
+
226
+ A release reads what Infra adds without breaking: a field it doesn't know
227
+ is dropped, a 429's `limit` is read as any name, and a request's or a
228
+ connection's `scopes` keep only the scopes the release knows. A refusal
229
+ whose `reason` it doesn't know is `unavailable`, with Infra's `message`.
230
+ `mode` and a login's `channel` stay closed lists: an app only meets a new
231
+ one once it asks for it.
140
232
 
141
233
  ## Working on it
142
234
 
@@ -150,13 +242,14 @@ checkout at this folder (`pnpm add @superforge/infra@link:<path to this
150
242
  folder>`), and back to the released version before its PR: a `link:` is
151
243
  this computer's alone, and CI can't install it.
152
244
 
153
- - `source/index.ts`: everything the package exports.
154
- - `source/contract/`: Infra's contract, exported on its own at
155
- `@superforge/infra/contract`, with nothing of Node's: every call's
156
- request and answer as zod schemas, which Infra checks what it's sent
157
- with, and every reason it refuses one (`errors.ts`), a file per area:
158
- `login.ts`, `comments.ts`, `agents.ts`, `project.ts` and `people.ts`
159
- (`user_id`, the app's ID for one of its people).
245
+ - `source/index.ts`: everything the package exports, by name.
246
+ - `source/contract/`: Infra's contract, with nothing of Node's: every
247
+ call's request and answer as zod schemas, which Infra checks what it's
248
+ sent with, and every reason it refuses one (`errors.ts`), a file per
249
+ area: `login.ts`, `comments.ts`, `agents.ts`, `project.ts` and
250
+ `people.ts` (`user_id`, the app's ID for one of its people).
251
+ `index.ts` is what `@superforge/infra/contract` exports, by name;
252
+ `all.ts` is all of it, which only the package itself imports.
160
253
  - `source/infra.ts`: `Infra`, what an app asks of it, and its results.
161
254
  - `source/client.ts`: Infra over HTTP with a project's key, its answers
162
255
  parsed with the contract and every one logged. No call is retried: a
@@ -1,10 +1,10 @@
1
1
  import { type JWTVerifyGetKey } from "jose";
2
- import { type AppPaths, type KeyMode, type OAuthCall } from "./contract/index.js";
3
- import type { AgentToken } from "./infra.js";
2
+ import { type AppPaths, type KeyMode, type OAuthCall } from "./contract/all.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`, saying which release asks, as every call does
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/all.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,21 @@ 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`, saying which release asks, as every call does
215
+ */
216
+ export function infraKeys(url, send = fetch) {
217
+ return createRemoteJWKSet(new URL("/.well-known/jwks.json", new URL(url).origin), {
218
+ headers: { [CLIENT_HEADER]: CLIENT },
219
+ timeoutDuration: 10 * SECOND,
220
+ cooldownDuration: 30 * SECOND,
221
+ [customFetch]: send
222
+ });
166
223
  }
224
+ // How much a token's times may be off, for an app server whose clock is a
225
+ // few seconds from Infra's
226
+ const CLOCK_TOLERANCE_SECONDS = 5;
167
227
  /**
168
228
  * Checks a token Claude brings, as Infra's README says to: Infra signed
169
229
  * it, for this app's `origin`, for `resource`, the address it was brought
@@ -174,7 +234,10 @@ export async function checkToken(keys, token, expected) {
174
234
  const { payload } = await jwtVerify(token, keys, {
175
235
  issuer: expected.origin,
176
236
  audience: expected.resource,
177
- algorithms: ["ES256"]
237
+ algorithms: ["ES256"],
238
+ typ: "at+jwt",
239
+ requiredClaims: ["exp"],
240
+ clockTolerance: CLOCK_TOLERANCE_SECONDS
178
241
  });
179
242
  const claims = agent_claims.safeParse(payload);
180
243
  if (!claims.success ||
@@ -183,7 +246,7 @@ export async function checkToken(keys, token, expected) {
183
246
  console.warn("Agent token not for this app", {
184
247
  origin: expected.origin
185
248
  });
186
- return { ok: false, error: "invalid-token" };
249
+ 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
250
  }
188
251
  else {
189
252
  const said = claims.data.scope.split(" ");
@@ -198,7 +261,56 @@ export async function checkToken(keys, token, expected) {
198
261
  }
199
262
  }
200
263
  catch (error) {
264
+ if (keySetFailed(error)) {
265
+ console.error("Infra's public keys couldn't be fetched", {
266
+ origin: expected.origin,
267
+ error
268
+ });
269
+ return {
270
+ ok: false,
271
+ error: {
272
+ reason: "unavailable",
273
+ 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."
274
+ }
275
+ };
276
+ }
201
277
  console.info("Agent token refused", { origin: expected.origin, error });
202
- return { ok: false, error: "invalid-token" };
278
+ return invalidToken(whyRefused(error));
279
+ }
280
+ }
281
+ function invalidToken(message) {
282
+ return { ok: false, error: { reason: "invalid-token", message } };
283
+ }
284
+ // Whether checking a token failed on fetching Infra's keys, rather than on
285
+ // the token: a timeout, no answer, an answer that isn't 200, or one that
286
+ // isn't a key set. Infra being down then isn't the token's fault.
287
+ function keySetFailed(error) {
288
+ return (error instanceof errors.JWKSTimeout ||
289
+ error instanceof errors.JWKSInvalid ||
290
+ error instanceof TypeError ||
291
+ (error instanceof DOMException && error.name === "AbortError") ||
292
+ (error instanceof errors.JOSEError &&
293
+ error.code === "ERR_JOSE_GENERIC" &&
294
+ (error.message.startsWith("Expected 200 OK") ||
295
+ error.message.startsWith("Failed to parse the JSON Web Key Set"))));
296
+ }
297
+ // Why a token was refused, in words, by what jose found
298
+ function whyRefused(error) {
299
+ if (error instanceof errors.JWTExpired) {
300
+ return "Claude's token has run out. Claude refreshes it, or logs in again.";
301
+ }
302
+ else if (error instanceof errors.JWTClaimValidationFailed) {
303
+ if (error.claim === "aud") {
304
+ return "Claude's token is for another address than the one it was brought to.";
305
+ }
306
+ else if (error.claim === "iss") {
307
+ return "Claude's token was made for another app, or for this app at another address.";
308
+ }
309
+ else {
310
+ return `Claude's token's ${error.claim} claim isn't what Infra signs.`;
311
+ }
312
+ }
313
+ else {
314
+ return "Claude's token isn't one Infra signed. Claude logs in again.";
203
315
  }
204
316
  }
@@ -1,4 +1,4 @@
1
- import { type AppPaths } from "./contract/index.js";
1
+ import { type AppPaths } from "./contract/all.js";
2
2
  import type { Infra } from "./infra.js";
3
3
  /** Which Infra a server calls, as `chooseInfra` chose it. */
4
4
  export type InfraChoice = {
package/output/choose.js CHANGED
@@ -4,8 +4,8 @@ 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";
8
- import { standInInfra } from "./stand-in.js";
7
+ import { APP_PATHS, KEY_BODY, KEY_PREFIXES } from "./contract/all.js";
8
+ import { standInWith } from "./stand-in.js";
9
9
  // Which Infra the server calls, by what it runs as and the keys it has:
10
10
  //
11
11
  // | Runs as | Has | Calls |
@@ -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;
@@ -87,7 +101,7 @@ export function chooseInfra({ development, environment, checkout, domains = [],
87
101
  console.info("Infra: no test key, so login uses the stand-in, which emails nothing");
88
102
  }
89
103
  return {
90
- infra: standInInfra({
104
+ infra: standInWith({
91
105
  waiting: devServerLogins(),
92
106
  logs: true,
93
107
  domains
@@ -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,
@@ -1,4 +1,4 @@
1
- import { type AppPaths } from "./contract/index.js";
1
+ import { type AppPaths } from "./contract/all.js";
2
2
  import type { Infra } from "./infra.js";
3
3
  /** Infra's API, which a project's keys call */
4
4
  export declare const INFRA_URL = "https://infra.superforge.studio/v1";