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.
- 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
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
chmod,
|
|
4
|
+
mkdir,
|
|
5
|
+
readdir,
|
|
6
|
+
rename,
|
|
7
|
+
rm,
|
|
8
|
+
stat,
|
|
9
|
+
writeFile
|
|
10
|
+
} from 'node:fs/promises'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
import { desiredState } from '@couriercrow/core'
|
|
14
|
+
import type { EmailAddress, MailConfig } from '@couriercrow/core'
|
|
15
|
+
import { Effect, Option, Schema } from 'effect'
|
|
16
|
+
|
|
17
|
+
import { readCredentials } from '../environment'
|
|
18
|
+
import { ciCredentialsMessage, MailboxApiError } from '../mailbox-api'
|
|
19
|
+
import type { AccessCredentials } from '../mailbox-api'
|
|
20
|
+
import {
|
|
21
|
+
credentialsPath,
|
|
22
|
+
deployPolicyName,
|
|
23
|
+
deployTokenName,
|
|
24
|
+
localFolder,
|
|
25
|
+
peoplePolicyName,
|
|
26
|
+
resourceName
|
|
27
|
+
} from '../product'
|
|
28
|
+
import { Cloudflare, CloudflareError } from './cloudflare-client'
|
|
29
|
+
import type {
|
|
30
|
+
AccessPolicy,
|
|
31
|
+
AccessPolicyInput,
|
|
32
|
+
ServiceTokenSummary
|
|
33
|
+
} from './cloudflare-client'
|
|
34
|
+
|
|
35
|
+
// A local step failed, such as writing a file.
|
|
36
|
+
export class DeployFailed extends Schema.TaggedError<DeployFailed>()(
|
|
37
|
+
'DeployFailed',
|
|
38
|
+
{ message: Schema.String }
|
|
39
|
+
) {}
|
|
40
|
+
|
|
41
|
+
// The deploy token is named for the app, so a token that no policy uses can
|
|
42
|
+
// be told from the tokens of anything else.
|
|
43
|
+
export { deployPolicyName, deployTokenName, peoplePolicyName, resourceName }
|
|
44
|
+
|
|
45
|
+
export const credentialsMissingMessage = `Created new deploy credentials because ${credentialsPath} was missing.`
|
|
46
|
+
|
|
47
|
+
export const credentialsMismatchMessage =
|
|
48
|
+
'Created new deploy credentials because the saved ones do not match the Access policy.'
|
|
49
|
+
|
|
50
|
+
// What the Worker needs to know about the account before it is deployed.
|
|
51
|
+
export interface AppSetup {
|
|
52
|
+
accessAudience: string
|
|
53
|
+
accessTeamDomain: string
|
|
54
|
+
// The people policy is already in place, so the later change can be skipped.
|
|
55
|
+
accessPolicyApplied: boolean
|
|
56
|
+
// Set when the Access application existed but its deploy credentials had to
|
|
57
|
+
// be created again: the file was missing, or it did not match the policy.
|
|
58
|
+
credentialsReplaced: 'missing' | 'mismatch' | undefined
|
|
59
|
+
databaseId: string
|
|
60
|
+
deployClientId: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function failedToWrite(path: string, reason: unknown): DeployFailed {
|
|
64
|
+
const detail = reason instanceof Error ? reason.message : String(reason)
|
|
65
|
+
|
|
66
|
+
return new DeployFailed({
|
|
67
|
+
message: `Could not write ${path}: ${detail}. Check the folder permissions and run deploy again.`
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The folder is for the owner only. The file is created with mode 600 under a
|
|
72
|
+
// temporary name and then renamed, so a failed write leaves the old file and
|
|
73
|
+
// no secret is ever readable by others, not even for a moment.
|
|
74
|
+
export function writeCredentials(
|
|
75
|
+
directory: string,
|
|
76
|
+
credentials: AccessCredentials
|
|
77
|
+
): Effect.Effect<void, DeployFailed> {
|
|
78
|
+
const folder = join(directory, localFolder)
|
|
79
|
+
const path = join(folder, 'credentials.json')
|
|
80
|
+
const temporary = join(folder, `credentials.json.${randomUUID()}.tmp`)
|
|
81
|
+
|
|
82
|
+
return Effect.tryPromise({
|
|
83
|
+
try: async () => {
|
|
84
|
+
await mkdir(folder, { mode: 0o700, recursive: true })
|
|
85
|
+
|
|
86
|
+
// A folder that exists may have a looser mode. A stricter one stays.
|
|
87
|
+
if (((await stat(folder)).mode & 0o077) !== 0) {
|
|
88
|
+
await chmod(folder, 0o700)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Temp files of runs that crashed hold secrets that nobody uses.
|
|
92
|
+
for (const name of await readdir(folder)) {
|
|
93
|
+
if (/^credentials\.json\..+\.tmp$/.test(name)) {
|
|
94
|
+
await rm(join(folder, name), { force: true })
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
await writeFile(
|
|
100
|
+
temporary,
|
|
101
|
+
`${JSON.stringify(credentials, null, 2)}\n`,
|
|
102
|
+
{ flag: 'wx', mode: 0o600 }
|
|
103
|
+
)
|
|
104
|
+
await rename(temporary, path)
|
|
105
|
+
} catch (error) {
|
|
106
|
+
await rm(temporary, { force: true })
|
|
107
|
+
|
|
108
|
+
throw error
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
catch: (reason) => failedToWrite(credentialsPath, reason)
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Adds .courier-crow/ to the .gitignore next to the config file. The file is
|
|
116
|
+
// created when it is missing. The line is added only once.
|
|
117
|
+
export function ensureIgnored(
|
|
118
|
+
directory: string
|
|
119
|
+
): Effect.Effect<void, DeployFailed> {
|
|
120
|
+
const path = join(directory, '.gitignore')
|
|
121
|
+
|
|
122
|
+
return Effect.tryPromise({
|
|
123
|
+
try: async () => {
|
|
124
|
+
const file = Bun.file(path)
|
|
125
|
+
const content = (await file.exists()) ? await file.text() : ''
|
|
126
|
+
const present = content
|
|
127
|
+
.split('\n')
|
|
128
|
+
.some((line) => [localFolder, `${localFolder}/`].includes(line.trim()))
|
|
129
|
+
|
|
130
|
+
if (present) {
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const separator = content === '' || content.endsWith('\n') ? '' : '\n'
|
|
135
|
+
|
|
136
|
+
await Bun.write(path, `${content}${separator}${localFolder}/\n`)
|
|
137
|
+
},
|
|
138
|
+
catch: (reason) => failedToWrite('.gitignore', reason)
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Creates the policy or updates the one with the same name.
|
|
143
|
+
export function savePolicy(
|
|
144
|
+
application: string,
|
|
145
|
+
existing: readonly AccessPolicy[],
|
|
146
|
+
policy: AccessPolicyInput
|
|
147
|
+
) {
|
|
148
|
+
return Effect.gen(function* () {
|
|
149
|
+
const cloudflare = yield* Cloudflare
|
|
150
|
+
const found = existing.find(
|
|
151
|
+
(candidate) =>
|
|
152
|
+
candidate.name === policy.name && candidate.decision === policy.decision
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
if (found === undefined) {
|
|
156
|
+
return yield* cloudflare.createAccessPolicy(application, policy)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return yield* cloudflare.updateAccessPolicy(application, found.id, policy)
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function peoplePolicy(emails: readonly EmailAddress[]): AccessPolicyInput {
|
|
164
|
+
return {
|
|
165
|
+
decision: 'allow',
|
|
166
|
+
include: emails.map((email) => ({ _tag: 'Email' as const, email })),
|
|
167
|
+
name: peoplePolicyName
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Makes the Access policy allow exactly these people.
|
|
172
|
+
export function setPeoplePolicy(
|
|
173
|
+
application: string,
|
|
174
|
+
emails: readonly EmailAddress[]
|
|
175
|
+
) {
|
|
176
|
+
return Effect.gen(function* () {
|
|
177
|
+
const cloudflare = yield* Cloudflare
|
|
178
|
+
const existing = yield* cloudflare.accessPolicies(application)
|
|
179
|
+
|
|
180
|
+
yield* savePolicy(application, existing, peoplePolicy(emails))
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Whether the saved credentials are the token that the deploy policy lets
|
|
185
|
+
// through. Otherwise the Worker would be deployed with credentials that
|
|
186
|
+
// nothing can use.
|
|
187
|
+
function credentialsMatch(
|
|
188
|
+
stored: AccessCredentials,
|
|
189
|
+
tokens: readonly ServiceTokenSummary[],
|
|
190
|
+
policies: readonly AccessPolicy[]
|
|
191
|
+
): boolean {
|
|
192
|
+
const token = tokens.find((candidate) => candidate.clientId === stored.clientId)
|
|
193
|
+
const policy = policies.find(
|
|
194
|
+
(candidate) =>
|
|
195
|
+
candidate.name === deployPolicyName &&
|
|
196
|
+
candidate.decision === 'non_identity'
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
return (
|
|
200
|
+
token !== undefined &&
|
|
201
|
+
policy !== undefined &&
|
|
202
|
+
policy.serviceTokenIds.includes(token.id)
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Everything that has to exist before the Worker is deployed, so the app is
|
|
207
|
+
// never reachable without Access: the database, the bucket, the Access
|
|
208
|
+
// application with its policies and the deploy credentials. Every step looks
|
|
209
|
+
// for what exists and reuses it.
|
|
210
|
+
export { ciCredentialsMessage }
|
|
211
|
+
|
|
212
|
+
export interface PrepareOptions {
|
|
213
|
+
// False in a run without a terminal: new deploy credentials would be
|
|
214
|
+
// written to a folder nobody keeps (CI), so the deploy stops instead.
|
|
215
|
+
canCreateCredentials: boolean
|
|
216
|
+
// COURIER_CROW_DEPLOY_CLIENT_ID and _SECRET win over the file.
|
|
217
|
+
environment: Readonly<Record<string, string | undefined>>
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function prepareApp(
|
|
221
|
+
config: MailConfig,
|
|
222
|
+
directory: string,
|
|
223
|
+
options: PrepareOptions = { canCreateCredentials: true, environment: {} }
|
|
224
|
+
): Effect.Effect<
|
|
225
|
+
AppSetup,
|
|
226
|
+
CloudflareError | DeployFailed | MailboxApiError,
|
|
227
|
+
Cloudflare
|
|
228
|
+
> {
|
|
229
|
+
return Effect.gen(function* () {
|
|
230
|
+
const cloudflare = yield* Cloudflare
|
|
231
|
+
const hostname = config.app.hostname
|
|
232
|
+
const emails = desiredState(config).people.map((person) => person.email)
|
|
233
|
+
|
|
234
|
+
// Whether the saved credentials can be used is known before anything is
|
|
235
|
+
// created, so a run that may not create them changes nothing.
|
|
236
|
+
const stored = yield* readCredentials(directory, options.environment)
|
|
237
|
+
const found = yield* cloudflare.findAccessApplication(hostname)
|
|
238
|
+
const foundPolicies = Option.isSome(found)
|
|
239
|
+
? yield* cloudflare.accessPolicies(found.value.id)
|
|
240
|
+
: []
|
|
241
|
+
const tokens = yield* cloudflare.serviceTokens()
|
|
242
|
+
|
|
243
|
+
// The secret of a service token is shown once, so a token can only be
|
|
244
|
+
// reused when the file with its secret is there and the policy knows it.
|
|
245
|
+
const reuse =
|
|
246
|
+
Option.isSome(found) &&
|
|
247
|
+
Option.isSome(stored) &&
|
|
248
|
+
credentialsMatch(stored.value, tokens, foundPolicies)
|
|
249
|
+
|
|
250
|
+
if (!reuse && !options.canCreateCredentials) {
|
|
251
|
+
return yield* new DeployFailed({ message: ciCredentialsMessage })
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const database = yield* cloudflare.findDatabase(resourceName)
|
|
255
|
+
const databaseId = Option.isSome(database)
|
|
256
|
+
? database.value
|
|
257
|
+
: yield* cloudflare.createDatabase(resourceName)
|
|
258
|
+
|
|
259
|
+
if (!(yield* cloudflare.findBucket(resourceName))) {
|
|
260
|
+
yield* cloudflare.createBucket(resourceName)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const accessTeamDomain = yield* cloudflare.accessTeamDomain()
|
|
264
|
+
const application = Option.isSome(found)
|
|
265
|
+
? found.value
|
|
266
|
+
: yield* cloudflare.createAccessApplication(hostname)
|
|
267
|
+
const policies = Option.isSome(found)
|
|
268
|
+
? foundPolicies
|
|
269
|
+
: yield* cloudflare.accessPolicies(application.id)
|
|
270
|
+
|
|
271
|
+
let credentials: AccessCredentials
|
|
272
|
+
|
|
273
|
+
if (reuse && Option.isSome(stored)) {
|
|
274
|
+
credentials = stored.value
|
|
275
|
+
} else {
|
|
276
|
+
// Tokens of earlier runs that failed before their policy was made.
|
|
277
|
+
for (const orphan of tokens.filter(
|
|
278
|
+
(token) =>
|
|
279
|
+
token.name === deployTokenName(hostname) &&
|
|
280
|
+
!policies.some((policy) => policy.serviceTokenIds.includes(token.id))
|
|
281
|
+
)) {
|
|
282
|
+
yield* cloudflare.deleteServiceToken(orphan.id)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const token = yield* cloudflare.createServiceToken(
|
|
286
|
+
deployTokenName(hostname)
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
// The token needs its policy before the credentials are saved. If
|
|
290
|
+
// anything fails in between, the next run creates a new token.
|
|
291
|
+
yield* savePolicy(application.id, policies, {
|
|
292
|
+
decision: 'non_identity',
|
|
293
|
+
include: [{ _tag: 'ServiceToken', tokenId: token.id }],
|
|
294
|
+
name: deployPolicyName
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
credentials = {
|
|
298
|
+
clientId: token.clientId,
|
|
299
|
+
clientSecret: token.clientSecret
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
yield* writeCredentials(directory, credentials)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
yield* savePolicy(application.id, policies, peoplePolicy(emails))
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
accessAudience: application.audience,
|
|
309
|
+
accessPolicyApplied: true,
|
|
310
|
+
accessTeamDomain,
|
|
311
|
+
credentialsReplaced: !Option.isSome(found)
|
|
312
|
+
? undefined
|
|
313
|
+
: Option.isNone(stored)
|
|
314
|
+
? 'missing'
|
|
315
|
+
: reuse
|
|
316
|
+
? undefined
|
|
317
|
+
: 'mismatch',
|
|
318
|
+
databaseId,
|
|
319
|
+
deployClientId: credentials.clientId
|
|
320
|
+
}
|
|
321
|
+
})
|
|
322
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Effect, Option } from 'effect'
|
|
2
|
+
|
|
3
|
+
import { DeployFailed } from './cloudflare/first-run'
|
|
4
|
+
import { readCredentials } from './environment'
|
|
5
|
+
import { printable } from './printable'
|
|
6
|
+
import { credentialsPath } from './product'
|
|
7
|
+
import { Terminal } from './terminal'
|
|
8
|
+
|
|
9
|
+
// crow credentials show: the deploy credentials from the local file, printed
|
|
10
|
+
// once, so they can be copied into the secrets of a CI. Only in a terminal,
|
|
11
|
+
// and only after the person types "show".
|
|
12
|
+
|
|
13
|
+
export const credentialsShowNeedsTerminalMessage =
|
|
14
|
+
'bunx couriercrow credentials show prints secrets, so it runs only in a terminal.'
|
|
15
|
+
|
|
16
|
+
export function showCredentials(directory: string) {
|
|
17
|
+
return Effect.gen(function* () {
|
|
18
|
+
const terminal = yield* Terminal
|
|
19
|
+
|
|
20
|
+
if (!terminal.stdinIsTerminal || !terminal.stdoutIsTerminal) {
|
|
21
|
+
return yield* new DeployFailed({ message: credentialsShowNeedsTerminalMessage })
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// The file only: the two variables are what this prints.
|
|
25
|
+
const stored = yield* readCredentials(directory).pipe(
|
|
26
|
+
Effect.mapError((error) => new DeployFailed({ message: error.message }))
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if (Option.isNone(stored)) {
|
|
30
|
+
return yield* new DeployFailed({
|
|
31
|
+
message: `There are no deploy credentials in ${credentialsPath}. Run bunx couriercrow deploy from a terminal first.`
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const answer = yield* terminal.ask(
|
|
36
|
+
'These are the deploy credentials: anyone who has them can change who has access to your mail. Type show to print them:'
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
if (answer.trim().toLowerCase() !== 'show') {
|
|
40
|
+
yield* terminal.print('Nothing was printed.')
|
|
41
|
+
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
yield* terminal.print(`COURIER_CROW_DEPLOY_CLIENT_ID=${printable(stored.value.clientId)}`)
|
|
46
|
+
yield* terminal.print(`COURIER_CROW_DEPLOY_CLIENT_SECRET=${printable(stored.value.clientSecret)}`)
|
|
47
|
+
yield* terminal.print('Store them as secrets of your CI, under these names.')
|
|
48
|
+
})
|
|
49
|
+
}
|