@superforge/infra 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +162 -2
- package/output/agents.d.ts +96 -0
- package/output/agents.js +171 -0
- package/output/answers.d.ts +154 -0
- package/output/answers.js +153 -0
- package/output/choose.d.ts +13 -0
- package/output/choose.js +223 -0
- package/output/client.d.ts +24 -0
- package/output/client.js +246 -0
- package/output/comments.d.ts +37 -0
- package/output/comments.js +58 -0
- package/output/index.d.ts +9 -0
- package/output/index.js +17 -0
- package/output/infra.d.ts +99 -0
- package/output/infra.js +1 -0
- package/output/primitives.d.ts +13 -0
- package/output/primitives.js +20 -0
- package/output/results.d.ts +14 -0
- package/output/results.js +6 -0
- package/output/stand-in.d.ts +43 -0
- package/output/stand-in.js +237 -0
- package/output/version.d.ts +6 -0
- package/output/version.js +12 -0
- package/package.json +47 -5
|
@@ -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;
|
package/output/choose.js
ADDED
|
@@ -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,24 @@
|
|
|
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 call says which version of the package made it (`Infra-Client`,
|
|
15
|
+
* version.ts). Every answer is logged with its call and status, and a
|
|
16
|
+
* refusal with its `error` and Infra's `message`, which says what went
|
|
17
|
+
* wrong and what fixes it (Infra's README, "Errors"), so an app's logs say
|
|
18
|
+
* why a call failed.
|
|
19
|
+
*/
|
|
20
|
+
export declare function infraClient({ key, url, send }: {
|
|
21
|
+
key: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
send?: typeof fetch;
|
|
24
|
+
}): Infra;
|
package/output/client.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
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
|
+
import { CLIENT, CLIENT_HEADER } from "./version.js";
|
|
5
|
+
/**
|
|
6
|
+
* Infra's API, which a project's keys call. A server can be pointed at
|
|
7
|
+
* another Infra with `INFRA_URL` (choose.ts).
|
|
8
|
+
*/
|
|
9
|
+
export const INFRA_URL = "https://infra.superforge.studio/v1";
|
|
10
|
+
// How long a call waits for Infra's answer. Starting a login waits on
|
|
11
|
+
// Infra sending the email, which takes a second or two.
|
|
12
|
+
const TIMEOUT = 15 * SECOND;
|
|
13
|
+
/**
|
|
14
|
+
* Infra, called over HTTP with a project's key: a secret key in a build, a
|
|
15
|
+
* test key in a dev server. No call is retried, since none is safe to send
|
|
16
|
+
* twice (a second start sends a second email, a second verify finds the
|
|
17
|
+
* code spent, and a comment sent again is kept twice); the visitor asks
|
|
18
|
+
* again instead. `send` is `fetch`, or a test's own.
|
|
19
|
+
*
|
|
20
|
+
* Every call says which version of the package made it (`Infra-Client`,
|
|
21
|
+
* version.ts). Every answer is logged with its call and status, and a
|
|
22
|
+
* refusal with its `error` and Infra's `message`, which says what went
|
|
23
|
+
* wrong and what fixes it (Infra's README, "Errors"), so an app's logs say
|
|
24
|
+
* why a call failed.
|
|
25
|
+
*/
|
|
26
|
+
export function infraClient({ key, url = INFRA_URL, send = fetch }) {
|
|
27
|
+
// One call: its status and its JSON, or why there's none, which is
|
|
28
|
+
// logged
|
|
29
|
+
async function ask(method, call, body) {
|
|
30
|
+
const response = await send(`${url}${call}`, {
|
|
31
|
+
method,
|
|
32
|
+
headers: body === undefined
|
|
33
|
+
? {
|
|
34
|
+
Authorization: `Bearer ${key}`,
|
|
35
|
+
[CLIENT_HEADER]: CLIENT
|
|
36
|
+
}
|
|
37
|
+
: {
|
|
38
|
+
Authorization: `Bearer ${key}`,
|
|
39
|
+
[CLIENT_HEADER]: CLIENT,
|
|
40
|
+
"Content-Type": "application/json"
|
|
41
|
+
},
|
|
42
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
43
|
+
signal: AbortSignal.timeout(TIMEOUT)
|
|
44
|
+
}).catch((error) => {
|
|
45
|
+
console.error("Infra didn't answer", { call, url, error });
|
|
46
|
+
return null;
|
|
47
|
+
});
|
|
48
|
+
if (response === null) {
|
|
49
|
+
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.`);
|
|
50
|
+
}
|
|
51
|
+
const json = await response.json().catch((error) => {
|
|
52
|
+
console.error("Infra answered without JSON", {
|
|
53
|
+
call,
|
|
54
|
+
status: response.status,
|
|
55
|
+
error
|
|
56
|
+
});
|
|
57
|
+
return undefined;
|
|
58
|
+
});
|
|
59
|
+
if (json === undefined) {
|
|
60
|
+
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.`);
|
|
61
|
+
}
|
|
62
|
+
const refusal = any_refusal.safeParse(json);
|
|
63
|
+
if (response.status >= 400 && refusal.success) {
|
|
64
|
+
console.info("Infra refused a call", {
|
|
65
|
+
call,
|
|
66
|
+
status: response.status,
|
|
67
|
+
error: refusal.data.error,
|
|
68
|
+
message: refusal.data.message
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
console.info("Infra answered", { call, status: response.status });
|
|
73
|
+
}
|
|
74
|
+
return { ok: true, data: { status: response.status, json } };
|
|
75
|
+
}
|
|
76
|
+
const post = (call, body) => ask("POST", call, body);
|
|
77
|
+
// An answer read with `schema` when it's `status`, else as `refused`,
|
|
78
|
+
// else as one the client doesn't know
|
|
79
|
+
async function answered(asked, call, expected, refused) {
|
|
80
|
+
if (!asked.ok) {
|
|
81
|
+
return asked;
|
|
82
|
+
}
|
|
83
|
+
const answer = asked.data;
|
|
84
|
+
if (answer.status === expected.status) {
|
|
85
|
+
const parsed = expected.schema.safeParse(answer.json);
|
|
86
|
+
return parsed.success
|
|
87
|
+
? { ok: true, data: parsed.data }
|
|
88
|
+
: unreadable(call, answer);
|
|
89
|
+
}
|
|
90
|
+
else if (refused !== undefined) {
|
|
91
|
+
const parsed = refused.safeParse(answer.json);
|
|
92
|
+
return parsed.success
|
|
93
|
+
? { ok: false, error: parsed.data }
|
|
94
|
+
: unexpected(call, answer);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
return unexpected(call, answer);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// Claude's login (agents.ts): Infra's public keys, fetched once and
|
|
101
|
+
// again for a key they don't have, and which project and mode the key
|
|
102
|
+
// is, which every token must be for, asked once
|
|
103
|
+
const keys = infraKeys(url);
|
|
104
|
+
let project;
|
|
105
|
+
async function projectOf() {
|
|
106
|
+
const call = "/project";
|
|
107
|
+
return answered(await ask("GET", call), call, {
|
|
108
|
+
status: 200,
|
|
109
|
+
schema: infra_project
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
// A call about Claude's requests and connections: its answer, or why
|
|
113
|
+
// Infra refused it, or that it couldn't be asked
|
|
114
|
+
async function agents(method, call, schema, body) {
|
|
115
|
+
return answered(await ask(method, call, body), call, { status: 200, schema }, agent_refused);
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
project() {
|
|
119
|
+
return projectOf();
|
|
120
|
+
},
|
|
121
|
+
async startLogin({ email, ip, origin }) {
|
|
122
|
+
const call = "/login/start";
|
|
123
|
+
return answered(await post(call, origin === null ? { email, ip } : { email, ip, origin }), call, { status: 200, schema: started_login }, start_refused);
|
|
124
|
+
},
|
|
125
|
+
async verifyLogin(proof) {
|
|
126
|
+
const call = "/login/verify";
|
|
127
|
+
return answered(await post(call, proof), call, { status: 200, schema: verified_login }, verify_refused);
|
|
128
|
+
},
|
|
129
|
+
async fileComment(comment) {
|
|
130
|
+
const call = "/comments";
|
|
131
|
+
const filed = await answered(await post(call, comment), call, { status: 201, schema: kept_comment }, comment_refused);
|
|
132
|
+
if (!filed.ok && filed.error.reason !== "unavailable") {
|
|
133
|
+
// What the app sent is wrong, which only a change to it
|
|
134
|
+
// fixes
|
|
135
|
+
console.error("Infra refused a comment", {
|
|
136
|
+
call,
|
|
137
|
+
refused: filed.error
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return filed;
|
|
141
|
+
},
|
|
142
|
+
passOAuth(request, path, origin) {
|
|
143
|
+
return passThrough({ url, key, send, request, path, origin });
|
|
144
|
+
},
|
|
145
|
+
async agentRequest(request_id) {
|
|
146
|
+
const asked = await agents("GET", `/agents/requests/${request_id}`, agent_request);
|
|
147
|
+
return asked.ok ? { ok: true, data: asked.data.request } : asked;
|
|
148
|
+
},
|
|
149
|
+
allowAgent(request_id, allowed) {
|
|
150
|
+
return agents("POST", `/agents/requests/${request_id}/allow`, agent_redirect, allowed);
|
|
151
|
+
},
|
|
152
|
+
denyAgent(request_id) {
|
|
153
|
+
return agents("POST", `/agents/requests/${request_id}/deny`, agent_redirect, {});
|
|
154
|
+
},
|
|
155
|
+
async agentConnections(email) {
|
|
156
|
+
const query = new URLSearchParams({ email });
|
|
157
|
+
const listed = await agents("GET", `/agents/connections?${query}`, agent_connections);
|
|
158
|
+
if (listed.ok) {
|
|
159
|
+
return { ok: true, data: listed.data.connections };
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
return { ok: false, error: asUnavailable(listed.error) };
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
async endAgentConnection(connection_id) {
|
|
166
|
+
const ended = await agents("DELETE", `/agents/connections/${connection_id}`, agent_ended);
|
|
167
|
+
return ended.ok ? { ok: true, data: null } : ended;
|
|
168
|
+
},
|
|
169
|
+
async endAgentConnections(email) {
|
|
170
|
+
const query = new URLSearchParams({ email });
|
|
171
|
+
const ended = await agents("DELETE", `/agents/connections?${query}`, agent_ended);
|
|
172
|
+
if (ended.ok) {
|
|
173
|
+
return { ok: true, data: ended.data.ended };
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
return { ok: false, error: asUnavailable(ended.error) };
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
async checkAgentToken(token, origin) {
|
|
180
|
+
project ??= projectOf();
|
|
181
|
+
const known = await project;
|
|
182
|
+
if (!known.ok) {
|
|
183
|
+
project = undefined;
|
|
184
|
+
console.error("Infra didn't say which project the key is", {
|
|
185
|
+
message: known.error.message
|
|
186
|
+
});
|
|
187
|
+
return known;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
return await checkToken(keys, token, {
|
|
191
|
+
origin,
|
|
192
|
+
project: known.data.project.id,
|
|
193
|
+
mode: known.data.mode
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
// Infra couldn't be asked, and why
|
|
200
|
+
function unavailable(message) {
|
|
201
|
+
return { ok: false, error: { reason: "unavailable", message } };
|
|
202
|
+
}
|
|
203
|
+
// A refusal a call that only lists or ends things can't otherwise answer,
|
|
204
|
+
// read as unavailable with Infra's own words
|
|
205
|
+
function asUnavailable(refused) {
|
|
206
|
+
if ("reason" in refused) {
|
|
207
|
+
return refused;
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
return { reason: "unavailable", message: refused.message };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// An answer the client doesn't expect: a key Infra refused (401, which an
|
|
214
|
+
// owner fixes in Railway), a body this app sent wrong (400 `invalid`, a
|
|
215
|
+
// bug), or an error Infra added after this version of the package. Logged
|
|
216
|
+
// with what it said, and unavailable, with Infra's own words for why when
|
|
217
|
+
// it gave them, which an app shows its team.
|
|
218
|
+
function unexpected(call, answer) {
|
|
219
|
+
const refusal = any_refusal.safeParse(answer.json);
|
|
220
|
+
const error = refusal.success ? refusal.data.error : null;
|
|
221
|
+
const said = refusal.success ? refusal.data.message : undefined;
|
|
222
|
+
console.error("Infra answered what the client doesn't expect", {
|
|
223
|
+
call,
|
|
224
|
+
status: answer.status,
|
|
225
|
+
answer: answer.json
|
|
226
|
+
});
|
|
227
|
+
if (said !== undefined) {
|
|
228
|
+
return unavailable(said);
|
|
229
|
+
}
|
|
230
|
+
else if (answer.status === 401) {
|
|
231
|
+
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.`);
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
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.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// A success the client can't read: Infra changed what a call answers since
|
|
238
|
+
// this version of the package
|
|
239
|
+
function unreadable(call, answer) {
|
|
240
|
+
console.error("Infra answered in a shape the client can't read", {
|
|
241
|
+
call,
|
|
242
|
+
status: answer.status,
|
|
243
|
+
answer: answer.json
|
|
244
|
+
});
|
|
245
|
+
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.`);
|
|
246
|
+
}
|