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.
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
package/src/doctor.ts ADDED
@@ -0,0 +1,504 @@
1
+ import type { ConfigError, MailConfig } from '@couriercrow/core'
2
+ import { Effect, Option, Result } from 'effect'
3
+
4
+ import { Cloudflare, CloudflareError } from './cloudflare/cloudflare-client'
5
+ import type { Zone } from './cloudflare/cloudflare-client'
6
+ import { existingSetupMessage, hasExistingSetup } from './cloudflare/cloudflare-state'
7
+ import { MailboxApi } from './mailbox-api'
8
+ import { needsEdit, permissionArea, permissions, tokenSteps } from './permissions'
9
+ import type { Permission } from './permissions'
10
+ import { printable } from './printable'
11
+ import { bunVersionProblem } from './runtime'
12
+
13
+ // crow doctor: read-only checks, one line each, with what to do when one
14
+ // fails. crow deploy runs the Cloudflare checks first and stops on a failure.
15
+
16
+ // fail: positively known to be wrong; deploy cannot work until it is fixed.
17
+ // unknown: could not be determined (an HTTP or decode problem, an answer
18
+ // not recognised); never blocks. warn: deploy works, but something needs
19
+ // attention. skip: not checked, or nothing to check yet.
20
+ export type CheckMark = 'fail' | 'pass' | 'skip' | 'unknown' | 'warn'
21
+
22
+ export interface Check {
23
+ mark: CheckMark
24
+ text: string
25
+ // The fix is a token: crow doctor prints how to create one after the
26
+ // lines.
27
+ tokenSteps?: true
28
+ }
29
+
30
+ const symbols: Record<CheckMark, string> = {
31
+ fail: '✗',
32
+ pass: '✓',
33
+ skip: '-',
34
+ unknown: '?',
35
+ warn: '!'
36
+ }
37
+
38
+ export function formatCheck(check: Check): string {
39
+ return `${symbols[check.mark]} ${check.text}`
40
+ }
41
+
42
+ export function hasFailed(checks: readonly Check[]): boolean {
43
+ return checks.some((check) => check.mark === 'fail')
44
+ }
45
+
46
+ export const doctorFailedMessage =
47
+ 'Some checks failed. Fix what the ✗ lines say, then run bunx couriercrow doctor again.'
48
+
49
+ // What crow doctor prints: a line per check, then how to create a token
50
+ // when a line asks for one.
51
+ export function doctorLines(checks: readonly Check[]): string[] {
52
+ return [
53
+ ...checks.map(formatCheck),
54
+ ...(checks.some((check) => check.tokenSteps === true) ? ['', ...tokenSteps] : [])
55
+ ]
56
+ }
57
+
58
+ // What deploy stops with: the failed lines, then the token steps when one
59
+ // of them asks for a token, as doctor prints them.
60
+ export function failedLines(checks: readonly Check[]): string[] {
61
+ const failed = checks.filter((check) => check.mark === 'fail')
62
+
63
+ return [
64
+ ...failed.map(formatCheck),
65
+ ...(failed.some((check) => check.tokenSteps === true) ? ['', ...tokenSteps] : [])
66
+ ]
67
+ }
68
+
69
+ // Whether the config loads and the app bundle is there.
70
+ export function configCheck(loaded: Result.Result<MailConfig, ConfigError>): Check {
71
+ return Result.isSuccess(loaded) ? pass('mail.config.ts is valid') : fail(loaded.failure.message)
72
+ }
73
+
74
+ export function bundleCheck(version: Result.Result<string, { message: string }>): Check {
75
+ return Result.isSuccess(version)
76
+ ? pass(`The app bundle is built (${version.success})`)
77
+ : fail(version.failure.message)
78
+ }
79
+
80
+ const pass = (text: string): Check => ({ mark: 'pass', text })
81
+ const fail = (text: string): Check => ({ mark: 'fail', text })
82
+ const tokenFail = (text: string): Check => ({ mark: 'fail', text, tokenSteps: true })
83
+ const warn = (text: string): Check => ({ mark: 'warn', text })
84
+ const skip = (text: string): Check => ({ mark: 'skip', text })
85
+ const unknown = (text: string): Check => ({ mark: 'unknown', text })
86
+
87
+ export const zeroTrustLink = 'https://one.dash.cloudflare.com/'
88
+
89
+ // Bun, and the two variables the Cloudflare checks need.
90
+ export function localChecks(
91
+ bunVersion: string,
92
+ environment: Readonly<Record<string, string | undefined>>
93
+ ): Check[] {
94
+ const tooOld = bunVersionProblem(bunVersion)
95
+ const isSet = (name: string) => (environment[name] ?? '') !== ''
96
+
97
+ return [
98
+ tooOld === undefined ? pass(`Bun ${bunVersion}`) : fail(tooOld),
99
+ isSet('CLOUDFLARE_API_TOKEN')
100
+ ? pass('CLOUDFLARE_API_TOKEN is set')
101
+ : tokenFail(
102
+ 'CLOUDFLARE_API_TOKEN is not set. Create a token with the steps below, then put it in .env in this folder or export it.'
103
+ ),
104
+ isSet('CLOUDFLARE_ACCOUNT_ID')
105
+ ? pass('CLOUDFLARE_ACCOUNT_ID is set')
106
+ : fail(
107
+ 'CLOUDFLARE_ACCOUNT_ID is not set. Copy it from the overview page of any domain in the Cloudflare dashboard (under API) into .env, or export it.'
108
+ )
109
+ ]
110
+ }
111
+
112
+ // Deploy deploys the app and checks RESEND_API_KEY itself, so it leaves
113
+ // those two out. Doctor reads the running app.
114
+ export type AccountCheckOptions =
115
+ | { forDeploy: true }
116
+ | {
117
+ // The build id of the bundle this command line carries, compared with
118
+ // the running app's. Undefined when the bundle could not be read.
119
+ appVersion: string | undefined
120
+ forDeploy: false
121
+ // Whether this folder has deploy credentials (the file or the two
122
+ // variables). Without them the app cannot be read at all.
123
+ hasCredentials: boolean
124
+ }
125
+
126
+ export const noCredentialsMessage =
127
+ 'Could not read the app: there are no deploy credentials in this folder.'
128
+
129
+ // An HTTP or decode problem: the check could not tell.
130
+ function couldNotCheck(what: string, error: { message: string }): Check {
131
+ return unknown(`Could not check ${what}: ${printable(error.message)}`)
132
+ }
133
+
134
+ // The zone of a name: found, not a zone of this account, or the lookup
135
+ // failed.
136
+ type ZoneLookup =
137
+ | { _tag: 'Found'; zone: Zone }
138
+ | { _tag: 'None' }
139
+ | { _tag: 'Unreadable'; error: CloudflareError; name: string }
140
+
141
+ // The zones the zone permissions are probed in, and the names whose zone
142
+ // could not be looked up.
143
+ interface ProbeZones {
144
+ found: readonly Zone[]
145
+ unreadable: readonly { error: CloudflareError; name: string }[]
146
+ }
147
+
148
+ // The zone with exactly this name.
149
+ function lookUpZone(name: string) {
150
+ return Effect.gen(function* () {
151
+ const id = yield* (yield* Cloudflare).zoneIdOf(name).pipe(Effect.result)
152
+ // A name that zoneIdOf found is a zone's name, so a domain name.
153
+ const lookup: ZoneLookup =
154
+ id._tag === 'Failure'
155
+ ? { _tag: 'Unreadable', error: id.failure, name }
156
+ : Option.isSome(id.success)
157
+ ? { _tag: 'Found', zone: { domain: name as Zone['domain'], id: id.success.value } }
158
+ : { _tag: 'None' }
159
+
160
+ return lookup
161
+ })
162
+ }
163
+
164
+ // The zone a hostname is under: the hostname itself, or the nearest name it
165
+ // ends in, that is a zone.
166
+ function zoneOfHostname(hostname: string) {
167
+ return Effect.gen(function* () {
168
+ const labels = hostname.split('.')
169
+
170
+ for (let start = 0; start <= labels.length - 2; start += 1) {
171
+ const lookup = yield* lookUpZone(labels.slice(start).join('.'))
172
+
173
+ if (lookup._tag === 'Unreadable') {
174
+ const unreadable: ZoneLookup = { ...lookup, name: hostname }
175
+
176
+ return unreadable
177
+ }
178
+
179
+ if (lookup._tag === 'Found') {
180
+ return lookup
181
+ }
182
+ }
183
+
184
+ const none: ZoneLookup = { _tag: 'None' }
185
+
186
+ return none
187
+ })
188
+ }
189
+
190
+ // Every zone the config uses: each mail domain's, and the app hostname's.
191
+ function zonesOf(config: MailConfig | undefined) {
192
+ return Effect.gen(function* () {
193
+ const lookups: ZoneLookup[] = []
194
+
195
+ // The keys of config.domains are domain names.
196
+ for (const domain of Object.keys(config?.domains ?? {})) {
197
+ lookups.push(yield* lookUpZone(domain))
198
+ }
199
+
200
+ if (config !== undefined) {
201
+ lookups.push(yield* zoneOfHostname(config.app.hostname))
202
+ }
203
+
204
+ const found = new Map<string, Zone>()
205
+ const unreadable = new Map<string, { error: CloudflareError; name: string }>()
206
+
207
+ for (const lookup of lookups) {
208
+ if (lookup._tag === 'Found') {
209
+ found.set(lookup.zone.domain, lookup.zone)
210
+ } else if (lookup._tag === 'Unreadable') {
211
+ unreadable.set(lookup.name, { error: lookup.error, name: lookup.name })
212
+ }
213
+ }
214
+
215
+ const zones: ProbeZones = { found: [...found.values()], unreadable: [...unreadable.values()] }
216
+
217
+ return zones
218
+ })
219
+ }
220
+
221
+ function reachedLine(permission: Permission, zone: Zone | undefined): string {
222
+ const area =
223
+ zone === undefined ? permissionArea(permission) : `${permissionArea(permission)} in ${zone.domain}`
224
+
225
+ // A read answers the same for Read and Edit, so a pass says only that the
226
+ // token reaches the area.
227
+ return needsEdit(permission)
228
+ ? `The token can reach ${area} (doctor cannot tell Read from Edit; deploy needs Edit)`
229
+ : `The token can reach ${area}`
230
+ }
231
+
232
+ function probe(permission: Permission, zone: Zone | undefined) {
233
+ return Effect.gen(function* () {
234
+ const probed = yield* (yield* Cloudflare)
235
+ .probePermission(permission.area, zone)
236
+ .pipe(Effect.result)
237
+
238
+ if (probed._tag === 'Success') {
239
+ return pass(reachedLine(permission, zone))
240
+ }
241
+
242
+ if (probed.failure.kind !== 'forbidden') {
243
+ return couldNotCheck(
244
+ zone === undefined ? permission.name : `${permission.name} in ${zone.domain}`,
245
+ probed.failure
246
+ )
247
+ }
248
+
249
+ return zone === undefined
250
+ ? tokenFail(
251
+ `${permission.name} is missing. Edit the token under My Profile > API Tokens and add it.`
252
+ )
253
+ : tokenFail(
254
+ `${permission.name} is missing for ${zone.domain}. Edit the token under My Profile > API Tokens: add the permission, and include ${zone.domain} under Zone Resources.`
255
+ )
256
+ })
257
+ }
258
+
259
+ // Account permissions once; zone permissions in every zone of the config.
260
+ function permissionChecks(zones: ProbeZones) {
261
+ return Effect.gen(function* () {
262
+ const checks: Check[] = []
263
+
264
+ for (const permission of permissions) {
265
+ if (permission.scope === 'account') {
266
+ checks.push(yield* probe(permission, undefined))
267
+
268
+ continue
269
+ }
270
+
271
+ if (zones.found.length === 0 && zones.unreadable.length === 0) {
272
+ checks.push(
273
+ skip(
274
+ `${permission.name} was not checked: no domain in mail.config.ts is a zone in this account yet.`
275
+ )
276
+ )
277
+
278
+ continue
279
+ }
280
+
281
+ for (const zone of zones.found) {
282
+ checks.push(yield* probe(permission, zone))
283
+ }
284
+
285
+ for (const { error, name } of zones.unreadable) {
286
+ checks.push(
287
+ unknown(
288
+ `Could not check ${permission.name}: the zone of ${name} could not be looked up. ${printable(error.message)}`
289
+ )
290
+ )
291
+ }
292
+ }
293
+
294
+ return checks
295
+ })
296
+ }
297
+
298
+ export const planUnknownMessage =
299
+ 'Could not tell whether this account is on Workers Paid. Courier Crow needs it. Check under Workers & Pages > Plans.'
300
+
301
+ // Passes on Workers Paid. Cloudflare documents no marker of Workers Free, so
302
+ // every other answer is unknown, never a failure.
303
+ function planCheck() {
304
+ return Effect.gen(function* () {
305
+ const plan = yield* (yield* Cloudflare).accountPlan().pipe(Effect.result)
306
+
307
+ if (plan._tag === 'Success') {
308
+ return plan.success === 'paid'
309
+ ? pass('The account is on Workers Paid')
310
+ : unknown(planUnknownMessage)
311
+ }
312
+
313
+ return unknown(
314
+ plan.failure.kind === 'forbidden'
315
+ ? `${planUnknownMessage} Reading the plan needs Account > Billing > Read, which the token does not need otherwise.`
316
+ : `${planUnknownMessage} Reading the plan failed: ${printable(plan.failure.message)}`
317
+ )
318
+ })
319
+ }
320
+
321
+ function zeroTrustChecks() {
322
+ return Effect.gen(function* () {
323
+ const cloudflare = yield* Cloudflare
324
+ const team = yield* cloudflare.accessTeamDomain().pipe(Effect.result)
325
+
326
+ if (team._tag === 'Failure') {
327
+ return [
328
+ team.failure.kind === 'notFound'
329
+ ? fail(
330
+ `Cloudflare Zero Trust is not set up for this account. Open ${zeroTrustLink}, choose a team name (the free plan is enough), then run bunx couriercrow doctor again.`
331
+ )
332
+ : couldNotCheck('Zero Trust', team.failure)
333
+ ]
334
+ }
335
+
336
+ const providers = yield* cloudflare.identityProviderTypes().pipe(Effect.result)
337
+
338
+ return [pass(`Zero Trust is set up (${printable(team.success)})`), signInCheck(providers)]
339
+ })
340
+ }
341
+
342
+ const addOneTimePin = 'Zero Trust > Integrations > Identity providers > Add new > One-time PIN'
343
+
344
+ // Cloudflare's docs: a new organization signs in members of the Cloudflare
345
+ // account through the Cloudflare identity provider, and nobody else. They do
346
+ // not say whether the list of identity providers shows it, so an empty list
347
+ // is unknown, not a failure. Everyone else needs One-time PIN.
348
+ function signInCheck(providers: Result.Result<readonly string[], CloudflareError>): Check {
349
+ if (Result.isFailure(providers)) {
350
+ return couldNotCheck('the sign-in methods of Zero Trust', providers.failure)
351
+ }
352
+
353
+ if (providers.success.includes('onetimepin')) {
354
+ return pass('Zero Trust has One-time PIN, so people outside your Cloudflare account can sign in')
355
+ }
356
+
357
+ return providers.success.length === 0
358
+ ? unknown(
359
+ `Zero Trust lists no sign-in method. A new organization signs in members of your Cloudflare account through Cloudflare, which may not be listed. For anyone else, add One-time PIN under ${addOneTimePin}.`
360
+ )
361
+ : warn(
362
+ `Zero Trust has no One-time PIN. Only people its other sign-in methods know can sign in. For anyone else, add it under ${addOneTimePin}.`
363
+ )
364
+ }
365
+
366
+ function domainChecks(config: MailConfig) {
367
+ return Effect.gen(function* () {
368
+ const cloudflare = yield* Cloudflare
369
+ const checks: Check[] = []
370
+
371
+ for (const domain of Object.keys(config.domains) as (keyof MailConfig['domains'])[]) {
372
+ const setup = yield* cloudflare.domainSetup(domain).pipe(Effect.result)
373
+
374
+ if (setup._tag === 'Failure') {
375
+ checks.push(couldNotCheck(domain, setup.failure))
376
+ } else if (setup.success.zoneId === null) {
377
+ checks.push(
378
+ fail(
379
+ `${domain} is not a zone in this Cloudflare account. Add it to Cloudflare and point its nameservers there, then run bunx couriercrow doctor again.`
380
+ )
381
+ )
382
+ } else if (!setup.success.catchAllPointsToWorker && hasExistingSetup(setup.success)) {
383
+ checks.push(warn(existingSetupMessage(setup.success)))
384
+ } else {
385
+ checks.push(pass(`${domain} is a zone in this account`))
386
+ }
387
+ }
388
+
389
+ return checks
390
+ })
391
+ }
392
+
393
+ // The hostname is under a zone when it, or a name it ends in, is a zone.
394
+ function hostnameCheck(hostname: string) {
395
+ return Effect.gen(function* () {
396
+ const lookup = yield* zoneOfHostname(hostname)
397
+
398
+ switch (lookup._tag) {
399
+ case 'Found':
400
+ return pass(`${hostname} is under ${lookup.zone.domain}, a zone in this account`)
401
+ case 'Unreadable':
402
+ return couldNotCheck(hostname, lookup.error)
403
+ case 'None':
404
+ return fail(
405
+ `${hostname} is not under a domain in this Cloudflare account. Add ${hostname.split('.').slice(-2).join('.')} to Cloudflare first, or change app.hostname.`
406
+ )
407
+ }
408
+ })
409
+ }
410
+
411
+ function appChecks(config: MailConfig, appVersion: string | undefined) {
412
+ return Effect.gen(function* () {
413
+ const api = yield* MailboxApi
414
+ const hostname = config.app.hostname
415
+ const checks: Check[] = []
416
+ const running = yield* api.version().pipe(Effect.result)
417
+
418
+ if (running._tag === 'Failure') {
419
+ checks.push(
420
+ unknown(`Could not read the version of the app at ${hostname}: ${running.failure.message}`)
421
+ )
422
+ } else if (Option.isNone(running.success)) {
423
+ checks.push(skip('The app is not deployed yet. bunx couriercrow deploy deploys it.'))
424
+ } else if (appVersion !== undefined && running.success.value === appVersion) {
425
+ checks.push(pass(`The app at ${hostname} runs this version (${appVersion})`))
426
+ } else if (appVersion !== undefined) {
427
+ checks.push(
428
+ warn(
429
+ `The app at ${hostname} runs ${printable(running.success.value)}; this command line has ${appVersion}. bunx couriercrow deploy updates it.`
430
+ )
431
+ )
432
+ }
433
+
434
+ const hasSeries = Object.values(config.apps ?? {}).some((app) => app.series !== undefined)
435
+
436
+ if (hasSeries && running._tag === 'Success' && Option.isSome(running.success)) {
437
+ const key = yield* api.hasSeriesProviderKey().pipe(Effect.result)
438
+
439
+ if (key._tag === 'Failure') {
440
+ checks.push(unknown(`Could not check RESEND_API_KEY: ${key.failure.message}`))
441
+ } else if (Option.isSome(key.success) && key.success.value) {
442
+ checks.push(pass('RESEND_API_KEY is set'))
443
+ } else {
444
+ checks.push(
445
+ warn('Series will not send until you run bunx couriercrow set-secret RESEND_API_KEY.')
446
+ )
447
+ }
448
+ } else if (hasSeries) {
449
+ checks.push(
450
+ skip(
451
+ 'RESEND_API_KEY was not checked: after the first deploy, run bunx couriercrow set-secret RESEND_API_KEY.'
452
+ )
453
+ )
454
+ }
455
+
456
+ return checks
457
+ })
458
+ }
459
+
460
+ // Everything that needs the token: the token, its permissions, the plan,
461
+ // Zero Trust, the domains and the hostname, and outside deploy the running
462
+ // app. Never fails: every problem is a line.
463
+ export function accountChecks(config: MailConfig | undefined, options: AccountCheckOptions) {
464
+ return Effect.gen(function* () {
465
+ const cloudflare = yield* Cloudflare
466
+ const token = yield* cloudflare.verifyToken().pipe(Effect.result)
467
+
468
+ // A token check that failed on the way says nothing about the token: the
469
+ // other checks still run and tell for themselves.
470
+ if (token._tag === 'Success' && !token.success) {
471
+ return [
472
+ tokenFail(
473
+ 'Cloudflare rejected the API token. Create a new one with the steps below and put it in CLOUDFLARE_API_TOKEN.'
474
+ ),
475
+ skip('The other Cloudflare checks need a token Cloudflare accepts.')
476
+ ]
477
+ }
478
+
479
+ const checks: Check[] = [
480
+ token._tag === 'Failure'
481
+ ? couldNotCheck('the API token', token.failure)
482
+ : pass('Cloudflare accepts the API token')
483
+ ]
484
+
485
+ checks.push(...(yield* permissionChecks(yield* zonesOf(config))))
486
+ checks.push(yield* planCheck())
487
+ checks.push(...(yield* zeroTrustChecks()))
488
+
489
+ if (config !== undefined) {
490
+ checks.push(...(yield* domainChecks(config)))
491
+ checks.push(yield* hostnameCheck(config.app.hostname))
492
+
493
+ if (!options.forDeploy) {
494
+ checks.push(
495
+ ...(options.hasCredentials
496
+ ? yield* appChecks(config, options.appVersion)
497
+ : [unknown(noCredentialsMessage)])
498
+ )
499
+ }
500
+ }
501
+
502
+ return checks
503
+ })
504
+ }
@@ -0,0 +1,141 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { Effect, Option, Schema } from 'effect'
5
+
6
+ import { MailboxApiError } from './mailbox-api'
7
+ import type { AccessCredentials } from './mailbox-api'
8
+ import { tokenInstructions } from './permissions'
9
+ import { credentialsPath, localFolder } from './product'
10
+
11
+ export class MissingEnvironment extends Schema.TaggedError<MissingEnvironment>()(
12
+ 'MissingEnvironment',
13
+ { message: Schema.String }
14
+ ) {}
15
+
16
+ export function readCloudflareSettings(
17
+ environment: Readonly<Record<string, string | undefined>>
18
+ ): Effect.Effect<{ accountId: string; token: string }, MissingEnvironment> {
19
+ const accountId = environment['CLOUDFLARE_ACCOUNT_ID'] ?? ''
20
+ const token = environment['CLOUDFLARE_API_TOKEN'] ?? ''
21
+ const missing = [
22
+ ...(token === '' ? ['CLOUDFLARE_API_TOKEN'] : []),
23
+ ...(accountId === '' ? ['CLOUDFLARE_ACCOUNT_ID'] : [])
24
+ ]
25
+
26
+ return missing.length === 0
27
+ ? Effect.succeed({ accountId, token })
28
+ : Effect.fail(
29
+ new MissingEnvironment({
30
+ message: `Set ${missing.join(' and ')} before running crow. ${tokenInstructions}`
31
+ })
32
+ )
33
+ }
34
+
35
+ const credentialsFile = Schema.Struct({
36
+ clientId: Schema.String,
37
+ clientSecret: Schema.String
38
+ })
39
+
40
+ type Environment = Readonly<Record<string, string | undefined>>
41
+
42
+ const deployClientIdVariable = 'COURIER_CROW_DEPLOY_CLIENT_ID'
43
+ const deployClientSecretVariable = 'COURIER_CROW_DEPLOY_CLIENT_SECRET'
44
+
45
+ // The deploy credentials CI keeps in its secrets. Both set: they win over the
46
+ // file. One alone: a mistake, which readCredentials names.
47
+ function fromEnvironment(
48
+ environment: Environment
49
+ ): { credentials: Option.Option<AccessCredentials>; missing: string | undefined } {
50
+ const clientId = environment[deployClientIdVariable] ?? ''
51
+ const clientSecret = environment[deployClientSecretVariable] ?? ''
52
+
53
+ if (clientId !== '' && clientSecret !== '') {
54
+ return { credentials: Option.some({ clientId, clientSecret }), missing: undefined }
55
+ }
56
+
57
+ return {
58
+ credentials: Option.none(),
59
+ missing:
60
+ clientId === '' && clientSecret === ''
61
+ ? undefined
62
+ : clientId === ''
63
+ ? deployClientIdVariable
64
+ : deployClientSecretVariable
65
+ }
66
+ }
67
+
68
+ // Whether the deploy credentials come from the two variables.
69
+ export function credentialsFromEnvironment(environment: Environment): boolean {
70
+ return Option.isSome(fromEnvironment(environment).credentials)
71
+ }
72
+
73
+ // The same file, read when it is needed. Deploy writes it while it runs, so
74
+ // the API client reads it again for every request. A file that is missing or
75
+ // not valid counts as no credentials. The two variables win over it.
76
+ export function readCredentialsSync(
77
+ directory: string,
78
+ environment: Environment = {}
79
+ ): Option.Option<AccessCredentials> {
80
+ const given = fromEnvironment(environment).credentials
81
+
82
+ if (Option.isSome(given)) {
83
+ return given
84
+ }
85
+
86
+ try {
87
+ const content: unknown = JSON.parse(
88
+ readFileSync(join(directory, localFolder, 'credentials.json'), 'utf8')
89
+ )
90
+
91
+ return Schema.decodeUnknownOption(credentialsFile)(content)
92
+ } catch {
93
+ return Option.none()
94
+ }
95
+ }
96
+
97
+ // The Access service token that deploy saved. Without the file the app is
98
+ // treated as not deployed.
99
+ export function readCredentials(
100
+ directory: string,
101
+ environment: Environment = {}
102
+ ): Effect.Effect<Option.Option<AccessCredentials>, MailboxApiError> {
103
+ return Effect.gen(function* () {
104
+ const given = fromEnvironment(environment)
105
+
106
+ if (given.missing !== undefined) {
107
+ return yield* new MailboxApiError({
108
+ message: `Set both ${deployClientIdVariable} and ${deployClientSecretVariable}, or neither: ${given.missing} is missing.`
109
+ })
110
+ }
111
+
112
+ if (Option.isSome(given.credentials)) {
113
+ return given.credentials
114
+ }
115
+
116
+ const file = Bun.file(join(directory, localFolder, 'credentials.json'))
117
+ const exists = yield* Effect.promise(() => file.exists())
118
+
119
+ if (!exists) {
120
+ return Option.none()
121
+ }
122
+
123
+ const content: unknown = yield* Effect.tryPromise({
124
+ try: () => file.json(),
125
+ catch: () =>
126
+ new MailboxApiError({
127
+ message: `Could not read ${credentialsPath}. Delete the file and run deploy again.`
128
+ })
129
+ })
130
+
131
+ return yield* Schema.decodeUnknownEffect(credentialsFile)(content).pipe(
132
+ Effect.map(Option.some),
133
+ Effect.mapError(
134
+ () =>
135
+ new MailboxApiError({
136
+ message: `${credentialsPath} must contain clientId and clientSecret. Delete the file and run deploy again.`
137
+ })
138
+ )
139
+ )
140
+ })
141
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ // What a config repository imports: mail.config.ts starts with
2
+ // import { defineMail } from 'couriercrow'.
3
+ export { defineMail } from '@couriercrow/core'
4
+ export type { MailConfig, MailConfigInput } from '@couriercrow/core'