@supatype/types 0.9.2 → 0.10.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +23 -15
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +19 -1
- package/dist/auth-settings-groups.d.ts +216 -0
- package/dist/auth-settings-groups.d.ts.map +1 -0
- package/dist/auth-settings-groups.js +424 -0
- package/dist/auth-settings-groups.js.map +1 -0
- package/dist/auth-settings.d.ts +168 -0
- package/dist/auth-settings.d.ts.map +1 -0
- package/dist/auth-settings.js +501 -0
- package/dist/auth-settings.js.map +1 -0
- package/dist/function-secret-name.d.ts +14 -0
- package/dist/function-secret-name.d.ts.map +1 -0
- package/dist/function-secret-name.js +20 -0
- package/dist/function-secret-name.js.map +1 -0
- package/dist/index.d.ts +145 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/public-env.d.ts +70 -0
- package/dist/public-env.d.ts.map +1 -0
- package/dist/public-env.js +146 -0
- package/dist/public-env.js.map +1 -0
- package/dist/seed-contract.d.ts +103 -0
- package/dist/seed-contract.d.ts.map +1 -0
- package/dist/seed-contract.js +99 -0
- package/dist/seed-contract.js.map +1 -0
- package/package.json +1 -1
- package/src/auth-settings-groups.ts +604 -0
- package/src/auth-settings.ts +649 -0
- package/src/function-secret-name.ts +21 -0
- package/src/index.ts +176 -2
- package/src/public-env.ts +167 -0
- package/src/seed-contract.ts +167 -0
- package/tests/auth-settings-groups.test.ts +342 -0
- package/tests/auth-settings.test.ts +327 -0
- package/tests/bucket-access.test.ts +33 -1
- package/tests/channel.test.ts +94 -0
- package/tests/function-secret-name.test.ts +17 -0
- package/tests/public-env.test.ts +179 -0
- package/tests/seed-contract.test.ts +110 -0
- package/tests/standalone-build.test.ts +35 -0
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The auth settings a project can declare, and the one renderer that turns them into the
|
|
3
|
+
* `SUPATYPE_*` variables the auth server reads.
|
|
4
|
+
*
|
|
5
|
+
* The shape is the `auth` and `email` sections of `supatype.config.ts`, so the CLI hands its config
|
|
6
|
+
* over as it is. The CLI renders it into the self-host compose file and native dev, and the Cloud
|
|
7
|
+
* control plane renders it into each environment's `auth.env`. Both go through this module so a
|
|
8
|
+
* setting means the same thing on both hosts.
|
|
9
|
+
*
|
|
10
|
+
* Pure types and pure functions: no I/O, no Node imports.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
GROUP_LEAF_PATHS,
|
|
15
|
+
GROUP_OWNED_KEYS,
|
|
16
|
+
GROUP_SECRET_KEYS,
|
|
17
|
+
AUTH_HOOK_NAMES,
|
|
18
|
+
groupProblems,
|
|
19
|
+
groupSecretInUse,
|
|
20
|
+
groupSecretRefs,
|
|
21
|
+
groupsEnv,
|
|
22
|
+
type AuthGroupSettings,
|
|
23
|
+
} from "./auth-settings-groups.js"
|
|
24
|
+
|
|
25
|
+
/** Every OAuth provider the auth server has, by the name `/auth/v1/authorize?provider=` takes. */
|
|
26
|
+
export const AUTH_PROVIDER_NAMES = [
|
|
27
|
+
"apple",
|
|
28
|
+
"azure",
|
|
29
|
+
"bitbucket",
|
|
30
|
+
"discord",
|
|
31
|
+
"facebook",
|
|
32
|
+
"figma",
|
|
33
|
+
"fly",
|
|
34
|
+
"github",
|
|
35
|
+
"gitlab",
|
|
36
|
+
"google",
|
|
37
|
+
"kakao",
|
|
38
|
+
"keycloak",
|
|
39
|
+
"linkedin",
|
|
40
|
+
"linkedin_oidc",
|
|
41
|
+
"notion",
|
|
42
|
+
"slack",
|
|
43
|
+
"slack_oidc",
|
|
44
|
+
"snapchat",
|
|
45
|
+
"spotify",
|
|
46
|
+
"twitch",
|
|
47
|
+
"twitter",
|
|
48
|
+
"vercel_marketplace",
|
|
49
|
+
"workos",
|
|
50
|
+
"x",
|
|
51
|
+
"zoom",
|
|
52
|
+
] as const
|
|
53
|
+
|
|
54
|
+
export type AuthProviderName = (typeof AUTH_PROVIDER_NAMES)[number]
|
|
55
|
+
|
|
56
|
+
/** A value read from the deploying machine's environment, never stored in the config. */
|
|
57
|
+
export type EnvReference = `env(${string})`
|
|
58
|
+
|
|
59
|
+
export interface AuthProviderSettings {
|
|
60
|
+
/** Default true: listing a provider is asking for it. False keeps the settings and turns it off. */
|
|
61
|
+
enabled?: boolean
|
|
62
|
+
clientId?: string
|
|
63
|
+
/** `env("NAME")` only: the config is committed. */
|
|
64
|
+
secret?: EnvReference
|
|
65
|
+
/** Where the provider sends the browser back. Default: the callback under the callback base URL. */
|
|
66
|
+
redirectUri?: string
|
|
67
|
+
/** The provider's base URL, for self-hosted ones. */
|
|
68
|
+
url?: string
|
|
69
|
+
skipNonceCheck?: boolean
|
|
70
|
+
emailOptional?: boolean
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type AuthProvidersSettings = Partial<Record<AuthProviderName, AuthProviderSettings>>
|
|
74
|
+
|
|
75
|
+
export interface AuthSmtpSettings {
|
|
76
|
+
host?: string
|
|
77
|
+
port?: number
|
|
78
|
+
user?: string
|
|
79
|
+
/** `env("NAME")`. A literal is accepted on self-host only, as it always was. */
|
|
80
|
+
pass?: string
|
|
81
|
+
admin_email?: string
|
|
82
|
+
sender_name?: string
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The `email` section of `supatype.config.ts` that the auth server's mailer reads. */
|
|
86
|
+
export interface AuthMailSettings {
|
|
87
|
+
provider?: "console" | "smtp" | "resend" | "ses"
|
|
88
|
+
smtp?: AuthSmtpSettings
|
|
89
|
+
/** `env("NAME")`. A literal is accepted on self-host only. */
|
|
90
|
+
resend_api_key?: string
|
|
91
|
+
resend_from?: string
|
|
92
|
+
ses_from?: string
|
|
93
|
+
/** The project's own SES access key, `env("NAME")`. With the secret below, replaces the ambient AWS credentials. */
|
|
94
|
+
ses_access_key_id?: string
|
|
95
|
+
/** `env("NAME")`. */
|
|
96
|
+
ses_secret_access_key?: string
|
|
97
|
+
/** The SES region, e.g. `eu-west-2`. */
|
|
98
|
+
ses_region?: string
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface AuthSettings {
|
|
102
|
+
auth?: AuthGroupSettings & {
|
|
103
|
+
email?: { enabled?: boolean; enableConfirmations?: boolean }
|
|
104
|
+
providers?: AuthProvidersSettings
|
|
105
|
+
/** Where emailed links and OAuth land when no `redirectTo` is given. */
|
|
106
|
+
siteUrl?: string
|
|
107
|
+
/** Which `redirectTo` values the server accepts, as globs. */
|
|
108
|
+
redirectUrls?: string[]
|
|
109
|
+
/** Turn new sign-ups off. */
|
|
110
|
+
disableSignup?: boolean
|
|
111
|
+
}
|
|
112
|
+
email?: AuthMailSettings
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Which host the settings are for. Cloud is stricter about secrets. */
|
|
116
|
+
export type AuthTarget = "cloud" | "self-host"
|
|
117
|
+
|
|
118
|
+
/** The platform's own sender, used when the project sets no provider of its own. */
|
|
119
|
+
export interface PlatformMailSettings {
|
|
120
|
+
host: string
|
|
121
|
+
port: number
|
|
122
|
+
user: string
|
|
123
|
+
pass: string
|
|
124
|
+
senderName: string
|
|
125
|
+
adminEmail: string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface AuthRenderContext {
|
|
129
|
+
/** Origin the provider callback hangs off: the environment's public API origin, no trailing slash. */
|
|
130
|
+
callbackBaseUrl: string
|
|
131
|
+
/** Site URL when the settings set none. */
|
|
132
|
+
siteUrl: string
|
|
133
|
+
/** Allow-list entries that are always present and cannot be removed, such as Studio's origin. */
|
|
134
|
+
platformRedirectUrls: readonly string[]
|
|
135
|
+
/** The platform sender, used when `email.provider` is unset or "console". Absent: console. */
|
|
136
|
+
platformMail?: PlatformMailSettings
|
|
137
|
+
/** Where the SAML service provider is served: the API's public origin plus `/auth/v1`. Absent: left to the server. */
|
|
138
|
+
samlExternalUrl?: string
|
|
139
|
+
/** Plain secret values by secret key ({@link AuthSecretRef.key}). A missing one renders empty. */
|
|
140
|
+
secrets: Readonly<Record<string, string>>
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface AuthSecretRef {
|
|
144
|
+
/** `providers.<name>.secret`, `email.smtp.pass` or `email.resend_api_key`. */
|
|
145
|
+
key: string
|
|
146
|
+
/** The variable `env("NAME")` names on the deploying machine. */
|
|
147
|
+
envName: string
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Where the auth server's callback is, under the API's public URL. */
|
|
151
|
+
export const AUTH_CALLBACK_PATH = "/auth/v1/callback"
|
|
152
|
+
|
|
153
|
+
const ENV_REFERENCE = /^env\(([A-Za-z_][A-Za-z0-9_]*)\)$/
|
|
154
|
+
/** What a line of the server's .env file cannot carry. */
|
|
155
|
+
const UNWRITABLE = /[\u0000-\u001f\u007f']/
|
|
156
|
+
|
|
157
|
+
/** The variable an `env(NAME)` value names, or undefined for a literal. */
|
|
158
|
+
export function envReferenceName(value: string): string | undefined {
|
|
159
|
+
return ENV_REFERENCE.exec(value.trim())?.[1]
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const PROVIDER_STRING_SUFFIXES = ["CLIENT_ID", "SECRET", "REDIRECT_URI", "URL"] as const
|
|
163
|
+
const PROVIDER_FLAG_SUFFIXES = ["ENABLED", "SKIP_NONCE_CHECK", "EMAIL_OPTIONAL"] as const
|
|
164
|
+
const SMTP_STRING_KEYS = ["HOST", "USER", "PASS", "ADMIN_EMAIL", "SENDER_NAME"] as const
|
|
165
|
+
|
|
166
|
+
function providerPrefix(name: AuthProviderName): string {
|
|
167
|
+
return `SUPATYPE_EXTERNAL_${name.toUpperCase()}_`
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const FIXED_KEYS = [
|
|
171
|
+
"SUPATYPE_EXTERNAL_EMAIL_ENABLED",
|
|
172
|
+
"SUPATYPE_MAILER_AUTOCONFIRM",
|
|
173
|
+
"SUPATYPE_DISABLE_SIGNUP",
|
|
174
|
+
"SUPATYPE_SITE_URL",
|
|
175
|
+
"SUPATYPE_URI_ALLOW_LIST",
|
|
176
|
+
"SUPATYPE_MAILER_MAILER_PROVIDER",
|
|
177
|
+
"SUPATYPE_SMTP_PORT",
|
|
178
|
+
...SMTP_STRING_KEYS.map((k) => `SUPATYPE_SMTP_${k}`),
|
|
179
|
+
"SUPATYPE_RESEND_API_KEY",
|
|
180
|
+
"SUPATYPE_RESEND_FROM",
|
|
181
|
+
"SUPATYPE_SES_FROM",
|
|
182
|
+
"SUPATYPE_SES_ACCESS_KEY_ID",
|
|
183
|
+
"SUPATYPE_SES_SECRET_ACCESS_KEY",
|
|
184
|
+
"SUPATYPE_SES_REGION",
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Every variable {@link authSettingsToEnv} writes, and the only ones it may. Platform-owned values
|
|
189
|
+
* (the JWT secret, database URLs, `SUPATYPE_API_EXTERNAL_URL`, the mailer URL paths, JWT expiry) are
|
|
190
|
+
* not here and no setting can reach them.
|
|
191
|
+
*/
|
|
192
|
+
export const AUTH_OWNED_KEYS: readonly string[] = [
|
|
193
|
+
...FIXED_KEYS,
|
|
194
|
+
...GROUP_OWNED_KEYS,
|
|
195
|
+
...AUTH_PROVIDER_NAMES.flatMap((name) => [
|
|
196
|
+
...PROVIDER_FLAG_SUFFIXES.map((s) => `${providerPrefix(name)}${s}`),
|
|
197
|
+
...PROVIDER_STRING_SUFFIXES.map((s) => `${providerPrefix(name)}${s}`),
|
|
198
|
+
]),
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
const DEFAULT_SMTP_PORT = "587"
|
|
202
|
+
|
|
203
|
+
function flag(value: boolean | undefined, fallback: boolean): string {
|
|
204
|
+
return String(value ?? fallback)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function providerEnv(name: AuthProviderName, settings: AuthSettings, ctx: AuthRenderContext): Record<string, string> {
|
|
208
|
+
const prefix = providerPrefix(name)
|
|
209
|
+
const provider = settings.auth?.providers?.[name]
|
|
210
|
+
const configured = provider !== undefined
|
|
211
|
+
return {
|
|
212
|
+
[`${prefix}ENABLED`]: flag(provider?.enabled, configured),
|
|
213
|
+
[`${prefix}SKIP_NONCE_CHECK`]: flag(provider?.skipNonceCheck, false),
|
|
214
|
+
[`${prefix}EMAIL_OPTIONAL`]: flag(provider?.emailOptional, false),
|
|
215
|
+
[`${prefix}CLIENT_ID`]: provider?.clientId?.trim() ?? "",
|
|
216
|
+
[`${prefix}SECRET`]: ctx.secrets[`providers.${name}.secret`] ?? "",
|
|
217
|
+
[`${prefix}URL`]: provider?.url?.trim() ?? "",
|
|
218
|
+
[`${prefix}REDIRECT_URI`]: configured
|
|
219
|
+
? (provider.redirectUri?.trim() ?? `${ctx.callbackBaseUrl}${AUTH_CALLBACK_PATH}`)
|
|
220
|
+
: "",
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function emptyMailEnv(): Record<string, string> {
|
|
225
|
+
return {
|
|
226
|
+
SUPATYPE_MAILER_MAILER_PROVIDER: "console",
|
|
227
|
+
SUPATYPE_SMTP_PORT: DEFAULT_SMTP_PORT,
|
|
228
|
+
SUPATYPE_SMTP_HOST: "",
|
|
229
|
+
SUPATYPE_SMTP_USER: "",
|
|
230
|
+
SUPATYPE_SMTP_PASS: "",
|
|
231
|
+
SUPATYPE_SMTP_ADMIN_EMAIL: "",
|
|
232
|
+
SUPATYPE_SMTP_SENDER_NAME: "",
|
|
233
|
+
SUPATYPE_RESEND_API_KEY: "",
|
|
234
|
+
SUPATYPE_RESEND_FROM: "",
|
|
235
|
+
SUPATYPE_SES_FROM: "",
|
|
236
|
+
SUPATYPE_SES_ACCESS_KEY_ID: "",
|
|
237
|
+
SUPATYPE_SES_SECRET_ACCESS_KEY: "",
|
|
238
|
+
SUPATYPE_SES_REGION: "",
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function platformMailEnv(mail: PlatformMailSettings): Record<string, string> {
|
|
243
|
+
return {
|
|
244
|
+
SUPATYPE_MAILER_MAILER_PROVIDER: "smtp",
|
|
245
|
+
SUPATYPE_SMTP_HOST: mail.host,
|
|
246
|
+
SUPATYPE_SMTP_PORT: String(mail.port),
|
|
247
|
+
SUPATYPE_SMTP_USER: mail.user,
|
|
248
|
+
SUPATYPE_SMTP_PASS: mail.pass,
|
|
249
|
+
SUPATYPE_SMTP_ADMIN_EMAIL: mail.adminEmail,
|
|
250
|
+
SUPATYPE_SMTP_SENDER_NAME: mail.senderName,
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function projectMailEnv(mail: AuthMailSettings, ctx: AuthRenderContext): Record<string, string> {
|
|
255
|
+
const smtp = mail.smtp ?? {}
|
|
256
|
+
return {
|
|
257
|
+
SUPATYPE_MAILER_MAILER_PROVIDER: mail.provider ?? "console",
|
|
258
|
+
...(mail.provider === "smtp" && {
|
|
259
|
+
SUPATYPE_SMTP_HOST: smtp.host?.trim() ?? "",
|
|
260
|
+
SUPATYPE_SMTP_PORT: String(smtp.port ?? DEFAULT_SMTP_PORT),
|
|
261
|
+
SUPATYPE_SMTP_USER: smtp.user?.trim() ?? "",
|
|
262
|
+
SUPATYPE_SMTP_PASS: ctx.secrets["email.smtp.pass"] ?? "",
|
|
263
|
+
SUPATYPE_SMTP_ADMIN_EMAIL: smtp.admin_email?.trim() ?? "",
|
|
264
|
+
SUPATYPE_SMTP_SENDER_NAME: smtp.sender_name?.trim() ?? "",
|
|
265
|
+
}),
|
|
266
|
+
...(mail.provider === "resend" && {
|
|
267
|
+
SUPATYPE_RESEND_API_KEY: ctx.secrets["email.resend_api_key"] ?? "",
|
|
268
|
+
SUPATYPE_RESEND_FROM: mail.resend_from?.trim() ?? "",
|
|
269
|
+
}),
|
|
270
|
+
...(mail.provider === "ses" && {
|
|
271
|
+
SUPATYPE_SES_FROM: mail.ses_from?.trim() ?? "",
|
|
272
|
+
SUPATYPE_SES_ACCESS_KEY_ID: ctx.secrets["email.ses_access_key_id"] ?? "",
|
|
273
|
+
SUPATYPE_SES_SECRET_ACCESS_KEY: ctx.secrets["email.ses_secret_access_key"] ?? "",
|
|
274
|
+
SUPATYPE_SES_REGION: mail.ses_region?.trim() ?? "",
|
|
275
|
+
}),
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function mailEnv(settings: AuthSettings, ctx: AuthRenderContext): Record<string, string> {
|
|
280
|
+
const mail = settings.email
|
|
281
|
+
const ownProvider = mail?.provider !== undefined && mail.provider !== "console"
|
|
282
|
+
if (!ownProvider && ctx.platformMail !== undefined) return { ...emptyMailEnv(), ...platformMailEnv(ctx.platformMail) }
|
|
283
|
+
return { ...emptyMailEnv(), ...(mail !== undefined ? projectMailEnv(mail, ctx) : {}) }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function allowList(settings: AuthSettings, ctx: AuthRenderContext): string {
|
|
287
|
+
const own = settings.auth?.redirectUrls ?? []
|
|
288
|
+
return [...new Set([...own, ...ctx.platformRedirectUrls])].join(",")
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The settings as the auth server's environment, every owned key always present: the server's
|
|
293
|
+
* reloader only ever sets variables, so a key missing from the file would keep its old value.
|
|
294
|
+
* Booleans and integers are always explicit, since the server fails to parse an empty one.
|
|
295
|
+
*/
|
|
296
|
+
export function authSettingsToEnv(settings: AuthSettings, ctx: AuthRenderContext): Record<string, string> {
|
|
297
|
+
const auth = settings.auth
|
|
298
|
+
return {
|
|
299
|
+
SUPATYPE_EXTERNAL_EMAIL_ENABLED: flag(auth?.email?.enabled, true),
|
|
300
|
+
SUPATYPE_MAILER_AUTOCONFIRM: String(!(auth?.email?.enableConfirmations ?? true)),
|
|
301
|
+
SUPATYPE_DISABLE_SIGNUP: flag(auth?.disableSignup, false),
|
|
302
|
+
SUPATYPE_SITE_URL: auth?.siteUrl?.trim() ?? ctx.siteUrl,
|
|
303
|
+
SUPATYPE_URI_ALLOW_LIST: allowList(settings, ctx),
|
|
304
|
+
...mailEnv(settings, ctx),
|
|
305
|
+
...groupsEnv(settings, ctx),
|
|
306
|
+
...Object.fromEntries(AUTH_PROVIDER_NAMES.flatMap((name) => Object.entries(providerEnv(name, settings, ctx)))),
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The secrets the settings point at with `env("NAME")`, in a stable order. */
|
|
311
|
+
export function authSecretRefs(settings: AuthSettings): AuthSecretRef[] {
|
|
312
|
+
const refs: AuthSecretRef[] = []
|
|
313
|
+
const push = (key: string, value: string | undefined): void => {
|
|
314
|
+
const envName = value === undefined ? undefined : envReferenceName(value)
|
|
315
|
+
if (envName !== undefined) refs.push({ key, envName })
|
|
316
|
+
}
|
|
317
|
+
for (const name of AUTH_PROVIDER_NAMES) push(`providers.${name}.secret`, settings.auth?.providers?.[name]?.secret)
|
|
318
|
+
push("email.smtp.pass", settings.email?.smtp?.pass)
|
|
319
|
+
push("email.resend_api_key", settings.email?.resend_api_key)
|
|
320
|
+
push("email.ses_access_key_id", settings.email?.ses_access_key_id)
|
|
321
|
+
push("email.ses_secret_access_key", settings.email?.ses_secret_access_key)
|
|
322
|
+
for (const { key, value } of groupSecretRefs(settings)) push(key, value)
|
|
323
|
+
return refs
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Whether the settings use the secret `key`. A stored secret that nothing uses (a removed provider's,
|
|
328
|
+
* a disabled CAPTCHA's) is not rendered. The platform's SAML key is in use while SAML is on.
|
|
329
|
+
*/
|
|
330
|
+
export function authSecretInUse(settings: AuthSettings, key: string): boolean {
|
|
331
|
+
const grouped = groupSecretInUse(settings, key)
|
|
332
|
+
if (grouped !== undefined) return grouped
|
|
333
|
+
if (key === "email.smtp.pass") return settings.email?.provider === "smtp"
|
|
334
|
+
if (key === "email.resend_api_key") return settings.email?.provider === "resend"
|
|
335
|
+
const name = /^providers\.(.+)\.secret$/.exec(key)?.[1]
|
|
336
|
+
return name !== undefined && Object.keys(settings.auth?.providers ?? {}).includes(name)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// Validation
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
|
|
343
|
+
const PROVIDER_FIELDS = new Set(["enabled", "clientId", "secret", "redirectUri", "url", "skipNonceCheck", "emailOptional"])
|
|
344
|
+
const MAIL_PROVIDERS = ["console", "smtp", "resend", "ses"]
|
|
345
|
+
|
|
346
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
347
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const HTTP_URL = /^https?:\/\/[^\s/?#]+[^\s]*$/
|
|
351
|
+
|
|
352
|
+
/** Not an absolute http(s) URL. No `URL` global: this package builds without the DOM lib. */
|
|
353
|
+
function badUrl(value: unknown): boolean {
|
|
354
|
+
return typeof value !== "string" || !HTTP_URL.test(value.trim())
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Schemes a browser runs or reads as content, never allowed as a redirect target. */
|
|
358
|
+
const DANGEROUS_SCHEMES = ["javascript", "data", "file", "vbscript"]
|
|
359
|
+
const SCHEME_FORM = /^([A-Za-z][A-Za-z0-9+.-]*):[^\s,]+$/
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* A redirect allow-list entry that is neither http(s) nor an app's own scheme (RFC 3986 form, such as
|
|
363
|
+
* `myapp://login-callback/`). An app scheme can be claimed by another app, which the docs say.
|
|
364
|
+
*/
|
|
365
|
+
function badRedirectUrl(value: unknown): boolean {
|
|
366
|
+
if (typeof value !== "string" || UNWRITABLE.test(value)) return true
|
|
367
|
+
const scheme = SCHEME_FORM.exec(value.trim())?.[1]?.toLowerCase()
|
|
368
|
+
if (scheme === undefined || DANGEROUS_SCHEMES.includes(scheme)) return true
|
|
369
|
+
return scheme === "http" || scheme === "https" ? badUrl(value) : false
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function stringProblem(value: unknown, path: string): string | undefined {
|
|
373
|
+
if (value === undefined) return undefined
|
|
374
|
+
if (typeof value !== "string" || value.trim() === "") return `${path} must be a non-empty string`
|
|
375
|
+
if (UNWRITABLE.test(value)) return `${path} cannot contain control characters, line breaks or single quotes`
|
|
376
|
+
return undefined
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function secretProblem(value: unknown, path: string, target: AuthTarget, literalOk: boolean): string | undefined {
|
|
380
|
+
if (value === undefined) return undefined
|
|
381
|
+
if (typeof value !== "string") return `${path} must be env("NAME")`
|
|
382
|
+
if (value.trim().startsWith("env(")) {
|
|
383
|
+
return envReferenceName(value) === undefined ? `${path} ${JSON.stringify(value)} is not a valid env("NAME") reference` : undefined
|
|
384
|
+
}
|
|
385
|
+
if (literalOk && target === "self-host") return undefined
|
|
386
|
+
return `${path} must name an environment variable, not hold the secret: ${path.split(".").pop()}: env("NAME")`
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function providerProblems(name: string, provider: unknown): string[] {
|
|
390
|
+
const path = `auth.providers.${name}`
|
|
391
|
+
if (!(AUTH_PROVIDER_NAMES as readonly string[]).includes(name)) {
|
|
392
|
+
return [`${path} is not a provider the auth server has. Use one of: ${AUTH_PROVIDER_NAMES.join(", ")}`]
|
|
393
|
+
}
|
|
394
|
+
if (!isObject(provider)) return [`${path} must be an object`]
|
|
395
|
+
const unknown = Object.keys(provider).filter((k) => !PROVIDER_FIELDS.has(k))
|
|
396
|
+
const found = [
|
|
397
|
+
...(unknown.length > 0 ? [`${path} has unknown field(s) ${unknown.join(", ")}`] : []),
|
|
398
|
+
...(["clientId", "redirectUri", "url"] as const).map((f) => stringProblem(provider[f], `${path}.${f}`)),
|
|
399
|
+
...(["redirectUri", "url"] as const).map((f) =>
|
|
400
|
+
provider[f] !== undefined && badUrl(provider[f]) ? `${path}.${f} must be an absolute http(s) URL` : undefined,
|
|
401
|
+
),
|
|
402
|
+
...(["enabled", "skipNonceCheck", "emailOptional"] as const).map((f) =>
|
|
403
|
+
provider[f] !== undefined && typeof provider[f] !== "boolean" ? `${path}.${f} must be true or false` : undefined,
|
|
404
|
+
),
|
|
405
|
+
secretProblem(provider["secret"], `${path}.secret`, "self-host", false),
|
|
406
|
+
]
|
|
407
|
+
return found.filter((p): p is string => p !== undefined)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function authProblems(auth: unknown, target: AuthTarget): string[] {
|
|
411
|
+
if (auth === undefined) return []
|
|
412
|
+
if (!isObject(auth)) return ["auth must be an object"]
|
|
413
|
+
const problems: string[] = []
|
|
414
|
+
const providers = auth["providers"]
|
|
415
|
+
if (providers !== undefined && !isObject(providers)) problems.push("auth.providers must be an object keyed by provider")
|
|
416
|
+
if (isObject(providers)) {
|
|
417
|
+
for (const [name, provider] of Object.entries(providers)) problems.push(...providerProblems(name, provider))
|
|
418
|
+
}
|
|
419
|
+
if (auth["siteUrl"] !== undefined && badUrl(auth["siteUrl"])) problems.push("auth.siteUrl must be an absolute http(s) URL")
|
|
420
|
+
const urls = auth["redirectUrls"]
|
|
421
|
+
if (urls !== undefined && (!Array.isArray(urls) || urls.some(badRedirectUrl))) {
|
|
422
|
+
problems.push(
|
|
423
|
+
"auth.redirectUrls must be a list of http(s) URLs or app scheme URLs such as myapp://callback (globs allowed; javascript:, data:, file: and vbscript: are refused)",
|
|
424
|
+
)
|
|
425
|
+
}
|
|
426
|
+
if (auth["disableSignup"] !== undefined && typeof auth["disableSignup"] !== "boolean") {
|
|
427
|
+
problems.push("auth.disableSignup must be true or false")
|
|
428
|
+
}
|
|
429
|
+
return [...problems, ...groupProblems(auth, target)]
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function smtpProblems(smtp: unknown, target: AuthTarget): string[] {
|
|
433
|
+
if (smtp === undefined) return []
|
|
434
|
+
if (!isObject(smtp)) return ["email.smtp must be an object"]
|
|
435
|
+
const found = [
|
|
436
|
+
...(["host", "user", "admin_email", "sender_name"] as const).map((f) => stringProblem(smtp[f], `email.smtp.${f}`)),
|
|
437
|
+
smtp["port"] !== undefined && !Number.isInteger(smtp["port"]) ? "email.smtp.port must be an integer" : undefined,
|
|
438
|
+
secretProblem(smtp["pass"], "email.smtp.pass", target, true),
|
|
439
|
+
]
|
|
440
|
+
return found.filter((p): p is string => p !== undefined)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function mailProblems(email: unknown, target: AuthTarget): string[] {
|
|
444
|
+
if (email === undefined) return []
|
|
445
|
+
if (!isObject(email)) return ["email must be an object"]
|
|
446
|
+
const provider = email["provider"]
|
|
447
|
+
const found = [
|
|
448
|
+
provider !== undefined && !MAIL_PROVIDERS.includes(String(provider))
|
|
449
|
+
? `email.provider must be one of ${MAIL_PROVIDERS.join(", ")}`
|
|
450
|
+
: undefined,
|
|
451
|
+
secretProblem(email["resend_api_key"], "email.resend_api_key", target, true),
|
|
452
|
+
secretProblem(email["ses_access_key_id"], "email.ses_access_key_id", target, true),
|
|
453
|
+
secretProblem(email["ses_secret_access_key"], "email.ses_secret_access_key", target, true),
|
|
454
|
+
...(["resend_from", "ses_from", "ses_region"] as const).map((f) => stringProblem(email[f], `email.${f}`)),
|
|
455
|
+
]
|
|
456
|
+
return [
|
|
457
|
+
...found.filter((p): p is string => p !== undefined),
|
|
458
|
+
...sesSenderProblems(provider, email["ses_from"], target),
|
|
459
|
+
...smtpProblems(email["smtp"], target),
|
|
460
|
+
]
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* SES with no sender cannot send: the server logs "falling back to noop" and every mail is dropped
|
|
465
|
+
* while the request answers 200. A self-hosted stack can take the sender from `.env`
|
|
466
|
+
* (SUPATYPE_SES_FROM); a hosted project has no `.env`, so the setting is required there.
|
|
467
|
+
*/
|
|
468
|
+
function sesSenderProblems(provider: unknown, from: unknown, target: AuthTarget): string[] {
|
|
469
|
+
if (target !== "cloud" || provider !== "ses") return []
|
|
470
|
+
if (typeof from === "string" && from.trim() !== "") return []
|
|
471
|
+
return ["email.ses_from must be set when email.provider is ses: without a sender address the server sends no mail and says nothing"]
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Every problem with the settings, none when they are fine. Cloud refuses a literal where a secret
|
|
476
|
+
* belongs (self-host kept accepting a literal SMTP password and Resend key, so it still does).
|
|
477
|
+
* Whether a secret a choice needs is present is not judged here: {@link groupRequiredSecretKeys} names
|
|
478
|
+
* what each choice needs, and the caller checks it against what it holds (the control plane against
|
|
479
|
+
* its held secrets, the CLI push against the references in the config).
|
|
480
|
+
*/
|
|
481
|
+
export function validateAuthSettings(settings: unknown, target: AuthTarget): string[] {
|
|
482
|
+
if (!isObject(settings)) return ["settings must be an object"]
|
|
483
|
+
return [...authProblems(settings["auth"], target), ...mailProblems(settings["email"], target)]
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// ---------------------------------------------------------------------------
|
|
487
|
+
// The file the server's reloader reads
|
|
488
|
+
// ---------------------------------------------------------------------------
|
|
489
|
+
|
|
490
|
+
function quoteEnvValue(key: string, value: string): string {
|
|
491
|
+
if (UNWRITABLE.test(value)) throw new Error(`${key} cannot be written: it holds a control character, line break or single quote`)
|
|
492
|
+
return `'${value}'`
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* `KEY='value'` lines in a stable order, for the auth server's `--config-dir` (a `.env` file).
|
|
497
|
+
* Single quotes mean no expansion. A value holding a single quote is refused: the server's .env parser
|
|
498
|
+
* (godotenv 1.5.1) mis-reads the double-quoted alternatives, as checked against the real parser.
|
|
499
|
+
*/
|
|
500
|
+
export function renderEnvFile(env: Readonly<Record<string, string>>): string {
|
|
501
|
+
return (
|
|
502
|
+
Object.keys(env)
|
|
503
|
+
.sort()
|
|
504
|
+
.map((key) => `${key}=${quoteEnvValue(key, env[key] ?? "")}\n`)
|
|
505
|
+
.join("")
|
|
506
|
+
)
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
// One leaf per setting: how the layers (default, code, Studio) are compared and merged
|
|
511
|
+
// ---------------------------------------------------------------------------
|
|
512
|
+
|
|
513
|
+
/** One setting's value. Arrays stand for a whole list (the redirect allow list). */
|
|
514
|
+
export type AuthSettingValue = string | number | boolean | string[]
|
|
515
|
+
|
|
516
|
+
/** Settings as `{ "auth.providers.github.clientId": "..." }`, secrets left out. */
|
|
517
|
+
export type FlatAuthSettings = Record<string, AuthSettingValue>
|
|
518
|
+
|
|
519
|
+
const PROVIDER_LEAF_FIELDS = ["clientId", "redirectUri", "url", "skipNonceCheck", "emailOptional"] as const
|
|
520
|
+
const SMTP_LEAF_FIELDS = ["host", "port", "user", "admin_email", "sender_name"] as const
|
|
521
|
+
|
|
522
|
+
const GLOBAL_LEAF_PATHS = [
|
|
523
|
+
"auth.siteUrl",
|
|
524
|
+
"auth.redirectUrls",
|
|
525
|
+
"auth.disableSignup",
|
|
526
|
+
"auth.email.enabled",
|
|
527
|
+
"auth.email.enableConfirmations",
|
|
528
|
+
"email.provider",
|
|
529
|
+
"email.resend_from",
|
|
530
|
+
"email.ses_from",
|
|
531
|
+
"email.ses_region",
|
|
532
|
+
...SMTP_LEAF_FIELDS.map((f) => `email.smtp.${f}`),
|
|
533
|
+
...GROUP_LEAF_PATHS,
|
|
534
|
+
]
|
|
535
|
+
|
|
536
|
+
const PROVIDER_LEAF_PATHS = AUTH_PROVIDER_NAMES.flatMap((name) =>
|
|
537
|
+
["enabled", ...PROVIDER_LEAF_FIELDS].map((f) => `auth.providers.${name}.${f}`),
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
const LEAF_PATHS: ReadonlySet<string> = new Set([...GLOBAL_LEAF_PATHS, ...PROVIDER_LEAF_PATHS])
|
|
541
|
+
|
|
542
|
+
/** The secret keys: each provider's secret, the SMTP password, the Resend key, hook, CAPTCHA and SMS secrets. */
|
|
543
|
+
const SECRET_KEYS: ReadonlySet<string> = new Set([
|
|
544
|
+
...AUTH_PROVIDER_NAMES.map((name) => `providers.${name}.secret`),
|
|
545
|
+
"email.smtp.pass",
|
|
546
|
+
"email.resend_api_key",
|
|
547
|
+
"email.ses_access_key_id",
|
|
548
|
+
"email.ses_secret_access_key",
|
|
549
|
+
...GROUP_SECRET_KEYS,
|
|
550
|
+
])
|
|
551
|
+
|
|
552
|
+
/** Whether `path` is a setting that can be saved: not a secret, not a platform-owned value. */
|
|
553
|
+
export function isAuthSettingPath(path: string): boolean {
|
|
554
|
+
return LEAF_PATHS.has(path)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Whether `key` names a secret ({@link AuthSecretRef.key}). */
|
|
558
|
+
export function isAuthSecretKey(key: string): boolean {
|
|
559
|
+
return SECRET_KEYS.has(key)
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Every path {@link isAuthSettingPath} accepts, for a view that lists each setting. */
|
|
563
|
+
export function authSettingPaths(): string[] {
|
|
564
|
+
return [...LEAF_PATHS]
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Every secret key, for a view that lists each as set or not set. */
|
|
568
|
+
export function authSecretKeys(): string[] {
|
|
569
|
+
return [...SECRET_KEYS]
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function isAuthSettingValue(value: unknown): value is AuthSettingValue {
|
|
573
|
+
return (
|
|
574
|
+
typeof value === "string" ||
|
|
575
|
+
typeof value === "number" ||
|
|
576
|
+
typeof value === "boolean" ||
|
|
577
|
+
(Array.isArray(value) && value.every((item): item is string => typeof item === "string"))
|
|
578
|
+
)
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function walk(node: unknown, path: string[], out: FlatAuthSettings): void {
|
|
582
|
+
const key = path.join(".")
|
|
583
|
+
if (LEAF_PATHS.has(key)) {
|
|
584
|
+
if (isAuthSettingValue(node)) out[key] = node
|
|
585
|
+
return
|
|
586
|
+
}
|
|
587
|
+
if (!isObject(node)) return
|
|
588
|
+
for (const [name, child] of Object.entries(node)) walk(child, [...path, name], out)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* The settings as one leaf per setting. A provider that is listed always gets an explicit `enabled`
|
|
593
|
+
* (true unless it says otherwise), so enabling or disabling it is a leaf that a layer can set or
|
|
594
|
+
* mask. Secret references are not leaves: secrets are stored apart, by {@link AuthSecretRef.key}.
|
|
595
|
+
*/
|
|
596
|
+
export function flattenAuthSettings(settings: AuthSettings): FlatAuthSettings {
|
|
597
|
+
const out: FlatAuthSettings = {}
|
|
598
|
+
walk(settings, [], out)
|
|
599
|
+
for (const name of AUTH_PROVIDER_NAMES) {
|
|
600
|
+
const provider = settings.auth?.providers?.[name]
|
|
601
|
+
if (provider !== undefined) out[`auth.providers.${name}.enabled`] = provider.enabled ?? true
|
|
602
|
+
}
|
|
603
|
+
for (const name of AUTH_HOOK_NAMES) {
|
|
604
|
+
const hook = settings.auth?.hooks?.[name]
|
|
605
|
+
if (hook !== undefined) out[`auth.hooks.${name}.enabled`] = hook.enabled ?? true
|
|
606
|
+
}
|
|
607
|
+
return out
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Whether a tree built from {@link LEAF_PATHS} alone has the {@link AuthSettings} shape. It does:
|
|
612
|
+
* those paths are the settings' own leaves, and each value arrived typed by {@link AuthSettingValue}.
|
|
613
|
+
*/
|
|
614
|
+
function isLeafTree(_tree: object): _tree is AuthSettings {
|
|
615
|
+
return true
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** The inverse of {@link flattenAuthSettings}. Paths that are not settings are ignored. */
|
|
619
|
+
export function unflattenAuthSettings(flat: Readonly<FlatAuthSettings>): AuthSettings {
|
|
620
|
+
const root: Record<string, unknown> = {}
|
|
621
|
+
for (const [path, value] of Object.entries(flat)) {
|
|
622
|
+
if (!LEAF_PATHS.has(path)) continue
|
|
623
|
+
const parts = path.split(".")
|
|
624
|
+
const last = parts.pop()
|
|
625
|
+
if (last === undefined) continue
|
|
626
|
+
let node = root
|
|
627
|
+
for (const part of parts) {
|
|
628
|
+
const next = node[part]
|
|
629
|
+
node = isObject(next) ? next : (node[part] = {})
|
|
630
|
+
}
|
|
631
|
+
node[last] = value
|
|
632
|
+
}
|
|
633
|
+
return isLeafTree(root) ? root : {}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Whether `raw` is an {@link AuthSettings}: it is once validation found no problem. */
|
|
637
|
+
function passedValidation(_raw: unknown, problems: readonly string[]): _raw is AuthSettings {
|
|
638
|
+
return problems.length === 0
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** The settings narrowed to {@link AuthSettings} when they pass {@link validateAuthSettings}, else the problems. */
|
|
642
|
+
export function parseAuthSettings(
|
|
643
|
+
raw: unknown,
|
|
644
|
+
target: AuthTarget,
|
|
645
|
+
): { ok: true; settings: AuthSettings } | { ok: false; problems: string[] } {
|
|
646
|
+
const problems = validateAuthSettings(raw, target)
|
|
647
|
+
// Validation has checked every field this type has, so the shape is known to hold.
|
|
648
|
+
return passedValidation(raw, problems) ? { ok: true, settings: raw } : { ok: false, problems }
|
|
649
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one rule for the name of a function secret (an environment variable of an edge function),
|
|
3
|
+
* shared by the CLI, Studio, the self-host server and the cloud control plane (decision D-65):
|
|
4
|
+
* letters, digits and underscore, not starting with a digit. The server layers repeat the message
|
|
5
|
+
* text exactly, so a refusal reads the same wherever it is raised.
|
|
6
|
+
*/
|
|
7
|
+
export const FUNCTION_SECRET_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
8
|
+
|
|
9
|
+
/** The rule in words, as the tail of every refusal. */
|
|
10
|
+
export const FUNCTION_SECRET_NAME_RULE = "use letters, digits and underscore, and do not start with a digit."
|
|
11
|
+
|
|
12
|
+
/** Whether `name` may name a function secret. */
|
|
13
|
+
export function isFunctionSecretName(name: string): boolean {
|
|
14
|
+
return FUNCTION_SECRET_NAME_PATTERN.test(name)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Why `name` is not a function secret name, or undefined when it is one. */
|
|
18
|
+
export function functionSecretNameProblem(name: string): string | undefined {
|
|
19
|
+
if (isFunctionSecretName(name)) return undefined
|
|
20
|
+
return `"${name}" is not a valid secret name: ${FUNCTION_SECRET_NAME_RULE}`
|
|
21
|
+
}
|