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,345 @@
1
+ import { AdminState, CurrentState } from '@couriercrow/core'
2
+ import type { Change, EmailAddress } from '@couriercrow/core'
3
+ import { Context, Effect, Layer, Option, Schema } from 'effect'
4
+ import {
5
+ FetchHttpClient,
6
+ HttpClient,
7
+ HttpClientRequest,
8
+ HttpClientResponse
9
+ } from 'effect/http'
10
+ import type { HttpClientError } from 'effect/http'
11
+
12
+ import { printable } from './printable'
13
+ import { credentialsPath } from './product'
14
+
15
+ // For deploy credentials a run cannot use or make: CI has them from its
16
+ // secrets, and only a deploy from a terminal makes new ones.
17
+ export const ciCredentialsMessage =
18
+ 'Deploy credentials are missing or no longer valid. Run bunx couriercrow deploy once from a terminal, then copy the values with bunx couriercrow credentials show into your CI secrets.'
19
+
20
+ export class MailboxApiError extends Schema.TaggedError<MailboxApiError>()(
21
+ 'MailboxApiError',
22
+ { message: Schema.String }
23
+ ) {}
24
+
25
+ // The state as GET /api/admin/state gives it, with what the plan needs about
26
+ // series history. The extras are absent from older apps.
27
+ export const DeployedState = Schema.Struct({
28
+ ...CurrentState.fields,
29
+ hasEnrollments: Schema.optional(Schema.Boolean),
30
+ unsubscribePageNeededUntil: Schema.optional(Schema.NullOr(Schema.String))
31
+ })
32
+ export type DeployedState = typeof DeployedState.Type
33
+
34
+ interface MailboxApiShape {
35
+ applyChanges: (
36
+ changes: readonly Change[]
37
+ ) => Effect.Effect<void, MailboxApiError>
38
+ // none when the app is not deployed yet.
39
+ currentState: () => Effect.Effect<Option.Option<DeployedState>, MailboxApiError>
40
+ // Whether the Worker has RESEND_API_KEY. The API never tells the value.
41
+ // none when the app is not deployed yet.
42
+ hasSeriesProviderKey: () => Effect.Effect<Option.Option<boolean>, MailboxApiError>
43
+ // Deletes part of the mail per call. isFinished is false while there is
44
+ // more: call it again.
45
+ purgeMailbox: (
46
+ address: EmailAddress
47
+ ) => Effect.Effect<
48
+ { deletedMessages: number; isFinished: boolean },
49
+ MailboxApiError
50
+ >
51
+ // none when the app is not deployed yet.
52
+ version: () => Effect.Effect<Option.Option<string>, MailboxApiError>
53
+ }
54
+
55
+ // The admin endpoints of the API Worker.
56
+ export class MailboxApi extends Context.Service<MailboxApi, MailboxApiShape>()(
57
+ 'MailboxApi'
58
+ ) {}
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Live
62
+
63
+ const timeout = '30 seconds'
64
+
65
+ const errorBody = Schema.Struct({ message: Schema.String })
66
+ const versionBody = Schema.Struct({ version: Schema.String })
67
+ const purgeBody = Schema.Struct({
68
+ deletedMessages: Schema.Number,
69
+ isFinished: Schema.Boolean
70
+ })
71
+
72
+ export interface AccessCredentials {
73
+ clientId: string
74
+ clientSecret: string
75
+ }
76
+
77
+ export interface MailboxApiSettings {
78
+ // Without credentials every read answers "not deployed" and writes fail.
79
+ credentials:
80
+ | Option.Option<AccessCredentials>
81
+ | (() => Option.Option<AccessCredentials>)
82
+ // The credentials come from COURIER_CROW_DEPLOY_CLIENT_ID and _SECRET, so
83
+ // deleting the file would not help when the app rejects them.
84
+ credentialsFromEnvironment?: boolean
85
+ hostname: string
86
+ }
87
+
88
+ const decodeErrorBody = Schema.decodeUnknownOption(errorBody)
89
+
90
+ function isJson(response: HttpClientResponse.HttpClientResponse): boolean {
91
+ return (response.headers['content-type'] ?? '').includes('application/json')
92
+ }
93
+
94
+ function notAnswering(hostname: string, status: number): MailboxApiError {
95
+ return new MailboxApiError({
96
+ message: `The Courier Crow app at ${hostname} is not answering correctly (status ${status}). Try again in a minute.`
97
+ })
98
+ }
99
+
100
+ // Reads one response from the admin API. Our own JSON { message } errors pass
101
+ // through. A redirect, 401 or 403 that is not our JSON is the Access login:
102
+ // the credentials are wrong or expired. Any other answer that is not our JSON
103
+ // means the app is failing. None of these mean "not deployed".
104
+ export function readMailboxApiResponse<Value extends Schema.Constraint>(
105
+ schema: Value,
106
+ hostname: string,
107
+ credentialsFromEnvironment = false
108
+ ): (
109
+ response: HttpClientResponse.HttpClientResponse
110
+ ) => Effect.Effect<Value['Type'], MailboxApiError, Value['DecodingServices']> {
111
+ const success = (body: unknown) =>
112
+ Schema.decodeUnknownEffect(schema)(body).pipe(
113
+ Effect.mapError(
114
+ () =>
115
+ new MailboxApiError({
116
+ message:
117
+ 'The Courier Crow app answered in a format this CLI does not understand. Run deploy to update the app.'
118
+ })
119
+ )
120
+ )
121
+
122
+ return Effect.fn('readMailboxApiResponse')(function* (response) {
123
+ const ok = response.status >= 200 && response.status < 300
124
+
125
+ if (!isJson(response)) {
126
+ if (
127
+ (response.status >= 300 && response.status < 400) ||
128
+ response.status === 401 ||
129
+ response.status === 403
130
+ ) {
131
+ return yield* new MailboxApiError({
132
+ message: credentialsFromEnvironment
133
+ ? ciCredentialsMessage
134
+ : `The Courier Crow app at ${hostname} rejected the deploy credentials. Delete ${credentialsPath} and run deploy again to create new ones.`
135
+ })
136
+ }
137
+
138
+ if (ok) {
139
+ const text = yield* response.text.pipe(
140
+ Effect.catch(() => Effect.succeed('unreadable'))
141
+ )
142
+
143
+ if (text === '') {
144
+ return yield* success(undefined)
145
+ }
146
+ }
147
+
148
+ return yield* notAnswering(hostname, response.status)
149
+ }
150
+
151
+ const body: unknown = yield* response.json.pipe(
152
+ Effect.mapError(() => notAnswering(hostname, response.status))
153
+ )
154
+
155
+ if (!ok) {
156
+ const detail = decodeErrorBody(body)
157
+
158
+ return yield* Option.isSome(detail) && response.status < 500
159
+ ? new MailboxApiError({ message: printable(detail.value.message) })
160
+ : notAnswering(hostname, response.status)
161
+ }
162
+
163
+ return yield* success(body)
164
+ })
165
+ }
166
+
167
+ // The app counts as not deployed only when the hostname does not resolve or
168
+ // the connection is refused. Bun's fetch reports these as the cause code
169
+ // ENOTFOUND (Node style) and ConnectionRefused (Bun) on the transport error.
170
+ const notDeployedCodes = new Set(['ConnectionRefused', 'ECONNREFUSED', 'ENOTFOUND'])
171
+
172
+ export function isNotDeployed(error: HttpClientError.HttpClientError): boolean {
173
+ const cause: unknown = error.reason._tag === 'TransportError' ? error.reason.cause : undefined
174
+ const code =
175
+ typeof cause === 'object' && cause !== null && 'code' in cause
176
+ ? cause.code
177
+ : undefined
178
+
179
+ return typeof code === 'string' && notDeployedCodes.has(code)
180
+ }
181
+
182
+ function shortReason(error: HttpClientError.HttpClientError): string {
183
+ const cause: unknown = error.reason._tag === 'TransportError' ? error.reason.cause : undefined
184
+
185
+ return printable(
186
+ cause instanceof Error && cause.message !== '' ? cause.message : error.message
187
+ )
188
+ }
189
+
190
+ type Reply<Value> = { _tag: 'NotDeployed' } | { _tag: 'Reply'; value: Value }
191
+
192
+ export function MailboxApiLive(
193
+ settings: MailboxApiSettings
194
+ ): Layer.Layer<MailboxApi, never, HttpClient.HttpClient> {
195
+ const { hostname } = settings
196
+
197
+ // A function is read on every request: deploy creates the credentials
198
+ // while it runs.
199
+ const credentials = (): Option.Option<AccessCredentials> =>
200
+ typeof settings.credentials === 'function'
201
+ ? settings.credentials()
202
+ : settings.credentials
203
+
204
+ return Layer.effect(
205
+ MailboxApi,
206
+ Effect.gen(function* () {
207
+ const client = (yield* HttpClient.HttpClient).pipe(
208
+ HttpClient.mapRequest((request) =>
209
+ request.pipe(
210
+ HttpClientRequest.prependUrl(`https://${hostname}`),
211
+ HttpClientRequest.acceptJson,
212
+ (withUrl) => {
213
+ const current = credentials()
214
+
215
+ return Option.isSome(current)
216
+ ? HttpClientRequest.setHeaders(withUrl, {
217
+ 'CF-Access-Client-Id': current.value.clientId,
218
+ 'CF-Access-Client-Secret': current.value.clientSecret
219
+ })
220
+ : withUrl
221
+ }
222
+ )
223
+ )
224
+ )
225
+
226
+ // Runs a request without following redirects: a redirect is the Access
227
+ // login page, which must not be mistaken for an answer.
228
+ const send = <Value extends Schema.Constraint>(
229
+ request: HttpClientRequest.HttpClientRequest,
230
+ schema: Value
231
+ ): Effect.Effect<
232
+ Reply<Value['Type']>,
233
+ MailboxApiError,
234
+ Value['DecodingServices']
235
+ > =>
236
+ client.execute(request).pipe(
237
+ Effect.provideService(FetchHttpClient.RequestInit, {
238
+ redirect: 'manual'
239
+ }),
240
+ Effect.matchEffect({
241
+ onFailure: (error) =>
242
+ isNotDeployed(error)
243
+ ? Effect.succeed({ _tag: 'NotDeployed' as const })
244
+ : Effect.fail(
245
+ new MailboxApiError({
246
+ message: `Could not reach the Courier Crow app at ${hostname}: ${shortReason(error)}. Check your connection and try again.`
247
+ })
248
+ ),
249
+ onSuccess: (response) =>
250
+ readMailboxApiResponse(
251
+ schema,
252
+ hostname,
253
+ settings.credentialsFromEnvironment === true
254
+ )(response).pipe(
255
+ Effect.map((value) => ({ _tag: 'Reply' as const, value }))
256
+ )
257
+ }),
258
+ Effect.timeoutOrElse({
259
+ duration: timeout,
260
+ orElse: () =>
261
+ Effect.fail(
262
+ new MailboxApiError({
263
+ message: `Could not reach the Courier Crow app at ${hostname}: no answer within 30 seconds. Check your connection and try again.`
264
+ })
265
+ )
266
+ })
267
+ )
268
+
269
+ // For writes, "not deployed" is a failure.
270
+ const write = <Value extends Schema.Constraint>(
271
+ request: HttpClientRequest.HttpClientRequest,
272
+ schema: Value
273
+ ) =>
274
+ Effect.gen(function* () {
275
+ if (Option.isNone(credentials())) {
276
+ return yield* new MailboxApiError({
277
+ message: `No Access service token found in ${credentialsPath}. Run deploy to create one.`
278
+ })
279
+ }
280
+
281
+ const reply = yield* send(request, schema)
282
+
283
+ if (reply._tag === 'NotDeployed') {
284
+ return yield* new MailboxApiError({
285
+ message: `The Courier Crow app is not reachable at ${hostname}. Run deploy first.`
286
+ })
287
+ }
288
+
289
+ return reply.value
290
+ })
291
+
292
+ const read = <Value extends Schema.Constraint>(
293
+ request: HttpClientRequest.HttpClientRequest,
294
+ schema: Value
295
+ ): Effect.Effect<
296
+ Option.Option<Value['Type']>,
297
+ MailboxApiError,
298
+ Value['DecodingServices']
299
+ > =>
300
+ Option.isNone(credentials())
301
+ ? Effect.succeed(Option.none())
302
+ : send(request, schema).pipe(
303
+ Effect.map((reply) =>
304
+ reply._tag === 'Reply'
305
+ ? Option.some(reply.value)
306
+ : Option.none()
307
+ )
308
+ )
309
+
310
+ return MailboxApi.of({
311
+ applyChanges: (changes) =>
312
+ write(
313
+ HttpClientRequest.post('/api/admin/changes').pipe(
314
+ HttpClientRequest.bodyJsonUnsafe({ changes })
315
+ ),
316
+ Schema.Undefined
317
+ ).pipe(Effect.asVoid),
318
+
319
+ currentState: () =>
320
+ read(HttpClientRequest.get('/api/admin/state'), DeployedState),
321
+
322
+ hasSeriesProviderKey: () =>
323
+ read(
324
+ HttpClientRequest.get('/api/admin/state'),
325
+ Schema.Struct({ hasSeriesProviderKey: AdminState.fields.hasSeriesProviderKey })
326
+ ).pipe(
327
+ Effect.map(Option.map((state) => state.hasSeriesProviderKey))
328
+ ),
329
+
330
+ purgeMailbox: (address) =>
331
+ write(
332
+ HttpClientRequest.delete(
333
+ `/api/admin/mailboxes/${encodeURIComponent(address)}`
334
+ ),
335
+ purgeBody
336
+ ),
337
+
338
+ version: () =>
339
+ read(HttpClientRequest.get('/api/admin/version'), versionBody).pipe(
340
+ Effect.map(Option.map((body) => body.version))
341
+ )
342
+ })
343
+ })
344
+ )
345
+ }
@@ -0,0 +1,133 @@
1
+ // The permissions of the Cloudflare API token, by their names in the
2
+ // dashboard. One list, so the messages, crow doctor and the README say the
3
+ // same.
4
+ export const accountPermissions = {
5
+ accessApplications: 'Account > Access: Apps and Policies > Edit',
6
+ accessOrganization:
7
+ 'Account > Access: Organizations, Identity Providers, and Groups > Edit',
8
+ accessServiceTokens: 'Account > Access: Service Tokens > Edit',
9
+ buckets: 'Account > Workers R2 Storage > Edit',
10
+ databases: 'Account > D1 > Edit',
11
+ workers: 'Account > Workers Scripts > Edit'
12
+ } as const
13
+
14
+ export const zonePermissions = [
15
+ 'Zone > Workers Routes > Edit',
16
+ 'Zone > DNS > Edit',
17
+ 'Zone > Email Routing Rules > Edit',
18
+ 'Zone > Email Sending > Edit'
19
+ ] as const
20
+
21
+ // What crow doctor reads to see that the token reaches each area.
22
+ export type PermissionArea =
23
+ | 'accessApplications'
24
+ | 'accessOrganization'
25
+ | 'accessServiceTokens'
26
+ | 'buckets'
27
+ | 'databases'
28
+ | 'dns'
29
+ | 'emailRouting'
30
+ | 'emailSending'
31
+ | 'workers'
32
+ | 'workersRoutes'
33
+
34
+ export interface Permission {
35
+ area: PermissionArea
36
+ name: string
37
+ scope: 'account' | 'zone'
38
+ // The short key of Cloudflare's token template link, for the permissions
39
+ // whose key Cloudflare documents. The link drops keys it does not know
40
+ // without a word, so the others are left out.
41
+ templateKey: string | undefined
42
+ }
43
+
44
+ export const permissions: readonly Permission[] = [
45
+ { area: 'databases', name: accountPermissions.databases, scope: 'account', templateKey: 'd1' },
46
+ { area: 'buckets', name: accountPermissions.buckets, scope: 'account', templateKey: 'workers_r2' },
47
+ {
48
+ area: 'workers',
49
+ name: accountPermissions.workers,
50
+ scope: 'account',
51
+ templateKey: 'workers_scripts'
52
+ },
53
+ {
54
+ area: 'accessApplications',
55
+ name: accountPermissions.accessApplications,
56
+ scope: 'account',
57
+ templateKey: 'access'
58
+ },
59
+ {
60
+ area: 'accessServiceTokens',
61
+ name: accountPermissions.accessServiceTokens,
62
+ scope: 'account',
63
+ templateKey: undefined
64
+ },
65
+ {
66
+ area: 'accessOrganization',
67
+ name: accountPermissions.accessOrganization,
68
+ scope: 'account',
69
+ templateKey: 'access_acct'
70
+ },
71
+ { area: 'workersRoutes', name: zonePermissions[0], scope: 'zone', templateKey: 'workers_routes' },
72
+ { area: 'dns', name: zonePermissions[1], scope: 'zone', templateKey: 'dns' },
73
+ { area: 'emailRouting', name: zonePermissions[2], scope: 'zone', templateKey: undefined },
74
+ { area: 'emailSending', name: zonePermissions[3], scope: 'zone', templateKey: undefined }
75
+ ]
76
+
77
+ export const requiredPermissions: readonly string[] = permissions.map(
78
+ (permission) => permission.name
79
+ )
80
+
81
+ // "Account > D1 > Edit" is the area "Account > D1" at the level Edit.
82
+ export function permissionArea(permission: Permission): string {
83
+ return permission.name.replace(/ > (?:Edit|Read)$/, '')
84
+ }
85
+
86
+ export function needsEdit(permission: Permission): boolean {
87
+ return permission.name.endsWith(' > Edit')
88
+ }
89
+
90
+ // "Account > Access: Service Tokens > Edit" as the form shows it:
91
+ // "Access: Service Tokens (Edit)".
92
+ function formName(permission: Permission): string {
93
+ const parts = permission.name.split(' > ')
94
+
95
+ return `${parts.slice(1, -1).join(' > ')} (${parts.at(-1) ?? ''})`
96
+ }
97
+
98
+ const numberWords = ['no', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
99
+
100
+ function inWords(count: number): string {
101
+ return numberWords[count] ?? String(count)
102
+ }
103
+
104
+ const linked = permissions.filter((permission) => permission.templateKey !== undefined)
105
+ const unlinked = permissions.filter((permission) => permission.templateKey === undefined)
106
+
107
+ // What the token link carries and what has to be added by hand, from the
108
+ // list: the permissions without a template key.
109
+ export const linkCoverage = `The link preselects ${inWords(linked.length)} permissions. Add these ${inWords(unlinked.length)} by hand before creating the token: ${unlinked.map(formName).join(', ')}.`
110
+
111
+ // Cloudflare's link to the "create token" page with permissions chosen
112
+ // (developers.cloudflare.com/fundamentals/api/how-to/account-owned-token-template/):
113
+ // a user token, every account and zone, named courier-crow. The page
114
+ // documents only `*` for accountId, so the link cannot preset one account.
115
+ export const tokenTemplateUrl = `https://dash.cloudflare.com/profile/api-tokens?permissionGroupKeys=${encodeURIComponent(
116
+ JSON.stringify(
117
+ permissions.flatMap((permission) =>
118
+ permission.templateKey === undefined ? [] : [{ key: permission.templateKey, type: 'edit' }]
119
+ )
120
+ )
121
+ )}&accountId=%2A&zoneId=all&name=courier-crow`
122
+
123
+ // How to create the token, one line per entry, for crow init and crow doctor.
124
+ export const tokenSteps: readonly string[] = [
125
+ 'Create a Cloudflare API token with this link:',
126
+ tokenTemplateUrl,
127
+ linkCoverage,
128
+ `The token needs all ${inWords(permissions.length)}:`,
129
+ ...requiredPermissions.map((permission) => `- ${permission}`),
130
+ 'Include your account under Account Resources, and the zones of your domains and of the app hostname (or all zones) under Zone Resources.'
131
+ ]
132
+
133
+ export const tokenInstructions = `Create a token in the Cloudflare dashboard under My Profile > API Tokens with these permissions: ${requiredPermissions.join(', ')}. This link opens the form with most of them chosen: ${tokenTemplateUrl} ${linkCoverage}`