@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.
Files changed (45) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +23 -15
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +19 -1
  5. package/dist/auth-settings-groups.d.ts +216 -0
  6. package/dist/auth-settings-groups.d.ts.map +1 -0
  7. package/dist/auth-settings-groups.js +424 -0
  8. package/dist/auth-settings-groups.js.map +1 -0
  9. package/dist/auth-settings.d.ts +168 -0
  10. package/dist/auth-settings.d.ts.map +1 -0
  11. package/dist/auth-settings.js +501 -0
  12. package/dist/auth-settings.js.map +1 -0
  13. package/dist/function-secret-name.d.ts +14 -0
  14. package/dist/function-secret-name.d.ts.map +1 -0
  15. package/dist/function-secret-name.js +20 -0
  16. package/dist/function-secret-name.js.map +1 -0
  17. package/dist/index.d.ts +145 -3
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +5 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/public-env.d.ts +70 -0
  22. package/dist/public-env.d.ts.map +1 -0
  23. package/dist/public-env.js +146 -0
  24. package/dist/public-env.js.map +1 -0
  25. package/dist/seed-contract.d.ts +103 -0
  26. package/dist/seed-contract.d.ts.map +1 -0
  27. package/dist/seed-contract.js +99 -0
  28. package/dist/seed-contract.js.map +1 -0
  29. package/package.json +1 -1
  30. package/src/auth-settings-groups.ts +604 -0
  31. package/src/auth-settings.ts +649 -0
  32. package/src/function-secret-name.ts +21 -0
  33. package/src/index.ts +176 -2
  34. package/src/public-env.ts +167 -0
  35. package/src/seed-contract.ts +167 -0
  36. package/tests/auth-settings-groups.test.ts +342 -0
  37. package/tests/auth-settings.test.ts +327 -0
  38. package/tests/bucket-access.test.ts +33 -1
  39. package/tests/channel.test.ts +94 -0
  40. package/tests/function-secret-name.test.ts +17 -0
  41. package/tests/public-env.test.ts +179 -0
  42. package/tests/seed-contract.test.ts +110 -0
  43. package/tests/standalone-build.test.ts +35 -0
  44. package/tsconfig.json +2 -1
  45. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,604 @@
