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
@@ -0,0 +1,64 @@
1
+ {
2
+ "$schema": "node_modules/wrangler/config-schema.json",
3
+ "name": "courier-crow",
4
+ "main": "src/worker.ts",
5
+ // The date of the installed workerd build (2026-11-19) or earlier.
6
+ "compatibility_date": "2026-11-19",
7
+ "observability": { "enabled": true },
8
+
9
+ // Cloudflare Access is bound to one hostname, so it must be the only one.
10
+ // No workers.dev hostname and no preview URLs.
11
+ "workers_dev": false,
12
+ "preview_urls": false,
13
+ // The pattern is a placeholder. The deploy command fills in app.hostname.
14
+ "routes": [{ "custom_domain": true, "pattern": "mail.placeholder.invalid" }],
15
+
16
+ "assets": {
17
+ "binding": "ASSETS",
18
+ "directory": "../web/dist",
19
+ "not_found_handling": "single-page-application",
20
+ // Requests to /api, /api/* and /u/* (the public unsubscribe page) run the
21
+ // Worker first. Everything else is served from the directory, and unknown
22
+ // paths get the web app's index.html.
23
+ "run_worker_first": ["/api", "/api/*", "/u/*"]
24
+ },
25
+
26
+ // The ids below are placeholders. The deploy command creates the database
27
+ // and the bucket and fills in the real values.
28
+ "d1_databases": [
29
+ {
30
+ "binding": "DATABASE",
31
+ "database_id": "00000000-0000-0000-0000-000000000000",
32
+ "database_name": "courier-crow",
33
+ "migrations_dir": "migrations"
34
+ }
35
+ ],
36
+ "r2_buckets": [{ "binding": "MAIL_STORE", "bucket_name": "courier-crow" }],
37
+ "send_email": [{ "name": "SEND_EMAIL" }],
38
+
39
+ // Once a day at 03:00 UTC the Worker's scheduled handler deletes uploads
40
+ // that no draft took for 24 hours, at most 500 per run, and expires stored
41
+ // bodies. Every 5 minutes it sends the series steps that are due, at most
42
+ // 100 per run. The handler tells the two apart by the cron string.
43
+ "triggers": { "crons": ["0 3 * * *", "*/5 * * * *"] },
44
+
45
+ // The deploy command fills these in. The Worker refuses every request while
46
+ // ACCESS_AUDIENCE, ACCESS_TEAM_DOMAIN or DEPLOY_CLIENT_ID is empty.
47
+ // APP_VERSION is the build id from the bundle's version.json; empty means
48
+ // "dev". AUTHENTICATION_HOST is app.authenticationHost; empty means no
49
+ // Authentication-Results header is stored.
50
+ // APP_HOSTNAME is app.hostname, for the unsubscribe links of series mail;
51
+ // series are not sent while it is empty. BRANDING_NAME and
52
+ // BRANDING_ACCENT_COLOR are app.branding; empty means Courier Crow and its
53
+ // own accent.
54
+ "vars": {
55
+ "ACCESS_AUDIENCE": "",
56
+ "ACCESS_TEAM_DOMAIN": "",
57
+ "APP_HOSTNAME": "",
58
+ "APP_VERSION": "",
59
+ "AUTHENTICATION_HOST": "",
60
+ "BRANDING_ACCENT_COLOR": "",
61
+ "BRANDING_NAME": "",
62
+ "DEPLOY_CLIENT_ID": ""
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "couriercrow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Courier Crow: a shared inbox for your side projects, in your own Cloudflare account. The crow command and the defineMail config.",
5
+ "keywords": [
6
+ "cli",
7
+ "cloudflare",
8
+ "cloudflare-workers",
9
+ "d1",
10
+ "email",
11
+ "email-routing",
12
+ "inbox",
13
+ "infrastructure-as-code",
14
+ "self-hosted",
15
+ "shared-inbox",
16
+ "transactional-email",
17
+ "webmail"
18
+ ],
19
+ "homepage": "https://github.com/Artmann/courier-crow#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/Artmann/courier-crow/issues"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/Artmann/courier-crow.git",
26
+ "directory": "packages/cli"
27
+ },
28
+ "license": "MIT",
29
+ "author": "Christoffer Artmann",
30
+ "type": "module",
31
+ "main": "./src/index.ts",
32
+ "types": "./src/index.ts",
33
+ "bin": {
34
+ "couriercrow": "./bin/couriercrow.js",
35
+ "crow": "./bin/crow.js"
36
+ },
37
+ "exports": {
38
+ ".": "./src/index.ts"
39
+ },
40
+ "files": [
41
+ "bundle",
42
+ "!bundle/worker/worker.js.map",
43
+ "src",
44
+ "!src/**/*.test.ts",
45
+ "!src/**/*.fake.ts",
46
+ "!src/deploy-world.ts"
47
+ ],
48
+ "engines": {
49
+ "bun": ">=1.4.0"
50
+ },
51
+ "scripts": {
52
+ "bundle": "bun scripts/bundle.ts",
53
+ "check": "tsc",
54
+ "lint": "oxlint --config ../../.oxlintrc.json src scripts",
55
+ "prepack": "bun run bundle && bun scripts/require-bundle.ts",
56
+ "test": "bun test"
57
+ },
58
+ "dependencies": {
59
+ "@couriercrow/core": "0.1.0",
60
+ "effect": "^4.1.5",
61
+ "wrangler": "^4.166.0"
62
+ }
63
+ }
@@ -0,0 +1,413 @@
1
+ import type { CurrentState } from '@couriercrow/core'
2
+ import { Effect, Option } from 'effect'
3
+
4
+ import { Cloudflare, CloudflareError } from './cloudflare/cloudflare-client'
5
+ import type {
6
+ AccessPolicy,
7
+ ServiceTokenSummary
8
+ } from './cloudflare/cloudflare-client'
9
+ import { DeployFailed, savePolicy } from './cloudflare/first-run'
10
+ import { MailboxApi, MailboxApiError } from './mailbox-api'
11
+ import { printable } from './printable'
12
+ import { appOfAppToken, appsPolicyName, appTokenName } from './product'
13
+ import { Terminal } from './terminal'
14
+
15
+ // Every app sends with its own Access service token. The tokens of all apps
16
+ // are in one non-identity policy, apart from the deploy token's policy. The
17
+ // secret of a token is shown once, when it is made, and never written to
18
+ // disk. A token is named for the app and the hostname, so the tokens of one
19
+ // deployment are told from everything else in the account.
20
+
21
+ export { appsPolicyName, appTokenName }
22
+
23
+ export interface AppCredentials {
24
+ clientId: string
25
+ clientSecret: string
26
+ name: string
27
+ }
28
+
29
+ interface AppToken extends ServiceTokenSummary {
30
+ app: string
31
+ }
32
+
33
+ // Tokens named for an app of this deployment that no app uses: left by a
34
+ // removed app, a deploy that stopped, or a rotate whose clean-up failed.
35
+ // Deploy deletes them.
36
+ export function unusedAppTokens(
37
+ tokens: readonly ServiceTokenSummary[],
38
+ hostname: string,
39
+ apps: CurrentState['apps']
40
+ ): { app: string; id: string }[] {
41
+ const inUse = new Set(
42
+ apps.flatMap((app) => (app.clientId === null ? [] : [app.clientId]))
43
+ )
44
+
45
+ return appTokens(tokens, hostname)
46
+ .filter((token) => !inUse.has(token.clientId))
47
+ .map((token) => ({ app: token.app, id: token.id }))
48
+ }
49
+
50
+ // Apps that have a token, but none of their tokens is named for this
51
+ // hostname: app.hostname changed, so the Access application is new and lets
52
+ // none of them through. They get new credentials. Empty while any token is
53
+ // named for the hostname.
54
+ export function appsMovedHostname(
55
+ tokens: readonly ServiceTokenSummary[],
56
+ hostname: string,
57
+ apps: CurrentState['apps']
58
+ ): string[] {
59
+ return appTokens(tokens, hostname).length > 0
60
+ ? []
61
+ : apps.filter((app) => app.clientId !== null).map((app) => app.name)
62
+ }
63
+
64
+ // The tokens of this deployment's apps, with the app each is named for.
65
+ function appTokens(
66
+ tokens: readonly ServiceTokenSummary[],
67
+ hostname: string
68
+ ): AppToken[] {
69
+ return tokens.flatMap((token) => {
70
+ const named = appOfAppToken(token.name)
71
+
72
+ return named?.hostname === hostname ? [{ ...token, app: named.app }] : []
73
+ })
74
+ }
75
+
76
+ // The block that tells the person what to put in the app's environment.
77
+ // The values come from Cloudflare, so they are made printable.
78
+ export function credentialLines(
79
+ hostname: string,
80
+ credentials: AppCredentials
81
+ ): string[] {
82
+ return [
83
+ '',
84
+ `App ${credentials.name} can now send mail. Store these in the app's environment. The secret is shown only once.`,
85
+ ` COURIER_CROW_URL=https://${hostname}`,
86
+ ` COURIER_CROW_CLIENT_ID=${printable(credentials.clientId)}`,
87
+ ` COURIER_CROW_CLIENT_SECRET=${printable(credentials.clientSecret)}`
88
+ ]
89
+ }
90
+
91
+ export function printCredentials(
92
+ hostname: string,
93
+ list: readonly AppCredentials[]
94
+ ) {
95
+ return Effect.gen(function* () {
96
+ const terminal = yield* Terminal
97
+
98
+ for (const credentials of list) {
99
+ for (const line of credentialLines(hostname, credentials)) {
100
+ yield* terminal.print(line)
101
+ }
102
+ }
103
+ })
104
+ }
105
+
106
+ // The Access application with its policies and the account's tokens.
107
+ function loadAccess(hostname: string) {
108
+ return Effect.gen(function* () {
109
+ const cloudflare = yield* Cloudflare
110
+ const application = yield* cloudflare.findAccessApplication(hostname)
111
+
112
+ if (Option.isNone(application)) {
113
+ return yield* new DeployFailed({
114
+ message: `The Access application for ${hostname} was not found. Run bunx couriercrow deploy to create it.`
115
+ })
116
+ }
117
+
118
+ const policies = yield* cloudflare.accessPolicies(application.value.id)
119
+ const tokens = yield* cloudflare.serviceTokens()
120
+
121
+ return { applicationId: application.value.id, policies, tokens }
122
+ })
123
+ }
124
+
125
+ // Makes the apps policy let exactly these tokens through. Without tokens the
126
+ // policy goes: Access does not take a policy that includes nobody. Nothing is
127
+ // written when the policy is right already.
128
+ function setAppsPolicy(
129
+ applicationId: string,
130
+ policies: readonly AccessPolicy[],
131
+ tokenIds: readonly string[]
132
+ ) {
133
+ return Effect.gen(function* () {
134
+ const cloudflare = yield* Cloudflare
135
+ const found = policies.find(
136
+ (policy) =>
137
+ policy.name === appsPolicyName && policy.decision === 'non_identity'
138
+ )
139
+ const wanted = new Set(tokenIds)
140
+
141
+ if (
142
+ found !== undefined &&
143
+ found.serviceTokenIds.length === wanted.size &&
144
+ found.serviceTokenIds.every((id) => wanted.has(id))
145
+ ) {
146
+ return
147
+ }
148
+
149
+ if (wanted.size === 0) {
150
+ if (found !== undefined) {
151
+ yield* skipGone(cloudflare.deleteAccessPolicy(applicationId, found.id))
152
+ }
153
+
154
+ return
155
+ }
156
+
157
+ yield* savePolicy(applicationId, policies, {
158
+ decision: 'non_identity',
159
+ include: [...wanted].map((tokenId) => ({
160
+ _tag: 'ServiceToken' as const,
161
+ tokenId
162
+ })),
163
+ name: appsPolicyName
164
+ })
165
+ })
166
+ }
167
+
168
+ // Something that is gone already does not need deleting.
169
+ function skipGone(effect: Effect.Effect<void, CloudflareError>) {
170
+ return effect.pipe(
171
+ Effect.catchIf(
172
+ (error) => error.kind === 'notFound',
173
+ () => Effect.void
174
+ )
175
+ )
176
+ }
177
+
178
+ function deleteTokens(tokens: readonly ServiceTokenSummary[]) {
179
+ return Effect.gen(function* () {
180
+ const cloudflare = yield* Cloudflare
181
+
182
+ for (const token of tokens) {
183
+ yield* skipGone(cloudflare.deleteServiceToken(token.id))
184
+ }
185
+ })
186
+ }
187
+
188
+ // Runs after deploy posted the mail changes, so the API knows every app.
189
+ // An app without a client id gets a new token in the apps policy, and the
190
+ // API is told its client id. Tokens no app uses go: those of removed apps,
191
+ // and those of a deploy that stopped before the API knew them. Gives the
192
+ // credentials the API now uses. When saving one fails, the ones saved before
193
+ // it are printed, so no working secret is lost, and the run fails.
194
+ //
195
+ // Without a terminal (CI) a new secret would land in a log, so no app gets
196
+ // one: needTerminal names the apps that need a deploy from a terminal.
197
+ export function applyAppCredentials(hostname: string, canShowSecrets = true) {
198
+ return Effect.gen(function* () {
199
+ const api = yield* MailboxApi
200
+ const cloudflare = yield* Cloudflare
201
+ const terminal = yield* Terminal
202
+ const state = yield* api.currentState()
203
+
204
+ if (Option.isNone(state)) {
205
+ return yield* new MailboxApiError({
206
+ message: `The Courier Crow app at ${hostname} did not answer, so no app got credentials. Run deploy again.`
207
+ })
208
+ }
209
+
210
+ const access = yield* loadAccess(hostname)
211
+ const ours = appTokens(access.tokens, hostname)
212
+ const inUse = new Set(
213
+ state.value.apps.flatMap((app) => (app.clientId === null ? [] : [app.clientId]))
214
+ )
215
+ const stale = ours.filter((token) => !inUse.has(token.clientId))
216
+ const kept = ours.filter((token) => inUse.has(token.clientId))
217
+ const moved = new Set(appsMovedHostname(access.tokens, hostname, state.value.apps))
218
+ const issued: AppCredentials[] = []
219
+ const needTerminal: string[] = []
220
+
221
+ for (const app of state.value.apps.filter(
222
+ (candidate) => candidate.clientId === null || moved.has(candidate.name)
223
+ )) {
224
+ if (!canShowSecrets) {
225
+ needTerminal.push(app.name)
226
+
227
+ continue
228
+ }
229
+
230
+ if (moved.has(app.name)) {
231
+ yield* terminal.print(`App ${app.name} got new credentials because the app moved to ${hostname}.`)
232
+ } else if (stale.some((token) => token.app === app.name)) {
233
+ yield* terminal.print(
234
+ `App ${app.name} got new credentials because the previous deploy did not finish.`
235
+ )
236
+ }
237
+
238
+ const token = yield* cloudflare.createServiceToken(
239
+ appTokenName(app.name, hostname)
240
+ )
241
+
242
+ issued.push({
243
+ clientId: token.clientId,
244
+ clientSecret: token.clientSecret,
245
+ name: app.name
246
+ })
247
+
248
+ kept.push({
249
+ app: app.name,
250
+ clientId: token.clientId,
251
+ id: token.id,
252
+ name: appTokenName(app.name, hostname)
253
+ })
254
+ }
255
+
256
+ yield* setAppsPolicy(
257
+ access.applicationId,
258
+ access.policies,
259
+ kept.map((token) => token.id)
260
+ )
261
+ yield* deleteTokens(stale)
262
+
263
+ const saved: AppCredentials[] = []
264
+
265
+ for (const credentials of issued) {
266
+ yield* saveAppClient(credentials).pipe(
267
+ Effect.catch(() =>
268
+ printCredentials(hostname, saved).pipe(
269
+ Effect.andThen(
270
+ Effect.fail(new MailboxApiError({ message: notSavedMessage(credentials.name) }))
271
+ )
272
+ )
273
+ )
274
+ )
275
+
276
+ saved.push(credentials)
277
+ }
278
+
279
+ return { needTerminal, saved }
280
+ })
281
+ }
282
+
283
+ export function appNeedsTerminalMessage(app: string): string {
284
+ return `App ${app} needs credentials. Run bunx couriercrow deploy from a terminal to create and see them.`
285
+ }
286
+
287
+ // Deploy's message, the same whether the save was refused or could not be
288
+ // checked: the next deploy shows which.
289
+ export function notSavedMessage(app: string): string {
290
+ return `Could not save the credentials of ${app}. Run deploy again. If it prints no credentials for ${app}, run bunx couriercrow rotate-app-secret ${app}.`
291
+ }
292
+
293
+ // notSaved: the API answered and does not use the new token.
294
+ // unconfirmed: neither the save nor the check got an answer, so the API may
295
+ // use the new token or the old one.
296
+ type SaveFailure = { _tag: 'NotSaved' } | { _tag: 'Unconfirmed' }
297
+
298
+ // Tells the API which token the app uses. When the call fails, the API may
299
+ // still have applied it and only the answer was lost, so the state is read
300
+ // again: an app that has the new client id counts as saved, so its secret is
301
+ // printed and not lost.
302
+ function saveAppClient(credentials: AppCredentials) {
303
+ return Effect.gen(function* () {
304
+ const api = yield* MailboxApi
305
+
306
+ yield* api
307
+ .applyChanges([
308
+ {
309
+ _tag: 'SetAppClient',
310
+ clientId: credentials.clientId,
311
+ name: credentials.name
312
+ }
313
+ ])
314
+ .pipe(
315
+ Effect.catch(() =>
316
+ Effect.gen(function* () {
317
+ const state = yield* api.currentState().pipe(
318
+ Effect.map((value) => (Option.isSome(value) ? value : null)),
319
+ Effect.catch(() => Effect.succeed(null))
320
+ )
321
+
322
+ if (state === null) {
323
+ return yield* Effect.fail<SaveFailure>({ _tag: 'Unconfirmed' })
324
+ }
325
+
326
+ const app = state.value.apps.find((candidate) => candidate.name === credentials.name)
327
+
328
+ if (app?.clientId !== credentials.clientId) {
329
+ return yield* Effect.fail<SaveFailure>({ _tag: 'NotSaved' })
330
+ }
331
+ })
332
+ )
333
+ )
334
+ })
335
+ }
336
+
337
+ // Gives one app a new token, in an order where a failure at any step leaves
338
+ // the app able to send with its old secret or with the new one that was
339
+ // printed: create the new token, add it to the apps policy beside the old
340
+ // one, tell the API, print the new values, then take the old token out of
341
+ // the policy and delete it (a failure there is only a warning). `apps` are
342
+ // the apps the API has now.
343
+ export function rotateAppToken(
344
+ name: string,
345
+ hostname: string,
346
+ apps: CurrentState['apps']
347
+ ) {
348
+ return Effect.gen(function* () {
349
+ const cloudflare = yield* Cloudflare
350
+ const terminal = yield* Terminal
351
+ const inUse = new Set(
352
+ apps.flatMap((app) => (app.clientId === null ? [] : [app.clientId]))
353
+ )
354
+ const access = yield* loadAccess(hostname)
355
+ const ours = appTokens(access.tokens, hostname)
356
+ const others = ours.filter(
357
+ (candidate) => candidate.app !== name && inUse.has(candidate.clientId)
358
+ )
359
+ const old = ours.filter((candidate) => candidate.app === name)
360
+
361
+ // Until the API uses the new token, the old one stays in the policy, so a
362
+ // failure up to here leaves the app sending with its old secret.
363
+ const token = yield* cloudflare.createServiceToken(appTokenName(name, hostname))
364
+
365
+ yield* setAppsPolicy(access.applicationId, access.policies, [
366
+ ...others.map((candidate) => candidate.id),
367
+ ...old
368
+ .filter((candidate) => inUse.has(candidate.clientId))
369
+ .map((candidate) => candidate.id),
370
+ token.id
371
+ ])
372
+
373
+ const credentials: AppCredentials = {
374
+ clientId: token.clientId,
375
+ clientSecret: token.clientSecret,
376
+ name
377
+ }
378
+
379
+ yield* saveAppClient(credentials).pipe(
380
+ Effect.mapError(
381
+ (failure) =>
382
+ new MailboxApiError({
383
+ message:
384
+ failure._tag === 'NotSaved'
385
+ ? `Could not save the new secret of ${name}. The current secret still works. Run bunx couriercrow rotate-app-secret ${name} again.`
386
+ : `Could not confirm that the new credentials of ${name} were saved. If ${name} can no longer send, run bunx couriercrow rotate-app-secret ${name} again.`
387
+ })
388
+ )
389
+ )
390
+
391
+ // The new secret works from here on, so it is shown before the clean-up,
392
+ // which can only leave an unused token behind.
393
+ yield* printCredentials(hostname, [credentials])
394
+
395
+ yield* Effect.gen(function* () {
396
+ const policies = yield* cloudflare.accessPolicies(access.applicationId)
397
+
398
+ yield* setAppsPolicy(access.applicationId, policies, [
399
+ ...others.map((candidate) => candidate.id),
400
+ token.id
401
+ ])
402
+ yield* deleteTokens(old)
403
+ }).pipe(
404
+ Effect.catch(() =>
405
+ terminal.warn(
406
+ `The old credentials of ${name} could not be deleted. They no longer work for sending. Run deploy to clean up.`
407
+ )
408
+ )
409
+ )
410
+
411
+ return credentials
412
+ })
413
+ }