@mistriwork/cloudflare 1.0.0-rc.66 → 1.0.0-rc.67

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.
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Certificates for a tenant's own domains through Cloudflare for SaaS: a verified domain becomes a custom hostname
3
+ * on the operator's zone (`POST /zones/{zone}/custom_hostnames`, HTTP validation, a DV certificate), its state is
4
+ * read back until Cloudflare says the certificate is active, and the hostname is deleted when the domain is removed. Every hostname made here carries
5
+ * `custom_metadata` naming mistri and the tenant, and one without it (made by someone else with the zone's token) is
6
+ * neither read as a tenant's certificate nor deleted.
7
+ * mistri loads this only when the suite says `customDomains.certificates: "cloudflare"` (http/customDomains.ts).
8
+ *
9
+ * The zone and the API token come from the environment and stay in this closure: they are never logged, stored, or
10
+ * put in an error, which names only the host, the HTTP status and Cloudflare's numeric error codes. The zone's
11
+ * fallback origin (the hostname custom hostnames are served from) is the operator's to set up in Cloudflare; this
12
+ * does not touch it.
13
+ *
14
+ * The shape is mistri's HostCertificates seam, said again here so this package does not import the server.
15
+ */
16
+ export type CertificateState = 'pending' | 'active' | 'failed';
17
+ export interface HostCertificates {
18
+ request(host: string, tenantId: string): Promise<CertificateState>;
19
+ status(host: string, tenantId: string): Promise<CertificateState>;
20
+ release(host: string, tenantId: string): Promise<void>;
21
+ }
22
+ interface CloudflareHostCertificatesOptions {
23
+ /** Where `CLOUDFLARE_ZONE_ID` and `CLOUDFLARE_API_TOKEN` are read. */
24
+ environment: Record<string, string | undefined>;
25
+ /** Cloudflare's API root; a test points it at a fake. */
26
+ apiBase?: string;
27
+ fetch?: typeof fetch;
28
+ }
29
+ export declare function cloudflareHostCertificates(options: CloudflareHostCertificatesOptions): HostCertificates;
30
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Certificates for a tenant's own domains through Cloudflare for SaaS: a verified domain becomes a custom hostname
3
+ * on the operator's zone (`POST /zones/{zone}/custom_hostnames`, HTTP validation, a DV certificate), its state is
4
+ * read back until Cloudflare says the certificate is active, and the hostname is deleted when the domain is removed. Every hostname made here carries
5
+ * `custom_metadata` naming mistri and the tenant, and one without it (made by someone else with the zone's token) is
6
+ * neither read as a tenant's certificate nor deleted.
7
+ * mistri loads this only when the suite says `customDomains.certificates: "cloudflare"` (http/customDomains.ts).
8
+ *
9
+ * The zone and the API token come from the environment and stay in this closure: they are never logged, stored, or
10
+ * put in an error, which names only the host, the HTTP status and Cloudflare's numeric error codes. The zone's
11
+ * fallback origin (the hostname custom hostnames are served from) is the operator's to set up in Cloudflare; this
12
+ * does not touch it.
13
+ *
14
+ * The shape is mistri's HostCertificates seam, said again here so this package does not import the server.
15
+ */
16
+ const API = 'https://api.cloudflare.com/client/v4';
17
+ /** A zone id is 32 hex characters; checked so it can only ever be one path segment. */
18
+ const ZONE = /^[0-9a-f]{32}$/i;
19
+ /** The certificate states that are still on their way; `active` is done, and anything else (timed out, expired,
20
+ * deleted) will not become active without a new request. */
21
+ const UNDER_WAY = new Set(['initializing', 'pending_validation', 'pending_issuance', 'pending_deployment', 'pending']);
22
+ /** What every hostname made here is marked with. The zone may hold hostnames made by anyone else with its token, and a
23
+ * name alone does not say whose a hostname is: only one carrying this marker and the tenant's id is touched. */
24
+ const MARKER = 'mistri-tenant-domain';
25
+ const metadataOf = (tenantId) => ({ mistri: MARKER, tenant: tenantId });
26
+ const ours = (found, tenantId) => found.custom_metadata?.mistri === MARKER && found.custom_metadata?.tenant === tenantId;
27
+ function stateOf(found) {
28
+ const status = found.ssl?.status ?? '';
29
+ if (status === 'active')
30
+ return 'active';
31
+ return UNDER_WAY.has(status) ? 'pending' : 'failed';
32
+ }
33
+ export function cloudflareHostCertificates(options) {
34
+ const zone = options.environment.CLOUDFLARE_ZONE_ID?.trim() ?? '';
35
+ const token = options.environment.CLOUDFLARE_API_TOKEN?.trim() ?? '';
36
+ if (!zone || !token)
37
+ throw new Error('Custom domain certificates through Cloudflare need CLOUDFLARE_ZONE_ID and CLOUDFLARE_API_TOKEN set.');
38
+ if (!ZONE.test(zone))
39
+ throw new Error('CLOUDFLARE_ZONE_ID is not a Cloudflare zone id (32 hexadecimal characters).');
40
+ const base = `${(options.apiBase ?? API).replace(/\/+$/, '')}/zones/${zone}/custom_hostnames`;
41
+ const fetcher = options.fetch ?? fetch;
42
+ const call = async (host, path, init = {}) => {
43
+ let response;
44
+ try {
45
+ response = await fetcher(`${base}${path}`, {
46
+ ...init,
47
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json' },
48
+ signal: AbortSignal.timeout(15_000),
49
+ });
50
+ }
51
+ catch {
52
+ throw new Error(`Cloudflare could not be reached for ${host}.`);
53
+ }
54
+ const body = (await response.json().catch(() => ({})));
55
+ if (!response.ok || body.success === false) {
56
+ const codes = (body.errors ?? []).map((error) => error.code).filter((code) => typeof code === 'number');
57
+ throw new Error(`Cloudflare answered ${response.status} for ${host}${codes.length ? ` (error ${codes.join(', ')})` : ''}.`);
58
+ }
59
+ return body.result;
60
+ };
61
+ /* The hostname query is an exact match, but the answer is filtered again: only the row for this host may count. */
62
+ const find = async (host) => (await call(host, `?hostname=${encodeURIComponent(host)}`))?.find((found) => found.hostname === host);
63
+ return Object.freeze({
64
+ /* A domain checked again after a restart or a suspension asks again: the existing hostname is read, not added
65
+ twice, so a second request is not a 409. */
66
+ async request(host, tenantId) {
67
+ const found = await find(host);
68
+ if (found) {
69
+ // A hostname the zone already holds for someone else is not this domain's certificate, and is left as it is.
70
+ if (!ours(found, tenantId))
71
+ throw new Error(`Cloudflare already holds ${host} for something else.`);
72
+ return stateOf(found);
73
+ }
74
+ const made = await call(host, '', {
75
+ method: 'POST',
76
+ body: JSON.stringify({ hostname: host, ssl: { method: 'http', type: 'dv' }, custom_metadata: metadataOf(tenantId) }),
77
+ });
78
+ return stateOf(made);
79
+ },
80
+ async status(host, tenantId) {
81
+ const found = await find(host);
82
+ return found && ours(found, tenantId) ? stateOf(found) : 'failed';
83
+ },
84
+ async release(host, tenantId) {
85
+ const found = await find(host);
86
+ if (found && ours(found, tenantId))
87
+ await call(host, `/${encodeURIComponent(found.id)}`, { method: 'DELETE' });
88
+ },
89
+ });
90
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/cloudflare",
3
- "version": "1.0.0-rc.66",
3
+ "version": "1.0.0-rc.67",
4
4
  "description": "A mistri App on Cloudflare Containers: the Container class and Worker handlers `mistri deploy init cloudflare` writes against, so a fix to the glue is a package upgrade.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -31,6 +31,10 @@
31
31
  ".": {
32
32
  "types": "./dist/index.d.ts",
33
33
  "default": "./dist/index.js"
34
+ },
35
+ "./host-certificates": {
36
+ "types": "./dist/hostCertificates.d.ts",
37
+ "default": "./dist/hostCertificates.js"
34
38
  }
35
39
  },
36
40
  "devDependencies": {