couriercrow 0.0.0-stage → 0.1.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/bin/couriercrow.js +5 -0
  4. package/bin/crow.js +14 -0
  5. package/bundle/migrations/0001_initial.sql +463 -0
  6. package/bundle/version.json +3 -0
  7. package/bundle/web/_headers +6 -0
  8. package/bundle/web/assets/index-Bim8rHvG.css +2 -0
  9. package/bundle/web/assets/index-YpJn_3e5.js +13 -0
  10. package/bundle/web/index.html +14 -0
  11. package/bundle/worker/README.md +1 -0
  12. package/bundle/worker/worker.js +57841 -0
  13. package/bundle/wrangler.jsonc +64 -0
  14. package/package.json +61 -4
  15. package/src/app-credentials.ts +413 -0
  16. package/src/bin.ts +578 -0
  17. package/src/build-config.ts +264 -0
  18. package/src/build-id.ts +39 -0
  19. package/src/cloudflare/cloudflare-client.ts +361 -0
  20. package/src/cloudflare/cloudflare-live-access.ts +454 -0
  21. package/src/cloudflare/cloudflare-live-account.ts +95 -0
  22. package/src/cloudflare/cloudflare-live-api.ts +87 -0
  23. package/src/cloudflare/cloudflare-live-checks.ts +151 -0
  24. package/src/cloudflare/cloudflare-live-zone.ts +363 -0
  25. package/src/cloudflare/cloudflare-live.ts +270 -0
  26. package/src/cloudflare/cloudflare-state.ts +152 -0
  27. package/src/cloudflare/first-run.ts +322 -0
  28. package/src/credentials-show.ts +49 -0
  29. package/src/deploy.ts +807 -0
  30. package/src/doctor.ts +504 -0
  31. package/src/environment.ts +141 -0
  32. package/src/index.ts +4 -0
  33. package/src/init.ts +332 -0
  34. package/src/load-config.ts +47 -0
  35. package/src/mailbox-api.ts +345 -0
  36. package/src/permissions.ts +133 -0
  37. package/src/plan.ts +517 -0
  38. package/src/printable.ts +8 -0
  39. package/src/product.ts +63 -0
  40. package/src/purge.ts +93 -0
  41. package/src/render.ts +406 -0
  42. package/src/rotate-app-secret.ts +53 -0
  43. package/src/runtime.ts +33 -0
  44. package/src/set-secret.ts +63 -0
  45. package/src/terminal.ts +163 -0
  46. package/src/wrangler.ts +168 -0
