@workbasehq/core 0.1.0 → 0.2.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/package.json +27 -2
- package/src/app.ts +5 -2
- package/src/config.ts +1 -1
- package/src/console-authorization.ts +85 -0
- package/src/console-contract.ts +74 -1
- package/src/console-input-schema.ts +135 -0
- package/src/console-model.ts +122 -0
- package/src/console-presentation.ts +136 -0
- package/src/console.ts +2 -2
- package/src/execution/types.ts +1 -1
- package/src/index.ts +1 -1
- package/src/infra/README.md +206 -0
- package/src/infra/bin.mjs +19 -0
- package/src/infra/cli-main.ts +8 -0
- package/src/infra/cli.ts +43 -0
- package/src/infra/d1-migrations.ts +30 -0
- package/src/infra/diagnostics.ts +52 -0
- package/src/infra/http-d1.ts +17 -0
- package/src/infra/index.ts +6 -0
- package/src/infra/instance-migrations.ts +54 -0
- package/src/infra/migration-files.ts +17 -0
- package/src/infra/package-tools.ts +9 -0
- package/src/infra/provision-config-main.mjs +29 -0
- package/src/infra/provision-config.ts +33 -0
- package/src/infra/provision-diagnostics.ts +45 -0
- package/src/infra/provision-plan.ts +143 -0
- package/src/infra/provision.ts +113 -0
- package/src/infra/schema.ts +21 -0
- package/src/infra/sst-runtime.ts +76 -0
- package/src/migrations/better-auth-schema.ts +1 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { dirname } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
// A bundled SST program has a different import.meta.url. Resolve the installed
|
|
5
|
+
// export first so config evaluation and migrations use the installed SDK bytes.
|
|
6
|
+
// Deployment providers must instead use SST's platform runtime (sst-runtime.ts).
|
|
7
|
+
export function installedInfraDirectory(): string {
|
|
8
|
+
return dirname(fileURLToPath(import.meta.resolve('@workbasehq/core/infra')))
|
|
9
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Executed only in a fresh Node process. Never import this entry into SST's bundle.
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
|
|
4
|
+
const finish = result => process.send(result, () => process.exit(0))
|
|
5
|
+
const [configPath, migrationsDirectory] = process.argv.slice(2)
|
|
6
|
+
async function main() {
|
|
7
|
+
let config
|
|
8
|
+
try {
|
|
9
|
+
const { tsImport } = await import('tsx/esm/api')
|
|
10
|
+
config = (await tsImport(pathToFileURL(configPath).href, import.meta.url)).default
|
|
11
|
+
} catch (error) {
|
|
12
|
+
return finish({ kind: 'load-error', message: error instanceof Error ? error.message : String(error) })
|
|
13
|
+
}
|
|
14
|
+
if (!config || typeof config.id !== 'string' || !Number.isInteger(config.revision) || config.revision < 1 || !config.entities) {
|
|
15
|
+
finish({ kind: 'invalid-config' })
|
|
16
|
+
} else {
|
|
17
|
+
try {
|
|
18
|
+
// Keep plugin functions, schemas and identity brands in this process. Only
|
|
19
|
+
// the resulting schema fingerprints cross the IPC boundary.
|
|
20
|
+
const { tsImport } = await import('tsx/esm/api')
|
|
21
|
+
const { expectedSchema } = await tsImport(new URL('./schema.ts', import.meta.url).href, import.meta.url)
|
|
22
|
+
const schema = await expectedSchema({ migrationsDirectory, revision: config.revision, config })
|
|
23
|
+
finish({ kind: 'schema', schema })
|
|
24
|
+
} catch {
|
|
25
|
+
finish({ kind: 'schema-error' })
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
await main()
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import type { SchemaRevision } from '../schema-compatibility'
|
|
4
|
+
import { installedInfraDirectory } from './package-tools'
|
|
5
|
+
import { ProvisionDiagnostic } from './provision-diagnostics'
|
|
6
|
+
|
|
7
|
+
type Result = { kind: 'schema'; schema: SchemaRevision }
|
|
8
|
+
| { kind: 'load-error'; message: string }
|
|
9
|
+
| { kind: 'invalid-config' | 'schema-error' }
|
|
10
|
+
|
|
11
|
+
/** SST registers process-wide ESM hooks. Evaluate trusted project code outside
|
|
12
|
+
* that process, without inheriting execArgv or NODE_OPTIONS loader registrations.
|
|
13
|
+
* stdout/stderr are discarded: config logs must not expose secrets or break IPC. */
|
|
14
|
+
export async function provisionConfigSchema(root: string, configPath: string, migrationsDirectory: string, secrets: string[]): Promise<SchemaRevision> {
|
|
15
|
+
const result = await new Promise<Result>((resolve, reject) => {
|
|
16
|
+
const child = spawn(process.execPath, [join(installedInfraDirectory(), 'provision-config-main.mjs'), configPath, migrationsDirectory], {
|
|
17
|
+
cwd: root, env: { ...process.env, NODE_OPTIONS: '' }, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
18
|
+
})
|
|
19
|
+
let result: Result | undefined
|
|
20
|
+
const timeout = setTimeout(() => { child.kill('SIGKILL') }, 30000)
|
|
21
|
+
child.on('message', message => { result = message as Result })
|
|
22
|
+
child.on('error', error => { clearTimeout(timeout); reject(error) })
|
|
23
|
+
child.on('close', code => {
|
|
24
|
+
clearTimeout(timeout)
|
|
25
|
+
if (code === 0 && result) resolve(result)
|
|
26
|
+
else reject(new Error(code === null ? 'Config evaluation timed out or was terminated' : `Config evaluation process exited with code ${code}`))
|
|
27
|
+
})
|
|
28
|
+
}).catch(error => { throw new ProvisionDiagnostic('provision_config_load_failed', { message: error instanceof Error ? error.message : String(error), secrets }) })
|
|
29
|
+
if (result.kind === 'schema') return result.schema
|
|
30
|
+
if (result.kind === 'invalid-config') throw new ProvisionDiagnostic('provision_invalid_config')
|
|
31
|
+
if (result.kind === 'load-error') throw new ProvisionDiagnostic('provision_config_load_failed', { message: result.message, secrets })
|
|
32
|
+
throw new ProvisionDiagnostic('provision_failed')
|
|
33
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { redactCliOutput } from './diagnostics'
|
|
2
|
+
|
|
3
|
+
const codes = [
|
|
4
|
+
'provision_invalid_stage', 'provision_invalid_prefix', 'provision_invalid_handler',
|
|
5
|
+
'provision_invalid_config_path', 'provision_invalid_migrations_dir', 'provision_invalid_assets_dir',
|
|
6
|
+
'provision_invalid_auth_secret', 'provision_invalid_auth_base_url', 'provision_invalid_domain',
|
|
7
|
+
'provision_invalid_email', 'provision_invalid_webhook', 'provision_invalid_account_id',
|
|
8
|
+
'provision_config_load_failed', 'provision_invalid_config', 'provision_inputs_unreadable',
|
|
9
|
+
'provision_requires_sst', 'provision_requires_command', 'provision_failed',
|
|
10
|
+
] as const
|
|
11
|
+
export type ProvisionDiagnosticCode = typeof codes[number]
|
|
12
|
+
|
|
13
|
+
const diagnostics = new WeakMap<object, { code: ProvisionDiagnosticCode; message: string }>()
|
|
14
|
+
|
|
15
|
+
/** Branded diagnostics; config loader messages redact deployment/environment secrets. */
|
|
16
|
+
export class ProvisionDiagnostic extends Error {
|
|
17
|
+
readonly code: ProvisionDiagnosticCode
|
|
18
|
+
constructor(code: ProvisionDiagnosticCode, detail?: { message: string; secrets: string[] }) {
|
|
19
|
+
const safeCode = codes.includes(code) ? code : 'provision_failed'
|
|
20
|
+
let message: string = safeCode
|
|
21
|
+
if (safeCode === 'provision_config_load_failed' && detail) {
|
|
22
|
+
const secrets = Object.fromEntries(detail.secrets.map((value, index) => [`SECRET_${index}`, value]))
|
|
23
|
+
const cause = redactCliOutput(detail.message, { ...process.env, ...secrets })
|
|
24
|
+
.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g, '$1[redacted]@')
|
|
25
|
+
.replace(/Bearer\s+[^\s'";,]+/gi, 'Bearer [redacted]')
|
|
26
|
+
.replace(/[\r\n\x00-\x1f\x7f]+/g, ' ').slice(0, 2000)
|
|
27
|
+
message += `: ${cause}`
|
|
28
|
+
}
|
|
29
|
+
super(message)
|
|
30
|
+
this.name = 'ProvisionDiagnostic'
|
|
31
|
+
this.code = safeCode
|
|
32
|
+
diagnostics.set(this, { code: safeCode, message })
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function provisionErrorMessage(error: unknown): string {
|
|
37
|
+
return typeof error === 'object' && error !== null ? diagnostics.get(error)?.message ?? 'provision_failed' : 'provision_failed'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function provisionFailure(error: unknown): ProvisionDiagnostic {
|
|
41
|
+
const saved = typeof error === 'object' && error !== null ? diagnostics.get(error) : undefined
|
|
42
|
+
const failure = new ProvisionDiagnostic(saved?.code ?? 'provision_failed')
|
|
43
|
+
if (saved) { failure.message = saved.message; diagnostics.set(failure, saved) }
|
|
44
|
+
return failure
|
|
45
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { Input } from '@pulumi/pulumi'
|
|
2
|
+
import { readFile, readdir, stat } from 'node:fs/promises'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import type { SchemaRevision } from '../schema-compatibility'
|
|
5
|
+
import { migrationHash, readMigrationFiles, sha256 } from './migration-files'
|
|
6
|
+
import { ProvisionDiagnostic, provisionFailure } from './provision-diagnostics'
|
|
7
|
+
import { installedInfraDirectory } from './package-tools'
|
|
8
|
+
import { provisionConfigSchema } from './provision-config'
|
|
9
|
+
|
|
10
|
+
export interface ProvisionOptions {
|
|
11
|
+
/** Trusted application module, default-exporting an InstanceConfig. Paths resolve from projectRoot. */
|
|
12
|
+
configPath: string
|
|
13
|
+
handler: string
|
|
14
|
+
migrationsDir: string
|
|
15
|
+
resourcePrefix: string
|
|
16
|
+
stage: string
|
|
17
|
+
/** Prebuilt console directory. Omit for an API-only Worker. */
|
|
18
|
+
assetsDir?: string
|
|
19
|
+
/** Stable, operator-supplied secret, e.g. new sst.Secret('AuthSecret').value. Never generated per deploy. */
|
|
20
|
+
authSecret: Input<string>
|
|
21
|
+
/** Exact public HTTPS origin; passed as AUTH_BASE_URL. */
|
|
22
|
+
authBaseUrl: string
|
|
23
|
+
domain?: string
|
|
24
|
+
email?: { from: string }
|
|
25
|
+
webhook?: { url: Input<string>; allowedHosts: Input<string>; service?: Input<string>; events?: string }
|
|
26
|
+
internalToken?: Input<string>
|
|
27
|
+
/** Defaults to CLOUDFLARE_DEFAULT_ACCOUNT_ID. Credentials stay in the deploy environment. */
|
|
28
|
+
accountId?: string
|
|
29
|
+
/** Defaults to the SST app root (process.cwd() inside SST run()). */
|
|
30
|
+
projectRoot?: string
|
|
31
|
+
/** Defaults to true for production. Also set the SST app's removal/protect policy. */
|
|
32
|
+
protect?: boolean
|
|
33
|
+
/** Extra fingerprints for application/plugin verification hooks imported by configPath. */
|
|
34
|
+
migrationTriggers?: Input<unknown>[]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ProvisionPlan {
|
|
38
|
+
stage: string
|
|
39
|
+
root: string
|
|
40
|
+
configPath: string
|
|
41
|
+
handler: string
|
|
42
|
+
migrationsDir: string
|
|
43
|
+
assetsDir?: string
|
|
44
|
+
names: { database: string; audit: string; events: string; deadLetter: string; worker: string }
|
|
45
|
+
/** Stable Pulumi logical-name prefix, scoped to this instance and stage. */
|
|
46
|
+
id: string
|
|
47
|
+
schema: SchemaRevision
|
|
48
|
+
environment: Record<string, string>
|
|
49
|
+
bindingNames: string[]
|
|
50
|
+
migration: { command: string; bin: string; triggers: string[] }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function nonempty(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0 && !value.includes('\0') }
|
|
54
|
+
function label(value: unknown, limit: number): value is string {
|
|
55
|
+
return typeof value === 'string' && value.length <= limit && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** No values supplied by callers are included in validation messages. */
|
|
59
|
+
export function validateProvisionOptions(options: ProvisionOptions): void {
|
|
60
|
+
if (!options || !label(options.stage, 32)) throw new ProvisionDiagnostic('provision_invalid_stage')
|
|
61
|
+
if (!label(options.resourcePrefix, 63)) throw new ProvisionDiagnostic('provision_invalid_prefix')
|
|
62
|
+
if (!nonempty(options.handler)) throw new ProvisionDiagnostic('provision_invalid_handler')
|
|
63
|
+
if (!nonempty(options.configPath)) throw new ProvisionDiagnostic('provision_invalid_config_path')
|
|
64
|
+
if (!nonempty(options.migrationsDir)) throw new ProvisionDiagnostic('provision_invalid_migrations_dir')
|
|
65
|
+
if (options.assetsDir !== undefined && !nonempty(options.assetsDir)) throw new ProvisionDiagnostic('provision_invalid_assets_dir')
|
|
66
|
+
if (!options.authSecret || (typeof options.authSecret === 'string' && options.authSecret.length < 32)) throw new ProvisionDiagnostic('provision_invalid_auth_secret')
|
|
67
|
+
try {
|
|
68
|
+
const url = new URL(options.authBaseUrl)
|
|
69
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw 0
|
|
70
|
+
if (options.domain !== undefined && (url.hostname !== options.domain || !options.domain.includes('.') || url.port)) throw new ProvisionDiagnostic('provision_invalid_domain')
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof ProvisionDiagnostic) throw error
|
|
73
|
+
throw new ProvisionDiagnostic('provision_invalid_auth_base_url')
|
|
74
|
+
}
|
|
75
|
+
if (options.email && !/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(options.email.from)) throw new ProvisionDiagnostic('provision_invalid_email')
|
|
76
|
+
if (options.webhook && (!options.webhook.url || !options.webhook.allowedHosts)) throw new ProvisionDiagnostic('provision_invalid_webhook')
|
|
77
|
+
if (options.accountId !== undefined && !/^[a-f0-9]{32}$/.test(options.accountId)) throw new ProvisionDiagnostic('provision_invalid_account_id')
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Deterministic names fit SST's 54-character Worker limit and Cloudflare's 63-character queue limit.
|
|
81
|
+
* The tuple hash disambiguates prefix/stage boundaries and truncated names. */
|
|
82
|
+
function resourceName(prefix: string, stage: string, suffix: string) {
|
|
83
|
+
const hash = sha256(JSON.stringify([prefix, stage, suffix])).slice(0, 12)
|
|
84
|
+
const stem = `${prefix}-${stage}-${suffix}`
|
|
85
|
+
const limit = suffix === 'worker' ? 54 : 63
|
|
86
|
+
return `${stem.slice(0, limit - hash.length - 1).replace(/-+$/, '')}-${hash}`
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// SST bundles the program, so import.meta.url is then the bundle, not this source file.
|
|
90
|
+
// Resolve the installed package export rather than constructing paths relative to the bundle.
|
|
91
|
+
async function packageTools() {
|
|
92
|
+
const infra = installedInfraDirectory()
|
|
93
|
+
const source = dirname(infra)
|
|
94
|
+
async function fingerprint(directory: string): Promise<string[]> {
|
|
95
|
+
const entries = (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))
|
|
96
|
+
return (await Promise.all(entries.map(async entry => {
|
|
97
|
+
const path = join(directory, entry.name)
|
|
98
|
+
return entry.isDirectory() ? fingerprint(path) : /\.(?:ts|mjs)$/.test(entry.name) ? [sha256(await readFile(path, 'utf8'))] : []
|
|
99
|
+
}))).flat()
|
|
100
|
+
}
|
|
101
|
+
return { bin: join(infra, 'bin.mjs'), hash: sha256(JSON.stringify(await fingerprint(source))) }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Build a secret-free resource specification, without SST, Pulumi execution, preview or network access.
|
|
105
|
+
* Config modules are trusted code, evaluated in an isolated Node process with tsx. */
|
|
106
|
+
export async function createProvisionPlan(options: ProvisionOptions): Promise<ProvisionPlan> {
|
|
107
|
+
validateProvisionOptions(options)
|
|
108
|
+
const root = resolve(options.projectRoot ?? process.cwd())
|
|
109
|
+
const configPath = resolve(root, options.configPath), handler = resolve(root, options.handler)
|
|
110
|
+
const migrationsDir = resolve(root, options.migrationsDir)
|
|
111
|
+
const assetsDir = options.assetsDir === undefined ? undefined : resolve(root, options.assetsDir)
|
|
112
|
+
try {
|
|
113
|
+
if (!(await stat(handler)).isFile() || !(await stat(configPath)).isFile() || !(await stat(migrationsDir)).isDirectory() || (assetsDir && !(await stat(assetsDir)).isDirectory())) throw 0
|
|
114
|
+
} catch { throw new ProvisionDiagnostic('provision_inputs_unreadable') }
|
|
115
|
+
const secrets = [options.authSecret, options.internalToken, options.webhook?.url, options.webhook?.allowedHosts, options.webhook?.service]
|
|
116
|
+
.filter((value): value is string => typeof value === 'string' && value.length > 0)
|
|
117
|
+
const schema = await provisionConfigSchema(root, configPath, migrationsDir, secrets)
|
|
118
|
+
try {
|
|
119
|
+
const files = await readMigrationFiles(migrationsDir)
|
|
120
|
+
const tools = await packageTools()
|
|
121
|
+
const name = (suffix: string) => resourceName(options.resourcePrefix, options.stage, suffix)
|
|
122
|
+
return {
|
|
123
|
+
stage: options.stage, root, configPath, handler, migrationsDir, ...(assetsDir ? { assetsDir } : {}),
|
|
124
|
+
names: { database: name('db'), audit: name('audit'), events: name('events'), deadLetter: name('events-dlq'), worker: name('worker') },
|
|
125
|
+
id: `Workbase${sha256(JSON.stringify([options.resourcePrefix, options.stage])).slice(0, 20)}`,
|
|
126
|
+
schema,
|
|
127
|
+
environment: { STAGE: options.stage, SCHEMA_EXPECTED: JSON.stringify(schema), AUTH_BASE_URL: options.authBaseUrl,
|
|
128
|
+
...(options.email ? { EMAIL_FROM: options.email.from } : {}),
|
|
129
|
+
...(options.webhook?.events ? { WEBHOOK_EVENTS: options.webhook.events } : {}),
|
|
130
|
+
},
|
|
131
|
+
bindingNames: ['DB', 'AUDIT_KV', 'EVENTS_QUEUE', 'BETTER_AUTH_SECRET', 'AUTH_BASE_URL', 'STAGE', 'SCHEMA_EXPECTED',
|
|
132
|
+
...(assetsDir ? ['ASSETS'] : []), ...(options.email ? ['EMAIL', 'EMAIL_FROM'] : []),
|
|
133
|
+
...(options.webhook ? ['WEBHOOK_URL', 'WEBHOOK_ALLOWED_HOSTS', ...(options.webhook.service ? ['WEBHOOK_SERVICE'] : []), ...(options.webhook.events ? ['WEBHOOK_EVENTS'] : [])] : []),
|
|
134
|
+
...(options.internalToken ? ['INTERNAL_TOKEN'] : []),
|
|
135
|
+
],
|
|
136
|
+
migration: {
|
|
137
|
+
command: '"$WB_NODE_BINARY" "$WB_MIGRATION_BIN" migrate "$WB_DATABASE_ID" "$WB_MIGRATIONS_DIRECTORY" --config "$WB_CONFIG_MODULE"',
|
|
138
|
+
bin: tools.bin,
|
|
139
|
+
triggers: [migrationHash(files), JSON.stringify(schema), tools.hash, sha256(await readFile(configPath, 'utf8'))],
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
} catch (error) { throw provisionFailure(error) }
|
|
143
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { ComponentResourceOptions, Input, Output } from '@pulumi/pulumi'
|
|
2
|
+
import type { local } from '@pulumi/command'
|
|
3
|
+
import { createProvisionPlan, type ProvisionOptions } from './provision-plan'
|
|
4
|
+
import { ProvisionDiagnostic, provisionFailure } from './provision-diagnostics'
|
|
5
|
+
import { sstCommand } from './sst-runtime'
|
|
6
|
+
import type { CloudflareRuntime, DatabaseResource, KvResource, NativeBinding, QueueResource, SstRuntime, WorkerResource, CronResource } from './sst-runtime'
|
|
7
|
+
|
|
8
|
+
export { createProvisionPlan, validateProvisionOptions, type ProvisionOptions, type ProvisionPlan } from './provision-plan'
|
|
9
|
+
export { ProvisionDiagnostic, provisionErrorMessage, type ProvisionDiagnosticCode } from './provision-diagnostics'
|
|
10
|
+
|
|
11
|
+
// These names are supplied by SST's run-time config bundler, including in npm
|
|
12
|
+
// dependencies. Type-only declarations disappear before SST injects its imports.
|
|
13
|
+
declare const sst: SstRuntime
|
|
14
|
+
declare const cloudflare: CloudflareRuntime
|
|
15
|
+
declare const $util: Pick<typeof import('@pulumi/pulumi'), 'output' | 'secret'>
|
|
16
|
+
declare const $cli: { paths: { platform: string } }
|
|
17
|
+
|
|
18
|
+
export interface ProvisionResult {
|
|
19
|
+
stage: string
|
|
20
|
+
url: Output<string | undefined>
|
|
21
|
+
workerName: Output<string>
|
|
22
|
+
databaseId: Output<string>
|
|
23
|
+
eventsQueueName: Output<string>
|
|
24
|
+
deadLetterQueueName: Output<string>
|
|
25
|
+
resources: {
|
|
26
|
+
database: DatabaseResource; audit: KvResource; events: QueueResource; deadLetter: QueueResource
|
|
27
|
+
migrations: local.Command; worker: WorkerResource; consumer: import('@pulumi/pulumi').Resource; cron: CronResource
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Single-instance SST Cloudflare provisioning. Call inside sst.config.ts run().
|
|
32
|
+
* No resources are registered until all local inputs and expected schema are prepared. */
|
|
33
|
+
export async function provision(options: ProvisionOptions): Promise<ProvisionResult> {
|
|
34
|
+
const plan = await createProvisionPlan(options)
|
|
35
|
+
if (typeof sst === 'undefined' || typeof cloudflare === 'undefined' || typeof $util === 'undefined' || typeof $cli === 'undefined') throw new ProvisionDiagnostic('provision_requires_sst')
|
|
36
|
+
const accountId = options.accountId ?? process.env.CLOUDFLARE_DEFAULT_ACCOUNT_ID
|
|
37
|
+
if (!accountId || !/^[a-f0-9]{32}$/.test(accountId)) throw new ProvisionDiagnostic('provision_invalid_account_id')
|
|
38
|
+
const command = sstCommand($cli.paths.platform)
|
|
39
|
+
try {
|
|
40
|
+
const protect = options.protect ?? options.stage === 'production'
|
|
41
|
+
const protection = { protect, retainOnDelete: protect }
|
|
42
|
+
const db = new sst.cloudflare.D1(`${plan.id}DB`, { accountId, transform: { database: (args, opts) => {
|
|
43
|
+
args.name = plan.names.database; Object.assign(opts, protection)
|
|
44
|
+
} } }, protection)
|
|
45
|
+
const audit = new sst.cloudflare.Kv(`${plan.id}Audit`, { accountId, transform: { namespace: (args, opts) => {
|
|
46
|
+
args.title = plan.names.audit; Object.assign(opts, protection)
|
|
47
|
+
} } }, protection)
|
|
48
|
+
const queue = (suffix: string, name: string) => new sst.cloudflare.Queue(`${plan.id}${suffix}`, { accountId, transform: { queue: (args, opts) => {
|
|
49
|
+
args.queueName = name; Object.assign(opts, protection)
|
|
50
|
+
} } }, protection)
|
|
51
|
+
const events = queue('Events', plan.names.events), deadLetter = queue('EventsDLQ', plan.names.deadLetter)
|
|
52
|
+
// Command replaces on trigger changes; protection would block production migrations.
|
|
53
|
+
const migrations = new command.local.Command(`${plan.id}Migrate`, {
|
|
54
|
+
create: plan.migration.command, update: plan.migration.command,
|
|
55
|
+
dir: plan.root, addPreviousOutputInEnv: false,
|
|
56
|
+
environment: {
|
|
57
|
+
WB_NODE_BINARY: process.execPath, WB_MIGRATION_BIN: plan.migration.bin,
|
|
58
|
+
WB_DATABASE_ID: db.databaseId, WB_MIGRATIONS_DIRECTORY: plan.migrationsDir,
|
|
59
|
+
WB_CONFIG_MODULE: plan.configPath, CLOUDFLARE_DEFAULT_ACCOUNT_ID: accountId,
|
|
60
|
+
},
|
|
61
|
+
triggers: [...plan.migration.triggers, ...(options.migrationTriggers ?? [])],
|
|
62
|
+
}, { protect: false, dependsOn: [db, db.nodes.database] })
|
|
63
|
+
|
|
64
|
+
function secret(value: Input<string>, auth = false) {
|
|
65
|
+
return $util.secret($util.output(value).apply(text => {
|
|
66
|
+
if (auth && (typeof text !== 'string' || text.length < 32)) throw new ProvisionDiagnostic('provision_invalid_auth_secret')
|
|
67
|
+
return text
|
|
68
|
+
}))
|
|
69
|
+
}
|
|
70
|
+
const bindings: NativeBinding[] = [
|
|
71
|
+
{ name: 'DB', type: 'd1', id: db.databaseId },
|
|
72
|
+
{ name: 'AUDIT_KV', type: 'kv_namespace', namespaceId: audit.namespaceId },
|
|
73
|
+
{ name: 'EVENTS_QUEUE', type: 'queue', queueName: events.nodes.queue.queueName },
|
|
74
|
+
{ name: 'BETTER_AUTH_SECRET', type: 'secret_text', text: secret(options.authSecret, true) },
|
|
75
|
+
...(options.internalToken ? [{ name: 'INTERNAL_TOKEN', type: 'secret_text', text: secret(options.internalToken) }] : []),
|
|
76
|
+
...(options.webhook ? [
|
|
77
|
+
{ name: 'WEBHOOK_URL', type: 'secret_text', text: secret(options.webhook.url) },
|
|
78
|
+
{ name: 'WEBHOOK_ALLOWED_HOSTS', type: 'secret_text', text: secret(options.webhook.allowedHosts) },
|
|
79
|
+
...(options.webhook.service ? [{ name: 'WEBHOOK_SERVICE', type: 'service', service: options.webhook.service }] : []),
|
|
80
|
+
] : []),
|
|
81
|
+
...(options.email ? [{ name: 'EMAIL', type: 'send_email', allowedSenderAddresses: [options.email.from] }] : []),
|
|
82
|
+
]
|
|
83
|
+
const worker = new sst.cloudflare.Worker(`${plan.id}Worker`, {
|
|
84
|
+
accountId, handler: plan.handler, domain: options.domain, url: true, dev: false,
|
|
85
|
+
...(plan.assetsDir ? { assets: { directory: plan.assetsDir, htmlHandling: 'none' as const, notFoundHandling: 'none' as const, runWorkerFirst: true as const } } : {}),
|
|
86
|
+
compatibility: { date: '2026-08-01', flags: ['nodejs_compat'] },
|
|
87
|
+
environment: plan.environment,
|
|
88
|
+
transform: { worker: (args, opts: ComponentResourceOptions) => {
|
|
89
|
+
args.scriptName = plan.names.worker
|
|
90
|
+
args.keepBindings = []
|
|
91
|
+
// Auth query strings contain credentials: retain explicit application logs only.
|
|
92
|
+
args.observability = { enabled: true, headSamplingRate: 1, logs: { enabled: true, invocationLogs: false, persist: true } }
|
|
93
|
+
args.bindings = $util.output({ existing: args.bindings, added: bindings }).apply(({ existing, added }) => [...(existing ?? []), ...added])
|
|
94
|
+
Object.assign(opts, protection)
|
|
95
|
+
// Fence the actual script upload as well as its enclosing SST component.
|
|
96
|
+
opts.dependsOn = [migrations]
|
|
97
|
+
} },
|
|
98
|
+
}, { ...protection, dependsOn: [migrations] })
|
|
99
|
+
const consumer = new cloudflare.QueueConsumer(`${plan.id}EventsConsumer`, {
|
|
100
|
+
accountId, queueId: events.id, scriptName: worker.nodes.worker.scriptName,
|
|
101
|
+
type: 'worker', deadLetterQueue: deadLetter.nodes.queue.queueName,
|
|
102
|
+
settings: { batchSize: 10, maxWaitTimeMs: 1000, maxRetries: 5 },
|
|
103
|
+
}, { ...protection, dependsOn: [worker, events, deadLetter] })
|
|
104
|
+
const cron = new cloudflare.WorkersCronTrigger(`${plan.id}RelayCron`, {
|
|
105
|
+
accountId, scriptName: worker.nodes.worker.scriptName, schedules: [{ cron: '*/5 * * * *' }],
|
|
106
|
+
}, { ...protection, dependsOn: [worker] })
|
|
107
|
+
return {
|
|
108
|
+
stage: plan.stage, url: worker.url, workerName: worker.nodes.worker.scriptName, databaseId: db.databaseId,
|
|
109
|
+
eventsQueueName: events.nodes.queue.queueName, deadLetterQueueName: deadLetter.nodes.queue.queueName,
|
|
110
|
+
resources: { database: db, audit, events, deadLetter, migrations, worker, consumer, cron },
|
|
111
|
+
}
|
|
112
|
+
} catch (error) { throw provisionFailure(error) }
|
|
113
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { CORE_VERSION, type InstanceConfig } from '../config'
|
|
2
|
+
import { expectedPluginMigrations } from '../kernel/migrations'
|
|
3
|
+
import { KernelRegistry } from '../kernel/registry'
|
|
4
|
+
import type { SchemaRevision } from '../schema-compatibility'
|
|
5
|
+
import { migrationHash, readMigrationFiles, sha256 } from './migration-files'
|
|
6
|
+
|
|
7
|
+
export interface ExpectedSchemaOptions {
|
|
8
|
+
migrationsDirectory: string
|
|
9
|
+
revision: number
|
|
10
|
+
config?: InstanceConfig
|
|
11
|
+
/** Override for non-Workbase SQL databases. Defaults to the installed core version. */
|
|
12
|
+
coreVersion?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function expectedSchema({ migrationsDirectory, revision, config, coreVersion = CORE_VERSION }: ExpectedSchemaOptions): Promise<SchemaRevision> {
|
|
16
|
+
const plugins = config ? new KernelRegistry(config).plugins : []
|
|
17
|
+
return {
|
|
18
|
+
revision, coreVersion, migrations: migrationHash(await readMigrationFiles(migrationsDirectory)),
|
|
19
|
+
...(config ? { pluginMigrations: sha256(JSON.stringify(await expectedPluginMigrations(plugins))) } : {}),
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { ComponentResourceOptions, Input, Output, Resource } from '@pulumi/pulumi'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { ProvisionDiagnostic } from './provision-diagnostics'
|
|
5
|
+
|
|
6
|
+
/** Load SST's built-in command provider, never a consumer's optional peer. Pulumi
|
|
7
|
+
* shares process-wide state, but protobuf messages must use the monitor's SDK. */
|
|
8
|
+
export function sstCommand(platform: string): typeof import('@pulumi/command') {
|
|
9
|
+
try {
|
|
10
|
+
const require = createRequire(join(platform, 'package.json'))
|
|
11
|
+
const entry = require.resolve('@pulumi/command')
|
|
12
|
+
// Fail before loading a provider with a nested, incompatible Pulumi runtime.
|
|
13
|
+
if (createRequire(entry).resolve('@pulumi/pulumi') !== require.resolve('@pulumi/pulumi')) throw new Error('duplicate_pulumi')
|
|
14
|
+
return require('@pulumi/command')
|
|
15
|
+
} catch { throw new ProvisionDiagnostic('provision_requires_command') }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// SST's infrastructure constructors are injected by its config bundler; they are
|
|
19
|
+
// not exports of the npm `sst` runtime. Keep this small structural boundary here so
|
|
20
|
+
// installed consumers do not need this repository's generated .sst declarations.
|
|
21
|
+
// infra/provision-contract.ts checks it against the pinned SST/provider types.
|
|
22
|
+
export interface NativeBinding {
|
|
23
|
+
name: Input<string>
|
|
24
|
+
type: Input<string>
|
|
25
|
+
text?: Input<string | undefined>
|
|
26
|
+
id?: Input<string | undefined>
|
|
27
|
+
namespaceId?: Input<string | undefined>
|
|
28
|
+
queueName?: Input<string | undefined>
|
|
29
|
+
service?: Input<string | undefined>
|
|
30
|
+
allowedSenderAddresses?: Input<Input<string>[] | undefined>
|
|
31
|
+
}
|
|
32
|
+
export interface NativeWorkerArgs {
|
|
33
|
+
scriptName?: Input<string | undefined>
|
|
34
|
+
keepBindings?: Input<Input<string>[] | undefined>
|
|
35
|
+
bindings?: Input<Input<NativeBinding>[] | undefined>
|
|
36
|
+
observability?: Input<{
|
|
37
|
+
enabled?: Input<boolean | undefined>
|
|
38
|
+
headSamplingRate?: Input<number | undefined>
|
|
39
|
+
logs?: Input<{ enabled?: Input<boolean | undefined>; invocationLogs?: Input<boolean | undefined>; persist?: Input<boolean | undefined> } | undefined>
|
|
40
|
+
} | undefined>
|
|
41
|
+
}
|
|
42
|
+
type Transform<T> = (args: T, opts: ComponentResourceOptions) => undefined
|
|
43
|
+
export type DatabaseResource = Resource & { databaseId: Output<string>; nodes: { database: Resource } }
|
|
44
|
+
export type KvResource = Resource & { namespaceId: Output<string> }
|
|
45
|
+
export type QueueResource = Resource & { id: Output<string>; nodes: { queue: Resource & { queueName: Output<string> } } }
|
|
46
|
+
export type WorkerResource = Resource & { url: Output<string | undefined>; nodes: { worker: Resource & { scriptName: Output<string> } } }
|
|
47
|
+
export type CronResource = Resource & { scriptName: Output<string>; schedules: Output<{ cron: string }[] | undefined> }
|
|
48
|
+
|
|
49
|
+
export interface SstRuntime {
|
|
50
|
+
cloudflare: {
|
|
51
|
+
D1: new (name: string, args: { accountId: string; transform: { database: Transform<{ name?: Input<string> }> } }, opts: ComponentResourceOptions) => DatabaseResource
|
|
52
|
+
Kv: new (name: string, args: { accountId: string; transform: { namespace: Transform<{ title?: Input<string> }> } }, opts: ComponentResourceOptions) => KvResource
|
|
53
|
+
Queue: new (name: string, args: { accountId: string; transform: { queue: Transform<{ queueName?: Input<string> }> } }, opts: ComponentResourceOptions) => QueueResource
|
|
54
|
+
Worker: new (name: string, args: {
|
|
55
|
+
accountId: string
|
|
56
|
+
handler: string
|
|
57
|
+
domain?: string
|
|
58
|
+
url: boolean
|
|
59
|
+
dev: false
|
|
60
|
+
assets?: { directory: string; htmlHandling: 'none'; notFoundHandling: 'none'; runWorkerFirst: true }
|
|
61
|
+
compatibility: { date: string; flags: string[] }
|
|
62
|
+
environment: Record<string, string>
|
|
63
|
+
transform: { worker: Transform<NativeWorkerArgs> }
|
|
64
|
+
}, opts: ComponentResourceOptions) => WorkerResource
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface CloudflareRuntime {
|
|
69
|
+
QueueConsumer: new (name: string, args: {
|
|
70
|
+
accountId: string; queueId: Input<string>; scriptName: Input<string>; type: 'worker'; deadLetterQueue: Input<string>
|
|
71
|
+
settings: { batchSize: number; maxWaitTimeMs: number; maxRetries: number }
|
|
72
|
+
}, opts: ComponentResourceOptions) => Resource
|
|
73
|
+
WorkersCronTrigger: new (name: string, args: {
|
|
74
|
+
accountId: string; scriptName: Input<string>; schedules: { cron: string }[]
|
|
75
|
+
}, opts: ComponentResourceOptions) => CronResource
|
|
76
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// Generated by packages/
|
|
1
|
+
// Generated by packages/plugins/local-auth/generate-auth-migration.mjs.
|
|
2
2
|
export const betterAuthSchema = "create table \"user\" (\"id\" text not null primary key, \"name\" text not null, \"email\" text not null unique, \"emailVerified\" integer not null, \"image\" text, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"session\" (\"id\" text not null primary key, \"expiresAt\" date not null, \"token\" text not null unique, \"createdAt\" date not null, \"updatedAt\" date not null, \"ipAddress\" text, \"userAgent\" text, \"userId\" text not null references \"user\" (\"id\") on delete cascade);\n\ncreate table \"account\" (\"id\" text not null primary key, \"issuer\" text not null, \"accountId\" text not null, \"providerId\" text not null, \"userId\" text not null references \"user\" (\"id\") on delete cascade, \"accessToken\" text, \"refreshToken\" text, \"idToken\" text, \"accessTokenExpiresAt\" date, \"refreshTokenExpiresAt\" date, \"scope\" text, \"password\" text, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"verification\" (\"id\" text not null primary key, \"identifier\" text not null, \"value\" text not null, \"expiresAt\" date not null, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"rateLimit\" (\"id\" text not null primary key, \"key\" text not null unique, \"count\" integer not null, \"lastRequest\" bigint not null);\n\ncreate index \"session_userId_idx\" on \"session\" (\"userId\");\n\ncreate index \"account_userId_idx\" on \"account\" (\"userId\");\n\ncreate index \"verification_identifier_idx\" on \"verification\" (\"identifier\");\n\ncreate unique index \"account_issuer_accountId_uidx\" on \"account\" (\"issuer\", \"accountId\");\n\n\n\n\nCREATE TABLE email_outbox_new (id TEXT PRIMARY KEY, organization_id TEXT REFERENCES organizations(id), recipient TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL);\nINSERT INTO email_outbox_new SELECT * FROM email_outbox;\nDROP TABLE email_outbox;\nALTER TABLE email_outbox_new RENAME TO email_outbox;\nCREATE TABLE identity_link_grants (state_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), session_id TEXT NOT NULL, expires_at TEXT NOT NULL);\nCREATE UNIQUE INDEX identities_issuer_subject_idx ON identities(issuer,subject);\n"
|