couriercrow 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +19 -2
- package/bin/couriercrow.js +5 -0
- package/bin/crow.js +14 -0
- package/bundle/migrations/0001_initial.sql +463 -0
- package/bundle/version.json +3 -0
- package/bundle/web/_headers +6 -0
- package/bundle/web/assets/index-Bim8rHvG.css +2 -0
- package/bundle/web/assets/index-YpJn_3e5.js +13 -0
- package/bundle/web/index.html +14 -0
- package/bundle/worker/README.md +1 -0
- package/bundle/worker/worker.js +57841 -0
- package/bundle/wrangler.jsonc +64 -0
- package/package.json +61 -4
- package/src/app-credentials.ts +413 -0
- package/src/bin.ts +578 -0
- package/src/build-config.ts +264 -0
- package/src/build-id.ts +39 -0
- package/src/cloudflare/cloudflare-client.ts +361 -0
- package/src/cloudflare/cloudflare-live-access.ts +454 -0
- package/src/cloudflare/cloudflare-live-account.ts +95 -0
- package/src/cloudflare/cloudflare-live-api.ts +87 -0
- package/src/cloudflare/cloudflare-live-checks.ts +151 -0
- package/src/cloudflare/cloudflare-live-zone.ts +363 -0
- package/src/cloudflare/cloudflare-live.ts +270 -0
- package/src/cloudflare/cloudflare-state.ts +152 -0
- package/src/cloudflare/first-run.ts +322 -0
- package/src/credentials-show.ts +49 -0
- package/src/deploy.ts +807 -0
- package/src/doctor.ts +504 -0
- package/src/environment.ts +141 -0
- package/src/index.ts +4 -0
- package/src/init.ts +332 -0
- package/src/load-config.ts +47 -0
- package/src/mailbox-api.ts +345 -0
- package/src/permissions.ts +133 -0
- package/src/plan.ts +517 -0
- package/src/printable.ts +8 -0
- package/src/product.ts +63 -0
- package/src/purge.ts +93 -0
- package/src/render.ts +406 -0
- package/src/rotate-app-secret.ts +53 -0
- package/src/runtime.ts +33 -0
- package/src/set-secret.ts +63 -0
- package/src/terminal.ts +163 -0
- package/src/wrangler.ts +168 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { mkdir, stat } from 'node:fs/promises'
|
|
2
|
+
import { join, relative } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import type { MailConfig } from '@couriercrow/core'
|
|
5
|
+
import { Effect } from 'effect'
|
|
6
|
+
|
|
7
|
+
import { DeployFailed } from './cloudflare/first-run'
|
|
8
|
+
import { localFolder, resourceName } from './product'
|
|
9
|
+
|
|
10
|
+
export type Branding = MailConfig['app']['branding']
|
|
11
|
+
|
|
12
|
+
// What the placeholders in the Worker config are replaced with.
|
|
13
|
+
export interface ConfigValues {
|
|
14
|
+
accessAudience: string
|
|
15
|
+
accessTeamDomain: string
|
|
16
|
+
appVersion: string
|
|
17
|
+
// app.authenticationHost; AUTHENTICATION_HOST is empty without it.
|
|
18
|
+
authenticationHost: string | undefined
|
|
19
|
+
branding: Branding
|
|
20
|
+
databaseId: string
|
|
21
|
+
deployClientId: string
|
|
22
|
+
hostname: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The layout of packages/cli/bundle, built by the bundle script.
|
|
26
|
+
export function bundlePaths(bundle: string) {
|
|
27
|
+
return {
|
|
28
|
+
assets: join(bundle, 'web'),
|
|
29
|
+
config: join(bundle, 'wrangler.jsonc'),
|
|
30
|
+
main: join(bundle, 'worker', 'worker.js'),
|
|
31
|
+
migrations: join(bundle, 'migrations'),
|
|
32
|
+
version: join(bundle, 'version.json')
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The command the person ran, named in the messages about a missing bundle.
|
|
37
|
+
export type BundleCommand = 'deploy' | 'plan'
|
|
38
|
+
|
|
39
|
+
export function notBuiltMessage(command: BundleCommand): string {
|
|
40
|
+
return `The Courier Crow app has not been built yet. Run bun run build in the Courier Crow repository, then run ${command} again.`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// In the repository the bundle sits at packages/cli/bundle, next to the API
|
|
44
|
+
// sources. An installed package has no API sources.
|
|
45
|
+
export async function isSourceCheckout(bundle: string): Promise<boolean> {
|
|
46
|
+
return Bun.file(
|
|
47
|
+
join(bundle, '..', '..', '..', 'apps', 'api', 'wrangler.jsonc')
|
|
48
|
+
).exists()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function missingPart(
|
|
52
|
+
bundle: string,
|
|
53
|
+
path: string,
|
|
54
|
+
command: BundleCommand
|
|
55
|
+
): Effect.Effect<DeployFailed> {
|
|
56
|
+
return Effect.promise(async () =>
|
|
57
|
+
(await isSourceCheckout(bundle))
|
|
58
|
+
? new DeployFailed({ message: notBuiltMessage(command) })
|
|
59
|
+
: new DeployFailed({
|
|
60
|
+
message: `The couriercrow package is incomplete (missing ${path}). Reinstall it with bun add couriercrow and run ${command} again.`
|
|
61
|
+
})
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// The files and folders deploy needs from the bundle.
|
|
66
|
+
function bundleParts(bundle: string): string[] {
|
|
67
|
+
const paths = bundlePaths(bundle)
|
|
68
|
+
|
|
69
|
+
return [paths.config, paths.main, join(paths.assets, 'index.html'), paths.migrations, paths.version]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function exists(path: string): Promise<boolean> {
|
|
73
|
+
try {
|
|
74
|
+
await stat(path)
|
|
75
|
+
|
|
76
|
+
return true
|
|
77
|
+
} catch {
|
|
78
|
+
return false
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// The parts of the bundle that are not there. The package's prepack fails
|
|
83
|
+
// on any.
|
|
84
|
+
export async function missingBundleParts(bundle: string): Promise<string[]> {
|
|
85
|
+
const parts = bundleParts(bundle)
|
|
86
|
+
const found = await Promise.all(parts.map(exists))
|
|
87
|
+
|
|
88
|
+
return parts.filter((_, index) => found[index] !== true)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Fails before anything is written when a part of the bundle is missing.
|
|
92
|
+
export function checkBundle(
|
|
93
|
+
bundle: string,
|
|
94
|
+
command: BundleCommand
|
|
95
|
+
): Effect.Effect<void, DeployFailed> {
|
|
96
|
+
return Effect.promise(() => missingBundleParts(bundle)).pipe(
|
|
97
|
+
Effect.flatMap((missing) =>
|
|
98
|
+
missing[0] === undefined
|
|
99
|
+
? Effect.void
|
|
100
|
+
: Effect.flatMap(missingPart(bundle, missing[0], command), Effect.fail)
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// The build id of the bundle, which the deployed app answers with.
|
|
106
|
+
export function readAppVersion(
|
|
107
|
+
bundle: string,
|
|
108
|
+
command: BundleCommand
|
|
109
|
+
): Effect.Effect<string, DeployFailed> {
|
|
110
|
+
const path = bundlePaths(bundle).version
|
|
111
|
+
|
|
112
|
+
return Effect.tryPromise(async () => {
|
|
113
|
+
const body: unknown = await Bun.file(path).json()
|
|
114
|
+
|
|
115
|
+
if (
|
|
116
|
+
typeof body === 'object' &&
|
|
117
|
+
body !== null &&
|
|
118
|
+
'version' in body &&
|
|
119
|
+
typeof body.version === 'string' &&
|
|
120
|
+
body.version !== ''
|
|
121
|
+
) {
|
|
122
|
+
return body.version
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
throw new Error('version.json has no version')
|
|
126
|
+
}).pipe(
|
|
127
|
+
Effect.catch(() =>
|
|
128
|
+
Effect.flatMap(missingPart(bundle, path, command), Effect.fail)
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The version the deployed app answers with: the build id of the bundle, and
|
|
134
|
+
// a short hash of the branding when there is one. The branding reaches the
|
|
135
|
+
// Worker as variables, so a change to it alone deploys the Worker again.
|
|
136
|
+
function shortHash(value: string): string {
|
|
137
|
+
return new Bun.CryptoHasher('sha256').update(value).digest('hex').slice(0, 8)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const authenticationPrefix = 'auth-'
|
|
141
|
+
|
|
142
|
+
// The settings of app in mail.config.ts that become Worker variables.
|
|
143
|
+
interface AppSettings {
|
|
144
|
+
authenticationHost?: string | undefined
|
|
145
|
+
branding?: Branding
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// The version deploy writes and compares: the bundle's build id, plus a
|
|
149
|
+
// short hash of each setting that is a Worker variable, so a change to one
|
|
150
|
+
// alone deploys the Worker again. The branding is the first part, the
|
|
151
|
+
// authentication host a part of its own (auth-<hash>), so the plan can tell
|
|
152
|
+
// that one changed.
|
|
153
|
+
export function appVersionFor(bundleVersion: string, app: AppSettings | undefined): string {
|
|
154
|
+
const name = app?.branding?.name
|
|
155
|
+
const accentColor = app?.branding?.accentColor
|
|
156
|
+
const host = app?.authenticationHost
|
|
157
|
+
const parts = [
|
|
158
|
+
...(name === undefined && accentColor === undefined
|
|
159
|
+
? []
|
|
160
|
+
: [shortHash(JSON.stringify({ accentColor: accentColor ?? null, name: name ?? null }))]),
|
|
161
|
+
...(host === undefined ? [] : [`${authenticationPrefix}${shortHash(host)}`])
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
return parts.length === 0 ? bundleVersion : `${bundleVersion}+${parts.join('.')}`
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The authentication host part of a version, if it has one.
|
|
168
|
+
export function authenticationPartOf(version: string): string | undefined {
|
|
169
|
+
const build = version.split('+')[1] ?? ''
|
|
170
|
+
|
|
171
|
+
return build.split('.').find((part) => part.startsWith(authenticationPrefix))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
175
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
176
|
+
? Object.fromEntries(Object.entries(value))
|
|
177
|
+
: {}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function asRecords(value: unknown): Record<string, unknown>[] {
|
|
181
|
+
return Array.isArray(value) ? value.map(asRecord) : []
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Fills the placeholders of the Worker config. Paths in the result are
|
|
185
|
+
// relative to `buildDirectory`, because wrangler resolves them from the
|
|
186
|
+
// config file.
|
|
187
|
+
export function fillConfig(
|
|
188
|
+
template: unknown,
|
|
189
|
+
values: ConfigValues,
|
|
190
|
+
paths: ReturnType<typeof bundlePaths>,
|
|
191
|
+
buildDirectory: string
|
|
192
|
+
): Record<string, unknown> {
|
|
193
|
+
const config = asRecord(template)
|
|
194
|
+
const from = (path: string) => relative(buildDirectory, path)
|
|
195
|
+
// The schema path points into the source tree, which is not there.
|
|
196
|
+
const rest = Object.fromEntries(
|
|
197
|
+
Object.entries(config).filter(([key]) => key !== '$schema')
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
...rest,
|
|
202
|
+
assets: { ...asRecord(config['assets']), directory: from(paths.assets) },
|
|
203
|
+
d1_databases: asRecords(config['d1_databases']).map((database) => ({
|
|
204
|
+
...database,
|
|
205
|
+
database_id: values.databaseId,
|
|
206
|
+
database_name: resourceName,
|
|
207
|
+
migrations_dir: from(paths.migrations)
|
|
208
|
+
})),
|
|
209
|
+
main: from(paths.main),
|
|
210
|
+
name: resourceName,
|
|
211
|
+
// The uploaded Worker is exactly the file the bundle script built.
|
|
212
|
+
no_bundle: true,
|
|
213
|
+
r2_buckets: asRecords(config['r2_buckets']).map((bucket) => ({
|
|
214
|
+
...bucket,
|
|
215
|
+
bucket_name: resourceName
|
|
216
|
+
})),
|
|
217
|
+
routes: [{ custom_domain: true, pattern: values.hostname }],
|
|
218
|
+
vars: {
|
|
219
|
+
...asRecord(config['vars']),
|
|
220
|
+
ACCESS_AUDIENCE: values.accessAudience,
|
|
221
|
+
ACCESS_TEAM_DOMAIN: values.accessTeamDomain,
|
|
222
|
+
APP_HOSTNAME: values.hostname,
|
|
223
|
+
APP_VERSION: values.appVersion,
|
|
224
|
+
AUTHENTICATION_HOST: values.authenticationHost ?? '',
|
|
225
|
+
BRANDING_ACCENT_COLOR: values.branding?.accentColor ?? '',
|
|
226
|
+
BRANDING_NAME: values.branding?.name ?? '',
|
|
227
|
+
DEPLOY_CLIENT_ID: values.deployClientId
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Writes the filled config to .courier-crow/build/ next to the config file
|
|
233
|
+
// and returns its path. Nothing inside the installed package is changed.
|
|
234
|
+
export function writeBuildConfig(
|
|
235
|
+
directory: string,
|
|
236
|
+
bundle: string,
|
|
237
|
+
values: ConfigValues
|
|
238
|
+
): Effect.Effect<string, DeployFailed> {
|
|
239
|
+
const buildDirectory = join(directory, localFolder, 'build')
|
|
240
|
+
const path = join(buildDirectory, 'wrangler.json')
|
|
241
|
+
const paths = bundlePaths(bundle)
|
|
242
|
+
|
|
243
|
+
return Effect.tryPromise({
|
|
244
|
+
try: async () => {
|
|
245
|
+
const template: unknown = Bun.JSONC.parse(
|
|
246
|
+
await Bun.file(paths.config).text()
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
await mkdir(buildDirectory, { recursive: true })
|
|
250
|
+
await Bun.write(
|
|
251
|
+
path,
|
|
252
|
+
`${JSON.stringify(fillConfig(template, values, paths, buildDirectory), null, 2)}\n`
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return path
|
|
256
|
+
},
|
|
257
|
+
catch: (reason) =>
|
|
258
|
+
new DeployFailed({
|
|
259
|
+
message: `Could not prepare the Worker config in ${localFolder}/build: ${
|
|
260
|
+
reason instanceof Error ? reason.message : String(reason)
|
|
261
|
+
}. Reinstall couriercrow and run deploy again.`
|
|
262
|
+
})
|
|
263
|
+
})
|
|
264
|
+
}
|
package/src/build-id.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
|
|
3
|
+
// What the build id covers: the Worker, every file of the web app, every
|
|
4
|
+
// migration and the Worker config template (its bindings, variables and
|
|
5
|
+
// triggers change what runs). Wrangler's README next to worker.js carries the
|
|
6
|
+
// build time and the source map does not change what runs, so neither counts.
|
|
7
|
+
const parts = [
|
|
8
|
+
{ directory: 'worker', pattern: 'worker.js' },
|
|
9
|
+
{ directory: 'web', pattern: '**/*' },
|
|
10
|
+
{ directory: 'migrations', pattern: '**/*' },
|
|
11
|
+
{ directory: '.', pattern: 'wrangler.jsonc' }
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
// The build id of a bundle: the CLI version plus a short hash of what is
|
|
15
|
+
// deployed. Deploy compares it with what the running app answers, so a
|
|
16
|
+
// changed Worker is deployed even when no version was bumped.
|
|
17
|
+
export async function computeBuildId(
|
|
18
|
+
bundle: string,
|
|
19
|
+
cliVersion: string
|
|
20
|
+
): Promise<string> {
|
|
21
|
+
const hasher = new Bun.CryptoHasher('sha256')
|
|
22
|
+
|
|
23
|
+
for (const part of parts) {
|
|
24
|
+
const directory = join(bundle, part.directory)
|
|
25
|
+
const files = (
|
|
26
|
+
await Array.fromAsync(
|
|
27
|
+
new Bun.Glob(part.pattern).scan({ cwd: directory, onlyFiles: true })
|
|
28
|
+
)
|
|
29
|
+
).sort()
|
|
30
|
+
|
|
31
|
+
for (const file of files) {
|
|
32
|
+
hasher.update(`${part.directory}/${file}\0`)
|
|
33
|
+
hasher.update(await Bun.file(join(directory, file)).bytes())
|
|
34
|
+
hasher.update('\0')
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return `${cliVersion}-${hasher.digest('hex').slice(0, 12)}`
|
|
39
|
+
}
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import type { DomainName, EmailAddress } from '@couriercrow/core'
|
|
2
|
+
import { Context, Schema } from 'effect'
|
|
3
|
+
import type { Effect, Option } from 'effect'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
applicationName,
|
|
7
|
+
resourceName,
|
|
8
|
+
unsubscribeApplicationName,
|
|
9
|
+
unsubscribePolicyName
|
|
10
|
+
} from '../product'
|
|
11
|
+
import type { PermissionArea } from '../permissions'
|
|
12
|
+
import type { DomainSetup } from './cloudflare-state'
|
|
13
|
+
|
|
14
|
+
// forbidden: the token is valid but lacks a permission (HTTP 403).
|
|
15
|
+
// unauthorized: Cloudflare does not accept the token at all (HTTP 401 or an
|
|
16
|
+
// invalid-token error code).
|
|
17
|
+
// paidPlanRequired and alreadyExists: only the sending onboarding call says
|
|
18
|
+
// these, see cloudflare-live-zone.ts.
|
|
19
|
+
export class CloudflareError extends Schema.TaggedError<CloudflareError>()(
|
|
20
|
+
'CloudflareError',
|
|
21
|
+
{
|
|
22
|
+
kind: Schema.Literals([
|
|
23
|
+
'alreadyExists',
|
|
24
|
+
'forbidden',
|
|
25
|
+
'notFound',
|
|
26
|
+
'other',
|
|
27
|
+
'paidPlanRequired',
|
|
28
|
+
'unauthorized'
|
|
29
|
+
]),
|
|
30
|
+
message: Schema.String
|
|
31
|
+
}
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
// A zone of the account, as the write calls need it.
|
|
35
|
+
export interface Zone {
|
|
36
|
+
domain: DomainName
|
|
37
|
+
id: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface AccessApplication {
|
|
41
|
+
// The audience tag the Worker checks in the Access token.
|
|
42
|
+
audience: string
|
|
43
|
+
id: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The settings of an Access application that deploy keeps as it created them.
|
|
47
|
+
export interface AccessApplicationSettings {
|
|
48
|
+
id: string
|
|
49
|
+
// None when Cloudflare's answer has no such field. Some(null) when the
|
|
50
|
+
// field is there without a value.
|
|
51
|
+
sameSiteCookie: Option.Option<string | null>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface AccessPolicy {
|
|
55
|
+
decision: string
|
|
56
|
+
id: string
|
|
57
|
+
name: string
|
|
58
|
+
// The service tokens this policy lets through.
|
|
59
|
+
serviceTokenIds: readonly string[]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type AccessRule =
|
|
63
|
+
| { _tag: 'Email'; email: EmailAddress }
|
|
64
|
+
| { _tag: 'Everyone' }
|
|
65
|
+
| { _tag: 'ServiceToken'; tokenId: string }
|
|
66
|
+
|
|
67
|
+
export interface AccessPolicyInput {
|
|
68
|
+
// bypass: no Access check at all. Only for the unsubscribe page.
|
|
69
|
+
decision: 'allow' | 'bypass' | 'non_identity'
|
|
70
|
+
include: readonly AccessRule[]
|
|
71
|
+
name: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The fields of a self-hosted Access application that the update (PUT
|
|
75
|
+
// /access/apps/:app) takes, from Cloudflare's API reference. Ids, the
|
|
76
|
+
// audience, timestamps and anything not listed are left out, and so are
|
|
77
|
+
// `policies`: sent as objects they would be taken as changes to them.
|
|
78
|
+
// `mfa_config`, `oauth_configuration` and `scim_config` are left out too:
|
|
79
|
+
// they hold secrets or a shape of their own that a read does not give back
|
|
80
|
+
// as written (spike question 14 checks that a PUT without them keeps them).
|
|
81
|
+
export const writableApplicationFields = [
|
|
82
|
+
'allow_authenticate_via_warp',
|
|
83
|
+
'allow_iframe',
|
|
84
|
+
'allowed_idps',
|
|
85
|
+
'app_launcher_visible',
|
|
86
|
+
'auto_redirect_to_identity',
|
|
87
|
+
'cors_headers',
|
|
88
|
+
'custom_deny_message',
|
|
89
|
+
'custom_deny_url',
|
|
90
|
+
'custom_non_identity_deny_url',
|
|
91
|
+
'custom_pages',
|
|
92
|
+
'destinations',
|
|
93
|
+
'domain',
|
|
94
|
+
'eager_redirect_cookie_setting',
|
|
95
|
+
'enable_binding_cookie',
|
|
96
|
+
'http_only_cookie_attribute',
|
|
97
|
+
'logo_url',
|
|
98
|
+
'name',
|
|
99
|
+
'options_preflight_bypass',
|
|
100
|
+
'path_cookie_attribute',
|
|
101
|
+
'read_service_tokens_from_header',
|
|
102
|
+
'same_site_cookie_attribute',
|
|
103
|
+
'self_hosted_domains',
|
|
104
|
+
'service_auth_401_redirect',
|
|
105
|
+
'session_duration',
|
|
106
|
+
'skip_interstitial',
|
|
107
|
+
'tags',
|
|
108
|
+
'type',
|
|
109
|
+
'use_clientless_isolation_app_launcher_url'
|
|
110
|
+
] as const
|
|
111
|
+
|
|
112
|
+
// The update of an application as it was read: its writable fields as they
|
|
113
|
+
// are, with the session cookie set to Lax.
|
|
114
|
+
export function applicationUpdateBody(
|
|
115
|
+
record: Readonly<Record<string, unknown>>
|
|
116
|
+
): Record<string, unknown> {
|
|
117
|
+
return {
|
|
118
|
+
...Object.fromEntries(
|
|
119
|
+
writableApplicationFields.flatMap((field) =>
|
|
120
|
+
Object.hasOwn(record, field) ? [[field, record[field]]] : []
|
|
121
|
+
)
|
|
122
|
+
),
|
|
123
|
+
same_site_cookie_attribute: 'lax'
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface ApplicationCoverage {
|
|
128
|
+
// A public destination as its uri; anything else in a form that never
|
|
129
|
+
// equals a hostname.
|
|
130
|
+
destinations: readonly string[] | null
|
|
131
|
+
domain: string | null
|
|
132
|
+
selfHostedDomains: readonly string[] | null
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Reads the coverage fields of an application as Cloudflare answers it.
|
|
136
|
+
export function coverageOf(record: Readonly<Record<string, unknown>>): ApplicationCoverage {
|
|
137
|
+
const destinations = record['destinations']
|
|
138
|
+
const selfHosted = record['self_hosted_domains']
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
destinations: Array.isArray(destinations)
|
|
142
|
+
? destinations.map((item: unknown) =>
|
|
143
|
+
typeof item === 'object' &&
|
|
144
|
+
item !== null &&
|
|
145
|
+
'type' in item &&
|
|
146
|
+
item.type === 'public' &&
|
|
147
|
+
'uri' in item &&
|
|
148
|
+
typeof item.uri === 'string'
|
|
149
|
+
? item.uri
|
|
150
|
+
: JSON.stringify(item)
|
|
151
|
+
)
|
|
152
|
+
: null,
|
|
153
|
+
domain: typeof record['domain'] === 'string' ? record['domain'] : null,
|
|
154
|
+
selfHostedDomains: Array.isArray(selfHosted)
|
|
155
|
+
? selfHosted.map((item: unknown) =>
|
|
156
|
+
typeof item === 'string' ? item : JSON.stringify(item)
|
|
157
|
+
)
|
|
158
|
+
: null
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Whether an application covers exactly this path and nothing else: its
|
|
163
|
+
// domain, and its destinations and self-hosted domains when it has them.
|
|
164
|
+
export function coversExactly(coverage: ApplicationCoverage, path: string): boolean {
|
|
165
|
+
const onlyPath = (list: readonly string[] | null) =>
|
|
166
|
+
list === null || (list.length === 1 && list[0] === path)
|
|
167
|
+
|
|
168
|
+
return (
|
|
169
|
+
coverage.domain === path &&
|
|
170
|
+
onlyPath(coverage.destinations) &&
|
|
171
|
+
onlyPath(coverage.selfHostedDomains)
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// What the plan shows of an application's coverage.
|
|
176
|
+
export function describeCoverage(coverage: ApplicationCoverage): string {
|
|
177
|
+
const all = [
|
|
178
|
+
...new Set([
|
|
179
|
+
...(coverage.domain === null ? [] : [coverage.domain]),
|
|
180
|
+
...(coverage.destinations ?? []),
|
|
181
|
+
...(coverage.selfHostedDomains ?? [])
|
|
182
|
+
])
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
return all.length === 0 ? 'no domain' : all.join(', ')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The Access application of the public unsubscribe page, by its domain.
|
|
189
|
+
export function unsubscribeDomain(hostname: string): string {
|
|
190
|
+
return `${hostname}/u/*`
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// The name of the app's own Access application, and of the unsubscribe page's
|
|
194
|
+
// application and policy. They come from product.ts.
|
|
195
|
+
export const mailboxApplicationName = applicationName
|
|
196
|
+
|
|
197
|
+
export { unsubscribeApplicationName, unsubscribePolicyName }
|
|
198
|
+
|
|
199
|
+
export interface ServiceToken {
|
|
200
|
+
clientId: string
|
|
201
|
+
// Cloudflare shows the secret only once, when the token is created.
|
|
202
|
+
clientSecret: string
|
|
203
|
+
id: string
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface ServiceTokenSummary {
|
|
207
|
+
clientId: string
|
|
208
|
+
id: string
|
|
209
|
+
name: string
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// An Email Routing rule that is not the catch-all, with what it matches and
|
|
213
|
+
// does in words, for the plan.
|
|
214
|
+
export interface RoutingRule {
|
|
215
|
+
description: string
|
|
216
|
+
id: string
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export interface MxRecord {
|
|
220
|
+
host: string
|
|
221
|
+
id: string
|
|
222
|
+
priority: number
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface CloudflareShape {
|
|
226
|
+
// What an Access application covers, as Cloudflare reads it back: its
|
|
227
|
+
// domain, and its destinations and self-hosted domains when it has those
|
|
228
|
+
// fields (null when not). None when the application is gone.
|
|
229
|
+
accessApplicationCoverage: (
|
|
230
|
+
application: string
|
|
231
|
+
) => Effect.Effect<Option.Option<ApplicationCoverage>, CloudflareError>
|
|
232
|
+
// None when there is no Access application on this hostname.
|
|
233
|
+
accessApplicationSettings: (
|
|
234
|
+
hostname: string
|
|
235
|
+
) => Effect.Effect<Option.Option<AccessApplicationSettings>, CloudflareError>
|
|
236
|
+
accessPolicies: (
|
|
237
|
+
application: string
|
|
238
|
+
) => Effect.Effect<readonly AccessPolicy[], CloudflareError>
|
|
239
|
+
// Empty when the Access application does not exist yet.
|
|
240
|
+
accessPolicyEmails: () => Effect.Effect<
|
|
241
|
+
readonly EmailAddress[],
|
|
242
|
+
CloudflareError
|
|
243
|
+
>
|
|
244
|
+
accessTeamDomain: () => Effect.Effect<string, CloudflareError>
|
|
245
|
+
// Whether the account is on Workers Paid. Fails forbidden when the token
|
|
246
|
+
// may not read the account's subscriptions (that needs Billing Read).
|
|
247
|
+
accountPlan: () => Effect.Effect<AccountPlan, CloudflareError>
|
|
248
|
+
createAccessApplication: (
|
|
249
|
+
hostname: string
|
|
250
|
+
) => Effect.Effect<AccessApplication, CloudflareError>
|
|
251
|
+
createAccessPolicy: (
|
|
252
|
+
application: string,
|
|
253
|
+
policy: AccessPolicyInput
|
|
254
|
+
) => Effect.Effect<void, CloudflareError>
|
|
255
|
+
createBucket: (name: string) => Effect.Effect<void, CloudflareError>
|
|
256
|
+
createDatabase: (name: string) => Effect.Effect<string, CloudflareError>
|
|
257
|
+
createServiceToken: (
|
|
258
|
+
name: string
|
|
259
|
+
) => Effect.Effect<ServiceToken, CloudflareError>
|
|
260
|
+
// A self-hosted application for <hostname>/u/* alone. Its policy is
|
|
261
|
+
// created on its own.
|
|
262
|
+
createUnsubscribeApplication: (
|
|
263
|
+
hostname: string
|
|
264
|
+
) => Effect.Effect<AccessApplication, CloudflareError>
|
|
265
|
+
// An application that is gone already is not an error: notFound.
|
|
266
|
+
deleteAccessApplication: (
|
|
267
|
+
application: string
|
|
268
|
+
) => Effect.Effect<void, CloudflareError>
|
|
269
|
+
deleteAccessPolicy: (
|
|
270
|
+
application: string,
|
|
271
|
+
policy: string
|
|
272
|
+
) => Effect.Effect<void, CloudflareError>
|
|
273
|
+
// A record or rule that is gone already is not an error: notFound.
|
|
274
|
+
deleteDnsRecord: (
|
|
275
|
+
zone: Zone,
|
|
276
|
+
record: string
|
|
277
|
+
) => Effect.Effect<void, CloudflareError>
|
|
278
|
+
deleteRoutingRule: (
|
|
279
|
+
zone: Zone,
|
|
280
|
+
rule: string
|
|
281
|
+
) => Effect.Effect<void, CloudflareError>
|
|
282
|
+
deleteServiceToken: (token: string) => Effect.Effect<void, CloudflareError>
|
|
283
|
+
disableCatchAll: (zone: Zone) => Effect.Effect<void, CloudflareError>
|
|
284
|
+
domainSetup: (
|
|
285
|
+
domain: DomainName
|
|
286
|
+
) => Effect.Effect<DomainSetup, CloudflareError>
|
|
287
|
+
enableRouting: (zone: Zone) => Effect.Effect<void, CloudflareError>
|
|
288
|
+
findAccessApplication: (
|
|
289
|
+
hostname: string
|
|
290
|
+
) => Effect.Effect<Option.Option<AccessApplication>, CloudflareError>
|
|
291
|
+
findBucket: (name: string) => Effect.Effect<boolean, CloudflareError>
|
|
292
|
+
// The id of the database, when there is one with that name.
|
|
293
|
+
findDatabase: (
|
|
294
|
+
name: string
|
|
295
|
+
) => Effect.Effect<Option.Option<string>, CloudflareError>
|
|
296
|
+
// MX records at the apex that Cloudflare Email Routing does not own.
|
|
297
|
+
foreignMxRecords: (
|
|
298
|
+
zone: Zone
|
|
299
|
+
) => Effect.Effect<readonly MxRecord[], CloudflareError>
|
|
300
|
+
// The types of the sign-in methods (identity providers) Zero Trust lists,
|
|
301
|
+
// for example onetimepin.
|
|
302
|
+
identityProviderTypes: () => Effect.Effect<readonly string[], CloudflareError>
|
|
303
|
+
// Throws alreadyExists when the sending domain is onboarded already.
|
|
304
|
+
onboardSending: (zone: Zone) => Effect.Effect<void, CloudflareError>
|
|
305
|
+
// The app's own Access applications deploy made, for any hostname: named
|
|
306
|
+
// "Courier Crow", on a domain without a path.
|
|
307
|
+
mailboxApplications: () => Effect.Effect<
|
|
308
|
+
readonly { domain: string; id: string }[],
|
|
309
|
+
CloudflareError
|
|
310
|
+
>
|
|
311
|
+
// One harmless read in an area, so forbidden tells that the token lacks
|
|
312
|
+
// its permission. Zone areas read in the zone given and need one.
|
|
313
|
+
probePermission: (
|
|
314
|
+
area: PermissionArea,
|
|
315
|
+
zone: Zone | undefined
|
|
316
|
+
) => Effect.Effect<void, CloudflareError>
|
|
317
|
+
// Ends the open Access sessions of one person.
|
|
318
|
+
revokeAccessSessions: (email: string) => Effect.Effect<void, CloudflareError>
|
|
319
|
+
// Email Routing rules, not counting the catch-all rule.
|
|
320
|
+
routingRules: (
|
|
321
|
+
zone: Zone
|
|
322
|
+
) => Effect.Effect<readonly RoutingRule[], CloudflareError>
|
|
323
|
+
serviceTokens: () => Effect.Effect<
|
|
324
|
+
readonly ServiceTokenSummary[],
|
|
325
|
+
CloudflareError
|
|
326
|
+
>
|
|
327
|
+
setCatchAll: (zone: Zone) => Effect.Effect<void, CloudflareError>
|
|
328
|
+
// Reads the application and sends it back with only the session cookie
|
|
329
|
+
// set to SameSite=Lax, so settings changed by hand stay.
|
|
330
|
+
updateAccessApplication: (
|
|
331
|
+
application: string
|
|
332
|
+
) => Effect.Effect<void, CloudflareError>
|
|
333
|
+
updateAccessPolicy: (
|
|
334
|
+
application: string,
|
|
335
|
+
policy: string,
|
|
336
|
+
input: AccessPolicyInput
|
|
337
|
+
) => Effect.Effect<void, CloudflareError>
|
|
338
|
+
// The unsubscribe applications deploy made, for any hostname: named
|
|
339
|
+
// "Courier Crow unsubscribe page", on a domain that ends in /u/*.
|
|
340
|
+
unsubscribeApplications: () => Effect.Effect<
|
|
341
|
+
readonly { domain: string; id: string }[],
|
|
342
|
+
CloudflareError
|
|
343
|
+
>
|
|
344
|
+
// Whether Cloudflare accepts the token and it is active.
|
|
345
|
+
verifyToken: () => Effect.Effect<boolean, CloudflareError>
|
|
346
|
+
// Whether a Worker with this name exists in the account.
|
|
347
|
+
workerExists: (name: string) => Effect.Effect<boolean, CloudflareError>
|
|
348
|
+
// The id of the zone with exactly this name in the account.
|
|
349
|
+
zoneIdOf: (name: string) => Effect.Effect<Option.Option<string>, CloudflareError>
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// paid: a subscription names Workers Paid. unrecognised: anything else.
|
|
353
|
+
// Cloudflare documents no marker of Workers Free, so no answer proves it.
|
|
354
|
+
export type AccountPlan = 'paid' | 'unrecognised'
|
|
355
|
+
|
|
356
|
+
export class Cloudflare extends Context.Service<Cloudflare, CloudflareShape>()(
|
|
357
|
+
'Cloudflare'
|
|
358
|
+
) {}
|
|
359
|
+
|
|
360
|
+
// The name of the Worker that deploy creates.
|
|
361
|
+
export const workerName = resourceName
|