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.
- package/LICENSE +21 -0
- package/README.md +19 -2
- package/bin/couriercrow.js +5 -0
- package/bin/crow.js +14 -0
- package/bundle/migrations/0001_initial.sql +463 -0
- package/bundle/version.json +3 -0
- package/bundle/web/_headers +6 -0
- package/bundle/web/assets/index-Bim8rHvG.css +2 -0
- package/bundle/web/assets/index-YpJn_3e5.js +13 -0
- package/bundle/web/index.html +14 -0
- package/bundle/worker/README.md +1 -0
- package/bundle/worker/worker.js +57841 -0
- package/bundle/wrangler.jsonc +64 -0
- package/package.json +61 -4
- package/src/app-credentials.ts +413 -0
- package/src/bin.ts +578 -0
- package/src/build-config.ts +264 -0
- package/src/build-id.ts +39 -0
- package/src/cloudflare/cloudflare-client.ts +361 -0
- package/src/cloudflare/cloudflare-live-access.ts +454 -0
- package/src/cloudflare/cloudflare-live-account.ts +95 -0
- package/src/cloudflare/cloudflare-live-api.ts +87 -0
- package/src/cloudflare/cloudflare-live-checks.ts +151 -0
- package/src/cloudflare/cloudflare-live-zone.ts +363 -0
- package/src/cloudflare/cloudflare-live.ts +270 -0
- package/src/cloudflare/cloudflare-state.ts +152 -0
- package/src/cloudflare/first-run.ts +322 -0
- package/src/credentials-show.ts +49 -0
- package/src/deploy.ts +807 -0
- package/src/doctor.ts +504 -0
- package/src/environment.ts +141 -0
- package/src/index.ts +4 -0
- package/src/init.ts +332 -0
- package/src/load-config.ts +47 -0
- package/src/mailbox-api.ts +345 -0
- package/src/permissions.ts +133 -0
- package/src/plan.ts +517 -0
- package/src/printable.ts +8 -0
- package/src/product.ts +63 -0
- package/src/purge.ts +93 -0
- package/src/render.ts +406 -0
- package/src/rotate-app-secret.ts +53 -0
- package/src/runtime.ts +33 -0
- package/src/set-secret.ts +63 -0
- package/src/terminal.ts +163 -0
- package/src/wrangler.ts +168 -0
package/src/plan.ts
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
import { desiredState, planChanges } from '@couriercrow/core'
|
|
2
|
+
import type {
|
|
3
|
+
Change,
|
|
4
|
+
CurrentState,
|
|
5
|
+
DomainName,
|
|
6
|
+
EmailAddress,
|
|
7
|
+
MailConfig
|
|
8
|
+
} from '@couriercrow/core'
|
|
9
|
+
import { Effect, Option } from 'effect'
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
Cloudflare,
|
|
13
|
+
CloudflareError,
|
|
14
|
+
coversExactly,
|
|
15
|
+
describeCoverage,
|
|
16
|
+
unsubscribeDomain,
|
|
17
|
+
unsubscribePolicyName,
|
|
18
|
+
workerName
|
|
19
|
+
} from './cloudflare/cloudflare-client'
|
|
20
|
+
import { appsMovedHostname, unusedAppTokens } from './app-credentials'
|
|
21
|
+
import { authenticationPartOf } from './build-config'
|
|
22
|
+
import { accountPermissions, zonePermissions } from './permissions'
|
|
23
|
+
import { printable } from './printable'
|
|
24
|
+
import {
|
|
25
|
+
appOfAppToken,
|
|
26
|
+
hostnameOfDeployToken,
|
|
27
|
+
productName,
|
|
28
|
+
resourceName
|
|
29
|
+
} from './product'
|
|
30
|
+
import {
|
|
31
|
+
accessPolicyChange,
|
|
32
|
+
DeployBlocked,
|
|
33
|
+
domainChanges,
|
|
34
|
+
existingSetupMessage,
|
|
35
|
+
hasExistingSetup,
|
|
36
|
+
notAZoneMessage
|
|
37
|
+
} from './cloudflare/cloudflare-state'
|
|
38
|
+
import type { ServiceTokenSummary } from './cloudflare/cloudflare-client'
|
|
39
|
+
import type { CloudflareChange } from './cloudflare/cloudflare-state'
|
|
40
|
+
import { MailboxApi, MailboxApiError } from './mailbox-api'
|
|
41
|
+
|
|
42
|
+
// What deploying the app creates or reuses in the account.
|
|
43
|
+
export interface AppResource {
|
|
44
|
+
_tag: 'AccessApplication' | 'Bucket' | 'Database' | 'Worker'
|
|
45
|
+
name: string
|
|
46
|
+
// replace: only for a Worker that is not ours, with --take-over.
|
|
47
|
+
state: 'create' | 'replace' | 'use'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface DeployPlan {
|
|
51
|
+
app: 'deploy' | 'unchanged'
|
|
52
|
+
// app.authenticationHost differs from the one the running app has (none
|
|
53
|
+
// before the first deploy). to: null when it is no longer set. Absent
|
|
54
|
+
// when it stays.
|
|
55
|
+
authenticationHost?: { to: string | null }
|
|
56
|
+
// Apps with a client id while no app token is named for this hostname:
|
|
57
|
+
// app.hostname changed. Deploy gives them new credentials. Absent when
|
|
58
|
+
// there are none.
|
|
59
|
+
appsMovedHostname?: readonly string[]
|
|
60
|
+
// Apps that are deployed but have no service token: a deploy stopped after
|
|
61
|
+
// adding them. Deploy gives them credentials.
|
|
62
|
+
appsWithoutCredentials: readonly string[]
|
|
63
|
+
cloudflare: readonly CloudflareChange[]
|
|
64
|
+
// No app has series any more, but mail already sent links to the
|
|
65
|
+
// unsubscribe page until then: it stays open. A note, not a change.
|
|
66
|
+
// Absent otherwise.
|
|
67
|
+
keepUnsubscribePageUntil?: string
|
|
68
|
+
// People the app has now, so a removal can show the name.
|
|
69
|
+
currentPeople: readonly { email: EmailAddress; name: string }[]
|
|
70
|
+
mail: readonly Change[]
|
|
71
|
+
// Apps the plan adds again because their domain changed: they keep their
|
|
72
|
+
// log and credentials, so the plan says "move". Absent when there are none.
|
|
73
|
+
movedApps?: readonly string[]
|
|
74
|
+
// app.hostname changed: deploy removes what Courier Crow made for the old
|
|
75
|
+
// hostnames, found by its names. While the app does not answer at the new
|
|
76
|
+
// one yet, apps get new credentials too. When it answers there already
|
|
77
|
+
// (isFinishing), a move that stopped halfway is finished. Absent
|
|
78
|
+
// otherwise.
|
|
79
|
+
movesFrom?: {
|
|
80
|
+
applications: readonly { hostname: string; id: string }[]
|
|
81
|
+
isFinishing: boolean
|
|
82
|
+
tokens: readonly { id: string; name: string }[]
|
|
83
|
+
}
|
|
84
|
+
// Mailboxes that `crow purge` started deleting and has not finished.
|
|
85
|
+
// Absent when there are none.
|
|
86
|
+
purgingMailboxes?: readonly EmailAddress[]
|
|
87
|
+
// Service tokens named for an app of this deployment that no app uses.
|
|
88
|
+
// Deploy deletes them. Absent when there are none.
|
|
89
|
+
unusedAppTokens?: readonly { app: string; id: string }[]
|
|
90
|
+
// Empty unless the app is deployed.
|
|
91
|
+
resources: readonly AppResource[]
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function purgingInConfigMessage(address: EmailAddress): string {
|
|
95
|
+
return `${address} is in mail.config.ts but is being purged. Finish the purge with bunx couriercrow purge ${address}, or remove it from the config.`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const emptyState: CurrentState = {
|
|
99
|
+
apps: [],
|
|
100
|
+
domains: [],
|
|
101
|
+
mailboxes: [],
|
|
102
|
+
people: [],
|
|
103
|
+
seriesProvider: null
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function missingPermissionMessage(domain: DomainName): string {
|
|
107
|
+
return `The Cloudflare API token is missing a permission for ${domain}. It needs ${zonePermissions.slice(1, 4).join(', ')} and ${zonePermissions[0]}. Update the token and run again.`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export const foreignWorkerMessage = `A Worker named ${workerName} already exists in this account and is not a ${productName} app. Deploying would replace it. Run deploy with --take-over to replace it, or rename that Worker.`
|
|
111
|
+
|
|
112
|
+
const accessPermissionMessage = `The Cloudflare API token cannot manage Access applications in this account. Add the permission ${accountPermissions.accessApplications} to the token and run deploy again.`
|
|
113
|
+
|
|
114
|
+
// appVersion: the build id of the bundle (bundle/version.json). The app is
|
|
115
|
+
// deployed when the running app answers with anything else.
|
|
116
|
+
export function buildPlan(
|
|
117
|
+
config: MailConfig,
|
|
118
|
+
options: { appVersion: string; takeOver: boolean }
|
|
119
|
+
): Effect.Effect<
|
|
120
|
+
DeployPlan,
|
|
121
|
+
CloudflareError | DeployBlocked | MailboxApiError,
|
|
122
|
+
Cloudflare | MailboxApi
|
|
123
|
+
> {
|
|
124
|
+
return Effect.gen(function* () {
|
|
125
|
+
const cloudflare = yield* Cloudflare
|
|
126
|
+
const api = yield* MailboxApi
|
|
127
|
+
|
|
128
|
+
const version = yield* api.version()
|
|
129
|
+
const state = yield* api.currentState()
|
|
130
|
+
const current = Option.getOrElse(state, () => emptyState)
|
|
131
|
+
const desired = desiredState(config)
|
|
132
|
+
|
|
133
|
+
const setupFor = (domain: DomainName) =>
|
|
134
|
+
cloudflare.domainSetup(domain).pipe(
|
|
135
|
+
Effect.mapError((error) =>
|
|
136
|
+
error.kind === 'forbidden'
|
|
137
|
+
? new CloudflareError({
|
|
138
|
+
kind: 'forbidden',
|
|
139
|
+
message: missingPermissionMessage(domain)
|
|
140
|
+
})
|
|
141
|
+
: error
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
const changes: CloudflareChange[] = []
|
|
146
|
+
|
|
147
|
+
for (const domain of desired.domains) {
|
|
148
|
+
const setup = yield* setupFor(domain)
|
|
149
|
+
|
|
150
|
+
if (setup.zoneId === null) {
|
|
151
|
+
return yield* new DeployBlocked({ message: notAZoneMessage(domain) })
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (
|
|
155
|
+
!setup.catchAllPointsToWorker &&
|
|
156
|
+
!options.takeOver &&
|
|
157
|
+
hasExistingSetup(setup)
|
|
158
|
+
) {
|
|
159
|
+
return yield* new DeployBlocked({
|
|
160
|
+
message: existingSetupMessage(setup)
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// With --take-over the plan lists exactly what will be replaced, by id.
|
|
165
|
+
// Deploy deletes only those.
|
|
166
|
+
const foreign =
|
|
167
|
+
options.takeOver && hasExistingSetup(setup)
|
|
168
|
+
? yield* Effect.gen(function* () {
|
|
169
|
+
const zone = { domain, id: setup.zoneId ?? '' }
|
|
170
|
+
const mxRecords = yield* cloudflare.foreignMxRecords(zone)
|
|
171
|
+
const rules = yield* cloudflare.routingRules(zone)
|
|
172
|
+
|
|
173
|
+
return { mxRecords, rules }
|
|
174
|
+
}).pipe(
|
|
175
|
+
Effect.mapError((error) =>
|
|
176
|
+
error.kind === 'forbidden'
|
|
177
|
+
? new CloudflareError({
|
|
178
|
+
kind: 'forbidden',
|
|
179
|
+
message: missingPermissionMessage(domain)
|
|
180
|
+
})
|
|
181
|
+
: error
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
: undefined
|
|
185
|
+
|
|
186
|
+
changes.push(...domainChanges(setup, foreign))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Domains that left the config stop receiving mail.
|
|
190
|
+
const wanted = new Set<string>(desired.domains)
|
|
191
|
+
|
|
192
|
+
for (const domain of current.domains.filter((name) => !wanted.has(name))) {
|
|
193
|
+
const setup = yield* setupFor(domain)
|
|
194
|
+
|
|
195
|
+
if (setup.catchAllPointsToWorker) {
|
|
196
|
+
changes.push({ _tag: 'RemoveCatchAll', domain })
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const withAccessMessage = Effect.mapError((error: CloudflareError) =>
|
|
201
|
+
error.kind === 'forbidden'
|
|
202
|
+
? new CloudflareError({
|
|
203
|
+
kind: 'forbidden',
|
|
204
|
+
message: accessPermissionMessage
|
|
205
|
+
})
|
|
206
|
+
: error
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
// What Courier Crow made for hostnames other than this one, found by
|
|
210
|
+
// its names only (see product.ts): deploy tokens, app tokens and Access
|
|
211
|
+
// applications named Courier Crow. While the app moves (it does not
|
|
212
|
+
// answer here yet), the old hostnames are those of the deploy tokens.
|
|
213
|
+
// Once it answers here (isFinishing), any of the three names one. None:
|
|
214
|
+
// undefined.
|
|
215
|
+
const leftAtOldHostnames = (
|
|
216
|
+
hostname: string,
|
|
217
|
+
tokens: readonly ServiceTokenSummary[],
|
|
218
|
+
isFinishing: boolean
|
|
219
|
+
) =>
|
|
220
|
+
Effect.gen(function* () {
|
|
221
|
+
const deployFor = hostnameOfDeployToken
|
|
222
|
+
const appFor = (name: string) => appOfAppToken(name)?.hostname
|
|
223
|
+
const others = (names: readonly (string | undefined)[]) =>
|
|
224
|
+
names.flatMap((found) => (found === undefined || found === hostname ? [] : [found]))
|
|
225
|
+
const deployHostnames = others(tokens.map((token) => deployFor(token.name)))
|
|
226
|
+
|
|
227
|
+
if (!isFinishing && deployHostnames.length === 0) {
|
|
228
|
+
return undefined
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const mailboxApplications = yield* cloudflare
|
|
232
|
+
.mailboxApplications()
|
|
233
|
+
.pipe(withAccessMessage)
|
|
234
|
+
const oldHostnames = new Set([
|
|
235
|
+
...deployHostnames,
|
|
236
|
+
...(isFinishing
|
|
237
|
+
? others([
|
|
238
|
+
...tokens.map((token) => appFor(token.name)),
|
|
239
|
+
...mailboxApplications.map((candidate) => candidate.domain)
|
|
240
|
+
])
|
|
241
|
+
: [])
|
|
242
|
+
])
|
|
243
|
+
|
|
244
|
+
if (oldHostnames.size === 0) {
|
|
245
|
+
return undefined
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const applications = mailboxApplications
|
|
249
|
+
.filter((candidate) => oldHostnames.has(candidate.domain))
|
|
250
|
+
.map((candidate) => ({ hostname: candidate.domain, id: candidate.id }))
|
|
251
|
+
const oldTokens = tokens
|
|
252
|
+
.filter((token) => {
|
|
253
|
+
const deployHostname = deployFor(token.name)
|
|
254
|
+
const appHostname = appFor(token.name)
|
|
255
|
+
|
|
256
|
+
return (
|
|
257
|
+
(deployHostname !== undefined && oldHostnames.has(deployHostname)) ||
|
|
258
|
+
(appHostname !== undefined && oldHostnames.has(appHostname))
|
|
259
|
+
)
|
|
260
|
+
})
|
|
261
|
+
.map((token) => ({ id: token.id, name: token.name }))
|
|
262
|
+
|
|
263
|
+
return { applications, isFinishing, tokens: oldTokens }
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
changes.push(
|
|
267
|
+
...accessPolicyChange(
|
|
268
|
+
desired.people.map((person) => person.email),
|
|
269
|
+
yield* cloudflare.accessPolicyEmails().pipe(withAccessMessage)
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
// An application whose session cookie is SameSite=None or has no value
|
|
274
|
+
// gets Lax. Strict is stricter and stays. When the answer has no such
|
|
275
|
+
// field, nothing is planned: an update could not be seen to work, and
|
|
276
|
+
// every plan would show it again.
|
|
277
|
+
const settings = yield* cloudflare
|
|
278
|
+
.accessApplicationSettings(config.app.hostname)
|
|
279
|
+
.pipe(withAccessMessage)
|
|
280
|
+
|
|
281
|
+
if (Option.isSome(settings)) {
|
|
282
|
+
const cookie = settings.value.sameSiteCookie
|
|
283
|
+
|
|
284
|
+
if (
|
|
285
|
+
Option.isSome(cookie) &&
|
|
286
|
+
(cookie.value === null ||
|
|
287
|
+
cookie.value === '' ||
|
|
288
|
+
cookie.value.toLowerCase() === 'none')
|
|
289
|
+
) {
|
|
290
|
+
changes.push({
|
|
291
|
+
_tag: 'UpdateAccessApplication',
|
|
292
|
+
applicationId: settings.value.id,
|
|
293
|
+
sameSiteCookie: cookie.value
|
|
294
|
+
})
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// The public unsubscribe page has its own Access application while any
|
|
299
|
+
// app has series, and after that for as long as mail already sent links
|
|
300
|
+
// to it. It is looked up only when series are or were in use.
|
|
301
|
+
const wantsUnsubscribePage = desired.apps.some((app) => app.series !== null)
|
|
302
|
+
const neededUntil = Option.isSome(state)
|
|
303
|
+
? (state.value.unsubscribePageNeededUntil ?? null)
|
|
304
|
+
: null
|
|
305
|
+
let keepUnsubscribePageUntil: string | null = null
|
|
306
|
+
|
|
307
|
+
if (
|
|
308
|
+
wantsUnsubscribePage ||
|
|
309
|
+
current.apps.some((app) => app.series !== null) ||
|
|
310
|
+
(Option.isSome(state) && state.value.hasEnrollments === true)
|
|
311
|
+
) {
|
|
312
|
+
const pages = yield* cloudflare.unsubscribeApplications().pipe(withAccessMessage)
|
|
313
|
+
const page = Option.fromNullishOr(
|
|
314
|
+
pages.find((candidate) => candidate.domain === unsubscribeDomain(config.app.hostname))
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
// Pages of an earlier app.hostname: the app no longer answers there.
|
|
318
|
+
for (const old of pages) {
|
|
319
|
+
if (old.domain !== unsubscribeDomain(config.app.hostname)) {
|
|
320
|
+
changes.push({
|
|
321
|
+
_tag: 'CloseUnsubscribePage',
|
|
322
|
+
applicationId: old.id,
|
|
323
|
+
hostname: old.domain.slice(0, -'/u/*'.length)
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// The bypass policy that opens the page to everyone, when it has one.
|
|
329
|
+
const bypassOf = (applicationId: string) =>
|
|
330
|
+
cloudflare.accessPolicies(applicationId).pipe(
|
|
331
|
+
withAccessMessage,
|
|
332
|
+
Effect.map((policies) =>
|
|
333
|
+
policies.find(
|
|
334
|
+
(policy) => policy.decision === 'bypass' && policy.name === unsubscribePolicyName
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
// An open page is checked again on every deploy: the bypass opens
|
|
340
|
+
// whatever the application covers, so when that is more than
|
|
341
|
+
// <hostname>/u/* the bypass goes.
|
|
342
|
+
const checkOpenPage = (applicationId: string, policyId: string) =>
|
|
343
|
+
Effect.gen(function* () {
|
|
344
|
+
const coverage = yield* cloudflare
|
|
345
|
+
.accessApplicationCoverage(applicationId)
|
|
346
|
+
.pipe(withAccessMessage)
|
|
347
|
+
|
|
348
|
+
if (
|
|
349
|
+
Option.isSome(coverage) &&
|
|
350
|
+
!coversExactly(coverage.value, unsubscribeDomain(config.app.hostname))
|
|
351
|
+
) {
|
|
352
|
+
changes.push({
|
|
353
|
+
_tag: 'RemoveUnsubscribeBypass',
|
|
354
|
+
applicationId,
|
|
355
|
+
coverage: describeCoverage(coverage.value),
|
|
356
|
+
hostname: config.app.hostname,
|
|
357
|
+
policyId
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
if (wantsUnsubscribePage) {
|
|
363
|
+
const bypass = Option.isSome(page) ? yield* bypassOf(page.value.id) : undefined
|
|
364
|
+
|
|
365
|
+
if (Option.isSome(page) && bypass !== undefined) {
|
|
366
|
+
yield* checkOpenPage(page.value.id, bypass.id)
|
|
367
|
+
} else {
|
|
368
|
+
changes.push({
|
|
369
|
+
_tag: 'OpenUnsubscribePage',
|
|
370
|
+
applicationId: Option.isSome(page) ? page.value.id : null,
|
|
371
|
+
hostname: config.app.hostname
|
|
372
|
+
})
|
|
373
|
+
}
|
|
374
|
+
} else if (Option.isSome(page) && neededUntil !== null) {
|
|
375
|
+
keepUnsubscribePageUntil = neededUntil
|
|
376
|
+
|
|
377
|
+
const bypass = yield* bypassOf(page.value.id)
|
|
378
|
+
|
|
379
|
+
if (bypass !== undefined) {
|
|
380
|
+
yield* checkOpenPage(page.value.id, bypass.id)
|
|
381
|
+
}
|
|
382
|
+
} else if (Option.isSome(page)) {
|
|
383
|
+
changes.push({
|
|
384
|
+
_tag: 'CloseUnsubscribePage',
|
|
385
|
+
applicationId: page.value.id,
|
|
386
|
+
hostname: config.app.hostname
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// App tokens no app uses, and apps whose tokens are all named for
|
|
392
|
+
// another hostname. Only an app that answers knows its apps.
|
|
393
|
+
const accountTokens = Option.isSome(state) ? yield* cloudflare.serviceTokens() : []
|
|
394
|
+
const unusedTokens = Option.isSome(state)
|
|
395
|
+
? unusedAppTokens(accountTokens, config.app.hostname, current.apps)
|
|
396
|
+
: []
|
|
397
|
+
const desiredAppNames = new Set(desired.apps.map((app) => app.name))
|
|
398
|
+
const movedHostname = Option.isSome(state)
|
|
399
|
+
? appsMovedHostname(accountTokens, config.app.hostname, current.apps).filter((name) =>
|
|
400
|
+
desiredAppNames.has(name)
|
|
401
|
+
)
|
|
402
|
+
: []
|
|
403
|
+
|
|
404
|
+
const deploysApp =
|
|
405
|
+
Option.isNone(version) || version.value !== options.appVersion
|
|
406
|
+
// The version carries a hash of the authentication host, so a change
|
|
407
|
+
// shows without asking the app for its variables.
|
|
408
|
+
const authenticationHostChanged =
|
|
409
|
+
authenticationPartOf(Option.getOrElse(version, () => '')) !==
|
|
410
|
+
authenticationPartOf(options.appVersion)
|
|
411
|
+
|
|
412
|
+
// What deploying the app would create, reuse or replace.
|
|
413
|
+
const resources: AppResource[] = []
|
|
414
|
+
let movesFrom: DeployPlan['movesFrom'] = undefined
|
|
415
|
+
|
|
416
|
+
if (deploysApp) {
|
|
417
|
+
const database = yield* cloudflare.findDatabase(resourceName)
|
|
418
|
+
const bucket = yield* cloudflare.findBucket(resourceName)
|
|
419
|
+
const application = yield* cloudflare.findAccessApplication(
|
|
420
|
+
config.app.hostname
|
|
421
|
+
)
|
|
422
|
+
const worker = yield* cloudflare.workerExists(workerName)
|
|
423
|
+
|
|
424
|
+
resources.push(
|
|
425
|
+
{
|
|
426
|
+
_tag: 'Database',
|
|
427
|
+
name: resourceName,
|
|
428
|
+
state: Option.isSome(database) ? 'use' : 'create'
|
|
429
|
+
},
|
|
430
|
+
{ _tag: 'Bucket', name: resourceName, state: bucket ? 'use' : 'create' },
|
|
431
|
+
{
|
|
432
|
+
_tag: 'AccessApplication',
|
|
433
|
+
name: config.app.hostname,
|
|
434
|
+
state: Option.isSome(application) ? 'use' : 'create'
|
|
435
|
+
}
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
// The rule: a Worker with our name that the app does not answer for,
|
|
439
|
+
// and that has no Access application on our hostname, belongs to
|
|
440
|
+
// someone else. (A first deploy that stopped half way has the Access
|
|
441
|
+
// application, so it passes.) Two known misjudgements:
|
|
442
|
+
// - our own app, after app.hostname changed: no Access application on
|
|
443
|
+
// the new hostname yet. The tokens tell this apart, see below.
|
|
444
|
+
// - a foreign Worker that has an Access application on our hostname is
|
|
445
|
+
// taken for ours.
|
|
446
|
+
if (worker && Option.isNone(version) && Option.isNone(application)) {
|
|
447
|
+
if (!options.takeOver) {
|
|
448
|
+
const tokens = yield* cloudflare.serviceTokens()
|
|
449
|
+
const other = tokens
|
|
450
|
+
.map((token) => hostnameOfDeployToken(token.name))
|
|
451
|
+
.map((found) => (found === undefined ? undefined : printable(found)))
|
|
452
|
+
.find(
|
|
453
|
+
(found) => found !== undefined && found !== config.app.hostname
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
return yield* new DeployBlocked({
|
|
457
|
+
message:
|
|
458
|
+
other === undefined
|
|
459
|
+
? foreignWorkerMessage
|
|
460
|
+
: `A ${productName} app is already deployed at ${other}. Changing app.hostname moves the app; run deploy with --take-over to replace the Worker and set up ${config.app.hostname}.`
|
|
461
|
+
})
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
resources.push({ _tag: 'Worker', name: workerName, state: 'replace' })
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Our Worker, and the app does not answer at this hostname: when deploy
|
|
468
|
+
// credentials are named for another hostname, the app is moving from
|
|
469
|
+
// there.
|
|
470
|
+
if (worker && Option.isNone(version)) {
|
|
471
|
+
movesFrom = yield* leftAtOldHostnames(
|
|
472
|
+
config.app.hostname,
|
|
473
|
+
yield* cloudflare.serviceTokens(),
|
|
474
|
+
false
|
|
475
|
+
)
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// The app answers at this hostname: what Courier Crow made for another
|
|
480
|
+
// hostname is left from a move that stopped halfway, and goes now.
|
|
481
|
+
if (Option.isSome(version) && Option.isSome(state)) {
|
|
482
|
+
movesFrom = yield* leftAtOldHostnames(config.app.hostname, accountTokens, true)
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const desiredApps = new Set(desired.apps.map((app) => app.name))
|
|
486
|
+
const purging = current.mailboxes
|
|
487
|
+
.filter((mailbox) => mailbox.state === 'purging')
|
|
488
|
+
.map((mailbox) => mailbox.address)
|
|
489
|
+
const mail = planChanges(desired, current)
|
|
490
|
+
const currentAppNames = new Set(current.apps.map((app) => app.name))
|
|
491
|
+
const moved = mail.flatMap((change) =>
|
|
492
|
+
change._tag === 'AddApp' && currentAppNames.has(change.name)
|
|
493
|
+
? [change.name]
|
|
494
|
+
: []
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
return {
|
|
498
|
+
...(movedHostname.length === 0 ? {} : { appsMovedHostname: movedHostname }),
|
|
499
|
+
...(keepUnsubscribePageUntil === null ? {} : { keepUnsubscribePageUntil }),
|
|
500
|
+
...(moved.length === 0 ? {} : { movedApps: moved }),
|
|
501
|
+
...(movesFrom === undefined ? {} : { movesFrom }),
|
|
502
|
+
...(purging.length === 0 ? {} : { purgingMailboxes: purging }),
|
|
503
|
+
...(unusedTokens.length === 0 ? {} : { unusedAppTokens: unusedTokens }),
|
|
504
|
+
...(authenticationHostChanged
|
|
505
|
+
? { authenticationHost: { to: config.app.authenticationHost ?? null } }
|
|
506
|
+
: {}),
|
|
507
|
+
app: deploysApp ? 'deploy' : 'unchanged',
|
|
508
|
+
appsWithoutCredentials: current.apps
|
|
509
|
+
.filter((app) => app.clientId === null && desiredApps.has(app.name))
|
|
510
|
+
.map((app) => app.name),
|
|
511
|
+
cloudflare: changes,
|
|
512
|
+
currentPeople: current.people,
|
|
513
|
+
mail,
|
|
514
|
+
resources
|
|
515
|
+
}
|
|
516
|
+
})
|
|
517
|
+
}
|
package/src/printable.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Text from Cloudflare or from our API goes into messages and plan lines.
|
|
2
|
+
// Someone who can edit the zone could put terminal escape sequences in it, so
|
|
3
|
+
// every control character (ESC included), the line and paragraph separators
|
|
4
|
+
// and the bidirectional controls (overrides, isolates and marks) become a
|
|
5
|
+
// visible "?".
|
|
6
|
+
export function printable(text: string): string {
|
|
7
|
+
return text.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, '?')
|
|
8
|
+
}
|
package/src/product.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The product's names. Everything the CLI creates in a Cloudflare account,
|
|
2
|
+
// and every rule that finds "ours" again, is named from these, so the names
|
|
3
|
+
// live in one place.
|
|
4
|
+
|
|
5
|
+
export const productName = 'Courier Crow'
|
|
6
|
+
|
|
7
|
+
// The Worker, the D1 database and the R2 bucket.
|
|
8
|
+
export const resourceName = 'courier-crow'
|
|
9
|
+
|
|
10
|
+
// The folder next to mail.config.ts that holds the deploy credentials and the
|
|
11
|
+
// Worker config deploy fills in.
|
|
12
|
+
export const localFolder = '.courier-crow'
|
|
13
|
+
|
|
14
|
+
export const credentialsPath = `${localFolder}/credentials.json`
|
|
15
|
+
|
|
16
|
+
// Access policies and the catch-all rule.
|
|
17
|
+
export const appsPolicyName = `${productName} apps`
|
|
18
|
+
export const catchAllRuleName = `${productName} catch-all`
|
|
19
|
+
export const deployPolicyName = `${productName} deploy`
|
|
20
|
+
export const peoplePolicyName = `${productName} people`
|
|
21
|
+
export const unsubscribePolicyName = `${productName} unsubscribe`
|
|
22
|
+
|
|
23
|
+
// Access applications: the app on its hostname, and the public unsubscribe
|
|
24
|
+
// page on <hostname>/u/*.
|
|
25
|
+
export const applicationName = productName
|
|
26
|
+
export const unsubscribeApplicationName = `${productName} unsubscribe page`
|
|
27
|
+
|
|
28
|
+
// Service tokens: "courier-crow deploy <hostname>" and
|
|
29
|
+
// "courier-crow app <app> <hostname>".
|
|
30
|
+
const deployTokenPrefix = `${resourceName} deploy `
|
|
31
|
+
const appTokenPrefix = `${resourceName} app `
|
|
32
|
+
|
|
33
|
+
export function deployTokenName(hostname: string): string {
|
|
34
|
+
return `${deployTokenPrefix}${hostname}`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function appTokenName(app: string, hostname: string): string {
|
|
38
|
+
return `${appTokenPrefix}${app} ${hostname}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The hostname a deploy token is named for, or undefined for any other token.
|
|
42
|
+
export function hostnameOfDeployToken(name: string): string | undefined {
|
|
43
|
+
return name.startsWith(deployTokenPrefix) && name.length > deployTokenPrefix.length
|
|
44
|
+
? name.slice(deployTokenPrefix.length)
|
|
45
|
+
: undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The app and hostname an app token is named for, or undefined for any other
|
|
49
|
+
// token. App names have no spaces, so the first space ends the app.
|
|
50
|
+
export function appOfAppToken(
|
|
51
|
+
name: string
|
|
52
|
+
): { app: string; hostname: string } | undefined {
|
|
53
|
+
if (!name.startsWith(appTokenPrefix)) {
|
|
54
|
+
return undefined
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const rest = name.slice(appTokenPrefix.length)
|
|
58
|
+
const match = /^([a-z0-9-]+) (.+)$/.exec(rest)
|
|
59
|
+
|
|
60
|
+
return match?.[1] === undefined || match[2] === undefined
|
|
61
|
+
? undefined
|
|
62
|
+
: { app: match[1], hostname: match[2] }
|
|
63
|
+
}
|
package/src/purge.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { EmailAddress } from '@couriercrow/core'
|
|
2
|
+
import { Effect, Schema } from 'effect'
|
|
3
|
+
|
|
4
|
+
import { MailboxApi, MailboxApiError } from './mailbox-api'
|
|
5
|
+
import { Terminal } from './terminal'
|
|
6
|
+
|
|
7
|
+
export class PurgeRefused extends Schema.TaggedError<PurgeRefused>()(
|
|
8
|
+
'PurgeRefused',
|
|
9
|
+
{ message: Schema.String }
|
|
10
|
+
) {}
|
|
11
|
+
|
|
12
|
+
export const purgeNeedsTerminalMessage =
|
|
13
|
+
'Purging deletes mail for good and needs to be confirmed by hand. Run it in a terminal.'
|
|
14
|
+
|
|
15
|
+
export function purgeWarning(address: EmailAddress): string {
|
|
16
|
+
return `This deletes all mail in ${address} for good. It cannot be undone.`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The API deletes up to 10,000 messages per call. This many calls is far more
|
|
20
|
+
// than any mailbox needs; past it something is wrong on the other side.
|
|
21
|
+
const maxRounds = 1000
|
|
22
|
+
|
|
23
|
+
// Deletes an archived mailbox and all its mail. The caller has asked the
|
|
24
|
+
// person to type the address, and passes what was typed. The API deletes the
|
|
25
|
+
// mail in parts, so it is called until it says the purge is finished;
|
|
26
|
+
// onProgress hears the count after each part that was not the last.
|
|
27
|
+
export function purge(
|
|
28
|
+
address: EmailAddress,
|
|
29
|
+
options: {
|
|
30
|
+
confirmedAddress: string
|
|
31
|
+
onProgress?: (deletedMessages: number) => Effect.Effect<void>
|
|
32
|
+
}
|
|
33
|
+
): Effect.Effect<
|
|
34
|
+
{ deletedMessages: number },
|
|
35
|
+
MailboxApiError | PurgeRefused,
|
|
36
|
+
MailboxApi
|
|
37
|
+
> {
|
|
38
|
+
return Effect.gen(function* () {
|
|
39
|
+
if (options.confirmedAddress !== address) {
|
|
40
|
+
return yield* new PurgeRefused({
|
|
41
|
+
message: `Type the full address ${address} to confirm. Nothing was deleted.`
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const api = yield* MailboxApi
|
|
46
|
+
let deletedMessages = 0
|
|
47
|
+
|
|
48
|
+
for (let round = 0; round < maxRounds; round += 1) {
|
|
49
|
+
const result = yield* api.purgeMailbox(address)
|
|
50
|
+
|
|
51
|
+
deletedMessages += result.deletedMessages
|
|
52
|
+
|
|
53
|
+
if (result.isFinished) {
|
|
54
|
+
return { deletedMessages }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
yield* options.onProgress?.(deletedMessages) ?? Effect.void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return yield* new MailboxApiError({
|
|
61
|
+
message: `The purge of ${address} did not finish after ${maxRounds} rounds. Run purge again to go on.`
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The terminal side of purge: warns, asks for the address, then purges.
|
|
67
|
+
export function purgeWithConfirmation(
|
|
68
|
+
address: EmailAddress
|
|
69
|
+
): Effect.Effect<
|
|
70
|
+
{ deletedMessages: number },
|
|
71
|
+
MailboxApiError | PurgeRefused,
|
|
72
|
+
MailboxApi | Terminal
|
|
73
|
+
> {
|
|
74
|
+
return Effect.gen(function* () {
|
|
75
|
+
const terminal = yield* Terminal
|
|
76
|
+
|
|
77
|
+
if (!terminal.stdinIsTerminal || !terminal.stdoutIsTerminal) {
|
|
78
|
+
return yield* new PurgeRefused({ message: purgeNeedsTerminalMessage })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
yield* terminal.print(purgeWarning(address))
|
|
82
|
+
|
|
83
|
+
const typed = yield* terminal.ask(`Type ${address} to confirm:`)
|
|
84
|
+
|
|
85
|
+
return yield* purge(address, {
|
|
86
|
+
confirmedAddress: typed.trim(),
|
|
87
|
+
onProgress: (deletedMessages) =>
|
|
88
|
+
terminal.print(
|
|
89
|
+
`Deleted ${deletedMessages} messages so far. Still deleting…`
|
|
90
|
+
)
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
}
|