@@ -0,0 +1,151 @@
1
+ import { Effect, Option, Schema } from 'effect'
2
+
3
+ import type { PermissionArea } from '../permissions'
4
+ import { CloudflareError } from './cloudflare-client'
5
+ import type { CloudflareShape, Zone } from './cloudflare-client'
6
+ import { accountNotFound, segment } from './cloudflare-live-api'
7
+ import type { LiveApi } from './cloudflare-live-api'
8
+
9
+ // The reads crow doctor makes. None of them changes anything.
10
+
11
+ const tokenStatus = Schema.Struct({ status: Schema.String })
12
+ const subscription = Schema.Struct({
13
+ rate_plan: Schema.optional(Schema.Struct({ id: Schema.optional(Schema.String) })),
14
+ state: Schema.optional(Schema.String)
15
+ })
16
+ const zoneItem = Schema.Struct({ id: Schema.String })
17
+ const identityProvider = Schema.Struct({ type: Schema.String })
18
+
19
+ // The rate plan of Workers Paid in the account's subscriptions. Not in
20
+ // Cloudflare's API reference; it is on the spike list.
21
+ const workersPaidPlan = 'workers_paid'
22
+
23
+ // Areas whose read answers 404 when they were never used: Email Routing and
24
+ // sending on a zone, Access in an account without Zero Trust (crow doctor
25
+ // says that on its own line). The token reached them.
26
+ const notFoundIsReached = new Set<PermissionArea>([
27
+ 'accessApplications',
28
+ 'accessOrganization',
29
+ 'accessServiceTokens',
30
+ 'emailRouting',
31
+ 'emailSending'
32
+ ])
33
+
34
+ const zoneAreas = new Set<PermissionArea>(['dns', 'emailRouting', 'emailSending', 'workersRoutes'])
35
+
36
+ function probePath(
37
+ api: LiveApi,
38
+ area: PermissionArea,
39
+ zone: Zone | undefined
40
+ ): { path: string; query: Record<string, string> } {
41
+ const zonePath = `/zones/${segment(zone?.id ?? '')}`
42
+
43
+ switch (area) {
44
+ case 'accessApplications':
45
+ return { path: `${api.account}/access/apps`, query: { per_page: '1' } }
46
+ case 'accessOrganization':
47
+ return { path: `${api.account}/access/identity_providers`, query: {} }
48
+ case 'accessServiceTokens':
49
+ return { path: `${api.account}/access/service_tokens`, query: { per_page: '1' } }
50
+ case 'buckets':
51
+ return { path: `${api.account}/r2/buckets`, query: { per_page: '1' } }
52
+ case 'databases':
53
+ return { path: `${api.account}/d1/database`, query: { per_page: '1' } }
54
+ case 'dns':
55
+ return { path: `${zonePath}/dns_records`, query: { per_page: '1' } }
56
+ case 'emailRouting':
57
+ return { path: `${zonePath}/email/routing/rules`, query: { per_page: '1' } }
58
+ case 'emailSending':
59
+ return { path: `${zonePath}/email/sending/subdomains`, query: {} }
60
+ case 'workers':
61
+ return { path: `${api.account}/workers/scripts`, query: {} }
62
+ case 'workersRoutes':
63
+ return { path: `${zonePath}/workers/routes`, query: {} }
64
+ }
65
+ }
66
+
67
+ export function checkMethods(
68
+ api: LiveApi
69
+ ): Pick<
70
+ CloudflareShape,
71
+ | 'accountPlan'
72
+ | 'identityProviderTypes'
73
+ | 'probePermission'
74
+ | 'verifyToken'
75
+ | 'zoneIdOf'
76
+ > {
77
+ const active = (path: string) =>
78
+ api.get(path, tokenStatus).pipe(Effect.map((page) => page.result.status === 'active'))
79
+
80
+ return {
81
+ // GET /accounts/:account/subscriptions. Needs Billing Read, which the
82
+ // token does not have to have; forbidden passes through. The documented
83
+ // rate plan ids are zone plans, so nothing here proves Workers Free.
84
+ accountPlan: () =>
85
+ api.get(`${api.account}/subscriptions`, Schema.Array(subscription)).pipe(
86
+ Effect.map((page) =>
87
+ page.result.some(
88
+ (item) => item.rate_plan?.id === workersPaidPlan && item.state !== 'Cancelled'
89
+ )
90
+ ? ('paid' as const)
91
+ : ('unrecognised' as const)
92
+ ),
93
+ Effect.mapError(accountNotFound)
94
+ ),
95
+
96
+ // GET /accounts/:account/access/identity_providers
97
+ identityProviderTypes: () =>
98
+ api
99
+ .getAll(`${api.account}/access/identity_providers`, identityProvider, 'identity providers')
100
+ .pipe(
101
+ Effect.map((providers) => providers.map((provider) => provider.type)),
102
+ Effect.mapError(accountNotFound)
103
+ ),
104
+
105
+ probePermission: (area, zone) => {
106
+ if (zone === undefined && zoneAreas.has(area)) {
107
+ return Effect.fail(
108
+ new CloudflareError({ kind: 'other', message: `Checking ${area} needs a zone.` })
109
+ )
110
+ }
111
+
112
+ const { path, query } = probePath(api, area, zone)
113
+
114
+ return api.get(path, Schema.Unknown, query).pipe(
115
+ Effect.asVoid,
116
+ Effect.catch((error: CloudflareError) =>
117
+ error.kind === 'notFound' && notFoundIsReached.has(area)
118
+ ? Effect.void
119
+ : Effect.fail(error.kind === 'notFound' ? accountNotFound(error) : error)
120
+ )
121
+ )
122
+ },
123
+
124
+ // GET /user/tokens/verify, then GET /accounts/:account/tokens/verify for
125
+ // a token the account owns.
126
+ verifyToken: () =>
127
+ active('/user/tokens/verify').pipe(
128
+ Effect.catch((error: CloudflareError) =>
129
+ error.kind === 'unauthorized' || error.kind === 'forbidden'
130
+ ? active(`${api.account}/tokens/verify`)
131
+ : Effect.fail(error)
132
+ ),
133
+ Effect.catch((error: CloudflareError) =>
134
+ error.kind === 'unauthorized' ? Effect.succeed(false) : Effect.fail(error)
135
+ )
136
+ ),
137
+
138
+ // GET /zones?name=<name>&account.id=<account>
139
+ zoneIdOf: (name) =>
140
+ api
141
+ .get('/zones', Schema.Array(zoneItem), {
142
+ 'account.id': api.accountId,
143
+ name,
144
+ per_page: '1'
145
+ })
146
+ .pipe(
147
+ Effect.map((page) => Option.fromNullishOr(page.result[0]?.id)),
148
+ Effect.mapError(accountNotFound)
149
+ )
150
+ }
151
+ }
@@ -0,0 +1,363 @@
1
+ import type { DomainName } from '@couriercrow/core'
2
+ import { Effect, Schema } from 'effect'
3
+
4
+ import { printable } from '../printable'
5
+ import { catchAllRuleName } from '../product'
6
+ import { CloudflareError, workerName } from './cloudflare-client'
7
+ import type { CloudflareShape } from './cloudflare-client'
8
+ import {
9
+ accountNotFound,
10
+ paidPlanMessage,
11
+ segment
12
+ } from './cloudflare-live-api'
13
+ import type { Interpret, LiveApi } from './cloudflare-live-api'
14
+
15
+ const zoneItem = Schema.Struct({ id: Schema.String })
16
+ const routingSettings = Schema.Struct({ enabled: Schema.Boolean })
17
+ const dnsRecord = Schema.Struct({
18
+ content: Schema.String,
19
+ id: Schema.optional(Schema.String),
20
+ name: Schema.String,
21
+ priority: Schema.optional(Schema.Number),
22
+ type: Schema.String
23
+ })
24
+ // The rules list may or may not include the catch-all rule, which has the
25
+ // matcher type "all". It is never one of the "other" rules.
26
+ const routingRule = Schema.Struct({
27
+ actions: Schema.optional(
28
+ Schema.Array(
29
+ Schema.Struct({
30
+ type: Schema.String,
31
+ value: Schema.optional(Schema.Array(Schema.String))
32
+ })
33
+ )
34
+ ),
35
+ id: Schema.optional(Schema.String),
36
+ matchers: Schema.optional(
37
+ Schema.Array(
38
+ Schema.Struct({
39
+ type: Schema.String,
40
+ value: Schema.optional(Schema.String)
41
+ })
42
+ )
43
+ )
44
+ })
45
+
46
+ // What a rule matches and does, in words: "sales@acme.dev → forward to x@y.z".
47
+ function describeRule(rule: Schema.Schema.Type<typeof routingRule>): string {
48
+ const matches = (rule.matchers ?? []).map((matcher) =>
49
+ matcher.type === 'all' ? 'all mail' : (matcher.value ?? matcher.type)
50
+ )
51
+ const actions = (rule.actions ?? []).map((action) => {
52
+ const values = (action.value ?? []).join(', ')
53
+
54
+ if (action.type === 'forward') {
55
+ return `forward to ${values}`
56
+ }
57
+
58
+ if (action.type === 'worker') {
59
+ return `send to the Worker ${values}`
60
+ }
61
+
62
+ return action.type
63
+ })
64
+
65
+ return printable(
66
+ matches.length === 0 && actions.length === 0
67
+ ? (rule.id ?? 'unknown rule')
68
+ : [matches.join(', '), actions.join(', ')]
69
+ .filter((part) => part !== '')
70
+ .join(' → ')
71
+ )
72
+ }
73
+ const catchAllRule = Schema.Struct({
74
+ actions: Schema.Array(
75
+ Schema.Struct({
76
+ type: Schema.String,
77
+ value: Schema.optional(Schema.Array(Schema.String))
78
+ })
79
+ ),
80
+ enabled: Schema.Boolean
81
+ })
82
+ const sendingSubdomain = Schema.Struct({
83
+ enabled: Schema.Boolean,
84
+ name: Schema.String
85
+ })
86
+
87
+ export function isCloudflareMxHost(host: string): boolean {
88
+ return /(^|\.)mx\.cloudflare\.net\.?$/i.test(host)
89
+ }
90
+
91
+ function isOtherRule(rule: Schema.Schema.Type<typeof routingRule>): boolean {
92
+ return !(rule.matchers ?? []).some((matcher) => matcher.type === 'all')
93
+ }
94
+
95
+ // What the sending onboarding call says that no other call does.
96
+ const interpretSending: Interpret = (status, messages) => {
97
+ const text = messages.join(' ')
98
+
99
+ if (/workers paid|paid plan/i.test(text)) {
100
+ return new CloudflareError({
101
+ kind: 'paidPlanRequired',
102
+ message: paidPlanMessage
103
+ })
104
+ }
105
+
106
+ if (status === 409 || /already (exists|onboarded|enabled)/i.test(text)) {
107
+ return new CloudflareError({
108
+ kind: 'alreadyExists',
109
+ message: printable(messages[0] ?? 'The sending domain exists already.')
110
+ })
111
+ }
112
+
113
+ return undefined
114
+ }
115
+
116
+ export function zoneMethods(
117
+ api: LiveApi
118
+ ): Pick<
119
+ CloudflareShape,
120
+ | 'deleteDnsRecord'
121
+ | 'deleteRoutingRule'
122
+ | 'disableCatchAll'
123
+ | 'domainSetup'
124
+ | 'enableRouting'
125
+ | 'foreignMxRecords'
126
+ | 'onboardSending'
127
+ | 'routingRules'
128
+ | 'setCatchAll'
129
+ > {
130
+ // Email Routing answers 404 for a zone that never enabled it. That means
131
+ // "not enabled", not a failure.
132
+ const orWhenNotFound = <Value, Failure, Requirements>(
133
+ fallback: Value,
134
+ effect: Effect.Effect<Value, Failure | CloudflareError, Requirements>
135
+ ) =>
136
+ effect.pipe(
137
+ Effect.catch((error: Failure | CloudflareError) =>
138
+ error instanceof CloudflareError && error.kind === 'notFound'
139
+ ? Effect.succeed(fallback)
140
+ : Effect.fail(error)
141
+ )
142
+ )
143
+
144
+ // GET /zones?name=<domain>&account.id=<account>
145
+ const zoneId = (domain: DomainName) =>
146
+ api
147
+ .get('/zones', Schema.Array(zoneItem), {
148
+ 'account.id': api.accountId,
149
+ name: domain,
150
+ per_page: '1'
151
+ })
152
+ .pipe(
153
+ Effect.map((page) => page.result[0]?.id ?? null),
154
+ Effect.mapError(accountNotFound)
155
+ )
156
+
157
+ // GET /zones/:zone/email/routing
158
+ const routingEnabled = (zone: string) =>
159
+ orWhenNotFound(
160
+ false,
161
+ api
162
+ .get(`/zones/${segment(zone)}/email/routing`, routingSettings)
163
+ .pipe(Effect.map((page) => page.result.enabled))
164
+ )
165
+
166
+ // GET /zones/:zone/dns_records?type=MX. Only records at the apex count.
167
+ const mxRecords = (zone: string, domain: DomainName) =>
168
+ api
169
+ .getAll(`/zones/${segment(zone)}/dns_records`, dnsRecord, 'DNS records', {
170
+ type: 'MX'
171
+ })
172
+ .pipe(
173
+ Effect.map((records) =>
174
+ records.filter(
175
+ (record) =>
176
+ record.type === 'MX' &&
177
+ record.name === domain &&
178
+ !isCloudflareMxHost(record.content)
179
+ )
180
+ )
181
+ )
182
+
183
+ // GET /zones/:zone/email/routing/rules, without the catch-all rule
184
+ const otherRules = (zone: string) =>
185
+ orWhenNotFound(
186
+ [],
187
+ api
188
+ .getAll(
189
+ `/zones/${segment(zone)}/email/routing/rules`,
190
+ routingRule,
191
+ 'Email Routing rules'
192
+ )
193
+ .pipe(Effect.map((rules) => rules.filter(isOtherRule)))
194
+ )
195
+
196
+ // GET /zones/:zone/email/routing/rules/catch_all
197
+ const catchAllPointsToWorker = (zone: string) =>
198
+ orWhenNotFound(
199
+ false,
200
+ api
201
+ .get(
202
+ `/zones/${segment(zone)}/email/routing/rules/catch_all`,
203
+ catchAllRule
204
+ )
205
+ .pipe(
206
+ Effect.map(
207
+ (page) =>
208
+ page.result.enabled &&
209
+ page.result.actions.some(
210
+ (action) =>
211
+ action.type === 'worker' && action.value?.[0] === workerName
212
+ )
213
+ )
214
+ )
215
+ )
216
+
217
+ // GET /zones/:zone/email/sending/subdomains
218
+ const sendingOnboarded = (zone: string, domain: DomainName) =>
219
+ orWhenNotFound(
220
+ false,
221
+ api
222
+ .getAll(
223
+ `/zones/${segment(zone)}/email/sending/subdomains`,
224
+ sendingSubdomain,
225
+ 'sending domains'
226
+ )
227
+ .pipe(
228
+ Effect.map((subdomains) =>
229
+ subdomains.some(
230
+ (subdomain) => subdomain.enabled && subdomain.name === domain
231
+ )
232
+ )
233
+ )
234
+ )
235
+
236
+ const catchAllPath = (zone: string) =>
237
+ `/zones/${segment(zone)}/email/routing/rules/catch_all`
238
+
239
+ return {
240
+ // DELETE /zones/:zone/dns_records/:record
241
+ deleteDnsRecord: (zone, record) =>
242
+ api.remove(`/zones/${segment(zone.id)}/dns_records/${segment(record)}`),
243
+
244
+ // DELETE /zones/:zone/email/routing/rules/:rule
245
+ deleteRoutingRule: (zone, rule) =>
246
+ api.remove(
247
+ `/zones/${segment(zone.id)}/email/routing/rules/${segment(rule)}`
248
+ ),
249
+
250
+ // PUT /zones/:zone/email/routing/rules/catch_all with enabled false
251
+ disableCatchAll: (zone) =>
252
+ api
253
+ .write(
254
+ 'PUT',
255
+ catchAllPath(zone.id),
256
+ {
257
+ actions: [{ type: 'drop' }],
258
+ enabled: false,
259
+ matchers: [{ type: 'all' }],
260
+ name: catchAllRuleName
261
+ },
262
+ Schema.Unknown
263
+ )
264
+ .pipe(Effect.asVoid),
265
+
266
+ domainSetup: (domain) =>
267
+ Effect.gen(function* () {
268
+ const zone = yield* zoneId(domain)
269
+
270
+ if (zone === null) {
271
+ return {
272
+ catchAllPointsToWorker: false,
273
+ domain,
274
+ foreignMxHosts: [],
275
+ foreignRoutingRuleCount: 0,
276
+ routingEnabled: false,
277
+ sendingOnboarded: false,
278
+ zoneId: null
279
+ }
280
+ }
281
+
282
+ return {
283
+ catchAllPointsToWorker: yield* catchAllPointsToWorker(zone),
284
+ domain,
285
+ foreignMxHosts: (yield* mxRecords(zone, domain)).map(
286
+ (record) => record.content
287
+ ),
288
+ foreignRoutingRuleCount: (yield* otherRules(zone)).length,
289
+ routingEnabled: yield* routingEnabled(zone),
290
+ sendingOnboarded: yield* sendingOnboarded(zone, domain),
291
+ zoneId: zone
292
+ }
293
+ }),
294
+
295
+ // POST /zones/:zone/email/routing/dns (adds the MX and SPF records)
296
+ enableRouting: (zone) =>
297
+ api
298
+ .write(
299
+ 'POST',
300
+ `/zones/${segment(zone.id)}/email/routing/dns`,
301
+ { name: zone.domain },
302
+ Schema.Unknown
303
+ )
304
+ .pipe(Effect.asVoid),
305
+
306
+ // The same MX read as the plan, with the ids
307
+ foreignMxRecords: (zone) =>
308
+ mxRecords(zone.id, zone.domain).pipe(
309
+ Effect.map((records) =>
310
+ records.flatMap((record) =>
311
+ record.id === undefined
312
+ ? []
313
+ : [
314
+ {
315
+ host: record.content,
316
+ id: record.id,
317
+ priority: record.priority ?? 0
318
+ }
319
+ ]
320
+ )
321
+ )
322
+ ),
323
+
324
+ // POST /zones/:zone/email/sending/subdomains
325
+ onboardSending: (zone) =>
326
+ api
327
+ .write(
328
+ 'POST',
329
+ `/zones/${segment(zone.id)}/email/sending/subdomains`,
330
+ { name: zone.domain },
331
+ Schema.Unknown,
332
+ interpretSending
333
+ )
334
+ .pipe(Effect.asVoid),
335
+
336
+ routingRules: (zone) =>
337
+ otherRules(zone.id).pipe(
338
+ Effect.map((rules) =>
339
+ rules.flatMap((rule) =>
340
+ rule.id === undefined
341
+ ? []
342
+ : [{ description: describeRule(rule), id: rule.id }]
343
+ )
344
+ )
345
+ ),
346
+
347
+ // PUT /zones/:zone/email/routing/rules/catch_all
348
+ setCatchAll: (zone) =>
349
+ api
350
+ .write(
351
+ 'PUT',
352
+ catchAllPath(zone.id),
353
+ {
354
+ actions: [{ type: 'worker', value: [workerName] }],
355
+ enabled: true,
356
+ matchers: [{ type: 'all' }],
357
+ name: catchAllRuleName
358
+ },
359
+ Schema.Unknown
360
+ )
361
+ .pipe(Effect.asVoid)
362
+ }
363
+ }