@principal-ai/subsystems-core 0.53.0 → 0.53.2
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/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/infra/index.d.ts +5 -1
- package/dist/infra/index.d.ts.map +1 -1
- package/dist/infra/index.js +13 -2
- package/dist/infra/index.js.map +1 -1
- package/dist/infra/observe.d.ts +140 -0
- package/dist/infra/observe.d.ts.map +1 -0
- package/dist/infra/observe.js +570 -0
- package/dist/infra/observe.js.map +1 -0
- package/dist/infra/types.d.ts +4 -4
- package/dist/infra/types.js +4 -4
- package/package.json +1 -1
- package/src/index.ts +3 -2
- package/src/infra/index.ts +21 -1
- package/src/infra/observe.neon.test.ts +232 -0
- package/src/infra/observe.test.ts +202 -0
- package/src/infra/observe.ts +741 -0
- package/src/infra/types.ts +4 -4
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Looking at a live account — the checks that turn declared resource keys into
|
|
3
|
+
* {@link InfraDeploymentObservation}s.
|
|
4
|
+
*
|
|
5
|
+
* This is the one place that knows how to ask a provider whether a declared
|
|
6
|
+
* resource exists. It is given a credential and returns observations; it does
|
|
7
|
+
* not know where the credential came from (a pasted token, a CLI login, a
|
|
8
|
+
* server-held token) and it stores nothing. Hosts own both ends: Studio and
|
|
9
|
+
* the desktop app run it in their main process, a hosted service can run it in
|
|
10
|
+
* a Worker.
|
|
11
|
+
*
|
|
12
|
+
* Fetch-only and browser-safe. The token travels only in the Authorization
|
|
13
|
+
* header of requests to the provider's API, and never appears in a result.
|
|
14
|
+
*
|
|
15
|
+
* Cloudflare (Workers, R2, D1, KV, Queues and Containers) and Neon (projects
|
|
16
|
+
* and their databases). A resource type with no lookup is reported as skipped
|
|
17
|
+
* rather than guessed at.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { InfraDeploymentObservation } from './types';
|
|
21
|
+
|
|
22
|
+
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
23
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
24
|
+
const ACCOUNT_ID_SHAPE = /^[a-f0-9]{32}$/;
|
|
25
|
+
|
|
26
|
+
/** What a check needs to run, besides the credential. */
|
|
27
|
+
export interface InfraObserveDeps {
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
now?: () => Date;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A credential for one Cloudflare account. */
|
|
33
|
+
export interface CloudflareAccess {
|
|
34
|
+
/** An API token or an OAuth access token; sent as a Bearer token. */
|
|
35
|
+
token: string;
|
|
36
|
+
accountId: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
40
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type CloudflareResult<T> =
|
|
44
|
+
| { ok: true; result: T }
|
|
45
|
+
| { ok: false; status: number; code?: number; message: string };
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* One read against the Cloudflare API. Failures come back as values: the
|
|
49
|
+
* caller decides whether "not there" and "could not ask" mean different
|
|
50
|
+
* things.
|
|
51
|
+
*/
|
|
52
|
+
async function cloudflareGet<T>(
|
|
53
|
+
path: string,
|
|
54
|
+
token: string,
|
|
55
|
+
doFetch: typeof fetch,
|
|
56
|
+
): Promise<CloudflareResult<T>> {
|
|
57
|
+
let response: Response;
|
|
58
|
+
try {
|
|
59
|
+
response = await doFetch(`${CLOUDFLARE_API}${path}`, {
|
|
60
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
61
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
62
|
+
});
|
|
63
|
+
} catch {
|
|
64
|
+
return { ok: false, status: 0, message: 'could not reach the Cloudflare API' };
|
|
65
|
+
}
|
|
66
|
+
let body: unknown;
|
|
67
|
+
try {
|
|
68
|
+
body = await response.json();
|
|
69
|
+
} catch {
|
|
70
|
+
return { ok: false, status: response.status, message: `Cloudflare answered ${response.status}` };
|
|
71
|
+
}
|
|
72
|
+
if (response.ok && isRecord(body) && body['success'] === true) {
|
|
73
|
+
return { ok: true, result: body['result'] as T };
|
|
74
|
+
}
|
|
75
|
+
// The containers API answers with the bare value, not the usual envelope.
|
|
76
|
+
if (response.ok && (Array.isArray(body) || (isRecord(body) && !('success' in body)))) {
|
|
77
|
+
return { ok: true, result: body as T };
|
|
78
|
+
}
|
|
79
|
+
const first =
|
|
80
|
+
isRecord(body) && Array.isArray(body['errors']) && isRecord(body['errors'][0])
|
|
81
|
+
? body['errors'][0]
|
|
82
|
+
: undefined;
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
status: response.status,
|
|
86
|
+
...(typeof first?.['code'] === 'number' ? { code: first['code'] } : {}),
|
|
87
|
+
message:
|
|
88
|
+
typeof first?.['message'] === 'string'
|
|
89
|
+
? first['message']
|
|
90
|
+
: `Cloudflare answered ${response.status}`,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type CloudflareAccountResult =
|
|
95
|
+
| { ok: true; accountId: string; account?: string }
|
|
96
|
+
| {
|
|
97
|
+
ok: false;
|
|
98
|
+
error: string;
|
|
99
|
+
/** Set when the token sees several accounts and one must be chosen. */
|
|
100
|
+
accounts?: Array<{ id: string; name: string }>;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Work out which account a Cloudflare token is for, and prove it can do the
|
|
105
|
+
* job: it must resolve to one account and be able to read that account's
|
|
106
|
+
* Workers. A token that cannot is refused with the reason, so a person finds
|
|
107
|
+
* out when connecting rather than from cards that never light up.
|
|
108
|
+
*/
|
|
109
|
+
export async function resolveCloudflareAccount(
|
|
110
|
+
input: { token: string; accountId?: string },
|
|
111
|
+
deps: InfraObserveDeps = {},
|
|
112
|
+
): Promise<CloudflareAccountResult> {
|
|
113
|
+
const doFetch = deps.fetch ?? fetch;
|
|
114
|
+
const { token } = input;
|
|
115
|
+
let accountId = input.accountId?.trim() ?? '';
|
|
116
|
+
if (accountId && !ACCOUNT_ID_SHAPE.test(accountId)) {
|
|
117
|
+
return { ok: false, error: 'The account id should be 32 hexadecimal characters.' };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let account: string | undefined;
|
|
121
|
+
const listed = await cloudflareGet<Array<{ id?: string; name?: string }>>(
|
|
122
|
+
'/accounts?per_page=50',
|
|
123
|
+
token,
|
|
124
|
+
doFetch,
|
|
125
|
+
);
|
|
126
|
+
if (!listed.ok && (listed.status === 401 || listed.status === 403) && !accountId) {
|
|
127
|
+
return { ok: false, error: `Cloudflare rejected the token: ${listed.message}` };
|
|
128
|
+
}
|
|
129
|
+
if (!listed.ok && listed.status === 0) return { ok: false, error: listed.message };
|
|
130
|
+
const accounts = (listed.ok && Array.isArray(listed.result) ? listed.result : [])
|
|
131
|
+
.filter((a): a is { id: string; name?: string } => typeof a?.id === 'string')
|
|
132
|
+
.map((a) => ({ id: a.id, name: a.name ?? a.id }));
|
|
133
|
+
if (accountId) {
|
|
134
|
+
account = accounts.find((a) => a.id === accountId)?.name;
|
|
135
|
+
} else if (accounts.length === 1) {
|
|
136
|
+
accountId = accounts[0]!.id;
|
|
137
|
+
account = accounts[0]!.name;
|
|
138
|
+
} else if (accounts.length > 1) {
|
|
139
|
+
return { ok: false, error: 'This token can see several accounts. Choose one.', accounts };
|
|
140
|
+
} else {
|
|
141
|
+
return {
|
|
142
|
+
ok: false,
|
|
143
|
+
error: 'This token cannot list its account. Enter the account id as well.',
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// The permission the checks need. Also proves the account id is right.
|
|
148
|
+
const probe = await cloudflareGet<{ subdomain?: string }>(
|
|
149
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
150
|
+
token,
|
|
151
|
+
doFetch,
|
|
152
|
+
);
|
|
153
|
+
if (!probe.ok) {
|
|
154
|
+
// 10007: no workers.dev subdomain registered — the token still works.
|
|
155
|
+
const usable = probe.status === 404 || probe.code === 10007;
|
|
156
|
+
if (!usable) {
|
|
157
|
+
return {
|
|
158
|
+
ok: false,
|
|
159
|
+
error:
|
|
160
|
+
probe.status === 0
|
|
161
|
+
? probe.message
|
|
162
|
+
: `The token cannot read Workers on that account: ${probe.message}`,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { ok: true, accountId, ...(account ? { account } : {}) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** `cloudflare:worker:name` → `name`. Names may not contain a colon. */
|
|
170
|
+
function parseKey(key: string): { provider: string; resourceType: string; identifier: string } | null {
|
|
171
|
+
const [provider, resourceType, ...rest] = key.split(':');
|
|
172
|
+
const identifier = rest.join(':');
|
|
173
|
+
return provider && resourceType && identifier ? { provider, resourceType, identifier } : null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** What one lookup learned about one resource. */
|
|
177
|
+
type Seen =
|
|
178
|
+
| {
|
|
179
|
+
state: 'deployed';
|
|
180
|
+
resourceId?: string;
|
|
181
|
+
liveUrls?: string[];
|
|
182
|
+
consoleUrl?: string;
|
|
183
|
+
version?: string;
|
|
184
|
+
deployedAt?: string;
|
|
185
|
+
}
|
|
186
|
+
| { state: 'not-found' }
|
|
187
|
+
/** The question could not be asked: auth, network, or an answer we cannot read. */
|
|
188
|
+
| { state: 'unknown'; reason: string };
|
|
189
|
+
|
|
190
|
+
interface CheckContext {
|
|
191
|
+
accountId: string;
|
|
192
|
+
get: <T>(path: string) => Promise<CloudflareResult<T>>;
|
|
193
|
+
/** The account's workers.dev subdomain, fetched once and only if needed. */
|
|
194
|
+
workersSubdomain: () => Promise<string | undefined>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function missing(result: { status: number; code?: number }): boolean {
|
|
198
|
+
return result.status === 404 || result.code === 10007;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function isoOrUndefined(value: unknown): string | undefined {
|
|
202
|
+
return typeof value === 'string' && !Number.isNaN(Date.parse(value))
|
|
203
|
+
? new Date(value).toISOString()
|
|
204
|
+
: undefined;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const dash = (accountId: string, path: string) => `https://dash.cloudflare.com/${accountId}/${path}`;
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* One lookup per resource type. Each asks for exactly the declared thing — by
|
|
211
|
+
* the same name or id the config uses — and never lists more of the account
|
|
212
|
+
* than it needs to find it. Every call is a read.
|
|
213
|
+
*/
|
|
214
|
+
const CHECKS: Record<string, (identifier: string, ctx: CheckContext) => Promise<Seen>> = {
|
|
215
|
+
worker: async (name, ctx) => {
|
|
216
|
+
const script = encodeURIComponent(name);
|
|
217
|
+
const base = `/accounts/${ctx.accountId}/workers/scripts/${script}`;
|
|
218
|
+
const state = await ctx.get<{ enabled?: boolean }>(`${base}/subdomain`);
|
|
219
|
+
if (!state.ok) return missing(state) ? { state: 'not-found' } : { state: 'unknown', reason: state.message };
|
|
220
|
+
|
|
221
|
+
// Everything below is best effort: the Worker is already known to exist.
|
|
222
|
+
const liveUrls: string[] = [];
|
|
223
|
+
const domains = await ctx.get<Array<{ hostname?: string }>>(
|
|
224
|
+
`/accounts/${ctx.accountId}/workers/domains/records?service=${script}`,
|
|
225
|
+
);
|
|
226
|
+
if (domains.ok && Array.isArray(domains.result)) {
|
|
227
|
+
for (const domain of domains.result) {
|
|
228
|
+
if (typeof domain?.hostname === 'string' && domain.hostname) {
|
|
229
|
+
liveUrls.push(`https://${domain.hostname}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (state.result?.enabled) {
|
|
234
|
+
const subdomain = await ctx.workersSubdomain();
|
|
235
|
+
if (subdomain) liveUrls.push(`https://${name}.${subdomain}.workers.dev`);
|
|
236
|
+
}
|
|
237
|
+
const deployments = await ctx.get<{
|
|
238
|
+
deployments?: Array<{ created_on?: string; versions?: Array<{ version_id?: string }> }>;
|
|
239
|
+
}>(`${base}/deployments`);
|
|
240
|
+
const latest = deployments.ok ? deployments.result?.deployments?.[0] : undefined;
|
|
241
|
+
const version = latest?.versions?.[0]?.version_id;
|
|
242
|
+
const deployedAt = isoOrUndefined(latest?.created_on);
|
|
243
|
+
return {
|
|
244
|
+
state: 'deployed',
|
|
245
|
+
// A custom domain, when there is one, is the address people use.
|
|
246
|
+
...(liveUrls.length > 0 ? { liveUrls } : {}),
|
|
247
|
+
consoleUrl: dash(ctx.accountId, `workers/services/view/${script}/production`),
|
|
248
|
+
...(typeof version === 'string' ? { version } : {}),
|
|
249
|
+
...(deployedAt ? { deployedAt } : {}),
|
|
250
|
+
};
|
|
251
|
+
},
|
|
252
|
+
|
|
253
|
+
r2_bucket: async (name, ctx) => {
|
|
254
|
+
const bucket = encodeURIComponent(name);
|
|
255
|
+
const found = await ctx.get<{ creation_date?: string }>(
|
|
256
|
+
`/accounts/${ctx.accountId}/r2/buckets/${bucket}`,
|
|
257
|
+
);
|
|
258
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
259
|
+
return {
|
|
260
|
+
state: 'deployed',
|
|
261
|
+
consoleUrl: dash(ctx.accountId, `r2/default/buckets/${bucket}`),
|
|
262
|
+
};
|
|
263
|
+
},
|
|
264
|
+
|
|
265
|
+
d1_database: async (name, ctx) => {
|
|
266
|
+
// The endpoint accepts a database name as well as its id.
|
|
267
|
+
const found = await ctx.get<{ uuid?: string }>(
|
|
268
|
+
`/accounts/${ctx.accountId}/d1/database/${encodeURIComponent(name)}`,
|
|
269
|
+
);
|
|
270
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
271
|
+
const uuid = typeof found.result?.uuid === 'string' ? found.result.uuid : undefined;
|
|
272
|
+
return {
|
|
273
|
+
state: 'deployed',
|
|
274
|
+
...(uuid ? { resourceId: uuid, consoleUrl: dash(ctx.accountId, `workers/d1/databases/${uuid}`) } : {}),
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
|
|
278
|
+
kv_namespace: async (id, ctx) => {
|
|
279
|
+
const found = await ctx.get<{ id?: string }>(
|
|
280
|
+
`/accounts/${ctx.accountId}/storage/kv/namespaces/${encodeURIComponent(id)}`,
|
|
281
|
+
);
|
|
282
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
283
|
+
return {
|
|
284
|
+
state: 'deployed',
|
|
285
|
+
resourceId: id,
|
|
286
|
+
consoleUrl: dash(ctx.accountId, `workers/kv/namespaces/${encodeURIComponent(id)}`),
|
|
287
|
+
};
|
|
288
|
+
},
|
|
289
|
+
|
|
290
|
+
queue: async (name, ctx) => {
|
|
291
|
+
const listed = await ctx.get<Array<{ queue_id?: string; queue_name?: string }>>(
|
|
292
|
+
`/accounts/${ctx.accountId}/queues?name=${encodeURIComponent(name)}`,
|
|
293
|
+
);
|
|
294
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
295
|
+
if (!Array.isArray(listed.result)) return { state: 'unknown', reason: 'unexpected answer for queues' };
|
|
296
|
+
// The filter may be a prefix match; only an exact name counts.
|
|
297
|
+
const queue = listed.result.find((q) => q?.queue_name === name);
|
|
298
|
+
if (!queue) return { state: 'not-found' };
|
|
299
|
+
return {
|
|
300
|
+
state: 'deployed',
|
|
301
|
+
...(typeof queue.queue_id === 'string' ? { resourceId: queue.queue_id } : {}),
|
|
302
|
+
};
|
|
303
|
+
},
|
|
304
|
+
|
|
305
|
+
container: async (name, ctx) => {
|
|
306
|
+
const listed = await ctx.get<Array<{ id?: string; name?: string; created_at?: string }>>(
|
|
307
|
+
`/accounts/${ctx.accountId}/containers/applications?name=${encodeURIComponent(name)}`,
|
|
308
|
+
);
|
|
309
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
310
|
+
if (!Array.isArray(listed.result)) {
|
|
311
|
+
return { state: 'unknown', reason: 'unexpected answer for container applications' };
|
|
312
|
+
}
|
|
313
|
+
const app = listed.result.find((a) => a?.name === name);
|
|
314
|
+
if (!app) return { state: 'not-found' };
|
|
315
|
+
return {
|
|
316
|
+
state: 'deployed',
|
|
317
|
+
...(typeof app.id === 'string' ? { resourceId: app.id } : {}),
|
|
318
|
+
};
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
/** Cloudflare resource types a check can look at. */
|
|
323
|
+
export const CLOUDFLARE_OBSERVED_TYPES: readonly string[] = Object.keys(CHECKS);
|
|
324
|
+
|
|
325
|
+
/** What one run of checks learned. Nothing here has been stored. */
|
|
326
|
+
export interface InfraObserveResult {
|
|
327
|
+
/**
|
|
328
|
+
* One observation per resource that was looked at, `unknown` ones included.
|
|
329
|
+
* A host that already holds an observation for a key should pass these
|
|
330
|
+
* through {@link withoutUnknownOverwrites} before storing them.
|
|
331
|
+
*/
|
|
332
|
+
observations: InfraDeploymentObservation[];
|
|
333
|
+
/** Keys that were not looked at, with the reason. */
|
|
334
|
+
skipped: Array<{ resourceKey: string; reason: string }>;
|
|
335
|
+
/** Why some lookups could not be made, when any could not. */
|
|
336
|
+
failure?: string;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Run one provider's lookups over the keys that are its own. Keys for other
|
|
341
|
+
* providers are ignored; a type with no lookup is skipped, with the reason.
|
|
342
|
+
*/
|
|
343
|
+
async function runChecks<C>(
|
|
344
|
+
provider: string,
|
|
345
|
+
source: string,
|
|
346
|
+
resourceKeys: readonly string[],
|
|
347
|
+
checks: Record<string, (identifier: string, ctx: C) => Promise<Seen>>,
|
|
348
|
+
ctx: C,
|
|
349
|
+
now: () => Date,
|
|
350
|
+
): Promise<InfraObserveResult> {
|
|
351
|
+
const skipped: InfraObserveResult['skipped'] = [];
|
|
352
|
+
const targets: Array<{ key: string; resourceType: string; identifier: string }> = [];
|
|
353
|
+
for (const key of new Set(resourceKeys)) {
|
|
354
|
+
const parsed = parseKey(key);
|
|
355
|
+
if (!parsed || parsed.provider !== provider) continue;
|
|
356
|
+
if (Object.prototype.hasOwnProperty.call(checks, parsed.resourceType)) targets.push({ key, ...parsed });
|
|
357
|
+
else skipped.push({ resourceKey: key, reason: `${parsed.resourceType} is not checked yet` });
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const observedAt = now().toISOString();
|
|
361
|
+
const observations: InfraDeploymentObservation[] = [];
|
|
362
|
+
const failures = new Set<string>();
|
|
363
|
+
for (const { key, resourceType, identifier } of targets) {
|
|
364
|
+
let seen: Seen;
|
|
365
|
+
try {
|
|
366
|
+
seen = await checks[resourceType]!(identifier, ctx);
|
|
367
|
+
} catch {
|
|
368
|
+
seen = { state: 'unknown', reason: `could not check ${resourceType}` };
|
|
369
|
+
}
|
|
370
|
+
if (seen.state === 'unknown') {
|
|
371
|
+
failures.add(`${resourceType.replace(/_/g, ' ')}: ${seen.reason}`);
|
|
372
|
+
observations.push({ resourceKey: key, status: 'unknown', observedAt, source });
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (seen.state === 'not-found') {
|
|
376
|
+
observations.push({ resourceKey: key, status: 'not-found', observedAt, source });
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const { state: _state, ...facts } = seen;
|
|
380
|
+
observations.push({ resourceKey: key, status: 'deployed', ...facts, observedAt, source });
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
observations,
|
|
384
|
+
skipped,
|
|
385
|
+
...(failures.size > 0 ? { failure: [...failures].join('; ') } : {}),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Look at the named Cloudflare resources and say what was seen.
|
|
391
|
+
*
|
|
392
|
+
* Three outcomes per resource, kept apart on purpose:
|
|
393
|
+
* - it is there → `deployed`, with whatever address and dashboard page it has;
|
|
394
|
+
* - Cloudflare says it does not exist → `not-found`;
|
|
395
|
+
* - the question could not be asked (auth, network) → `unknown`.
|
|
396
|
+
*
|
|
397
|
+
* Failures are per resource: a token that cannot read R2 still gets the
|
|
398
|
+
* Workers checked, and the R2 failure is reported in `failure`. Keys for other
|
|
399
|
+
* providers are ignored.
|
|
400
|
+
*/
|
|
401
|
+
export async function observeCloudflare(
|
|
402
|
+
resourceKeys: readonly string[],
|
|
403
|
+
access: CloudflareAccess,
|
|
404
|
+
deps: InfraObserveDeps = {},
|
|
405
|
+
): Promise<InfraObserveResult> {
|
|
406
|
+
const doFetch = deps.fetch ?? fetch;
|
|
407
|
+
const now = deps.now ?? (() => new Date());
|
|
408
|
+
const { token, accountId } = access;
|
|
409
|
+
|
|
410
|
+
let subdomain: Promise<string | undefined> | undefined;
|
|
411
|
+
const ctx: CheckContext = {
|
|
412
|
+
accountId,
|
|
413
|
+
get: (path) => cloudflareGet(path, token, doFetch),
|
|
414
|
+
workersSubdomain: () => {
|
|
415
|
+
subdomain ??= cloudflareGet<{ subdomain?: string }>(
|
|
416
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
417
|
+
token,
|
|
418
|
+
doFetch,
|
|
419
|
+
).then((sub) =>
|
|
420
|
+
sub.ok && typeof sub.result?.subdomain === 'string' ? sub.result.subdomain : undefined,
|
|
421
|
+
);
|
|
422
|
+
return subdomain;
|
|
423
|
+
},
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
return runChecks('cloudflare', 'cloudflare-api', resourceKeys, CHECKS, ctx, now);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Drop `unknown` observations for resources something is already known about.
|
|
431
|
+
* A failed check must not erase what was known: `unknown` is only worth
|
|
432
|
+
* keeping when it is the first thing said about a resource.
|
|
433
|
+
*/
|
|
434
|
+
export function withoutUnknownOverwrites(
|
|
435
|
+
observations: readonly InfraDeploymentObservation[],
|
|
436
|
+
alreadyKnown: ReadonlySet<string>,
|
|
437
|
+
): InfraDeploymentObservation[] {
|
|
438
|
+
return observations.filter(
|
|
439
|
+
(observation) => observation.status !== 'unknown' || !alreadyKnown.has(observation.resourceKey),
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Read the answer of `wrangler auth token --json` — the credential of whoever
|
|
445
|
+
* is logged in to wrangler on this machine, refreshed by wrangler itself.
|
|
446
|
+
*
|
|
447
|
+
* Only a Bearer credential is usable here: an OAuth login or an API token. A
|
|
448
|
+
* global API key (key + email) is not, and reads as null, as does anything
|
|
449
|
+
* that is not wrangler's JSON.
|
|
450
|
+
*/
|
|
451
|
+
export function parseWranglerAuthToken(
|
|
452
|
+
stdout: string,
|
|
453
|
+
): { token: string; type: 'oauth' | 'api_token' } | null {
|
|
454
|
+
let parsed: unknown;
|
|
455
|
+
try {
|
|
456
|
+
parsed = JSON.parse(stdout);
|
|
457
|
+
} catch {
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
if (!isRecord(parsed)) return null;
|
|
461
|
+
const { type, token } = parsed;
|
|
462
|
+
if (type !== 'oauth' && type !== 'api_token') return null;
|
|
463
|
+
// A header value: refuse anything that could not have been a token.
|
|
464
|
+
if (typeof token !== 'string' || !/^[\x21-\x7e]{20,4096}$/.test(token)) return null;
|
|
465
|
+
return { token, type };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ── Neon ─────────────────────────────────────────────────────────────────────
|
|
469
|
+
|
|
470
|
+
const NEON_API = 'https://console.neon.tech/api/v2';
|
|
471
|
+
const NEON_ORG_ID_SHAPE = /^[a-z0-9-]{1,60}$/;
|
|
472
|
+
/** How many projects are opened to look for a database known only by name. */
|
|
473
|
+
const NEON_PROJECTS_SEARCHED = 20;
|
|
474
|
+
|
|
475
|
+
/** A credential for Neon: an API key, and the organization it is used in. */
|
|
476
|
+
export interface NeonAccess {
|
|
477
|
+
/** A personal, organization or project-scoped API key; sent as a Bearer token. */
|
|
478
|
+
token: string;
|
|
479
|
+
/** Needed with a personal key whose owner belongs to an organization. */
|
|
480
|
+
orgId?: string;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
type NeonResult<T> =
|
|
484
|
+
| { ok: true; result: T }
|
|
485
|
+
| { ok: false; status: number; message: string };
|
|
486
|
+
|
|
487
|
+
/** One read against the Neon API. Failures come back as values. */
|
|
488
|
+
async function neonGet<T>(path: string, token: string, doFetch: typeof fetch): Promise<NeonResult<T>> {
|
|
489
|
+
let response: Response;
|
|
490
|
+
try {
|
|
491
|
+
response = await doFetch(`${NEON_API}${path}`, {
|
|
492
|
+
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
493
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
494
|
+
});
|
|
495
|
+
} catch {
|
|
496
|
+
return { ok: false, status: 0, message: 'could not reach the Neon API' };
|
|
497
|
+
}
|
|
498
|
+
let body: unknown;
|
|
499
|
+
try {
|
|
500
|
+
body = await response.json();
|
|
501
|
+
} catch {
|
|
502
|
+
return { ok: false, status: response.status, message: `Neon answered ${response.status}` };
|
|
503
|
+
}
|
|
504
|
+
if (response.ok) return { ok: true, result: body as T };
|
|
505
|
+
return {
|
|
506
|
+
ok: false,
|
|
507
|
+
status: response.status,
|
|
508
|
+
message:
|
|
509
|
+
isRecord(body) && typeof body['message'] === 'string' && body['message']
|
|
510
|
+
? body['message']
|
|
511
|
+
: `Neon answered ${response.status}`,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export type NeonAccountResult =
|
|
516
|
+
| { ok: true; orgId?: string; account?: string }
|
|
517
|
+
| {
|
|
518
|
+
ok: false;
|
|
519
|
+
error: string;
|
|
520
|
+
/** Set when the key's owner is in several organizations and one must be chosen. */
|
|
521
|
+
accounts?: Array<{ id: string; name: string }>;
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Prove a Neon API key can do the job — list projects — and work out which
|
|
526
|
+
* organization it is used in. A personal key whose owner belongs to
|
|
527
|
+
* organizations has to name one; an organization or project key carries its
|
|
528
|
+
* own.
|
|
529
|
+
*/
|
|
530
|
+
export async function resolveNeonAccount(
|
|
531
|
+
input: { token: string; orgId?: string },
|
|
532
|
+
deps: InfraObserveDeps = {},
|
|
533
|
+
): Promise<NeonAccountResult> {
|
|
534
|
+
const doFetch = deps.fetch ?? fetch;
|
|
535
|
+
const { token } = input;
|
|
536
|
+
let orgId = input.orgId?.trim() ?? '';
|
|
537
|
+
if (orgId && !NEON_ORG_ID_SHAPE.test(orgId)) {
|
|
538
|
+
return { ok: false, error: 'That does not look like a Neon organization id.' };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const probe = (org: string) =>
|
|
542
|
+
neonGet<unknown>(`/projects?limit=1${org ? `&org_id=${encodeURIComponent(org)}` : ''}`, token, doFetch);
|
|
543
|
+
let probed = await probe(orgId);
|
|
544
|
+
if (!probed.ok && !orgId && probed.status === 400 && /org_id/i.test(probed.message)) {
|
|
545
|
+
const listed = await neonGet<{ organizations?: Array<{ id?: string; name?: string }> }>(
|
|
546
|
+
'/users/me/organizations',
|
|
547
|
+
token,
|
|
548
|
+
doFetch,
|
|
549
|
+
);
|
|
550
|
+
const organizations = (listed.ok && Array.isArray(listed.result?.organizations)
|
|
551
|
+
? listed.result.organizations
|
|
552
|
+
: []
|
|
553
|
+
)
|
|
554
|
+
.filter((o): o is { id: string; name?: string } => typeof o?.id === 'string')
|
|
555
|
+
.map((o) => ({ id: o.id, name: o.name ?? o.id }));
|
|
556
|
+
if (organizations.length > 1) {
|
|
557
|
+
return {
|
|
558
|
+
ok: false,
|
|
559
|
+
error: 'This key can see several organizations. Choose one.',
|
|
560
|
+
accounts: organizations,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
if (organizations.length === 0) {
|
|
564
|
+
return {
|
|
565
|
+
ok: false,
|
|
566
|
+
error: 'This key needs an organization. Enter its organization id as the account id.',
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
orgId = organizations[0]!.id;
|
|
570
|
+
probed = await probe(orgId);
|
|
571
|
+
if (probed.ok) return { ok: true, orgId, account: organizations[0]!.name };
|
|
572
|
+
}
|
|
573
|
+
if (!probed.ok) {
|
|
574
|
+
return {
|
|
575
|
+
ok: false,
|
|
576
|
+
error:
|
|
577
|
+
probed.status === 0
|
|
578
|
+
? probed.message
|
|
579
|
+
: probed.status === 401 || probed.status === 403
|
|
580
|
+
? `Neon rejected the key: ${probed.message}`
|
|
581
|
+
: `The key cannot list projects: ${probed.message}`,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Who it is, best effort: an organization's name, or the key owner's.
|
|
586
|
+
let account: string | undefined;
|
|
587
|
+
if (orgId) {
|
|
588
|
+
const org = await neonGet<{ name?: string }>(`/organizations/${encodeURIComponent(orgId)}`, token, doFetch);
|
|
589
|
+
if (org.ok && typeof org.result?.name === 'string') account = org.result.name;
|
|
590
|
+
} else {
|
|
591
|
+
const me = await neonGet<{ name?: string; last_name?: string; login?: string }>('/users/me', token, doFetch);
|
|
592
|
+
if (me.ok) {
|
|
593
|
+
const full = [me.result?.name, me.result?.last_name].filter((part) => typeof part === 'string' && part).join(' ');
|
|
594
|
+
account = full || (typeof me.result?.login === 'string' ? me.result.login : undefined);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return { ok: true, ...(orgId ? { orgId } : {}), ...(account ? { account } : {}) };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
interface NeonProject {
|
|
601
|
+
id: string;
|
|
602
|
+
name?: string;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
interface NeonContext {
|
|
606
|
+
get: <T>(path: string) => Promise<NeonResult<T>>;
|
|
607
|
+
/** `&org_id=…`, or nothing. */
|
|
608
|
+
org: string;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const neonConsole = (projectId: string) =>
|
|
612
|
+
`https://console.neon.tech/app/projects/${encodeURIComponent(projectId)}`;
|
|
613
|
+
|
|
614
|
+
/** Projects whose name or id is exactly `wanted`. The search itself is partial. */
|
|
615
|
+
async function neonProjectsNamed(wanted: string, ctx: NeonContext): Promise<NeonResult<NeonProject[]>> {
|
|
616
|
+
const listed = await ctx.get<{ projects?: NeonProject[] }>(
|
|
617
|
+
`/projects?limit=100&search=${encodeURIComponent(wanted)}${ctx.org}`,
|
|
618
|
+
);
|
|
619
|
+
if (!listed.ok) return listed;
|
|
620
|
+
if (!Array.isArray(listed.result?.projects)) {
|
|
621
|
+
return { ok: false, status: 200, message: 'unexpected answer for projects' };
|
|
622
|
+
}
|
|
623
|
+
return {
|
|
624
|
+
ok: true,
|
|
625
|
+
result: listed.result.projects.filter(
|
|
626
|
+
(p) => typeof p?.id === 'string' && (p.id === wanted || p.name === wanted),
|
|
627
|
+
),
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Whether the project's default branch holds a database of that name. */
|
|
632
|
+
async function neonHasDatabase(
|
|
633
|
+
projectId: string,
|
|
634
|
+
database: string,
|
|
635
|
+
ctx: NeonContext,
|
|
636
|
+
): Promise<{ found: boolean } | { reason: string }> {
|
|
637
|
+
const project = encodeURIComponent(projectId);
|
|
638
|
+
const branches = await ctx.get<{
|
|
639
|
+
branches?: Array<{ id?: string; default?: boolean; primary?: boolean }>;
|
|
640
|
+
}>(`/projects/${project}/branches`);
|
|
641
|
+
if (!branches.ok) return { reason: branches.message };
|
|
642
|
+
const list = Array.isArray(branches.result?.branches) ? branches.result.branches : [];
|
|
643
|
+
const branch = list.find((b) => b?.default === true) ?? list.find((b) => b?.primary === true);
|
|
644
|
+
if (typeof branch?.id !== 'string') return { reason: 'no default branch found' };
|
|
645
|
+
const databases = await ctx.get<{ databases?: Array<{ name?: string }> }>(
|
|
646
|
+
`/projects/${project}/branches/${encodeURIComponent(branch.id)}/databases`,
|
|
647
|
+
);
|
|
648
|
+
if (!databases.ok) return { reason: databases.message };
|
|
649
|
+
if (!Array.isArray(databases.result?.databases)) return { reason: 'unexpected answer for databases' };
|
|
650
|
+
return { found: databases.result.databases.some((d) => d?.name === database) };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Neon lookups. A key names a project by its name or id; a database is named
|
|
655
|
+
* either as `project/database`, or by one name alone, which is taken as the
|
|
656
|
+
* project's name first (people call the whole project "the database") and
|
|
657
|
+
* then as a database inside whichever project holds it. Every call is a read.
|
|
658
|
+
*/
|
|
659
|
+
const NEON_CHECKS: Record<string, (identifier: string, ctx: NeonContext) => Promise<Seen>> = {
|
|
660
|
+
project: async (wanted, ctx) => {
|
|
661
|
+
const found = await neonProjectsNamed(wanted, ctx);
|
|
662
|
+
if (!found.ok) return { state: 'unknown', reason: found.message };
|
|
663
|
+
const project = found.result[0];
|
|
664
|
+
if (!project) return { state: 'not-found' };
|
|
665
|
+
return { state: 'deployed', resourceId: project.id, consoleUrl: neonConsole(project.id) };
|
|
666
|
+
},
|
|
667
|
+
|
|
668
|
+
database: async (wanted, ctx) => {
|
|
669
|
+
const slash = wanted.indexOf('/');
|
|
670
|
+
const projectName = slash > 0 ? wanted.slice(0, slash) : wanted;
|
|
671
|
+
const databaseName = slash > 0 ? wanted.slice(slash + 1) : '';
|
|
672
|
+
|
|
673
|
+
const named = await neonProjectsNamed(projectName, ctx);
|
|
674
|
+
if (!named.ok) return { state: 'unknown', reason: named.message };
|
|
675
|
+
const project = named.result[0];
|
|
676
|
+
if (databaseName) {
|
|
677
|
+
if (!project) return { state: 'not-found' };
|
|
678
|
+
const held = await neonHasDatabase(project.id, databaseName, ctx);
|
|
679
|
+
if ('reason' in held) return { state: 'unknown', reason: held.reason };
|
|
680
|
+
return held.found
|
|
681
|
+
? { state: 'deployed', resourceId: `${project.id}/${databaseName}`, consoleUrl: neonConsole(project.id) }
|
|
682
|
+
: { state: 'not-found' };
|
|
683
|
+
}
|
|
684
|
+
if (project) {
|
|
685
|
+
return { state: 'deployed', resourceId: project.id, consoleUrl: neonConsole(project.id) };
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// No project of that name: look for a database of that name instead.
|
|
689
|
+
const all = await ctx.get<{ projects?: NeonProject[] }>(
|
|
690
|
+
`/projects?limit=${NEON_PROJECTS_SEARCHED + 1}${ctx.org}`,
|
|
691
|
+
);
|
|
692
|
+
if (!all.ok) return { state: 'unknown', reason: all.message };
|
|
693
|
+
const projects = (Array.isArray(all.result?.projects) ? all.result.projects : []).filter(
|
|
694
|
+
(p) => typeof p?.id === 'string',
|
|
695
|
+
);
|
|
696
|
+
let unread: string | undefined;
|
|
697
|
+
for (const candidate of projects.slice(0, NEON_PROJECTS_SEARCHED)) {
|
|
698
|
+
const held = await neonHasDatabase(candidate.id, wanted, ctx);
|
|
699
|
+
if ('reason' in held) {
|
|
700
|
+
unread ??= held.reason;
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
if (held.found) {
|
|
704
|
+
return {
|
|
705
|
+
state: 'deployed',
|
|
706
|
+
resourceId: `${candidate.id}/${wanted}`,
|
|
707
|
+
consoleUrl: neonConsole(candidate.id),
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
// "Not there" is only said when everywhere it could be was read.
|
|
712
|
+
if (unread) return { state: 'unknown', reason: unread };
|
|
713
|
+
if (projects.length > NEON_PROJECTS_SEARCHED) {
|
|
714
|
+
return {
|
|
715
|
+
state: 'unknown',
|
|
716
|
+
reason: `no project is named ${wanted}, and there are too many to search; name it as project/database`,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
return { state: 'not-found' };
|
|
720
|
+
},
|
|
721
|
+
};
|
|
722
|
+
|
|
723
|
+
/** Neon resource types a check can look at. */
|
|
724
|
+
export const NEON_OBSERVED_TYPES: readonly string[] = Object.keys(NEON_CHECKS);
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Look at the named Neon resources and say what was seen, with the same three
|
|
728
|
+
* outcomes as {@link observeCloudflare}. Keys for other providers are ignored.
|
|
729
|
+
*/
|
|
730
|
+
export async function observeNeon(
|
|
731
|
+
resourceKeys: readonly string[],
|
|
732
|
+
access: NeonAccess,
|
|
733
|
+
deps: InfraObserveDeps = {},
|
|
734
|
+
): Promise<InfraObserveResult> {
|
|
735
|
+
const doFetch = deps.fetch ?? fetch;
|
|
736
|
+
const ctx: NeonContext = {
|
|
737
|
+
get: (path) => neonGet(path, access.token, doFetch),
|
|
738
|
+
org: access.orgId ? `&org_id=${encodeURIComponent(access.orgId)}` : '',
|
|
739
|
+
};
|
|
740
|
+
return runChecks('neon', 'neon-api', resourceKeys, NEON_CHECKS, ctx, deps.now ?? (() => new Date()));
|
|
741
|
+
}
|