1
+ /**
2
+ * The auth settings beyond sign-in basics: hooks, attack protection, sessions, MFA, phone sign-in,
3
+ * anonymous sign-in, rate limits and SAML enablement.
4
+ *
5
+ * Each setting is one row in a table (its config path, the variable the auth server reads, its kind
6
+ * and its value when nothing is set), and everything else is derived from the table: the leaf paths a
7
+ * Studio layer can save, the variables the renderers own, validation, and both renderings. A new
8
+ * setting is a new row.
9
+ *
10
+ * Two renderings, for two hosts:
11
+ * - {@link groupsEnv} writes every variable, with a default for one that is not set. Cloud reloads the
12
+ * file into a running server, which can set a variable but never unset it, so a removed setting
13
+ * has to come back as its default.
14
+ * - {@link groupsSelfHostVars} writes only what the config states, so a config that sets none of
15
+ * these renders exactly what it did before they existed.
16
+ *
17
+ * Pure types and pure functions: no I/O, no Node imports.
18
+ */
19
+
20
+ import type { AuthRenderContext, AuthSettings, AuthTarget, EnvReference } from "./auth-settings.js"
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Shapes (the `auth` section of supatype.config.ts)
24
+ // ---------------------------------------------------------------------------
25
+
26
+ export const AUTH_HOOK_NAMES = [
27
+ "customAccessToken",
28
+ "beforeUserCreated",
29
+ "afterUserCreated",
30
+ "mfaVerificationAttempt",
31
+ "passwordVerificationAttempt",
32
+ "sendEmail",
33
+ "sendSms",
34
+ ] as const
35
+
36
+ export type AuthHookName = (typeof AUTH_HOOK_NAMES)[number]
37
+
38
+ /** The part of each hook's variable names between `SUPATYPE_HOOK_` and the suffix. */
39
+ const HOOK_ENV_SEGMENT: Readonly<Record<AuthHookName, string>> = {
40
+ customAccessToken: "CUSTOM_ACCESS_TOKEN",
41
+ beforeUserCreated: "BEFORE_USER_CREATED",
42
+ afterUserCreated: "AFTER_USER_CREATED",
43
+ mfaVerificationAttempt: "MFA_VERIFICATION_ATTEMPT",
44
+ passwordVerificationAttempt: "PASSWORD_VERIFICATION_ATTEMPT",
45
+ sendEmail: "SEND_EMAIL",
46
+ sendSms: "SEND_SMS",
47
+ }
48
+
49
+ export interface AuthHookSettings {
50
+ /** Default true: listing a hook is asking for it. False keeps the settings and turns it off. */
51
+ enabled?: boolean
52
+ /**
53
+ * Where the server calls: an https URL (a project edge function's URL works), or a Postgres
54
+ * function as `pg-functions://postgres/<schema>/<function>`.
55
+ */
56
+ uri?: string
57
+ /** `env("NAME")`: the Standard Webhooks signing secret(s), `v1,whsec_...`, pipe-separated for rotation. */
58
+ secrets?: EnvReference
59
+ }
60
+
61
+ export type AuthHooksSettings = Partial<Record<AuthHookName, AuthHookSettings>>
62
+
63
+ /** The character classes a password can be required to contain. */
64
+ export const PASSWORD_CHARACTER_CLASSES = ["lower", "upper", "digit", "symbol"] as const
65
+
66
+ export type PasswordCharacterClass = (typeof PASSWORD_CHARACTER_CLASSES)[number]
67
+
68
+ export const SMS_PROVIDERS = ["twilio", "twilio_verify", "messagebird", "textlocal", "vonage"] as const
69
+
70
+ export type SmsProviderName = (typeof SMS_PROVIDERS)[number]
71
+
72
+ export const CAPTCHA_PROVIDERS = ["hcaptcha", "turnstile"] as const
73
+
74
+ export interface AuthGroupSettings {
75
+ hooks?: AuthHooksSettings
76
+ /**
77
+ * Bot protection on sign-up, sign-in and recovery. The secret is the provider's server-side key.
78
+ * The site key is the provider's public one: the server's public settings answer hands it to Studio
79
+ * and to apps, which render the provider's widget and send its token with the sign-in.
80
+ */
81
+ captcha?: { enabled?: boolean; provider?: (typeof CAPTCHA_PROVIDERS)[number]; secret?: EnvReference; siteKey?: string }
82
+ password?: {
83
+ /** Shortest password accepted, 6 to 72. */
84
+ minLength?: number
85
+ /** Classes every password must hold at least one character of. */
86
+ requiredCharacters?: PasswordCharacterClass[]
87
+ /** Refuse a password found in a known breach (Have I Been Pwned, by k-anonymity range). */
88
+ leakedPasswordCheck?: boolean
89
+ }
90
+ /** Session lifetimes are in seconds. Unset is no limit. */
91
+ sessions?: { timebox?: number; inactivityTimeout?: number; singlePerUser?: boolean }
92
+ security?: {
93
+ /** Default true: each refresh issues a new refresh token and retires the old one. */
94
+ refreshTokenRotation?: boolean
95
+ /** Seconds an already-used refresh token still works, for clients that retry. Default 0. */
96
+ refreshTokenReuseInterval?: number
97
+ updatePasswordRequireReauthentication?: boolean
98
+ updatePasswordRequireCurrentPassword?: boolean
99
+ /** Let a signed-in user link another identity to their account. */
100
+ manualLinking?: boolean
101
+ }
102
+ mfa?: {
103
+ /** Authenticator-app factors. Both default true. */
104
+ totp?: { enroll?: boolean; verify?: boolean }
105
+ /** SMS factors. Both default false; they need a phone provider. */
106
+ phone?: { enroll?: boolean; verify?: boolean }
107
+ maxEnrolledFactors?: number
108
+ maxVerifiedFactors?: number
109
+ }
110
+ anonymous?: { enabled?: boolean }
111
+ /** Sign-in by phone number, and the SMS provider that sends the codes. Credentials are secrets. */
112
+ phone?: {
113
+ enabled?: boolean
114
+ provider?: SmsProviderName
115
+ /** Digits in a code, 6 to 10. */
116
+ otpLength?: number
117
+ /** Seconds a code stays valid. */
118
+ otpExpiry?: number
119
+ /** Seconds before another code may be sent to the same number. */
120
+ maxFrequency?: number
121
+ twilio?: { accountSid?: string; authToken?: EnvReference; messageServiceSid?: string; contentSid?: string }
122
+ twilioVerify?: { accountSid?: string; authToken?: EnvReference; messageServiceSid?: string }
123
+ messagebird?: { accessKey?: EnvReference; originator?: string }
124
+ textlocal?: { apiKey?: EnvReference; sender?: string }
125
+ vonage?: { apiKey?: string; apiSecret?: EnvReference; from?: string }
126
+ }
127
+ /**
128
+ * Requests one client may make in a window that depends on the limit: 5 minutes for `otp`,
129
+ * `tokenRefresh`, `verify` and `sso`, an hour for `smsSent` and `anonymousUsers`, and a minute for
130
+ * `mfa` (challenges and verifies together). The email limit is the platform's on Cloud and is not here.
131
+ */
132
+ rateLimits?: {
133
+ otp?: number
134
+ tokenRefresh?: number
135
+ verify?: number
136
+ smsSent?: number
137
+ anonymousUsers?: number
138
+ sso?: number
139
+ mfa?: number
140
+ }
141
+ /** SAML single sign-on. The signing key is the platform's on Cloud; on self-host the CLI keeps it in `.env`. */
142
+ sso?: {
143
+ saml?: { enabled?: boolean; allowEncryptedAssertions?: boolean; relayStateValidity?: number; rateLimitAssertion?: number }
144
+ }
145
+ }
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // The table
149
+ // ---------------------------------------------------------------------------
150
+
151
+ type SpecKind = "flag" | "count" | "seconds" | "text" | "choice" | "list"
152
+
153
+ interface Spec {
154
+ /** Under `auth`, as dotted keys. */
155
+ path: string
156
+ env: string
157
+ kind: SpecKind
158
+ /** What the server runs with when the setting is not set, as the variable's text. */
159
+ fallback: string
160
+ /**
161
+ * What the server actually runs with when the fallback it is sent is a 0 that means "use your own
162
+ * default". The values mirror supatype-auth internal/conf (configuration.go and saml.go), which
163
+ * replace those zeros at load. In the setting's own unit (seconds for a duration).
164
+ */
165
+ effective?: string
166
+ min?: number
167
+ max?: number
168
+ choices?: readonly string[]
169
+ /** False: not rendered by the self-host path, which has its own handling (SAML). Default true. */
170
+ selfHost?: boolean
171
+ }
172
+
173
+ /**
174
+ * Written for an unset session lifetime. The server cannot be told "none" in a reloaded file (an empty
175
+ * duration does not parse and zero is refused), so none is a hundred years.
176
+ */
177
+ const NO_SESSION_LIMIT = "876000h"
178
+
179
+ const CHARACTER_SETS: Readonly<Record<PasswordCharacterClass, string>> = {
180
+ lower: "abcdefghijklmnopqrstuvwxyz",
181
+ upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
182
+ digit: "0123456789",
183
+ // No $ { } \ " ' or : here: the compose file and the server's separator cannot carry them.
184
+ symbol: "!@#%^&*()_+-=[];<>?,./~|`",
185
+ }
186
+
187
+ const flag = (path: string, env: string, fallback: boolean): Spec => ({ path, env, kind: "flag", fallback: String(fallback) })
188
+ const count = (path: string, env: string, fallback: string, min: number, max?: number): Spec => ({
189
+ path,
190
+ env,
191
+ kind: "count",
192
+ fallback,
193
+ min,
194
+ ...(max !== undefined && { max }),
195
+ })
196
+ const text = (path: string, env: string): Spec => ({ path, env, kind: "text", fallback: "" })
197
+
198
+ const HOOK_SPECS: readonly Spec[] = AUTH_HOOK_NAMES.map((name) => text(`hooks.${name}.uri`, `SUPATYPE_HOOK_${HOOK_ENV_SEGMENT[name]}_URI`))
199
+
200
+ const SPECS: readonly Spec[] = [
201
+ ...HOOK_SPECS,
202
+ flag("captcha.enabled", "SUPATYPE_SECURITY_CAPTCHA_ENABLED", false),
203
+ { path: "captcha.provider", env: "SUPATYPE_SECURITY_CAPTCHA_PROVIDER", kind: "choice", fallback: "hcaptcha", choices: CAPTCHA_PROVIDERS },
204
+ text("captcha.siteKey", "SUPATYPE_SECURITY_CAPTCHA_SITE_KEY"),
205
+ { ...count("password.minLength", "SUPATYPE_PASSWORD_MIN_LENGTH", "0", 6, 72), effective: "6" },
206
+ { path: "password.requiredCharacters", env: "SUPATYPE_PASSWORD_REQUIRED_CHARACTERS", kind: "list", fallback: "" },
207
+ flag("password.leakedPasswordCheck", "SUPATYPE_PASSWORD_HIBP_ENABLED", false),
208
+ { path: "sessions.timebox", env: "SUPATYPE_SESSIONS_TIMEBOX", kind: "seconds", fallback: NO_SESSION_LIMIT, min: 60 },
209
+ { path: "sessions.inactivityTimeout", env: "SUPATYPE_SESSIONS_INACTIVITY_TIMEOUT", kind: "seconds", fallback: NO_SESSION_LIMIT, min: 60 },
210
+ flag("sessions.singlePerUser", "SUPATYPE_SESSIONS_SINGLE_PER_USER", false),
211
+ flag("security.refreshTokenRotation", "SUPATYPE_SECURITY_REFRESH_TOKEN_ROTATION_ENABLED", true),
212
+ count("security.refreshTokenReuseInterval", "SUPATYPE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL", "0", 0, 3600),
213
+ flag("security.updatePasswordRequireReauthentication", "SUPATYPE_SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION", false),
214
+ flag("security.updatePasswordRequireCurrentPassword", "SUPATYPE_SECURITY_UPDATE_PASSWORD_REQUIRE_CURRENT_PASSWORD", false),
215
+ flag("security.manualLinking", "SUPATYPE_SECURITY_MANUAL_LINKING_ENABLED", false),
216
+ flag("mfa.totp.enroll", "SUPATYPE_MFA_TOTP_ENROLL_ENABLED", true),
217
+ flag("mfa.totp.verify", "SUPATYPE_MFA_TOTP_VERIFY_ENABLED", true),
218
+ flag("mfa.phone.enroll", "SUPATYPE_MFA_PHONE_ENROLL_ENABLED", false),
219
+ flag("mfa.phone.verify", "SUPATYPE_MFA_PHONE_VERIFY_ENABLED", false),
220
+ count("mfa.maxEnrolledFactors", "SUPATYPE_MFA_MAX_ENROLLED_FACTORS", "10", 1, 100),
221
+ count("mfa.maxVerifiedFactors", "SUPATYPE_MFA_MAX_VERIFIED_FACTORS", "10", 1, 100),
222
+ flag("anonymous.enabled", "SUPATYPE_EXTERNAL_ANONYMOUS_USERS_ENABLED", false),
223
+ flag("phone.enabled", "SUPATYPE_EXTERNAL_PHONE_ENABLED", false),
224
+ { path: "phone.provider", env: "SUPATYPE_SMS_PROVIDER", kind: "choice", fallback: "", choices: SMS_PROVIDERS },
225
+ { ...count("phone.otpLength", "SUPATYPE_SMS_OTP_LENGTH", "0", 6, 10), effective: "6" },
226
+ { ...count("phone.otpExpiry", "SUPATYPE_SMS_OTP_EXP", "0", 1, 86400), effective: "60" },
227
+ { path: "phone.maxFrequency", env: "SUPATYPE_SMS_MAX_FREQUENCY", kind: "seconds", fallback: "0s", effective: "60", min: 1 },
228
+ text("phone.twilio.accountSid", "SUPATYPE_SMS_TWILIO_ACCOUNT_SID"),
229
+ text("phone.twilio.messageServiceSid", "SUPATYPE_SMS_TWILIO_MESSAGE_SERVICE_SID"),
230
+ text("phone.twilio.contentSid", "SUPATYPE_SMS_TWILIO_CONTENT_SID"),
231
+ text("phone.twilioVerify.accountSid", "SUPATYPE_SMS_TWILIO_VERIFY_ACCOUNT_SID"),
232
+ text("phone.twilioVerify.messageServiceSid", "SUPATYPE_SMS_TWILIO_VERIFY_MESSAGE_SERVICE_SID"),
233
+ text("phone.messagebird.originator", "SUPATYPE_SMS_MESSAGEBIRD_ORIGINATOR"),
234
+ text("phone.textlocal.sender", "SUPATYPE_SMS_TEXTLOCAL_SENDER"),
235
+ text("phone.vonage.apiKey", "SUPATYPE_SMS_VONAGE_API_KEY"),
236
+ text("phone.vonage.from", "SUPATYPE_SMS_VONAGE_FROM"),
237
+ count("rateLimits.otp", "SUPATYPE_RATE_LIMIT_OTP", "30", 1, 100000),
238
+ count("rateLimits.tokenRefresh", "SUPATYPE_RATE_LIMIT_TOKEN_REFRESH", "150", 1, 100000),
239
+ count("rateLimits.verify", "SUPATYPE_RATE_LIMIT_VERIFY", "30", 1, 100000),
240
+ count("rateLimits.smsSent", "SUPATYPE_RATE_LIMIT_SMS_SENT", "30", 1, 100000),
241
+ count("rateLimits.anonymousUsers", "SUPATYPE_RATE_LIMIT_ANONYMOUS_USERS", "30", 1, 100000),
242
+ count("rateLimits.sso", "SUPATYPE_RATE_LIMIT_SSO", "30", 1, 100000),
243
+ count("rateLimits.mfa", "SUPATYPE_MFA_RATE_LIMIT_CHALLENGE_AND_VERIFY", "15", 1, 100000),
244
+ { ...flag("sso.saml.enabled", "SUPATYPE_SAML_ENABLED", false), selfHost: false },
245
+ { ...flag("sso.saml.allowEncryptedAssertions", "SUPATYPE_SAML_ALLOW_ENCRYPTED_ASSERTIONS", false), selfHost: false },
246
+ { path: "sso.saml.relayStateValidity", env: "SUPATYPE_SAML_RELAY_STATE_VALIDITY_PERIOD", kind: "seconds", fallback: "0s", effective: "120", min: 1, selfHost: false },
247
+ { ...count("sso.saml.rateLimitAssertion", "SUPATYPE_SAML_RATE_LIMIT_ASSERTION", "15", 1, 100000), selfHost: false },
248
+ ]
249
+
250
+ /** What a setting's default looks like to a person: a number, a switch, a choice, or null for none. */
251
+ export type GroupDefault = string | number | boolean | null
252
+
253
+ /**
254
+ * What the server runs with for a setting nothing sets, by its saved path (`auth.rateLimits.otp`):
255
+ * a number for a count or a duration in seconds, a boolean for a switch, the name of a choice, or
256
+ * null when there is none (no session limit, no provider, no hook). Undefined for a path this table
257
+ * does not hold. This is the value in force, so a fallback the server raises (a minimum length of 0
258
+ * becomes 6) reports what it is raised to.
259
+ */
260
+ export function groupDefault(path: string): GroupDefault | undefined {
261
+ const spec = SPEC_BY_PATH.get(path.startsWith("auth.") ? path.slice("auth.".length) : path)
262
+ if (spec === undefined) return undefined
263
+ const text = spec.effective ?? spec.fallback
264
+ switch (spec.kind) {
265
+ case "flag":
266
+ return text === "true"
267
+ case "count":
268
+ return Number(text)
269
+ case "seconds":
270
+ return text === NO_SESSION_LIMIT ? null : Number.parseInt(text, 10)
271
+ case "choice":
272
+ case "text":
273
+ case "list":
274
+ return text === "" ? null : text
275
+ default: {
276
+ const unhandled: never = spec.kind
277
+ return unhandled
278
+ }
279
+ }
280
+ }
281
+
282
+ /** A setting that is a secret: the config holds `env("NAME")`, the platform holds the value. */
283
+ interface SecretSpec {
284
+ /** The secret's key, as {@link AuthSecretRef.key} carries it. */
285
+ key: string
286
+ /** Under `auth`, where the `env("NAME")` sits. */
287
+ path: string
288
+ /**
289
+ * The variable the group renderers write. Absent for a held secret: one the settings never state as
290
+ * a reference under `auth` (the mail section's) and whose variable the mail renderer writes.
291
+ */
292
+ env?: string
293
+ /** Whether the settings use the secret: a stored one that nothing uses is not rendered. */
294
+ active: (settings: AuthSettings) => boolean
295
+ /** True when the feature cannot work without it. */
296
+ required: (settings: AuthSettings) => boolean
297
+ }
298
+
299
+ /** A secret the group renderers own: it has a variable of its own. */
300
+ type OwnedSecretSpec = SecretSpec & { env: string }
301
+
302
+ function isObject(value: unknown): value is Record<string, unknown> {
303
+ return typeof value === "object" && value !== null && !Array.isArray(value)
304
+ }
305
+
306
+ /** The value at a dotted path, or undefined. */
307
+ function at(node: unknown, path: string): unknown {
308
+ return path.split(".").reduce<unknown>((current, key) => (isObject(current) ? current[key] : undefined), node)
309
+ }
310
+
311
+ const providerIs =
312
+ (name: SmsProviderName) =>
313
+ (settings: AuthSettings): boolean =>
314
+ at(settings.auth, "phone.provider") === name
315
+
316
+ const mailProviderIs =
317
+ (name: string) =>
318
+ (settings: AuthSettings): boolean =>
319
+ settings.email?.provider === name
320
+
321
+ /** A mail secret the platform holds: never a stored reference, and rendered by the mail variables. */
322
+ function sesSecret(key: string): SecretSpec {
323
+ return { key, path: key, active: mailProviderIs("ses"), required: mailProviderIs("ses") }
324
+ }
325
+
326
+ const HOOK_SECRETS: readonly SecretSpec[] = AUTH_HOOK_NAMES.map((name) => ({
327
+ key: `hooks.${name}.secrets`,
328
+ path: `hooks.${name}.secrets`,
329
+ env: `SUPATYPE_HOOK_${HOOK_ENV_SEGMENT[name]}_SECRETS`,
330
+ active: (settings) => isObject(at(settings.auth, `hooks.${name}`)),
331
+ required: () => false,
332
+ }))
333
+
334
+ const SECRET_SPECS: readonly SecretSpec[] = [
335
+ ...HOOK_SECRETS,
336
+ {
337
+ key: "captcha.secret",
338
+ path: "captcha.secret",
339
+ env: "SUPATYPE_SECURITY_CAPTCHA_SECRET",
340
+ active: (settings) => at(settings.auth, "captcha.enabled") === true,
341
+ required: (settings) => at(settings.auth, "captcha.enabled") === true,
342
+ },
343
+ smsSecret("phone.twilio.authToken", "SUPATYPE_SMS_TWILIO_AUTH_TOKEN", "twilio"),
344
+ smsSecret("phone.twilioVerify.authToken", "SUPATYPE_SMS_TWILIO_VERIFY_AUTH_TOKEN", "twilio_verify"),
345
+ smsSecret("phone.messagebird.accessKey", "SUPATYPE_SMS_MESSAGEBIRD_ACCESS_KEY", "messagebird"),
346
+ smsSecret("phone.textlocal.apiKey", "SUPATYPE_SMS_TEXTLOCAL_API_KEY", "textlocal"),
347
+ smsSecret("phone.vonage.apiSecret", "SUPATYPE_SMS_VONAGE_API_SECRET", "vonage"),
348
+ sesSecret("email.ses_access_key_id"),
349
+ sesSecret("email.ses_secret_access_key"),
350
+ ]
351
+
352
+ /** The secrets with a variable of their own, which the group renderers and validation handle. */
353
+ const OWNED_SECRET_SPECS: readonly OwnedSecretSpec[] = SECRET_SPECS.filter((s): s is OwnedSecretSpec => s.env !== undefined)
354
+
355
+ function smsSecret(key: string, env: string, provider: SmsProviderName): SecretSpec {
356
+ return { key, path: key, env, active: providerIs(provider), required: providerIs(provider) }
357
+ }
358
+
359
+ /** The key the platform generates and holds for a project's SAML service provider. Never settable or shown. */
360
+ export const SAML_PRIVATE_KEY_SECRET = "sso.saml.private_key"
361
+ const SAML_PRIVATE_KEY_ENV = "SUPATYPE_SAML_PRIVATE_KEY"
362
+ /**
363
+ * The key a rotation moves to, held beside the current one while identity providers take its
364
+ * certificate: the server publishes both and decrypts with either. Made and promoted by the platform,
365
+ * never settable or shown, as the current key is.
366
+ */
367
+ export const SAML_NEXT_PRIVATE_KEY_SECRET = "sso.saml.next_private_key"
368
+ const SAML_NEXT_PRIVATE_KEY_ENV = "SUPATYPE_SAML_NEXT_PRIVATE_KEY"
369
+ const SAML_EXTERNAL_URL_ENV = "SUPATYPE_SAML_EXTERNAL_URL"
370
+
371
+ // ---------------------------------------------------------------------------
372
+ // What the rest of the model reads from the table
373
+ // ---------------------------------------------------------------------------
374
+
375
+ /** Every variable the group renderers write. */
376
+ export const GROUP_OWNED_KEYS: readonly string[] = [
377
+ ...SPECS.map((s) => s.env),
378
+ ...AUTH_HOOK_NAMES.map((name) => `SUPATYPE_HOOK_${HOOK_ENV_SEGMENT[name]}_ENABLED`),
379
+ ...OWNED_SECRET_SPECS.map((s) => s.env),
380
+ SAML_PRIVATE_KEY_ENV,
381
+ SAML_NEXT_PRIVATE_KEY_ENV,
382
+ SAML_EXTERNAL_URL_ENV,
383
+ ]
384
+
385
+ /**
386
+ * The variables the server reads once, when it starts: its rate limiters are kept across a reload, so
387
+ * a changed value reaches a running server only when it restarts.
388
+ */
389
+ export const GROUP_RESTART_KEYS: readonly string[] = SPECS.filter(
390
+ (s) => s.path.startsWith("rateLimits.") || s.path === "sso.saml.rateLimitAssertion",
391
+ ).map((s) => s.env)
392
+
393
+ /** The paths a layer can save, as `auth.<path>`. */
394
+ export const GROUP_LEAF_PATHS: readonly string[] = [
395
+ ...SPECS.map((s) => `auth.${s.path}`),
396
+ ...AUTH_HOOK_NAMES.map((name) => `auth.hooks.${name}.enabled`),
397
+ ]
398
+
399
+ /** Every secret key a project can set. */
400
+ export const GROUP_SECRET_KEYS: readonly string[] = SECRET_SPECS.map((s) => s.key)
401
+
402
+ /** The secrets the settings point at with `env("NAME")`: `[key, name]`. */
403
+ export function groupSecretRefs(settings: AuthSettings): { key: string; value: string | undefined }[] {
404
+ return OWNED_SECRET_SPECS.map((s) => {
405
+ const value = at(settings.auth, s.path)
406
+ return { key: s.key, value: typeof value === "string" ? value : undefined }
407
+ })
408
+ }
409
+
410
+ /** Whether the settings use the secret `key`, among the group secrets and the platform's SAML key. */
411
+ export function groupSecretInUse(settings: AuthSettings, key: string): boolean | undefined {
412
+ if (key === SAML_PRIVATE_KEY_SECRET || key === SAML_NEXT_PRIVATE_KEY_SECRET) return at(settings.auth, "sso.saml.enabled") === true
413
+ const spec = SECRET_SPECS.find((s) => s.key === key)
414
+ return spec === undefined ? undefined : spec.active(settings)
415
+ }
416
+
417
+ /**
418
+ * Secrets the settings cannot work without, by key: an enabled CAPTCHA's key, the chosen SMS
419
+ * provider's credential, and the project's own AWS keys when SES sends the mail.
420
+ */
421
+ export function groupRequiredSecretKeys(settings: AuthSettings): string[] {
422
+ return SECRET_SPECS.filter((s) => s.required(settings)).map((s) => s.key)
423
+ }
424
+
425
+ /** A rule on a secret's value beyond non-empty, or undefined when it holds. Hook secrets are Standard Webhooks keys. */
426
+ export function groupSecretFormatProblem(key: string, value: string): string | undefined {
427
+ if (!key.startsWith("hooks.")) return undefined
428
+ const entries = value.split("|").filter((entry) => entry !== "")
429
+ const symmetric = /^v1,whsec_[A-Za-z0-9+/=]{32,88}$/
430
+ const asymmetric = /^v1a,whpk_[A-Za-z0-9+/=]{44,}:whsk_[A-Za-z0-9+/=]{44,}$/
431
+ const bad = entries.length === 0 || entries.some((entry) => !symmetric.test(entry) && !asymmetric.test(entry))
432
+ return bad ? `${key} must be v1,whsec_... (32 to 88 base64 characters), or v1a,whpk_...:whsk_..., separated by | for several` : undefined
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Rendering
437
+ // ---------------------------------------------------------------------------
438
+
439
+ /** One setting's value as the variable's text. */
440
+ function renderValue(spec: Spec, value: unknown): string {
441
+ if (spec.kind === "seconds") return `${String(value)}s`
442
+ if (spec.kind === "text") return typeof value === "string" ? value.trim() : ""
443
+ if (spec.kind === "list") {
444
+ const classes = Array.isArray(value) ? value : []
445
+ return PASSWORD_CHARACTER_CLASSES.filter((c) => classes.includes(c))
446
+ .map((c) => CHARACTER_SETS[c])
447
+ .join(":")
448
+ }
449
+ return String(value)
450
+ }
451
+
452
+ /** The variable's text for a spec when the settings set it, else undefined. */
453
+ function stated(auth: unknown, spec: Spec): string | undefined {
454
+ const value = at(auth, spec.path)
455
+ return value === undefined ? undefined : renderValue(spec, value)
456
+ }
457
+
458
+ function hookConfigured(auth: unknown, name: AuthHookName): boolean {
459
+ return isObject(at(auth, `hooks.${name}`))
460
+ }
461
+
462
+ function hookEnabled(auth: unknown, name: AuthHookName): string {
463
+ const enabled = at(auth, `hooks.${name}.enabled`)
464
+ return String(typeof enabled === "boolean" ? enabled : hookConfigured(auth, name))
465
+ }
466
+
467
+ /**
468
+ * Every group variable, explicit: a default for each setting that is not set, a secret's value from
469
+ * `ctx.secrets` when the settings use it and empty otherwise. SAML is only on when its key is held.
470
+ */
471
+ export function groupsEnv(settings: AuthSettings, ctx: AuthRenderContext): Record<string, string> {
472
+ const auth = settings.auth
473
+ const env: Record<string, string> = {}
474
+ for (const spec of SPECS) env[spec.env] = stated(auth, spec) ?? spec.fallback
475
+ for (const name of AUTH_HOOK_NAMES) env[`SUPATYPE_HOOK_${HOOK_ENV_SEGMENT[name]}_ENABLED`] = hookEnabled(auth, name)
476
+ for (const secret of OWNED_SECRET_SPECS) env[secret.env] = secret.active(settings) ? (ctx.secrets[secret.key] ?? "") : ""
477
+ const key = ctx.secrets[SAML_PRIVATE_KEY_SECRET] ?? ""
478
+ const samlOn = at(auth, "sso.saml.enabled") === true && key !== ""
479
+ env["SUPATYPE_SAML_ENABLED"] = String(samlOn)
480
+ env[SAML_PRIVATE_KEY_ENV] = samlOn ? key : ""
481
+ env[SAML_NEXT_PRIVATE_KEY_ENV] = samlOn ? (ctx.secrets[SAML_NEXT_PRIVATE_KEY_SECRET] ?? "") : ""
482
+ env[SAML_EXTERNAL_URL_ENV] = samlOn ? (ctx.samlExternalUrl ?? "") : ""
483
+ return env
484
+ }
485
+
486
+ /** A variable for the self-host path: a literal, or the name of the variable that holds the value. */
487
+ export type SelfHostVar = { key: string; value: string } | { key: string; fromEnv: string }
488
+
489
+ /**
490
+ * Only what the settings state, for the self-host compose file and native dev. A secret is the name of
491
+ * the variable holding it. SAML is left to the CLI, which keeps its signing key in `.env`.
492
+ */
493
+ export function groupsSelfHostVars(settings: AuthSettings): SelfHostVar[] {
494
+ const auth = settings.auth
495
+ const out: SelfHostVar[] = []
496
+ for (const spec of SPECS) {
497
+ const value = spec.selfHost === false ? undefined : stated(auth, spec)
498
+ if (value !== undefined) out.push({ key: spec.env, value })
499
+ }
500
+ for (const name of AUTH_HOOK_NAMES) {
501
+ if (hookConfigured(auth, name)) out.push({ key: `SUPATYPE_HOOK_${HOOK_ENV_SEGMENT[name]}_ENABLED`, value: hookEnabled(auth, name) })
502
+ }
503
+ for (const secret of OWNED_SECRET_SPECS) {
504
+ const value = at(auth, secret.path)
505
+ const name = typeof value === "string" ? /^env\(([A-Za-z_][A-Za-z0-9_]*)\)$/.exec(value.trim())?.[1] : undefined
506
+ if (name !== undefined) out.push({ key: secret.env, fromEnv: name })
507
+ }
508
+ return out
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // Validation
513
+ // ---------------------------------------------------------------------------
514
+
515
+ const GROUP_KEYS = ["hooks", "captcha", "password", "sessions", "security", "mfa", "anonymous", "phone", "rateLimits", "sso"]
516
+
517
+ /** What a value written into the compose file's `"${KEY:-...}"` or an env file cannot carry. */
518
+ const UNSAFE_TEXT = /[$"'{}\\\u0000-\u001f\u007f]/
519
+
520
+ const SPEC_BY_PATH: ReadonlyMap<string, Spec> = new Map(SPECS.map((s) => [s.path, s]))
521
+ const SECRET_BY_PATH: ReadonlyMap<string, SecretSpec> = new Map(OWNED_SECRET_SPECS.map((s) => [s.path, s]))
522
+ const HOOK_ENABLED_PATHS: ReadonlySet<string> = new Set(AUTH_HOOK_NAMES.map((name) => `hooks.${name}.enabled`))
523
+
524
+ /** The names a node at `prefix` may hold, from every path in the table that starts with it. */
525
+ function allowedChildren(prefix: string): string[] {
526
+ const all = [...SPEC_BY_PATH.keys(), ...SECRET_BY_PATH.keys(), ...HOOK_ENABLED_PATHS]
527
+ const names = all.filter((p) => p.startsWith(`${prefix}.`)).map((p) => p.slice(prefix.length + 1).split(".")[0] ?? "")
528
+ return [...new Set(names)]
529
+ }
530
+
531
+ function valueProblem(spec: Spec, value: unknown, path: string): string | undefined {
532
+ switch (spec.kind) {
533
+ case "flag":
534
+ return typeof value === "boolean" ? undefined : `${path} must be true or false`
535
+ case "count":
536
+ case "seconds": {
537
+ const unit = spec.kind === "seconds" ? "a whole number of seconds" : "a whole number"
538
+ const low = spec.min ?? 0
539
+ const ok = typeof value === "number" && Number.isInteger(value) && value >= low && (spec.max === undefined || value <= spec.max)
540
+ const range = spec.max === undefined ? `${low} or more` : `${low} to ${spec.max}`
541
+ return ok ? undefined : `${path} must be ${unit}, ${range}`
542
+ }
543
+ case "choice":
544
+ return typeof value === "string" && (spec.choices ?? []).includes(value) ? undefined : `${path} must be one of ${(spec.choices ?? []).join(", ")}`
545
+ case "list": {
546
+ const ok = Array.isArray(value) && value.every((v) => typeof v === "string" && (PASSWORD_CHARACTER_CLASSES as readonly string[]).includes(v))
547
+ return ok ? undefined : `${path} must be a list of ${PASSWORD_CHARACTER_CLASSES.join(", ")}`
548
+ }
549
+ case "text":
550
+ if (typeof value !== "string" || value.trim() === "") return `${path} must be a non-empty string`
551
+ return UNSAFE_TEXT.test(value) ? `${path} cannot contain $, braces, quotes, backslashes or control characters` : undefined
552
+ }
553
+ }
554
+
555
+ function secretReferenceProblem(value: unknown, path: string): string | undefined {
556
+ if (typeof value !== "string") return `${path} must be env("NAME")`
557
+ if (!/^env\([A-Za-z_][A-Za-z0-9_]*\)$/.test(value.trim())) return `${path} must name an environment variable, not hold the secret: ${path.split(".").pop()}: env("NAME")`
558
+ return undefined
559
+ }
560
+
561
+ function nodeProblems(node: unknown, prefix: string): string[] {
562
+ const path = `auth.${prefix}`
563
+ if (!isObject(node)) return [`${path} must be an object`]
564
+ const known = allowedChildren(prefix)
565
+ const unknown = Object.keys(node).filter((key) => !known.includes(key))
566
+ const found: (string | undefined)[] = unknown.length > 0 ? [`${path} has unknown field(s) ${unknown.join(", ")}. Known fields: ${known.join(", ")}`] : []
567
+ for (const [key, value] of Object.entries(node)) {
568
+ if (!known.includes(key) || value === undefined) continue
569
+ const child = `${prefix}.${key}`
570
+ const spec = SPEC_BY_PATH.get(child)
571
+ if (spec !== undefined) found.push(valueProblem(spec, value, `auth.${child}`))
572
+ else if (SECRET_BY_PATH.has(child)) found.push(secretReferenceProblem(value, `auth.${child}`))
573
+ else if (HOOK_ENABLED_PATHS.has(child)) found.push(typeof value === "boolean" ? undefined : `auth.${child} must be true or false`)
574
+ else found.push(...nodeProblems(value, child))
575
+ }
576
+ return found.filter((p): p is string => p !== undefined)
577
+ }
578
+
579
+ const HTTPS_URL = /^https:\/\/[^\s/?#]+[^\s]*$/
580
+ const LOCAL_HTTP_URL = /^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?([/?#][^\s]*)?$/
581
+ const PG_FUNCTION_URI = /^pg-functions:\/\/[^/\s]*\/[A-Za-z_][A-Za-z0-9_]*\/[A-Za-z_][A-Za-z0-9_]*$/
582
+
583
+ function hookProblems(auth: Record<string, unknown>, target: AuthTarget): string[] {
584
+ const found: string[] = []
585
+ for (const name of AUTH_HOOK_NAMES) {
586
+ const hook = at(auth, `hooks.${name}`)
587
+ if (!isObject(hook)) continue
588
+ const uri = hook["uri"]
589
+ const path = `auth.hooks.${name}`
590
+ if (hook["enabled"] !== false && uri === undefined) found.push(`${path}.uri is required while the hook is enabled`)
591
+ if (typeof uri !== "string") continue
592
+ const local = target === "self-host" && LOCAL_HTTP_URL.test(uri.trim())
593
+ if (!HTTPS_URL.test(uri.trim()) && !PG_FUNCTION_URI.test(uri.trim()) && !local) {
594
+ found.push(`${path}.uri must be an https URL or pg-functions://postgres/<schema>/<function>`)
595
+ }
596
+ }
597
+ return found
598
+ }
599
+
600
+ /** Every problem with the group settings; none when they are fine. */
601
+ export function groupProblems(auth: Record<string, unknown>, target: AuthTarget): string[] {
602
+ const found = GROUP_KEYS.filter((key) => auth[key] !== undefined).flatMap((key) => nodeProblems(auth[key], key))
603
+ return found.length > 0 ? found : hookProblems(auth, target)
604
+ }