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