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,270 @@
1
+ import { Effect, Layer, Schema } from 'effect'
2
+ import {
3
+ HttpClient,
4
+ HttpClientRequest,
5
+ HttpClientResponse
6
+ } from 'effect/http'
7
+
8
+ import { printable } from '../printable'
9
+ import { Cloudflare, CloudflareError } from './cloudflare-client'
10
+ import { accessMethods } from './cloudflare-live-access'
11
+ import { accountMethods } from './cloudflare-live-account'
12
+ import { paidPlanMessage } from './cloudflare-live-api'
13
+ import { checkMethods } from './cloudflare-live-checks'
14
+ import type {
15
+ CloudflarePage,
16
+ Interpret,
17
+ LiveApi
18
+ } from './cloudflare-live-api'
19
+ import { isCloudflareMxHost, zoneMethods } from './cloudflare-live-zone'
20
+
21
+ export { isCloudflareMxHost, paidPlanMessage }
22
+ export type { CloudflarePage }
23
+
24
+ const apiUrl = 'https://api.cloudflare.com/client/v4'
25
+ const pageSize = 50
26
+ // Stops a paging loop that never ends.
27
+ const maxPages = 100
28
+ const timeout = '30 seconds'
29
+
30
+ // Cloudflare error codes that mean the token itself is not accepted.
31
+ const invalidTokenCodes = new Set([6003, 6111, 9106, 9109])
32
+
33
+ const envelope = Schema.Struct({
34
+ result: Schema.Unknown,
35
+ result_info: Schema.optional(
36
+ Schema.Struct({ total_pages: Schema.optional(Schema.Number) })
37
+ )
38
+ })
39
+
40
+ const errorEnvelope = Schema.Struct({
41
+ errors: Schema.optional(
42
+ Schema.Array(
43
+ Schema.Struct({
44
+ code: Schema.optional(Schema.Number),
45
+ message: Schema.optional(Schema.String)
46
+ })
47
+ )
48
+ )
49
+ })
50
+
51
+ const decodeErrorEnvelope = Schema.decodeUnknownOption(errorEnvelope)
52
+
53
+ export const unauthorizedMessage =
54
+ 'Cloudflare rejected the API token. Check CLOUDFLARE_API_TOKEN, or create a new token under My Profile > API Tokens.'
55
+
56
+ // Turns one Cloudflare response into the decoded result, or a CloudflareError.
57
+ // The plan turns forbidden into a message that names the missing permission.
58
+ // A call can pass `interpret` to read an error its own way.
59
+ export function readCloudflareResponse<Value extends Schema.Constraint>(
60
+ schema: Value,
61
+ interpret?: Interpret
62
+ ): (
63
+ response: HttpClientResponse.HttpClientResponse
64
+ ) => Effect.Effect<
65
+ CloudflarePage<Value['Type']>,
66
+ CloudflareError,
67
+ Value['DecodingServices']
68
+ > {
69
+ return Effect.fn('readCloudflareResponse')(function* (response) {
70
+ const body: unknown = yield* response.json.pipe(
71
+ Effect.catch(() => Effect.succeed(undefined))
72
+ )
73
+ const detail = decodeErrorEnvelope(body)
74
+ const errors = detail._tag === 'Some' ? (detail.value.errors ?? []) : []
75
+ const failed = response.status < 200 || response.status >= 300
76
+
77
+ // A 403 is always a missing permission, whatever its error code says.
78
+ if (
79
+ response.status === 401 ||
80
+ (response.status !== 403 &&
81
+ errors.some((error) => invalidTokenCodes.has(error.code ?? 0)))
82
+ ) {
83
+ return yield* new CloudflareError({
84
+ kind: 'unauthorized',
85
+ message: unauthorizedMessage
86
+ })
87
+ }
88
+
89
+ const interpreted = failed
90
+ ? interpret?.(
91
+ response.status,
92
+ errors.flatMap((error) =>
93
+ error.message === undefined ? [] : [error.message]
94
+ )
95
+ )
96
+ : undefined
97
+
98
+ if (interpreted !== undefined) {
99
+ return yield* interpreted
100
+ }
101
+
102
+ if (response.status === 403) {
103
+ return yield* new CloudflareError({
104
+ kind: 'forbidden',
105
+ message:
106
+ 'Cloudflare refused the request (HTTP 403). The API token is missing a permission.'
107
+ })
108
+ }
109
+
110
+ if (response.status === 404) {
111
+ return yield* new CloudflareError({
112
+ kind: 'notFound',
113
+ message: 'Cloudflare could not find what was asked for (HTTP 404).'
114
+ })
115
+ }
116
+
117
+ if (failed) {
118
+ const first = errors[0]?.message
119
+
120
+ return yield* new CloudflareError({
121
+ kind: 'other',
122
+ message: `Cloudflare answered with HTTP ${response.status}${
123
+ first === undefined ? '' : `: ${printable(first)}`
124
+ }. Try again in a moment.`
125
+ })
126
+ }
127
+
128
+ const notUnderstood = () =>
129
+ new CloudflareError({
130
+ kind: 'other',
131
+ message:
132
+ 'Cloudflare answered in a format Courier Crow does not understand. Update the Courier Crow CLI and try again.'
133
+ })
134
+
135
+ const outer = yield* Schema.decodeUnknownEffect(envelope)(body).pipe(
136
+ Effect.mapError(notUnderstood)
137
+ )
138
+ const result = yield* Schema.decodeUnknownEffect(schema)(
139
+ outer.result
140
+ ).pipe(Effect.mapError(notUnderstood))
141
+
142
+ return {
143
+ result,
144
+ totalPages: outer.result_info?.total_pages ?? 1
145
+ }
146
+ })
147
+ }
148
+
149
+ export interface CloudflareSettings {
150
+ accountId: string
151
+ // The hostname of the Courier Crow app, which is the domain of its Access
152
+ // application.
153
+ hostname: string
154
+ token: string
155
+ }
156
+
157
+ export function CloudflareLive(
158
+ settings: CloudflareSettings
159
+ ): Layer.Layer<Cloudflare, never, HttpClient.HttpClient> {
160
+ return Layer.effect(
161
+ Cloudflare,
162
+ Effect.gen(function* () {
163
+ const client = (yield* HttpClient.HttpClient).pipe(
164
+ HttpClient.mapRequest((request) =>
165
+ request.pipe(
166
+ HttpClientRequest.prependUrl(apiUrl),
167
+ HttpClientRequest.bearerToken(settings.token),
168
+ HttpClientRequest.acceptJson
169
+ )
170
+ )
171
+ )
172
+
173
+ // One request with a 30 second timeout and the response decoded.
174
+ const execute = <Value extends Schema.Constraint>(
175
+ request: HttpClientRequest.HttpClientRequest,
176
+ schema: Value,
177
+ interpret?: Interpret
178
+ ): Effect.Effect<
179
+ CloudflarePage<Value['Type']>,
180
+ CloudflareError,
181
+ Value['DecodingServices']
182
+ > =>
183
+ client.execute(request).pipe(
184
+ Effect.mapError(
185
+ (error) =>
186
+ new CloudflareError({
187
+ kind: 'other',
188
+ message: `Could not reach Cloudflare: ${printable(error.message)}. Check your network connection and try again.`
189
+ })
190
+ ),
191
+ Effect.flatMap(readCloudflareResponse(schema, interpret)),
192
+ Effect.timeoutOrElse({
193
+ duration: timeout,
194
+ orElse: () =>
195
+ Effect.fail(
196
+ new CloudflareError({
197
+ kind: 'other',
198
+ message:
199
+ 'Cloudflare did not answer within 30 seconds. Try again in a moment.'
200
+ })
201
+ )
202
+ })
203
+ )
204
+
205
+ const get: LiveApi['get'] = (path, schema, urlParams = {}) =>
206
+ execute(HttpClientRequest.get(path, { urlParams }), schema)
207
+
208
+ const getAll: LiveApi['getAll'] = (path, item, what, urlParams = {}) =>
209
+ Effect.gen(function* () {
210
+ const items: (typeof item)['Type'][] = []
211
+ let page = 1
212
+ let totalPages = 1
213
+
214
+ while (page <= totalPages) {
215
+ if (page > maxPages) {
216
+ return yield* new CloudflareError({
217
+ kind: 'other',
218
+ message: `Cloudflare returned more pages than expected for ${what}. This is a bug in Courier Crow; please report it.`
219
+ })
220
+ }
221
+
222
+ const response = yield* get(path, Schema.Array(item), {
223
+ ...urlParams,
224
+ page: String(page),
225
+ per_page: String(pageSize)
226
+ })
227
+
228
+ items.push(...response.result)
229
+ totalPages = response.totalPages
230
+ page += 1
231
+ }
232
+
233
+ return items
234
+ })
235
+
236
+ // A write with a JSON body. The result is decoded with the schema.
237
+ const write: LiveApi['write'] = (method, path, body, schema, interpret) =>
238
+ execute(
239
+ (method === 'POST'
240
+ ? HttpClientRequest.post(path)
241
+ : HttpClientRequest.put(path)
242
+ ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
243
+ schema,
244
+ interpret
245
+ ).pipe(Effect.map((page) => page.result))
246
+
247
+ const remove: LiveApi['remove'] = (path) =>
248
+ execute(HttpClientRequest.delete(path), Schema.Unknown).pipe(
249
+ Effect.asVoid
250
+ )
251
+
252
+ const api: LiveApi = {
253
+ account: `/accounts/${encodeURIComponent(settings.accountId)}`,
254
+ accountId: settings.accountId,
255
+ get,
256
+ getAll,
257
+ hostname: settings.hostname,
258
+ remove,
259
+ write
260
+ }
261
+
262
+ return Cloudflare.of({
263
+ ...accessMethods(api),
264
+ ...accountMethods(api),
265
+ ...checkMethods(api),
266
+ ...zoneMethods(api)
267
+ })
268
+ })
269
+ )
270
+ }
@@ -0,0 +1,152 @@
1
+ import type { DomainName, EmailAddress } from '@couriercrow/core'
2
+ import { Schema } from 'effect'
3
+
4
+ import { printable } from '../printable'
5
+ import type { MxRecord, RoutingRule } from './cloudflare-client'
6
+
7
+ export interface DomainSetup {
8
+ catchAllPointsToWorker: boolean
9
+ domain: DomainName
10
+ foreignMxHosts: readonly string[]
11
+ foreignRoutingRuleCount: number
12
+ routingEnabled: boolean
13
+ sendingOnboarded: boolean
14
+ zoneId: string | null
15
+ }
16
+
17
+ export type CloudflareChange =
18
+ | { _tag: 'EnableRouting'; domain: DomainName }
19
+ | { _tag: 'OnboardSending'; domain: DomainName }
20
+ | { _tag: 'RemoveCatchAll'; domain: DomainName }
21
+ // Only with --take-over: other Email Routing rules and MX records that
22
+ // were there before Courier Crow.
23
+ | { _tag: 'RemoveRoutingRules'; domain: DomainName; rules: readonly RoutingRule[] }
24
+ | { _tag: 'ReplaceMxRecords'; domain: DomainName; records: readonly MxRecord[] }
25
+ | { _tag: 'SetCatchAll'; domain: DomainName }
26
+ // The Access application exists but its session cookie is SameSite=None
27
+ // or has no value. sameSiteCookie is the value now.
28
+ | {
29
+ _tag: 'UpdateAccessApplication'
30
+ applicationId: string
31
+ sameSiteCookie: string | null
32
+ }
33
+ | {
34
+ _tag: 'UpdateAccessPolicy'
35
+ add: readonly EmailAddress[]
36
+ remove: readonly EmailAddress[]
37
+ }
38
+ // An app has series: <hostname>/u/* gets its own Access application with a
39
+ // bypass policy. applicationId is set when the application is there but
40
+ // its policy is missing.
41
+ | { _tag: 'OpenUnsubscribePage'; applicationId: string | null; hostname: string }
42
+ // No app has series any more: the application goes.
43
+ | { _tag: 'CloseUnsubscribePage'; applicationId: string; hostname: string }
44
+ // The unsubscribe page is open to everyone, but its application covers
45
+ // more than <hostname>/u/* (coverage says what): the bypass policy goes,
46
+ // and deploy fails.
47
+ | {
48
+ _tag: 'RemoveUnsubscribeBypass'
49
+ applicationId: string
50
+ coverage: string
51
+ hostname: string
52
+ policyId: string
53
+ }
54
+
55
+ export class DeployBlocked extends Schema.TaggedError<DeployBlocked>()(
56
+ 'DeployBlocked',
57
+ { message: Schema.String }
58
+ ) {}
59
+
60
+ export function notAZoneMessage(domain: DomainName): string {
61
+ return `${domain} is not a zone in this Cloudflare account. Add the domain to Cloudflare and point its nameservers there, then run deploy again.`
62
+ }
63
+
64
+ export function existingSetupMessage(setup: DomainSetup): string {
65
+ const parts: string[] = []
66
+ const consequences: string[] = []
67
+
68
+ if (setup.foreignMxHosts.length > 0) {
69
+ parts.push(
70
+ `MX records pointing to ${setup.foreignMxHosts.map(printable).join(', ')}`
71
+ )
72
+ consequences.push('move incoming mail to Courier Crow')
73
+ }
74
+
75
+ if (setup.foreignRoutingRuleCount > 0) {
76
+ const noun = setup.foreignRoutingRuleCount === 1 ? 'rule' : 'rules'
77
+
78
+ parts.push(`${setup.foreignRoutingRuleCount} Email Routing ${noun}`)
79
+ consequences.push(
80
+ `replace ${setup.foreignRoutingRuleCount === 1 ? 'that rule' : 'those rules'}`
81
+ )
82
+ }
83
+
84
+ return `${setup.domain} already has ${parts.join(' and ')}. Deploying would ${consequences.join(' and ')}. Run deploy with --take-over to continue.`
85
+ }
86
+
87
+ export function hasExistingSetup(setup: DomainSetup): boolean {
88
+ return setup.foreignMxHosts.length > 0 || setup.foreignRoutingRuleCount > 0
89
+ }
90
+
91
+ // What has to change for a domain that the config lists.
92
+ // The other mail setup that --take-over replaces, with the ids of exactly the
93
+ // records and rules the person sees in the plan.
94
+ export interface Foreign {
95
+ mxRecords: readonly MxRecord[]
96
+ rules: readonly RoutingRule[]
97
+ }
98
+
99
+ // Receiving comes first (routing, then the catch-all), sending last: a
100
+ // sending domain that cannot be onboarded must not stop mail from arriving.
101
+ export function domainChanges(
102
+ setup: DomainSetup,
103
+ foreign: Foreign = { mxRecords: [], rules: [] }
104
+ ): readonly CloudflareChange[] {
105
+ return [
106
+ ...(foreign.mxRecords.length > 0
107
+ ? [
108
+ {
109
+ _tag: 'ReplaceMxRecords' as const,
110
+ domain: setup.domain,
111
+ records: foreign.mxRecords
112
+ }
113
+ ]
114
+ : []),
115
+ ...(foreign.rules.length > 0
116
+ ? [
117
+ {
118
+ _tag: 'RemoveRoutingRules' as const,
119
+ domain: setup.domain,
120
+ rules: foreign.rules
121
+ }
122
+ ]
123
+ : []),
124
+ ...(setup.routingEnabled
125
+ ? []
126
+ : [{ _tag: 'EnableRouting' as const, domain: setup.domain }]),
127
+ ...(setup.catchAllPointsToWorker
128
+ ? []
129
+ : [{ _tag: 'SetCatchAll' as const, domain: setup.domain }]),
130
+ ...(setup.sendingOnboarded
131
+ ? []
132
+ : [{ _tag: 'OnboardSending' as const, domain: setup.domain }])
133
+ ]
134
+ }
135
+
136
+ function compare(left: string, right: string): number {
137
+ return left < right ? -1 : left > right ? 1 : 0
138
+ }
139
+
140
+ export function accessPolicyChange(
141
+ wanted: readonly EmailAddress[],
142
+ current: readonly EmailAddress[]
143
+ ): readonly CloudflareChange[] {
144
+ const wantedSet = new Set<string>(wanted)
145
+ const currentSet = new Set<string>(current)
146
+ const add = wanted.filter((email) => !currentSet.has(email)).sort(compare)
147
+ const remove = current.filter((email) => !wantedSet.has(email)).sort(compare)
148
+
149
+ return add.length === 0 && remove.length === 0
150
+ ? []
151
+ : [{ _tag: 'UpdateAccessPolicy', add, remove }]
152
+ }