@principal-ai/subsystems-core 0.53.0 → 0.53.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/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 +10 -2
- package/dist/infra/index.js.map +1 -1
- package/dist/infra/observe.d.ts +102 -0
- package/dist/infra/observe.d.ts.map +1 -0
- package/dist/infra/observe.js +347 -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 +16 -1
- package/src/infra/observe.test.ts +202 -0
- package/src/infra/observe.ts +451 -0
- package/src/infra/types.ts +4 -4
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
observeCloudflare,
|
|
4
|
+
parseWranglerAuthToken,
|
|
5
|
+
resolveCloudflareAccount,
|
|
6
|
+
withoutUnknownOverwrites,
|
|
7
|
+
} from './observe';
|
|
8
|
+
|
|
9
|
+
const TOKEN = 'cf_test_token_0123456789abcdefghij';
|
|
10
|
+
const ACCOUNT = 'a'.repeat(32);
|
|
11
|
+
const NOW = () => new Date('2026-12-05T12:00:00.000Z');
|
|
12
|
+
|
|
13
|
+
type Route = { status?: number; result?: unknown; errors?: Array<{ code: number; message: string }> };
|
|
14
|
+
|
|
15
|
+
/** A Cloudflare API stand-in: path → answer. Records what it was asked. */
|
|
16
|
+
function fakeCloudflare(routes: Record<string, Route>) {
|
|
17
|
+
const seen: Array<{ method: string; path: string; authorization: string | null }> = [];
|
|
18
|
+
const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
|
|
19
|
+
const url = new URL(String(input));
|
|
20
|
+
const path = url.pathname.replace('/client/v4', '');
|
|
21
|
+
seen.push({
|
|
22
|
+
method: init?.method ?? 'GET',
|
|
23
|
+
path,
|
|
24
|
+
authorization: new Headers(init?.headers).get('authorization'),
|
|
25
|
+
});
|
|
26
|
+
const route = routes[`${path}${url.search}`] ?? routes[path];
|
|
27
|
+
if (!route) {
|
|
28
|
+
return Response.json(
|
|
29
|
+
{ success: false, errors: [{ code: 10007, message: 'not found' }] },
|
|
30
|
+
{ status: 404 },
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const status = route.status ?? 200;
|
|
34
|
+
return Response.json(
|
|
35
|
+
{ success: status < 400, result: route.result ?? null, errors: route.errors ?? [] },
|
|
36
|
+
{ status },
|
|
37
|
+
);
|
|
38
|
+
}) as typeof fetch;
|
|
39
|
+
return { fetchImpl, seen };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('resolveCloudflareAccount', () => {
|
|
43
|
+
test('one visible account that can read Workers is accepted', async () => {
|
|
44
|
+
const { fetchImpl } = fakeCloudflare({
|
|
45
|
+
'/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
|
|
46
|
+
[`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
|
|
47
|
+
});
|
|
48
|
+
expect(await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl })).toEqual({
|
|
49
|
+
ok: true,
|
|
50
|
+
accountId: ACCOUNT,
|
|
51
|
+
account: 'Acme',
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('several accounts: the caller has to choose', async () => {
|
|
56
|
+
const other = 'b'.repeat(32);
|
|
57
|
+
const { fetchImpl } = fakeCloudflare({
|
|
58
|
+
'/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }, { id: other, name: 'Other' }] },
|
|
59
|
+
});
|
|
60
|
+
const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
|
|
61
|
+
expect(result).toMatchObject({ ok: false, accounts: [{ id: ACCOUNT }, { id: other }] });
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('a token that cannot read Workers is refused with the reason', async () => {
|
|
65
|
+
const { fetchImpl } = fakeCloudflare({
|
|
66
|
+
'/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
|
|
67
|
+
[`/accounts/${ACCOUNT}/workers/subdomain`]: {
|
|
68
|
+
status: 403,
|
|
69
|
+
errors: [{ code: 10000, message: 'Authentication error' }],
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
|
|
73
|
+
expect(result).toEqual({
|
|
74
|
+
ok: false,
|
|
75
|
+
error: 'The token cannot read Workers on that account: Authentication error',
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('a malformed account id is refused before asking anyone', async () => {
|
|
80
|
+
const { fetchImpl, seen } = fakeCloudflare({});
|
|
81
|
+
const result = await resolveCloudflareAccount(
|
|
82
|
+
{ token: TOKEN, accountId: 'nope' },
|
|
83
|
+
{ fetch: fetchImpl },
|
|
84
|
+
);
|
|
85
|
+
expect(result.ok).toBe(false);
|
|
86
|
+
expect(seen).toEqual([]);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe('observeCloudflare', () => {
|
|
91
|
+
const access = { token: TOKEN, accountId: ACCOUNT };
|
|
92
|
+
|
|
93
|
+
test('deployed, not-found, unknown and skipped are told apart, and nothing but reads is sent', async () => {
|
|
94
|
+
const { fetchImpl, seen } = fakeCloudflare({
|
|
95
|
+
[`/accounts/${ACCOUNT}/workers/scripts/api/subdomain`]: { result: { enabled: true } },
|
|
96
|
+
[`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
|
|
97
|
+
[`/accounts/${ACCOUNT}/workers/scripts/api/deployments`]: {
|
|
98
|
+
result: {
|
|
99
|
+
deployments: [{ created_on: '2026-12-01T08:00:00Z', versions: [{ version_id: 'v-123' }] }],
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
[`/accounts/${ACCOUNT}/r2/buckets/blobs`]: {
|
|
103
|
+
status: 403,
|
|
104
|
+
errors: [{ code: 10000, message: 'Authentication error' }],
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
const result = await observeCloudflare(
|
|
108
|
+
[
|
|
109
|
+
'cloudflare:worker:api',
|
|
110
|
+
'cloudflare:worker:gone',
|
|
111
|
+
'cloudflare:r2_bucket:blobs',
|
|
112
|
+
'cloudflare:hyperdrive:pg',
|
|
113
|
+
'aws:lambda:ignored',
|
|
114
|
+
'cloudflare:worker:api',
|
|
115
|
+
],
|
|
116
|
+
access,
|
|
117
|
+
{ fetch: fetchImpl, now: NOW },
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
expect(result.observations).toEqual([
|
|
121
|
+
{
|
|
122
|
+
resourceKey: 'cloudflare:worker:api',
|
|
123
|
+
status: 'deployed',
|
|
124
|
+
liveUrls: ['https://api.acme.workers.dev'],
|
|
125
|
+
consoleUrl: `https://dash.cloudflare.com/${ACCOUNT}/workers/services/view/api/production`,
|
|
126
|
+
version: 'v-123',
|
|
127
|
+
deployedAt: '2026-12-01T08:00:00.000Z',
|
|
128
|
+
observedAt: '2026-12-05T12:00:00.000Z',
|
|
129
|
+
source: 'cloudflare-api',
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
resourceKey: 'cloudflare:worker:gone',
|
|
133
|
+
status: 'not-found',
|
|
134
|
+
observedAt: '2026-12-05T12:00:00.000Z',
|
|
135
|
+
source: 'cloudflare-api',
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
resourceKey: 'cloudflare:r2_bucket:blobs',
|
|
139
|
+
status: 'unknown',
|
|
140
|
+
observedAt: '2026-12-05T12:00:00.000Z',
|
|
141
|
+
source: 'cloudflare-api',
|
|
142
|
+
},
|
|
143
|
+
]);
|
|
144
|
+
expect(result.skipped).toEqual([
|
|
145
|
+
{ resourceKey: 'cloudflare:hyperdrive:pg', reason: 'hyperdrive is not checked yet' },
|
|
146
|
+
]);
|
|
147
|
+
expect(result.failure).toBe('r2 bucket: Authentication error');
|
|
148
|
+
expect(seen.every((call) => call.method === 'GET')).toBe(true);
|
|
149
|
+
expect(seen.every((call) => call.authorization === `Bearer ${TOKEN}`)).toBe(true);
|
|
150
|
+
expect(JSON.stringify(result)).not.toContain(TOKEN);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('an unreachable API reads as unknown, never as not-found', async () => {
|
|
154
|
+
const failing = (async () => {
|
|
155
|
+
throw new Error('offline');
|
|
156
|
+
}) as unknown as typeof fetch;
|
|
157
|
+
const result = await observeCloudflare(['cloudflare:worker:api'], access, {
|
|
158
|
+
fetch: failing,
|
|
159
|
+
now: NOW,
|
|
160
|
+
});
|
|
161
|
+
expect(result.observations.map((o) => o.status)).toEqual(['unknown']);
|
|
162
|
+
expect(result.failure).toBe('worker: could not reach the Cloudflare API');
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
describe('withoutUnknownOverwrites', () => {
|
|
167
|
+
test('an unknown is kept only when nothing is known about the resource', () => {
|
|
168
|
+
const at = { observedAt: '2026-12-05T12:00:00.000Z', source: 'cloudflare-api' };
|
|
169
|
+
const kept = withoutUnknownOverwrites(
|
|
170
|
+
[
|
|
171
|
+
{ resourceKey: 'a', status: 'unknown', ...at },
|
|
172
|
+
{ resourceKey: 'b', status: 'unknown', ...at },
|
|
173
|
+
{ resourceKey: 'c', status: 'not-found', ...at },
|
|
174
|
+
],
|
|
175
|
+
new Set(['a', 'c']),
|
|
176
|
+
);
|
|
177
|
+
expect(kept.map((o) => o.resourceKey)).toEqual(['b', 'c']);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe('parseWranglerAuthToken', () => {
|
|
182
|
+
test('an OAuth login and an API token are usable', () => {
|
|
183
|
+
const oauth = `${'x'.repeat(40)}.${'y'.repeat(40)}`;
|
|
184
|
+
expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: oauth }))).toEqual({
|
|
185
|
+
type: 'oauth',
|
|
186
|
+
token: oauth,
|
|
187
|
+
});
|
|
188
|
+
expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_token', token: TOKEN }))).toEqual({
|
|
189
|
+
type: 'api_token',
|
|
190
|
+
token: TOKEN,
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test('a global API key, a logged-out answer and noise are not', () => {
|
|
195
|
+
expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_key', key: 'k', email: 'e' }))).toBeNull();
|
|
196
|
+
expect(parseWranglerAuthToken('Not logged in.')).toBeNull();
|
|
197
|
+
expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: 'short' }))).toBeNull();
|
|
198
|
+
expect(
|
|
199
|
+
parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: `${'x'.repeat(30)}\r\nX-Evil: 1` })),
|
|
200
|
+
).toBeNull();
|
|
201
|
+
});
|
|
202
|
+
});
|
|
@@ -0,0 +1,451 @@
|
|
|
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 only: Workers, R2, D1, KV, Queues and Containers. A resource type
|
|
16
|
+
* with no lookup is reported as skipped rather than guessed at.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { InfraDeploymentObservation } from './types';
|
|
20
|
+
|
|
21
|
+
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
22
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
23
|
+
const ACCOUNT_ID_SHAPE = /^[a-f0-9]{32}$/;
|
|
24
|
+
|
|
25
|
+
/** What a check needs to run, besides the credential. */
|
|
26
|
+
export interface InfraObserveDeps {
|
|
27
|
+
fetch?: typeof fetch;
|
|
28
|
+
now?: () => Date;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A credential for one Cloudflare account. */
|
|
32
|
+
export interface CloudflareAccess {
|
|
33
|
+
/** An API token or an OAuth access token; sent as a Bearer token. */
|
|
34
|
+
token: string;
|
|
35
|
+
accountId: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
39
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type CloudflareResult<T> =
|
|
43
|
+
| { ok: true; result: T }
|
|
44
|
+
| { ok: false; status: number; code?: number; message: string };
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One read against the Cloudflare API. Failures come back as values: the
|
|
48
|
+
* caller decides whether "not there" and "could not ask" mean different
|
|
49
|
+
* things.
|
|
50
|
+
*/
|
|
51
|
+
async function cloudflareGet<T>(
|
|
52
|
+
path: string,
|
|
53
|
+
token: string,
|
|
54
|
+
doFetch: typeof fetch,
|
|
55
|
+
): Promise<CloudflareResult<T>> {
|
|
56
|
+
let response: Response;
|
|
57
|
+
try {
|
|
58
|
+
response = await doFetch(`${CLOUDFLARE_API}${path}`, {
|
|
59
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
60
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
61
|
+
});
|
|
62
|
+
} catch {
|
|
63
|
+
return { ok: false, status: 0, message: 'could not reach the Cloudflare API' };
|
|
64
|
+
}
|
|
65
|
+
let body: unknown;
|
|
66
|
+
try {
|
|
67
|
+
body = await response.json();
|
|
68
|
+
} catch {
|
|
69
|
+
return { ok: false, status: response.status, message: `Cloudflare answered ${response.status}` };
|
|
70
|
+
}
|
|
71
|
+
if (response.ok && isRecord(body) && body['success'] === true) {
|
|
72
|
+
return { ok: true, result: body['result'] as T };
|
|
73
|
+
}
|
|
74
|
+
// The containers API answers with the bare value, not the usual envelope.
|
|
75
|
+
if (response.ok && (Array.isArray(body) || (isRecord(body) && !('success' in body)))) {
|
|
76
|
+
return { ok: true, result: body as T };
|
|
77
|
+
}
|
|
78
|
+
const first =
|
|
79
|
+
isRecord(body) && Array.isArray(body['errors']) && isRecord(body['errors'][0])
|
|
80
|
+
? body['errors'][0]
|
|
81
|
+
: undefined;
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
status: response.status,
|
|
85
|
+
...(typeof first?.['code'] === 'number' ? { code: first['code'] } : {}),
|
|
86
|
+
message:
|
|
87
|
+
typeof first?.['message'] === 'string'
|
|
88
|
+
? first['message']
|
|
89
|
+
: `Cloudflare answered ${response.status}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type CloudflareAccountResult =
|
|
94
|
+
| { ok: true; accountId: string; account?: string }
|
|
95
|
+
| {
|
|
96
|
+
ok: false;
|
|
97
|
+
error: string;
|
|
98
|
+
/** Set when the token sees several accounts and one must be chosen. */
|
|
99
|
+
accounts?: Array<{ id: string; name: string }>;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Work out which account a Cloudflare token is for, and prove it can do the
|
|
104
|
+
* job: it must resolve to one account and be able to read that account's
|
|
105
|
+
* Workers. A token that cannot is refused with the reason, so a person finds
|
|
106
|
+
* out when connecting rather than from cards that never light up.
|
|
107
|
+
*/
|
|
108
|
+
export async function resolveCloudflareAccount(
|
|
109
|
+
input: { token: string; accountId?: string },
|
|
110
|
+
deps: InfraObserveDeps = {},
|
|
111
|
+
): Promise<CloudflareAccountResult> {
|
|
112
|
+
const doFetch = deps.fetch ?? fetch;
|
|
113
|
+
const { token } = input;
|
|
114
|
+
let accountId = input.accountId?.trim() ?? '';
|
|
115
|
+
if (accountId && !ACCOUNT_ID_SHAPE.test(accountId)) {
|
|
116
|
+
return { ok: false, error: 'The account id should be 32 hexadecimal characters.' };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let account: string | undefined;
|
|
120
|
+
const listed = await cloudflareGet<Array<{ id?: string; name?: string }>>(
|
|
121
|
+
'/accounts?per_page=50',
|
|
122
|
+
token,
|
|
123
|
+
doFetch,
|
|
124
|
+
);
|
|
125
|
+
if (!listed.ok && (listed.status === 401 || listed.status === 403) && !accountId) {
|
|
126
|
+
return { ok: false, error: `Cloudflare rejected the token: ${listed.message}` };
|
|
127
|
+
}
|
|
128
|
+
if (!listed.ok && listed.status === 0) return { ok: false, error: listed.message };
|
|
129
|
+
const accounts = (listed.ok && Array.isArray(listed.result) ? listed.result : [])
|
|
130
|
+
.filter((a): a is { id: string; name?: string } => typeof a?.id === 'string')
|
|
131
|
+
.map((a) => ({ id: a.id, name: a.name ?? a.id }));
|
|
132
|
+
if (accountId) {
|
|
133
|
+
account = accounts.find((a) => a.id === accountId)?.name;
|
|
134
|
+
} else if (accounts.length === 1) {
|
|
135
|
+
accountId = accounts[0]!.id;
|
|
136
|
+
account = accounts[0]!.name;
|
|
137
|
+
} else if (accounts.length > 1) {
|
|
138
|
+
return { ok: false, error: 'This token can see several accounts. Choose one.', accounts };
|
|
139
|
+
} else {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
error: 'This token cannot list its account. Enter the account id as well.',
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The permission the checks need. Also proves the account id is right.
|
|
147
|
+
const probe = await cloudflareGet<{ subdomain?: string }>(
|
|
148
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
149
|
+
token,
|
|
150
|
+
doFetch,
|
|
151
|
+
);
|
|
152
|
+
if (!probe.ok) {
|
|
153
|
+
// 10007: no workers.dev subdomain registered — the token still works.
|
|
154
|
+
const usable = probe.status === 404 || probe.code === 10007;
|
|
155
|
+
if (!usable) {
|
|
156
|
+
return {
|
|
157
|
+
ok: false,
|
|
158
|
+
error:
|
|
159
|
+
probe.status === 0
|
|
160
|
+
? probe.message
|
|
161
|
+
: `The token cannot read Workers on that account: ${probe.message}`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { ok: true, accountId, ...(account ? { account } : {}) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `cloudflare:worker:name` → `name`. Names may not contain a colon. */
|
|
169
|
+
function parseKey(key: string): { provider: string; resourceType: string; identifier: string } | null {
|
|
170
|
+
const [provider, resourceType, ...rest] = key.split(':');
|
|
171
|
+
const identifier = rest.join(':');
|
|
172
|
+
return provider && resourceType && identifier ? { provider, resourceType, identifier } : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** What one lookup learned about one resource. */
|
|
176
|
+
type Seen =
|
|
177
|
+
| {
|
|
178
|
+
state: 'deployed';
|
|
179
|
+
resourceId?: string;
|
|
180
|
+
liveUrls?: string[];
|
|
181
|
+
consoleUrl?: string;
|
|
182
|
+
version?: string;
|
|
183
|
+
deployedAt?: string;
|
|
184
|
+
}
|
|
185
|
+
| { state: 'not-found' }
|
|
186
|
+
/** The question could not be asked: auth, network, or an answer we cannot read. */
|
|
187
|
+
| { state: 'unknown'; reason: string };
|
|
188
|
+
|
|
189
|
+
interface CheckContext {
|
|
190
|
+
accountId: string;
|
|
191
|
+
get: <T>(path: string) => Promise<CloudflareResult<T>>;
|
|
192
|
+
/** The account's workers.dev subdomain, fetched once and only if needed. */
|
|
193
|
+
workersSubdomain: () => Promise<string | undefined>;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function missing(result: { status: number; code?: number }): boolean {
|
|
197
|
+
return result.status === 404 || result.code === 10007;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function isoOrUndefined(value: unknown): string | undefined {
|
|
201
|
+
return typeof value === 'string' && !Number.isNaN(Date.parse(value))
|
|
202
|
+
? new Date(value).toISOString()
|
|
203
|
+
: undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const dash = (accountId: string, path: string) => `https://dash.cloudflare.com/${accountId}/${path}`;
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* One lookup per resource type. Each asks for exactly the declared thing — by
|
|
210
|
+
* the same name or id the config uses — and never lists more of the account
|
|
211
|
+
* than it needs to find it. Every call is a read.
|
|
212
|
+
*/
|
|
213
|
+
const CHECKS: Record<string, (identifier: string, ctx: CheckContext) => Promise<Seen>> = {
|
|
214
|
+
worker: async (name, ctx) => {
|
|
215
|
+
const script = encodeURIComponent(name);
|
|
216
|
+
const base = `/accounts/${ctx.accountId}/workers/scripts/${script}`;
|
|
217
|
+
const state = await ctx.get<{ enabled?: boolean }>(`${base}/subdomain`);
|
|
218
|
+
if (!state.ok) return missing(state) ? { state: 'not-found' } : { state: 'unknown', reason: state.message };
|
|
219
|
+
|
|
220
|
+
// Everything below is best effort: the Worker is already known to exist.
|
|
221
|
+
const liveUrls: string[] = [];
|
|
222
|
+
const domains = await ctx.get<Array<{ hostname?: string }>>(
|
|
223
|
+
`/accounts/${ctx.accountId}/workers/domains/records?service=${script}`,
|
|
224
|
+
);
|
|
225
|
+
if (domains.ok && Array.isArray(domains.result)) {
|
|
226
|
+
for (const domain of domains.result) {
|
|
227
|
+
if (typeof domain?.hostname === 'string' && domain.hostname) {
|
|
228
|
+
liveUrls.push(`https://${domain.hostname}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (state.result?.enabled) {
|
|
233
|
+
const subdomain = await ctx.workersSubdomain();
|
|
234
|
+
if (subdomain) liveUrls.push(`https://${name}.${subdomain}.workers.dev`);
|
|
235
|
+
}
|
|
236
|
+
const deployments = await ctx.get<{
|
|
237
|
+
deployments?: Array<{ created_on?: string; versions?: Array<{ version_id?: string }> }>;
|
|
238
|
+
}>(`${base}/deployments`);
|
|
239
|
+
const latest = deployments.ok ? deployments.result?.deployments?.[0] : undefined;
|
|
240
|
+
const version = latest?.versions?.[0]?.version_id;
|
|
241
|
+
const deployedAt = isoOrUndefined(latest?.created_on);
|
|
242
|
+
return {
|
|
243
|
+
state: 'deployed',
|
|
244
|
+
// A custom domain, when there is one, is the address people use.
|
|
245
|
+
...(liveUrls.length > 0 ? { liveUrls } : {}),
|
|
246
|
+
consoleUrl: dash(ctx.accountId, `workers/services/view/${script}/production`),
|
|
247
|
+
...(typeof version === 'string' ? { version } : {}),
|
|
248
|
+
...(deployedAt ? { deployedAt } : {}),
|
|
249
|
+
};
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
r2_bucket: async (name, ctx) => {
|
|
253
|
+
const bucket = encodeURIComponent(name);
|
|
254
|
+
const found = await ctx.get<{ creation_date?: string }>(
|
|
255
|
+
`/accounts/${ctx.accountId}/r2/buckets/${bucket}`,
|
|
256
|
+
);
|
|
257
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
258
|
+
return {
|
|
259
|
+
state: 'deployed',
|
|
260
|
+
consoleUrl: dash(ctx.accountId, `r2/default/buckets/${bucket}`),
|
|
261
|
+
};
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
d1_database: async (name, ctx) => {
|
|
265
|
+
// The endpoint accepts a database name as well as its id.
|
|
266
|
+
const found = await ctx.get<{ uuid?: string }>(
|
|
267
|
+
`/accounts/${ctx.accountId}/d1/database/${encodeURIComponent(name)}`,
|
|
268
|
+
);
|
|
269
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
270
|
+
const uuid = typeof found.result?.uuid === 'string' ? found.result.uuid : undefined;
|
|
271
|
+
return {
|
|
272
|
+
state: 'deployed',
|
|
273
|
+
...(uuid ? { resourceId: uuid, consoleUrl: dash(ctx.accountId, `workers/d1/databases/${uuid}`) } : {}),
|
|
274
|
+
};
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
kv_namespace: async (id, ctx) => {
|
|
278
|
+
const found = await ctx.get<{ id?: string }>(
|
|
279
|
+
`/accounts/${ctx.accountId}/storage/kv/namespaces/${encodeURIComponent(id)}`,
|
|
280
|
+
);
|
|
281
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
282
|
+
return {
|
|
283
|
+
state: 'deployed',
|
|
284
|
+
resourceId: id,
|
|
285
|
+
consoleUrl: dash(ctx.accountId, `workers/kv/namespaces/${encodeURIComponent(id)}`),
|
|
286
|
+
};
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
queue: async (name, ctx) => {
|
|
290
|
+
const listed = await ctx.get<Array<{ queue_id?: string; queue_name?: string }>>(
|
|
291
|
+
`/accounts/${ctx.accountId}/queues?name=${encodeURIComponent(name)}`,
|
|
292
|
+
);
|
|
293
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
294
|
+
if (!Array.isArray(listed.result)) return { state: 'unknown', reason: 'unexpected answer for queues' };
|
|
295
|
+
// The filter may be a prefix match; only an exact name counts.
|
|
296
|
+
const queue = listed.result.find((q) => q?.queue_name === name);
|
|
297
|
+
if (!queue) return { state: 'not-found' };
|
|
298
|
+
return {
|
|
299
|
+
state: 'deployed',
|
|
300
|
+
...(typeof queue.queue_id === 'string' ? { resourceId: queue.queue_id } : {}),
|
|
301
|
+
};
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
container: async (name, ctx) => {
|
|
305
|
+
const listed = await ctx.get<Array<{ id?: string; name?: string; created_at?: string }>>(
|
|
306
|
+
`/accounts/${ctx.accountId}/containers/applications?name=${encodeURIComponent(name)}`,
|
|
307
|
+
);
|
|
308
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
309
|
+
if (!Array.isArray(listed.result)) {
|
|
310
|
+
return { state: 'unknown', reason: 'unexpected answer for container applications' };
|
|
311
|
+
}
|
|
312
|
+
const app = listed.result.find((a) => a?.name === name);
|
|
313
|
+
if (!app) return { state: 'not-found' };
|
|
314
|
+
return {
|
|
315
|
+
state: 'deployed',
|
|
316
|
+
...(typeof app.id === 'string' ? { resourceId: app.id } : {}),
|
|
317
|
+
};
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
/** Cloudflare resource types a check can look at. */
|
|
322
|
+
export const CLOUDFLARE_OBSERVED_TYPES: readonly string[] = Object.keys(CHECKS);
|
|
323
|
+
|
|
324
|
+
/** What one run of checks learned. Nothing here has been stored. */
|
|
325
|
+
export interface InfraObserveResult {
|
|
326
|
+
/**
|
|
327
|
+
* One observation per resource that was looked at, `unknown` ones included.
|
|
328
|
+
* A host that already holds an observation for a key should pass these
|
|
329
|
+
* through {@link withoutUnknownOverwrites} before storing them.
|
|
330
|
+
*/
|
|
331
|
+
observations: InfraDeploymentObservation[];
|
|
332
|
+
/** Keys that were not looked at, with the reason. */
|
|
333
|
+
skipped: Array<{ resourceKey: string; reason: string }>;
|
|
334
|
+
/** Why some lookups could not be made, when any could not. */
|
|
335
|
+
failure?: string;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Look at the named Cloudflare resources and say what was seen.
|
|
340
|
+
*
|
|
341
|
+
* Three outcomes per resource, kept apart on purpose:
|
|
342
|
+
* - it is there → `deployed`, with whatever address and dashboard page it has;
|
|
343
|
+
* - Cloudflare says it does not exist → `not-found`;
|
|
344
|
+
* - the question could not be asked (auth, network) → `unknown`.
|
|
345
|
+
*
|
|
346
|
+
* Failures are per resource: a token that cannot read R2 still gets the
|
|
347
|
+
* Workers checked, and the R2 failure is reported in `failure`. Keys for other
|
|
348
|
+
* providers are ignored.
|
|
349
|
+
*/
|
|
350
|
+
export async function observeCloudflare(
|
|
351
|
+
resourceKeys: readonly string[],
|
|
352
|
+
access: CloudflareAccess,
|
|
353
|
+
deps: InfraObserveDeps = {},
|
|
354
|
+
): Promise<InfraObserveResult> {
|
|
355
|
+
const doFetch = deps.fetch ?? fetch;
|
|
356
|
+
const now = deps.now ?? (() => new Date());
|
|
357
|
+
const { token, accountId } = access;
|
|
358
|
+
|
|
359
|
+
const skipped: InfraObserveResult['skipped'] = [];
|
|
360
|
+
const targets: Array<{ key: string; resourceType: string; identifier: string }> = [];
|
|
361
|
+
for (const key of new Set(resourceKeys)) {
|
|
362
|
+
const parsed = parseKey(key);
|
|
363
|
+
if (!parsed || parsed.provider !== 'cloudflare') continue;
|
|
364
|
+
if (CHECKS[parsed.resourceType]) targets.push({ key, ...parsed });
|
|
365
|
+
else skipped.push({ resourceKey: key, reason: `${parsed.resourceType} is not checked yet` });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const observedAt = now().toISOString();
|
|
369
|
+
const source = 'cloudflare-api';
|
|
370
|
+
let subdomain: Promise<string | undefined> | undefined;
|
|
371
|
+
const ctx: CheckContext = {
|
|
372
|
+
accountId,
|
|
373
|
+
get: (path) => cloudflareGet(path, token, doFetch),
|
|
374
|
+
workersSubdomain: () => {
|
|
375
|
+
subdomain ??= cloudflareGet<{ subdomain?: string }>(
|
|
376
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
377
|
+
token,
|
|
378
|
+
doFetch,
|
|
379
|
+
).then((sub) =>
|
|
380
|
+
sub.ok && typeof sub.result?.subdomain === 'string' ? sub.result.subdomain : undefined,
|
|
381
|
+
);
|
|
382
|
+
return subdomain;
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const observations: InfraDeploymentObservation[] = [];
|
|
387
|
+
const failures = new Set<string>();
|
|
388
|
+
for (const { key, resourceType, identifier } of targets) {
|
|
389
|
+
let seen: Seen;
|
|
390
|
+
try {
|
|
391
|
+
seen = await CHECKS[resourceType]!(identifier, ctx);
|
|
392
|
+
} catch {
|
|
393
|
+
seen = { state: 'unknown', reason: `could not check ${resourceType}` };
|
|
394
|
+
}
|
|
395
|
+
if (seen.state === 'unknown') {
|
|
396
|
+
failures.add(`${resourceType.replace(/_/g, ' ')}: ${seen.reason}`);
|
|
397
|
+
observations.push({ resourceKey: key, status: 'unknown', observedAt, source });
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
if (seen.state === 'not-found') {
|
|
401
|
+
observations.push({ resourceKey: key, status: 'not-found', observedAt, source });
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const { state: _state, ...facts } = seen;
|
|
405
|
+
observations.push({ resourceKey: key, status: 'deployed', ...facts, observedAt, source });
|
|
406
|
+
}
|
|
407
|
+
return {
|
|
408
|
+
observations,
|
|
409
|
+
skipped,
|
|
410
|
+
...(failures.size > 0 ? { failure: [...failures].join('; ') } : {}),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Drop `unknown` observations for resources something is already known about.
|
|
416
|
+
* A failed check must not erase what was known: `unknown` is only worth
|
|
417
|
+
* keeping when it is the first thing said about a resource.
|
|
418
|
+
*/
|
|
419
|
+
export function withoutUnknownOverwrites(
|
|
420
|
+
observations: readonly InfraDeploymentObservation[],
|
|
421
|
+
alreadyKnown: ReadonlySet<string>,
|
|
422
|
+
): InfraDeploymentObservation[] {
|
|
423
|
+
return observations.filter(
|
|
424
|
+
(observation) => observation.status !== 'unknown' || !alreadyKnown.has(observation.resourceKey),
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Read the answer of `wrangler auth token --json` — the credential of whoever
|
|
430
|
+
* is logged in to wrangler on this machine, refreshed by wrangler itself.
|
|
431
|
+
*
|
|
432
|
+
* Only a Bearer credential is usable here: an OAuth login or an API token. A
|
|
433
|
+
* global API key (key + email) is not, and reads as null, as does anything
|
|
434
|
+
* that is not wrangler's JSON.
|
|
435
|
+
*/
|
|
436
|
+
export function parseWranglerAuthToken(
|
|
437
|
+
stdout: string,
|
|
438
|
+
): { token: string; type: 'oauth' | 'api_token' } | null {
|
|
439
|
+
let parsed: unknown;
|
|
440
|
+
try {
|
|
441
|
+
parsed = JSON.parse(stdout);
|
|
442
|
+
} catch {
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
if (!isRecord(parsed)) return null;
|
|
446
|
+
const { type, token } = parsed;
|
|
447
|
+
if (type !== 'oauth' && type !== 'api_token') return null;
|
|
448
|
+
// A header value: refuse anything that could not have been a token.
|
|
449
|
+
if (typeof token !== 'string' || !/^[\x21-\x7e]{20,4096}$/.test(token)) return null;
|
|
450
|
+
return { token, type };
|
|
451
|
+
}
|
package/src/infra/types.ts
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
* commit. No credentials, always available, verifiable like source.
|
|
9
9
|
* - **Deployed** ({@link InfraDeploymentObservation}) is an observation of
|
|
10
10
|
* the live account. It needs credentials, carries a timestamp, and goes
|
|
11
|
-
* stale.
|
|
12
|
-
* only has to produce this shape.
|
|
11
|
+
* stale. `./observe` produces them from a credential its caller supplies;
|
|
12
|
+
* any other tooling only has to produce this shape.
|
|
13
13
|
*
|
|
14
|
-
* Everything in this folder is
|
|
15
|
-
*
|
|
14
|
+
* Everything in this folder is browser-safe: extractors take text or parsed
|
|
15
|
+
* JSON, never a path, and the checks reach the network only through `fetch`.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
/** The tool whose file declared a resource. */
|