@superforge/infra 0.0.0-stage → 0.1.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.
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ // What Infra answers, parsed by the client (client.ts) so an app gets typed
3
+ // values, each refusal read into an app's own shape: its `error` as
4
+ // `reason`. Every refusal carries Infra's `message`, what went wrong and
5
+ // what fixes it in plain words, for whoever runs the app and their agent
6
+ // (Infra's README, "Errors"), or the client's own words when an Infra from
7
+ // before it said one answers. The types in infra.ts come from these, and
8
+ // the stand-in answers the same.
9
+ // Infra's words for a refusal, or these when it gave none
10
+ const said = (fallback) => z.string().catch(fallback);
11
+ /**
12
+ * Which project the key is for, its mode, and its domains, the only hosts
13
+ * besides localhost its login emails link to. An Infra from before it
14
+ * answered the domains answers none here, `null`, which an app shows as
15
+ * not known.
16
+ */
17
+ export const infra_project = z.object({
18
+ project: z.object({
19
+ id: z.string(),
20
+ name: z.string(),
21
+ domains: z.array(z.string()).nullable().default(null)
22
+ }),
23
+ mode: z.enum(["live", "test"])
24
+ });
25
+ /** A login email that went out. */
26
+ export const started_login = z.object({
27
+ // The address as Infra keeps it, which verifying the code takes
28
+ email: z.string(),
29
+ // Whether the email holds a link as well as the code
30
+ with_link: z.boolean(),
31
+ // When the code and the link stop working
32
+ expires_at: z.iso.datetime().transform((value) => new Date(value)),
33
+ // With a test key, which sends nothing: what the email would have held,
34
+ // for a dev server to show on the page. Null with a secret key.
35
+ test: z.object({ code: z.string(), link: z.string().nullable() }).nullable()
36
+ });
37
+ /** Why Infra didn't send a login email. */
38
+ export const start_refused = z.union([
39
+ // This address was sent one less than a minute ago
40
+ z
41
+ .object({
42
+ error: z.literal("too-soon"),
43
+ retry_after: z.number(),
44
+ message: said("A login email went to this address less than a minute ago.")
45
+ })
46
+ .transform(({ retry_after, message }) => ({
47
+ reason: "too-soon",
48
+ retry_after,
49
+ message
50
+ })),
51
+ // Over one of Infra's limits, an hour each: `email`, `ip` or `project`.
52
+ // Kept as a string, so a limit Infra adds later still reads.
53
+ z
54
+ .object({
55
+ error: z.literal("too-many"),
56
+ limit: z.string(),
57
+ retry_after: z.number(),
58
+ message: said("Infra has sent as many login emails as it sends in an hour.")
59
+ })
60
+ .transform(({ limit, retry_after, message }) => ({
61
+ reason: "too-many",
62
+ limit,
63
+ retry_after,
64
+ message
65
+ })),
66
+ // The email didn't go out, and nothing was counted, so asking again can
67
+ // work at once
68
+ z
69
+ .object({
70
+ error: z.literal("not-sent"),
71
+ message: said("The login email didn't go out.")
72
+ })
73
+ .transform(({ message }) => ({ reason: "not-sent", message }))
74
+ ]);
75
+ /** Whose email the code or the link was. */
76
+ export const verified_login = z.object({ email: z.string() });
77
+ /** Why what the visitor brought back didn't log them in. */
78
+ export const verify_refused = z.union([
79
+ // Not the code, which still works for this many more tries
80
+ z
81
+ .object({
82
+ error: z.literal("wrong-code"),
83
+ attempts_left: z.number(),
84
+ message: said("That isn't the code Infra emailed this address.")
85
+ })
86
+ .transform(({ attempts_left, message }) => ({
87
+ reason: "wrong-code",
88
+ attempts_left,
89
+ message
90
+ })),
91
+ // Nothing left to try: never sent, expired, already used, or out of
92
+ // tries
93
+ z
94
+ .object({
95
+ error: z.literal("no-code"),
96
+ message: said("No code is waiting for this address.")
97
+ })
98
+ .transform(({ message }) => ({ reason: "no-code", message })),
99
+ // The link is spent, expired, or never was this project's
100
+ z
101
+ .object({
102
+ error: z.literal("no-link"),
103
+ message: said("That link has been used or has run out.")
104
+ })
105
+ .transform(({ message }) => ({ reason: "no-link", message }))
106
+ ]);
107
+ /** A comment Infra kept: its ID, and when. */
108
+ export const kept_comment = z
109
+ .object({
110
+ comment: z.object({
111
+ id: z.string(),
112
+ created_at: z.iso.datetime().transform((value) => new Date(value))
113
+ })
114
+ })
115
+ .transform(({ comment }) => comment);
116
+ /**
117
+ * Why Infra didn't keep a comment. Either is a bug in what the app sent,
118
+ * so sending it again won't help.
119
+ */
120
+ export const comment_refused = z.union([
121
+ // Not the call's shape: `fields` names what failed, like `element.tag`
122
+ z
123
+ .object({
124
+ error: z.literal("invalid"),
125
+ fields: z.array(z.string()),
126
+ message: said("The comment didn't fit what Infra takes.")
127
+ })
128
+ .transform(({ fields, message }) => ({
129
+ reason: "invalid",
130
+ fields,
131
+ message
132
+ })),
133
+ // Over the most a call's body can be, in bytes
134
+ z
135
+ .object({
136
+ error: z.literal("too-large"),
137
+ limit: z.number(),
138
+ message: said("The comment is bigger than Infra takes.")
139
+ })
140
+ .transform(({ limit, message }) => ({
141
+ reason: "too-large",
142
+ limit,
143
+ message
144
+ }))
145
+ ]);
146
+ /**
147
+ * Any refusal of Infra's, read only for its words: what the client logs,
148
+ * and what it tells an app about an error it doesn't know
149
+ */
150
+ export const any_refusal = z.object({
151
+ error: z.string(),
152
+ message: z.string().optional()
153
+ });
@@ -0,0 +1,13 @@
1
+ import type { Infra } from "./infra.js";
2
+ /** Which Infra a server calls, as `chooseInfra` chose it. */
3
+ export type InfraChoice = {
4
+ infra: Infra;
5
+ using: "secret key" | "test key" | "stand-in" | "nothing";
6
+ };
7
+ /** The Infra a server calls, by how it runs and what it's been given. */
8
+ export declare function chooseInfra({ development, environment, checkout, domains }: {
9
+ development: boolean;
10
+ environment: Record<string, string | undefined>;
11
+ checkout: string;
12
+ domains?: string[];
13
+ }): InfraChoice;
@@ -0,0 +1,223 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { parseEnv } from "node:util";
4
+ import { z } from "zod";
5
+ import { unavailableOAuth } from "./agents.js";
6
+ import { INFRA_URL, infraClient } from "./client.js";
7
+ import { standInInfra } from "./stand-in.js";
8
+ // Which Infra the server calls, by what it runs as and the keys it has:
9
+ //
10
+ // | Runs as | Has | Calls |
11
+ // | ---------- | ---------------------------- | ----------------------------- |
12
+ // | a build | INFRA_SECRET_KEY, sf_secret_ | Infra, which sends the emails |
13
+ // | a build | anything else | nothing: login is down |
14
+ // | dev server | INFRA_TEST_KEY, sf_test_ | Infra, in test mode |
15
+ // | dev server | none | the stand-in (stand-in.ts) |
16
+ //
17
+ // A build never falls back to the stand-in, which shows the code on the
18
+ // page, nor takes a test key, which sends no email; a dev server never
19
+ // takes a secret key, so it can't email real people. An app's tests use
20
+ // the stand-in themselves. When there's nothing to call, every call
21
+ // answers unavailable with why, which an app shows its team.
22
+ // A key's shape: its prefix, then 32 letters and digits
23
+ const SECRET_KEY = /^sf_secret_[0-9A-Za-z]{32}$/;
24
+ const TEST_KEY = /^sf_test_[0-9A-Za-z]{32}$/;
25
+ // What the server reads to reach Infra, by the variables' names: the
26
+ // secret key Railway holds, a checkout's test key, and where Infra is, to
27
+ // point a dev server at another one, like a Superforge checkout's own. A
28
+ // dev server reads them from the checkout's `.env` too (`checkoutVariables`),
29
+ // under whatever the shell sets. One set empty, as `.env.example` has them,
30
+ // is unset.
31
+ const unset_when_empty = (value) => typeof value === "string" && value.trim() === "" ? undefined : value;
32
+ const infra_environment = z.object({
33
+ INFRA_SECRET_KEY: z.preprocess(unset_when_empty, z.string().trim().optional()),
34
+ INFRA_TEST_KEY: z.preprocess(unset_when_empty, z.string().trim().optional()),
35
+ INFRA_URL: z.preprocess(unset_when_empty, z.url().optional())
36
+ });
37
+ /** The Infra a server calls, by how it runs and what it's been given. */
38
+ export function chooseInfra({ development, environment, checkout, domains = [] }) {
39
+ const parsed = infra_environment.safeParse(development
40
+ ? { ...checkoutVariables(checkout), ...environment }
41
+ : environment);
42
+ if (!parsed.success) {
43
+ const names = parsed.error.issues.map((issue) => issue.path.join("."));
44
+ console.error("Infra can't be reached: these aren't set right", {
45
+ names
46
+ });
47
+ return {
48
+ infra: unavailableInfra(`Infra can't be reached: ${names.join(", ")} ${names.length === 1 ? "isn't" : "aren't"} set right${development ? " in the checkout's .env" : " on the app's service in Railway"}. INFRA_URL, when it's set, is an http or https address.`),
49
+ using: "nothing"
50
+ };
51
+ }
52
+ const { INFRA_SECRET_KEY } = parsed.data;
53
+ // Without a slash at the end, since each call's path starts with one
54
+ const url = (parsed.data.INFRA_URL ?? INFRA_URL).replace(/\/+$/, "");
55
+ if (!development) {
56
+ if (INFRA_SECRET_KEY !== undefined &&
57
+ SECRET_KEY.test(INFRA_SECRET_KEY)) {
58
+ console.info("Infra: calling it with the secret key", { url });
59
+ return {
60
+ infra: infraClient({ key: INFRA_SECRET_KEY, url }),
61
+ using: "secret key"
62
+ };
63
+ }
64
+ else {
65
+ const message = noSecretKey(INFRA_SECRET_KEY);
66
+ console.error("Login is down", { message });
67
+ return { infra: unavailableInfra(message), using: "nothing" };
68
+ }
69
+ }
70
+ const test_key = parsed.data.INFRA_TEST_KEY;
71
+ if (test_key !== undefined && TEST_KEY.test(test_key)) {
72
+ console.info("Infra: calling it with a test key", { url });
73
+ return { infra: infraClient({ key: test_key, url }), using: "test key" };
74
+ }
75
+ else {
76
+ if (test_key !== undefined) {
77
+ console.error("INFRA_TEST_KEY isn't a test key (sf_test_…), so a dev server won't use it: using the stand-in");
78
+ }
79
+ else {
80
+ console.info("Infra: no test key, so login uses the stand-in, which emails nothing");
81
+ }
82
+ return {
83
+ infra: standInInfra({
84
+ waiting: devServerLogins(),
85
+ logs: true,
86
+ domains
87
+ }),
88
+ using: "stand-in"
89
+ };
90
+ }
91
+ }
92
+ /**
93
+ * The variables in this checkout's `.env`, or, in a git worktree with no
94
+ * `.env` of its own, in its main checkout's: so a computer's test key is
95
+ * set once, in the main checkout, and every worktree of it has it.
96
+ */
97
+ function checkoutVariables(checkout) {
98
+ const own = envFile(join(checkout, ".env"));
99
+ if (own !== undefined) {
100
+ return own;
101
+ }
102
+ const main = mainCheckout(checkout);
103
+ if (main === null) {
104
+ return {};
105
+ }
106
+ else {
107
+ return envFile(join(main, ".env")) ?? {};
108
+ }
109
+ }
110
+ // What a `.env` file sets, or undefined when there's no such file
111
+ function envFile(path) {
112
+ if (!existsSync(path)) {
113
+ return undefined;
114
+ }
115
+ try {
116
+ return parseEnv(readFileSync(path, "utf8"));
117
+ }
118
+ catch (error) {
119
+ console.warn("A .env file couldn't be read", { path, error });
120
+ return undefined;
121
+ }
122
+ }
123
+ // The main checkout of a git worktree, or null for a checkout that isn't
124
+ // one. A worktree's `.git` is a file naming its folder in the main
125
+ // checkout's `.git` (`gitdir: …/.git/worktrees/<name>`), whose `commondir`
126
+ // names that `.git`.
127
+ function mainCheckout(checkout) {
128
+ const dot_git = join(checkout, ".git");
129
+ try {
130
+ if (!existsSync(dot_git) || statSync(dot_git).isDirectory()) {
131
+ return null;
132
+ }
133
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dot_git, "utf8"));
134
+ if (pointer?.[1] === undefined) {
135
+ return null;
136
+ }
137
+ const worktree_git = resolve(checkout, pointer[1].trim());
138
+ const common = readFileSync(join(worktree_git, "commondir"), "utf8");
139
+ return dirname(resolve(worktree_git, common.trim()));
140
+ }
141
+ catch (error) {
142
+ console.warn("A worktree's main checkout couldn't be found", {
143
+ checkout,
144
+ error
145
+ });
146
+ return null;
147
+ }
148
+ }
149
+ // A dev server's stand-in logins, kept for the process rather than the
150
+ // module, since Vite's dev server can evaluate a module again, and a code
151
+ // sent before an edit should still log in after it. Kept on `globalThis`,
152
+ // under a key of the package's own.
153
+ const LOGINS = Symbol.for("@superforge/infra stand-in logins");
154
+ function devServerLogins() {
155
+ const kept = Reflect.get(globalThis, LOGINS);
156
+ if (kept instanceof Map) {
157
+ return kept;
158
+ }
159
+ else {
160
+ const logins = new Map();
161
+ Reflect.set(globalThis, LOGINS, logins);
162
+ return logins;
163
+ }
164
+ }
165
+ // Why a build has no secret key to call Infra with, and what fixes it
166
+ function noSecretKey(set) {
167
+ const fix = "Make a secret key on superforge.studio, in the project's Settings, and paste it into INFRA_SECRET_KEY on the app's service in Railway.";
168
+ if (set === undefined) {
169
+ return `No one can log in: INFRA_SECRET_KEY isn't set on the app's service in Railway. ${fix}`;
170
+ }
171
+ else if (TEST_KEY.test(set)) {
172
+ 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}`;
173
+ }
174
+ else {
175
+ 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}`;
176
+ }
177
+ }
178
+ // Infra when it can't be reached at all: every call answers unavailable,
179
+ // with why, and choosing it logged it
180
+ function unavailableInfra(message) {
181
+ const unavailable = {
182
+ ok: false,
183
+ error: { reason: "unavailable", message }
184
+ };
185
+ return {
186
+ async project() {
187
+ return unavailable;
188
+ },
189
+ async startLogin() {
190
+ return unavailable;
191
+ },
192
+ async verifyLogin() {
193
+ return unavailable;
194
+ },
195
+ async fileComment() {
196
+ return unavailable;
197
+ },
198
+ async passOAuth() {
199
+ return unavailableOAuth(message);
200
+ },
201
+ async agentRequest() {
202
+ return unavailable;
203
+ },
204
+ async allowAgent() {
205
+ return unavailable;
206
+ },
207
+ async denyAgent() {
208
+ return unavailable;
209
+ },
210
+ async agentConnections() {
211
+ return unavailable;
212
+ },
213
+ async endAgentConnection() {
214
+ return unavailable;
215
+ },
216
+ async endAgentConnections() {
217
+ return unavailable;
218
+ },
219
+ async checkAgentToken() {
220
+ return unavailable;
221
+ }
222
+ };
223
+ }
@@ -0,0 +1,22 @@
1
+ import type { Infra } from "./infra.js";
2
+ /**
3
+ * Infra's API, which a project's keys call. A server can be pointed at
4
+ * another Infra with `INFRA_URL` (choose.ts).
5
+ */
6
+ export declare const INFRA_URL = "https://infra.superforge.studio/v1";
7
+ /**
8
+ * Infra, called over HTTP with a project's key: a secret key in a build, a
9
+ * test key in a dev server. No call is retried, since none is safe to send
10
+ * twice (a second start sends a second email, a second verify finds the
11
+ * code spent, and a comment sent again is kept twice); the visitor asks
12
+ * again instead. `send` is `fetch`, or a test's own.
13
+ *
14
+ * Every answer is logged with its call and status, and a refusal with its
15
+ * `error` and Infra's `message`, which says what went wrong and what fixes
16
+ * it (Infra's README, "Errors"), so an app's logs say why a call failed.
17
+ */
18
+ export declare function infraClient({ key, url, send }: {
19
+ key: string;
20
+ url?: string;
21
+ send?: typeof fetch;
22
+ }): Infra;
@@ -0,0 +1,239 @@
1
+ import { agent_connections, agent_ended, agent_redirect, agent_refused, agent_request, checkToken, infraKeys, passThrough } from "./agents.js";
2
+ import { any_refusal, comment_refused, infra_project, kept_comment, start_refused, started_login, verified_login, verify_refused } from "./answers.js";
3
+ import { SECOND } from "./primitives.js";
4
+ /**
5
+ * Infra's API, which a project's keys call. A server can be pointed at
6
+ * another Infra with `INFRA_URL` (choose.ts).
7
+ */
8
+ export const INFRA_URL = "https://infra.superforge.studio/v1";
9
+ // How long a call waits for Infra's answer. Starting a login waits on
10
+ // Infra sending the email, which takes a second or two.
11
+ const TIMEOUT = 15 * SECOND;
12
+ /**
13
+ * Infra, called over HTTP with a project's key: a secret key in a build, a
14
+ * test key in a dev server. No call is retried, since none is safe to send
15
+ * twice (a second start sends a second email, a second verify finds the
16
+ * code spent, and a comment sent again is kept twice); the visitor asks
17
+ * again instead. `send` is `fetch`, or a test's own.
18
+ *
19
+ * Every answer is logged with its call and status, and a refusal with its
20
+ * `error` and Infra's `message`, which says what went wrong and what fixes
21
+ * it (Infra's README, "Errors"), so an app's logs say why a call failed.
22
+ */
23
+ export function infraClient({ key, url = INFRA_URL, send = fetch }) {
24
+ // One call: its status and its JSON, or why there's none, which is
25
+ // logged
26
+ async function ask(method, call, body) {
27
+ const response = await send(`${url}${call}`, {
28
+ method,
29
+ headers: body === undefined
30
+ ? { Authorization: `Bearer ${key}` }
31
+ : {
32
+ Authorization: `Bearer ${key}`,
33
+ "Content-Type": "application/json"
34
+ },
35
+ body: body === undefined ? undefined : JSON.stringify(body),
36
+ signal: AbortSignal.timeout(TIMEOUT)
37
+ }).catch((error) => {
38
+ console.error("Infra didn't answer", { call, url, error });
39
+ return null;
40
+ });
41
+ if (response === null) {
42
+ return unavailable(`Infra didn't answer ${call} at ${url}. It may be down, or INFRA_URL may point somewhere it isn't; trying again in a few minutes may work.`);
43
+ }
44
+ const json = await response.json().catch((error) => {
45
+ console.error("Infra answered without JSON", {
46
+ call,
47
+ status: response.status,
48
+ error
49
+ });
50
+ return undefined;
51
+ });
52
+ if (json === undefined) {
53
+ return unavailable(`Infra answered ${call} with ${response.status} and no JSON, which usually means it's down or INFRA_URL points somewhere that isn't Infra.`);
54
+ }
55
+ const refusal = any_refusal.safeParse(json);
56
+ if (response.status >= 400 && refusal.success) {
57
+ console.info("Infra refused a call", {
58
+ call,
59
+ status: response.status,
60
+ error: refusal.data.error,
61
+ message: refusal.data.message
62
+ });
63
+ }
64
+ else {
65
+ console.info("Infra answered", { call, status: response.status });
66
+ }
67
+ return { ok: true, data: { status: response.status, json } };
68
+ }
69
+ const post = (call, body) => ask("POST", call, body);
70
+ // An answer read with `schema` when it's `status`, else as `refused`,
71
+ // else as one the client doesn't know
72
+ async function answered(asked, call, expected, refused) {
73
+ if (!asked.ok) {
74
+ return asked;
75
+ }
76
+ const answer = asked.data;
77
+ if (answer.status === expected.status) {
78
+ const parsed = expected.schema.safeParse(answer.json);
79
+ return parsed.success
80
+ ? { ok: true, data: parsed.data }
81
+ : unreadable(call, answer);
82
+ }
83
+ else if (refused !== undefined) {
84
+ const parsed = refused.safeParse(answer.json);
85
+ return parsed.success
86
+ ? { ok: false, error: parsed.data }
87
+ : unexpected(call, answer);
88
+ }
89
+ else {
90
+ return unexpected(call, answer);
91
+ }
92
+ }
93
+ // Claude's login (agents.ts): Infra's public keys, fetched once and
94
+ // again for a key they don't have, and which project and mode the key
95
+ // is, which every token must be for, asked once
96
+ const keys = infraKeys(url);
97
+ let project;
98
+ async function projectOf() {
99
+ const call = "/project";
100
+ return answered(await ask("GET", call), call, {
101
+ status: 200,
102
+ schema: infra_project
103
+ });
104
+ }
105
+ // A call about Claude's requests and connections: its answer, or why
106
+ // Infra refused it, or that it couldn't be asked
107
+ async function agents(method, call, schema, body) {
108
+ return answered(await ask(method, call, body), call, { status: 200, schema }, agent_refused);
109
+ }
110
+ return {
111
+ project() {
112
+ return projectOf();
113
+ },
114
+ async startLogin({ email, ip, origin }) {
115
+ const call = "/login/start";
116
+ return answered(await post(call, origin === null ? { email, ip } : { email, ip, origin }), call, { status: 200, schema: started_login }, start_refused);
117
+ },
118
+ async verifyLogin(proof) {
119
+ const call = "/login/verify";
120
+ return answered(await post(call, proof), call, { status: 200, schema: verified_login }, verify_refused);
121
+ },
122
+ async fileComment(comment) {
123
+ const call = "/comments";
124
+ const filed = await answered(await post(call, comment), call, { status: 201, schema: kept_comment }, comment_refused);
125
+ if (!filed.ok && filed.error.reason !== "unavailable") {
126
+ // What the app sent is wrong, which only a change to it
127
+ // fixes
128
+ console.error("Infra refused a comment", {
129
+ call,
130
+ refused: filed.error
131
+ });
132
+ }
133
+ return filed;
134
+ },
135
+ passOAuth(request, path, origin) {
136
+ return passThrough({ url, key, send, request, path, origin });
137
+ },
138
+ async agentRequest(request_id) {
139
+ const asked = await agents("GET", `/agents/requests/${request_id}`, agent_request);
140
+ return asked.ok ? { ok: true, data: asked.data.request } : asked;
141
+ },
142
+ allowAgent(request_id, allowed) {
143
+ return agents("POST", `/agents/requests/${request_id}/allow`, agent_redirect, allowed);
144
+ },
145
+ denyAgent(request_id) {
146
+ return agents("POST", `/agents/requests/${request_id}/deny`, agent_redirect, {});
147
+ },
148
+ async agentConnections(email) {
149
+ const query = new URLSearchParams({ email });
150
+ const listed = await agents("GET", `/agents/connections?${query}`, agent_connections);
151
+ if (listed.ok) {
152
+ return { ok: true, data: listed.data.connections };
153
+ }
154
+ else {
155
+ return { ok: false, error: asUnavailable(listed.error) };
156
+ }
157
+ },
158
+ async endAgentConnection(connection_id) {
159
+ const ended = await agents("DELETE", `/agents/connections/${connection_id}`, agent_ended);
160
+ return ended.ok ? { ok: true, data: null } : ended;
161
+ },
162
+ async endAgentConnections(email) {
163
+ const query = new URLSearchParams({ email });
164
+ const ended = await agents("DELETE", `/agents/connections?${query}`, agent_ended);
165
+ if (ended.ok) {
166
+ return { ok: true, data: ended.data.ended };
167
+ }
168
+ else {
169
+ return { ok: false, error: asUnavailable(ended.error) };
170
+ }
171
+ },
172
+ async checkAgentToken(token, origin) {
173
+ project ??= projectOf();
174
+ const known = await project;
175
+ if (!known.ok) {
176
+ project = undefined;
177
+ console.error("Infra didn't say which project the key is", {
178
+ message: known.error.message
179
+ });
180
+ return known;
181
+ }
182
+ else {
183
+ return await checkToken(keys, token, {
184
+ origin,
185
+ project: known.data.project.id,
186
+ mode: known.data.mode
187
+ });
188
+ }
189
+ }
190
+ };
191
+ }
192
+ // Infra couldn't be asked, and why
193
+ function unavailable(message) {
194
+ return { ok: false, error: { reason: "unavailable", message } };
195
+ }
196
+ // A refusal a call that only lists or ends things can't otherwise answer,
197
+ // read as unavailable with Infra's own words
198
+ function asUnavailable(refused) {
199
+ if ("reason" in refused) {
200
+ return refused;
201
+ }
202
+ else {
203
+ return { reason: "unavailable", message: refused.message };
204
+ }
205
+ }
206
+ // An answer the client doesn't expect: a key Infra refused (401, which an
207
+ // owner fixes in Railway), a body this app sent wrong (400 `invalid`, a
208
+ // bug), or an error Infra added after this version of the package. Logged
209
+ // with what it said, and unavailable, with Infra's own words for why when
210
+ // it gave them, which an app shows its team.
211
+ function unexpected(call, answer) {
212
+ const refusal = any_refusal.safeParse(answer.json);
213
+ const error = refusal.success ? refusal.data.error : null;
214
+ const said = refusal.success ? refusal.data.message : undefined;
215
+ console.error("Infra answered what the client doesn't expect", {
216
+ call,
217
+ status: answer.status,
218
+ answer: answer.json
219
+ });
220
+ if (said !== undefined) {
221
+ return unavailable(said);
222
+ }
223
+ else if (answer.status === 401) {
224
+ return unavailable(`Infra refused this app's key${error === null ? "" : ` (${error})`}. Make a secret key on superforge.studio, in the project's Settings, and paste it into INFRA_SECRET_KEY on the app's service in Railway.`);
225
+ }
226
+ else {
227
+ return unavailable(`Infra answered ${call} with ${answer.status}${error === null ? "" : ` ${error}`}, which this version of @superforge/infra doesn't know. Ask Claude to update @superforge/infra in the app.`);
228
+ }
229
+ }
230
+ // A success the client can't read: Infra changed what a call answers since
231
+ // this version of the package
232
+ function unreadable(call, answer) {
233
+ console.error("Infra answered in a shape the client can't read", {
234
+ call,
235
+ status: answer.status,
236
+ answer: answer.json
237
+ });
238
+ return unavailable(`Infra answered ${call} in a shape this version of @superforge/infra can't read. Ask Claude to update @superforge/infra in the app.`);
239
+ }
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ /** The most a comment says, in characters, as Infra takes it */
3
+ export declare const LONGEST_COMMENT = 5000;
4
+ /** How big one comment's body can be, in bytes, as Infra takes it */
5
+ export declare const COMMENT_BODY_LIMIT: number;
6
+ /**
7
+ * One call's body: what was written, the page's path and title, the
8
+ * element it's about (a CSS selector from the page's body, its tag, the
9
+ * text it shows or null, its `class`, and its box on the page), or null for
10
+ * the page as a whole, the window's size, the app's own ID for whoever
11
+ * filed it, never their email, and their browser's User-Agent, for what
12
+ * they were on, which Infra doesn't keep
13
+ */
14
+ export declare const filed_comment: z.ZodObject<{
15
+ body: z.ZodString;
16
+ path: z.ZodString;
17
+ title: z.ZodNullable<z.ZodString>;
18
+ element: z.ZodNullable<z.ZodObject<{
19
+ selector: z.ZodString;
20
+ tag: z.ZodString;
21
+ text: z.ZodNullable<z.ZodString>;
22
+ classes: z.ZodNullable<z.ZodString>;
23
+ box: z.ZodObject<{
24
+ x: z.ZodNumber;
25
+ y: z.ZodNumber;
26
+ width: z.ZodNumber;
27
+ height: z.ZodNumber;
28
+ }, z.core.$strip>;
29
+ }, z.core.$strip>>;
30
+ viewport: z.ZodNullable<z.ZodObject<{
31
+ width: z.ZodNumber;
32
+ height: z.ZodNumber;
33
+ }, z.core.$strip>>;
34
+ user: z.ZodNullable<z.ZodString>;
35
+ user_agent: z.ZodNullable<z.ZodString>;
36
+ }, z.core.$strip>;
37
+ export type FiledComment = z.infer<typeof filed_comment>;