@cdwr/fly-node 0.3.0 → 0.3.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/api.js ADDED
@@ -0,0 +1,483 @@
1
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
2
+ import { z } from "zod";
3
+ var CertificateApiResponseSchema = z.object({
4
+ hostname: z.string(),
5
+ /** Issued and serving. This is what decides whether a domain is usable */
6
+ isConfigured: z.boolean(),
7
+ id: z.string().optional(),
8
+ /** The apex or a subdomain — apex domains cannot use a CNAME */
9
+ isApex: z.boolean().optional(),
10
+ isWildcard: z.boolean().optional(),
11
+ /** Which ACME challenge has been satisfied, if any */
12
+ isAcmeDnsConfigured: z.boolean().optional(),
13
+ isAcmeAlpnConfigured: z.boolean().optional(),
14
+ isAcmeHttpConfigured: z.boolean().optional(),
15
+ certificateAuthority: z.string().nullish(),
16
+ certificateRequestedAt: z.string().nullish(),
17
+ createdAt: z.string().nullish(),
18
+ domain: z.string().nullish(),
19
+ dnsProvider: z.string().nullish(),
20
+ /** Hostname the validation record must be created on */
21
+ dnsValidationHostname: z.string().nullish(),
22
+ /** Value that record must contain */
23
+ dnsValidationTarget: z.string().nullish(),
24
+ /** Fly's own prose describing the records to create */
25
+ dnsValidationInstructions: z.string().nullish(),
26
+ /** Fly's summary of where issuance has got to */
27
+ clientStatus: z.string().nullish(),
28
+ /**
29
+ * Set when Let's Encrypt has rate-limited further attempts for this domain.
30
+ *
31
+ * Worth surfacing rather than swallowing: it is the one failure a customer
32
+ * cannot fix by correcting DNS, and retrying only makes it worse.
33
+ */
34
+ rateLimitedUntil: z.string().nullish(),
35
+ source: z.string().nullish(),
36
+ /**
37
+ * Fly's own prose for a failed issuance attempt — what the dashboard shows,
38
+ * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
39
+ */
40
+ validationErrors: z.array(
41
+ z.object({
42
+ message: z.string(),
43
+ timestamp: z.string()
44
+ })
45
+ ).nullish(),
46
+ /**
47
+ * The certificates actually issued for this hostname, once any have been.
48
+ *
49
+ * A connection rather than a list because that is how Fly models it. Two
50
+ * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
51
+ * which is why a caller usually wants the expiry rather than the rows.
52
+ */
53
+ issued: z.object({
54
+ nodes: z.array(
55
+ z.object({
56
+ id: z.string().nullish(),
57
+ /** Key type, e.g. `RSA` or `ECDSA` */
58
+ type: z.string().nullish(),
59
+ hostname: z.string().nullish(),
60
+ expiresAt: z.string().nullish()
61
+ })
62
+ ).nullish()
63
+ }).nullish()
64
+ });
65
+ var HostnameCheckApiResponseSchema = z.object({
66
+ aRecords: z.array(z.string()).nullish(),
67
+ aaaaRecords: z.array(z.string()).nullish(),
68
+ cnameRecords: z.array(z.string()).nullish(),
69
+ caaRecords: z.array(z.string()).nullish(),
70
+ soa: z.string().nullish(),
71
+ dnsProvider: z.string().nullish(),
72
+ dnsVerificationRecord: z.string().nullish(),
73
+ dnsConfigured: z.boolean().nullish(),
74
+ acmeDnsConfigured: z.boolean().nullish(),
75
+ resolvedAddresses: z.array(z.string()).nullish(),
76
+ isProxied: z.boolean().nullish(),
77
+ errors: z.array(z.string()).nullish()
78
+ });
79
+ var DnsInstructionsSchema = z.object({
80
+ hostname: z.string().nullish(),
81
+ target: z.string().nullish(),
82
+ instructions: z.string().nullish(),
83
+ isApex: z.boolean().optional()
84
+ });
85
+ var CertificateListApiResponseSchema = z.array(
86
+ CertificateApiResponseSchema
87
+ );
88
+
89
+ // packages/fly-node/src/lib/schemas/machine.schema.ts
90
+ import { z as z2 } from "zod";
91
+ var MachineApiResponseSchema = z2.object({
92
+ id: z2.string(),
93
+ name: z2.string().nullish(),
94
+ /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
95
+ state: z2.string().nullish(),
96
+ region: z2.string().nullish()
97
+ });
98
+ var MachineListApiResponseSchema = z2.array(MachineApiResponseSchema);
99
+
100
+ // packages/fly-node/src/lib/fly-api.class.ts
101
+ var FLY_API_URL = "https://api.fly.io/graphql";
102
+ var FLY_MACHINES_URL = "https://api.machines.dev/v1";
103
+ var FlyApiError = class extends Error {
104
+ errors;
105
+ constructor(message, errors) {
106
+ super(message);
107
+ this.name = "FlyApiError";
108
+ this.errors = errors;
109
+ }
110
+ /** Whether every error is Fly saying the thing simply does not exist */
111
+ get isNotFound() {
112
+ return this.errors.length > 0 && this.errors.every((error) => error.extensions?.code === "NOT_FOUND");
113
+ }
114
+ /**
115
+ * Whether every error is Fly refusing a hostname that already has a
116
+ * certificate on the app.
117
+ *
118
+ * No `extensions.code` comes with this one — Fly's own dashboard and
119
+ * `flyctl` hit the same message, and both work around it the same way this
120
+ * class does, by re-reading rather than retrying the mutation.
121
+ */
122
+ get isAlreadyExists() {
123
+ return this.errors.length > 0 && this.errors.every((error) => /already exists/i.test(error.message));
124
+ }
125
+ };
126
+ var FlyApi = class {
127
+ token;
128
+ apiUrl;
129
+ machinesUrl;
130
+ log;
131
+ constructor(config) {
132
+ if (!config.token) {
133
+ throw new Error("[fly-api] A Fly API token is required");
134
+ }
135
+ this.token = config.token;
136
+ this.apiUrl = config.apiUrl ?? FLY_API_URL;
137
+ this.machinesUrl = config.machinesUrl ?? FLY_MACHINES_URL;
138
+ this.log = config.log ?? (() => void 0);
139
+ }
140
+ /**
141
+ * Manage certificates for an app.
142
+ *
143
+ * Every method takes the app name explicitly: this client is used by a
144
+ * process acting on *other* apps — the cms managing a tenant's web app — so
145
+ * there is no ambient "current app" to default to.
146
+ */
147
+ certs = {
148
+ /**
149
+ * Request a certificate for a hostname.
150
+ *
151
+ * Safe to call when one already exists: Fly's own mutation is not
152
+ * idempotent — a hostname it already has a certificate for on this app is
153
+ * a fault, not a no-op, so this re-reads the existing certificate itself
154
+ * rather than surfacing that as an error a caller has to know to expect.
155
+ *
156
+ * Requesting before DNS is in place is normal and expected — the
157
+ * certificate stays pending until the records resolve, and the returned
158
+ * validation fields are what you show the customer meanwhile.
159
+ *
160
+ * @param app - Fly app name the domain should serve from
161
+ * @param hostname - Domain without a scheme, e.g. `tours.example.com`
162
+ * @returns The certificate, plus what Fly resolves for that hostname now
163
+ */
164
+ add: async (app, hostname) => {
165
+ try {
166
+ const data = await this.request(
167
+ `mutation AddCertificate($appId: ID!, $hostname: String!) {
168
+ addCertificate(appId: $appId, hostname: $hostname) {
169
+ certificate { ${CERTIFICATE_FIELDS} }
170
+ check { ${HOSTNAME_CHECK_FIELDS} }
171
+ }
172
+ }`,
173
+ { appId: app, hostname }
174
+ );
175
+ return {
176
+ certificate: CertificateApiResponseSchema.parse(
177
+ data.addCertificate.certificate
178
+ ),
179
+ // Live resolution, and it comes back with the mutation for free —
180
+ // the customer has usually just edited DNS and wants to know if it
181
+ // took
182
+ check: data.addCertificate.check ? HostnameCheckApiResponseSchema.parse(data.addCertificate.check) : null
183
+ };
184
+ } catch (error) {
185
+ if (error instanceof FlyApiError && error.isAlreadyExists) {
186
+ const certificate = await this.certs.get(app, hostname);
187
+ if (certificate) {
188
+ return { certificate, check: null };
189
+ }
190
+ }
191
+ throw error;
192
+ }
193
+ },
194
+ /**
195
+ * Read one certificate, or `null` when the app has none for that hostname.
196
+ *
197
+ * This is the call behind a "check" button: it re-reads issuance state from
198
+ * Fly rather than trusting anything stored locally.
199
+ *
200
+ * Fly reports an absent certificate as a `NOT_FOUND` *error* rather than a
201
+ * null field, so that case is translated here — asking about a domain
202
+ * nobody has added yet is an ordinary question with an ordinary answer.
203
+ */
204
+ get: async (app, hostname) => {
205
+ let data;
206
+ try {
207
+ data = await this.request(
208
+ `query AppCertificate($appName: String!, $hostname: String!) {
209
+ app(name: $appName) {
210
+ certificate(hostname: $hostname) { ${CERTIFICATE_FIELDS} }
211
+ }
212
+ }`,
213
+ { appName: app, hostname }
214
+ );
215
+ } catch (error) {
216
+ if (error instanceof FlyApiError && error.isNotFound) {
217
+ return null;
218
+ }
219
+ throw error;
220
+ }
221
+ const certificate = data.app?.certificate;
222
+ return certificate ? CertificateApiResponseSchema.parse(certificate) : null;
223
+ },
224
+ /**
225
+ * What Fly resolves for a hostname right now, and what it objects to.
226
+ *
227
+ * A mutation on Fly's side despite reading rather than writing anything —
228
+ * `AppCertificate.check` is a plain boolean flag, and `HostnameCheck` is
229
+ * only ever returned by `addCertificate` and this, `checkCertificate`.
230
+ * Separate from `get` rather than folded into it: triggering a live dns
231
+ * resolution on every read would cost a caller that only wants issuance
232
+ * state. Pair the two when a person has just edited their records and
233
+ * wants to know whether it took.
234
+ *
235
+ * `errors` is the useful half — it is what Fly's own dashboard prints as
236
+ * "validation issues", already phrased for whoever owns the domain.
237
+ *
238
+ * @returns `null` when the app has no certificate for that hostname
239
+ */
240
+ check: async (app, hostname) => {
241
+ let data;
242
+ try {
243
+ data = await this.request(
244
+ `mutation CheckCertificate($appId: ID!, $hostname: String!) {
245
+ checkCertificate(input: { appId: $appId, hostname: $hostname }) {
246
+ check { ${HOSTNAME_CHECK_FIELDS} }
247
+ }
248
+ }`,
249
+ { appId: app, hostname }
250
+ );
251
+ } catch (error) {
252
+ if (error instanceof FlyApiError && error.isNotFound) {
253
+ return null;
254
+ }
255
+ throw error;
256
+ }
257
+ const check = data.checkCertificate?.check;
258
+ return check ? HostnameCheckApiResponseSchema.parse(check) : null;
259
+ },
260
+ /** Every certificate on an app */
261
+ list: async (app) => {
262
+ const data = await this.request(
263
+ `query AppCertificates($appName: String!) {
264
+ app(name: $appName) {
265
+ certificates { nodes { ${CERTIFICATE_FIELDS} } }
266
+ }
267
+ }`,
268
+ { appName: app }
269
+ );
270
+ return CertificateListApiResponseSchema.parse(
271
+ data.app?.certificates?.nodes ?? []
272
+ );
273
+ },
274
+ /**
275
+ * Remove a certificate.
276
+ *
277
+ * The hostname keeps resolving until its DNS is changed — this only stops
278
+ * Fly serving TLS for it.
279
+ */
280
+ remove: async (app, hostname) => {
281
+ await this.request(
282
+ `mutation DeleteCertificate($appId: ID!, $hostname: String!) {
283
+ deleteCertificate(appId: $appId, hostname: $hostname) {
284
+ certificate { hostname }
285
+ }
286
+ }`,
287
+ { appId: app, hostname }
288
+ );
289
+ }
290
+ };
291
+ /**
292
+ * Operate an app's machines.
293
+ *
294
+ * Over Fly's REST Machines API rather than GraphQL, which has no current
295
+ * equivalent — the GraphQL mutations date from the Nomad platform and no
296
+ * longer apply.
297
+ */
298
+ machines = {
299
+ /** Every machine on an app */
300
+ list: async (app) => {
301
+ const data = await this.machinesRequest(
302
+ "GET",
303
+ `/apps/${encodeURIComponent(app)}/machines`
304
+ );
305
+ return MachineListApiResponseSchema.parse(data ?? []);
306
+ },
307
+ /**
308
+ * Restart an app's machines.
309
+ *
310
+ * One at a time on purpose: a settings change that only takes effect at
311
+ * boot should not cost the app its availability to apply. Restarting them
312
+ * together would drop every machine at once, while sequentially leaves the
313
+ * others serving. The trade is that a large app takes longer.
314
+ *
315
+ * A machine that fails to restart stops the run rather than being skipped —
316
+ * a half-restarted app is running two configurations at the same time, and
317
+ * silently returning "some of them" invites calling that done.
318
+ *
319
+ * @param app - Fly app name
320
+ * @param machineId - Restart only this machine, instead of all of them
321
+ * @returns Ids of the machines that were restarted, in the order they were
322
+ */
323
+ restart: async (app, machineId) => {
324
+ const ids = machineId ? [machineId] : (await this.machines.list(app)).map((machine) => machine.id);
325
+ const restarted = [];
326
+ for (const id of ids) {
327
+ await this.machinesRequest(
328
+ "POST",
329
+ `/apps/${encodeURIComponent(app)}/machines/${encodeURIComponent(id)}/restart`
330
+ );
331
+ restarted.push(id);
332
+ }
333
+ return restarted;
334
+ }
335
+ };
336
+ /**
337
+ * The DNS records a customer must create for a certificate to validate.
338
+ *
339
+ * Pulled out of the certificate rather than fetched, so a caller that
340
+ * already has one does not pay for a second round trip.
341
+ */
342
+ static dnsInstructions(certificate) {
343
+ return {
344
+ hostname: certificate.dnsValidationHostname,
345
+ target: certificate.dnsValidationTarget,
346
+ instructions: certificate.dnsValidationInstructions,
347
+ isApex: certificate.isApex
348
+ };
349
+ }
350
+ /**
351
+ * @private
352
+ * One GraphQL round trip.
353
+ *
354
+ * Fly answers a failed query with HTTP 200 and an `errors` array, so a
355
+ * response is only successful when both are checked — trusting the status
356
+ * alone would turn "permission denied" into a parse error further down.
357
+ */
358
+ async request(query, variables) {
359
+ const operation = /(?:query|mutation)\s+(\w+)/.exec(query)?.[1] ?? "query";
360
+ this.log(`[fly-api] ${operation} ${JSON.stringify(variables)}`);
361
+ let response;
362
+ try {
363
+ response = await fetch(this.apiUrl, {
364
+ method: "POST",
365
+ headers: {
366
+ Authorization: `Bearer ${this.token}`,
367
+ "Content-Type": "application/json"
368
+ },
369
+ body: JSON.stringify({ query, variables })
370
+ });
371
+ } catch (error) {
372
+ throw new Error(`[fly-api] ${operation} could not reach Fly: ${error}`);
373
+ }
374
+ if (!response.ok) {
375
+ throw new Error(
376
+ `[fly-api] ${operation} failed: ${response.status} ${response.statusText}`
377
+ );
378
+ }
379
+ const body = await response.json();
380
+ if (body.errors?.length) {
381
+ throw new FlyApiError(
382
+ `[fly-api] ${operation} failed: ${body.errors.map((error) => error.message).join("; ")}`,
383
+ body.errors
384
+ );
385
+ }
386
+ if (!body.data) {
387
+ throw new Error(`[fly-api] ${operation} returned no data`);
388
+ }
389
+ return body.data;
390
+ }
391
+ /**
392
+ * @private
393
+ * One call to the Machines REST API.
394
+ *
395
+ * Unlike GraphQL this one reports failure through the status code, and puts
396
+ * its reason in an `error` field. Worth reading rather than reporting the
397
+ * status alone: "machine not found" and "unauthorized" are different problems
398
+ * with different fixes.
399
+ */
400
+ async machinesRequest(method, path) {
401
+ this.log(`[fly-api] ${method} ${path}`);
402
+ let response;
403
+ try {
404
+ response = await fetch(`${this.machinesUrl}${path}`, {
405
+ method,
406
+ headers: {
407
+ Authorization: `Bearer ${this.token}`,
408
+ "Content-Type": "application/json"
409
+ }
410
+ });
411
+ } catch (error) {
412
+ throw new Error(
413
+ `[fly-api] ${method} ${path} could not reach Fly: ${error}`
414
+ );
415
+ }
416
+ const body = await response.json().catch(() => null);
417
+ if (!response.ok) {
418
+ throw new Error(
419
+ `[fly-api] ${method} ${path} failed: ${response.status} ${body?.error ?? response.statusText}`
420
+ );
421
+ }
422
+ return body;
423
+ }
424
+ };
425
+ var CERTIFICATE_FIELDS = `
426
+ id
427
+ hostname
428
+ isConfigured
429
+ isApex
430
+ isWildcard
431
+ isAcmeDnsConfigured
432
+ isAcmeAlpnConfigured
433
+ isAcmeHttpConfigured
434
+ certificateAuthority
435
+ certificateRequestedAt
436
+ createdAt
437
+ domain
438
+ dnsProvider
439
+ dnsValidationHostname
440
+ dnsValidationTarget
441
+ dnsValidationInstructions
442
+ clientStatus
443
+ rateLimitedUntil
444
+ source
445
+ validationErrors {
446
+ message
447
+ timestamp
448
+ }
449
+ # Fly issues one certificate per key type (RSA and ECDSA), so a hostname
450
+ # with a single expiry date still comes back as two rows
451
+ issued(first: 10) {
452
+ nodes {
453
+ id
454
+ type
455
+ hostname
456
+ expiresAt
457
+ }
458
+ }
459
+ `;
460
+ var HOSTNAME_CHECK_FIELDS = `
461
+ aRecords
462
+ aaaaRecords
463
+ cnameRecords
464
+ caaRecords
465
+ soa
466
+ dnsProvider
467
+ dnsVerificationRecord
468
+ dnsConfigured
469
+ acmeDnsConfigured
470
+ resolvedAddresses
471
+ isProxied
472
+ errors
473
+ `;
474
+ export {
475
+ CertificateApiResponseSchema,
476
+ CertificateListApiResponseSchema,
477
+ DnsInstructionsSchema,
478
+ FlyApi,
479
+ FlyApiError,
480
+ HostnameCheckApiResponseSchema,
481
+ MachineApiResponseSchema,
482
+ MachineListApiResponseSchema
483
+ };