@supatype/types 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +101 -0
  26. package/dist/seed-contract.d.ts.map +1 -0
  27. package/dist/seed-contract.js +96 -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 +162 -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 +94 -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,342 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import {
3
+ AUTH_OWNED_KEYS,
4
+ authSecretInUse,
5
+ authSecretRefs,
6
+ authSettingsToEnv,
7
+ flattenAuthSettings,
8
+ isAuthSecretKey,
9
+ isAuthSettingPath,
10
+ unflattenAuthSettings,
11
+ validateAuthSettings,
12
+ type AuthRenderContext,
13
+ type AuthSettings,
14
+ } from "../src/auth-settings.js"
15
+ import {
16
+ SAML_NEXT_PRIVATE_KEY_SECRET,
17
+ SAML_PRIVATE_KEY_SECRET,
18
+ GROUP_LEAF_PATHS,
19
+ GROUP_OWNED_KEYS,
20
+ GROUP_SECRET_KEYS,
21
+ groupDefault,
22
+ groupRequiredSecretKeys,
23
+ groupSecretFormatProblem,
24
+ groupSecretRefs,
25
+ groupsEnv,
26
+ groupsSelfHostVars,
27
+ } from "../src/auth-settings-groups.js"
28
+
29
+ const ctx: AuthRenderContext = {
30
+ callbackBaseUrl: "https://abc.supatype.io",
31
+ siteUrl: "https://abc.supatype.io",
32
+ platformRedirectUrls: [],
33
+ secrets: {},
34
+ }
35
+
36
+ const GOOD_SECRET = "v1,whsec_abcdefghijklmnopqrstuvwxyz01234567"
37
+
38
+ describe("group settings rendering", () => {
39
+ it("writes a default for every group variable when nothing is set, so a removed setting is unset", () => {
40
+ const env = authSettingsToEnv({}, ctx)
41
+ expect(env["SUPATYPE_SECURITY_REFRESH_TOKEN_ROTATION_ENABLED"]).toBe("true")
42
+ expect(env["SUPATYPE_MFA_TOTP_ENROLL_ENABLED"]).toBe("true")
43
+ expect(env["SUPATYPE_RATE_LIMIT_TOKEN_REFRESH"]).toBe("150")
44
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_ENABLED"]).toBe("false")
45
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_URI"]).toBe("")
46
+ expect(env["SUPATYPE_SAML_ENABLED"]).toBe("false")
47
+ for (const key of AUTH_OWNED_KEYS) expect(env[key]).not.toBeUndefined()
48
+ })
49
+
50
+ it("renders an unset session lifetime as a very long one, since a reloaded file cannot unset it", () => {
51
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_SESSIONS_TIMEBOX"]).toBe("876000h")
52
+ const env = authSettingsToEnv({ auth: { sessions: { timebox: 86400, inactivityTimeout: 3600 } } }, ctx)
53
+ expect(env["SUPATYPE_SESSIONS_TIMEBOX"]).toBe("86400s")
54
+ expect(env["SUPATYPE_SESSIONS_INACTIVITY_TIMEOUT"]).toBe("3600s")
55
+ })
56
+
57
+ it("turns a listed hook on, with its secret from the stored secrets", () => {
58
+ const settings: AuthSettings = {
59
+ auth: { hooks: { sendEmail: { uri: "https://fn.example.com/hook", secrets: "env(HOOK)" } } },
60
+ }
61
+ const env = authSettingsToEnv(settings, { ...ctx, secrets: { "hooks.sendEmail.secrets": GOOD_SECRET } })
62
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_ENABLED"]).toBe("true")
63
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_URI"]).toBe("https://fn.example.com/hook")
64
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_SECRETS"]).toBe(GOOD_SECRET)
65
+ expect(env["SUPATYPE_HOOK_SEND_SMS_ENABLED"]).toBe("false")
66
+ })
67
+
68
+ it("keeps a hook off when enabled is false, and does not render a secret nothing uses", () => {
69
+ const settings: AuthSettings = { auth: { hooks: { sendSms: { enabled: false, uri: "https://fn.example.com/sms" } } } }
70
+ const env = authSettingsToEnv(settings, { ...ctx, secrets: { "hooks.sendEmail.secrets": GOOD_SECRET } })
71
+ expect(env["SUPATYPE_HOOK_SEND_SMS_ENABLED"]).toBe("false")
72
+ expect(env["SUPATYPE_HOOK_SEND_EMAIL_SECRETS"]).toBe("")
73
+ })
74
+
75
+ it("renders the captcha secret only while captcha is on", () => {
76
+ const secrets = { "captcha.secret": "0xSECRET" }
77
+ const on = authSettingsToEnv({ auth: { captcha: { enabled: true, provider: "turnstile" } } }, { ...ctx, secrets })
78
+ expect(on["SUPATYPE_SECURITY_CAPTCHA_ENABLED"]).toBe("true")
79
+ expect(on["SUPATYPE_SECURITY_CAPTCHA_PROVIDER"]).toBe("turnstile")
80
+ expect(on["SUPATYPE_SECURITY_CAPTCHA_SECRET"]).toBe("0xSECRET")
81
+ const off = authSettingsToEnv({ auth: { captcha: { enabled: false } } }, { ...ctx, secrets })
82
+ expect(off["SUPATYPE_SECURITY_CAPTCHA_SECRET"]).toBe("")
83
+ })
84
+
85
+ it("renders the captcha site key, which is public, whether or not captcha is on (FF-12)", () => {
86
+ const on = authSettingsToEnv({ auth: { captcha: { enabled: true, provider: "hcaptcha", siteKey: "10000000-ffff-ffff-ffff-000000000001" } } }, ctx)
87
+ expect(on["SUPATYPE_SECURITY_CAPTCHA_SITE_KEY"]).toBe("10000000-ffff-ffff-ffff-000000000001")
88
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_SECURITY_CAPTCHA_SITE_KEY"]).toBe("")
89
+ })
90
+
91
+ it("renders required password characters as the server's colon-separated sets, with nothing a compose file cannot carry", () => {
92
+ const env = authSettingsToEnv({ auth: { password: { minLength: 10, requiredCharacters: ["digit", "lower", "symbol"] } } }, ctx)
93
+ expect(env["SUPATYPE_PASSWORD_MIN_LENGTH"]).toBe("10")
94
+ const sets = (env["SUPATYPE_PASSWORD_REQUIRED_CHARACTERS"] ?? "").split(":")
95
+ expect(sets).toHaveLength(3)
96
+ expect(sets[0]).toBe("abcdefghijklmnopqrstuvwxyz")
97
+ expect(env["SUPATYPE_PASSWORD_REQUIRED_CHARACTERS"]).not.toMatch(/[$"'{}\\]/)
98
+ })
99
+
100
+ it("renders the SMS provider and the credential of the chosen provider only", () => {
101
+ const settings: AuthSettings = {
102
+ auth: { phone: { enabled: true, provider: "twilio", twilio: { accountSid: "AC1", authToken: "env(TW)" } } },
103
+ }
104
+ const env = authSettingsToEnv(settings, { ...ctx, secrets: { "phone.twilio.authToken": "tok", "phone.vonage.apiSecret": "old" } })
105
+ expect(env["SUPATYPE_EXTERNAL_PHONE_ENABLED"]).toBe("true")
106
+ expect(env["SUPATYPE_SMS_PROVIDER"]).toBe("twilio")
107
+ expect(env["SUPATYPE_SMS_TWILIO_ACCOUNT_SID"]).toBe("AC1")
108
+ expect(env["SUPATYPE_SMS_TWILIO_AUTH_TOKEN"]).toBe("tok")
109
+ expect(env["SUPATYPE_SMS_VONAGE_API_SECRET"]).toBe("")
110
+ })
111
+
112
+ it("turns SAML on only when the platform holds its key, and gives the server its URL", () => {
113
+ const settings: AuthSettings = { auth: { sso: { saml: { enabled: true, relayStateValidity: 300 } } } }
114
+ const without = authSettingsToEnv(settings, { ...ctx, samlExternalUrl: "https://abc.supatype.io/auth/v1" })
115
+ expect(without["SUPATYPE_SAML_ENABLED"]).toBe("false")
116
+ const withKey = authSettingsToEnv(settings, {
117
+ ...ctx,
118
+ samlExternalUrl: "https://abc.supatype.io/auth/v1",
119
+ secrets: { [SAML_PRIVATE_KEY_SECRET]: "KEY" },
120
+ })
121
+ expect(withKey["SUPATYPE_SAML_ENABLED"]).toBe("true")
122
+ expect(withKey["SUPATYPE_SAML_PRIVATE_KEY"]).toBe("KEY")
123
+ expect(withKey["SUPATYPE_SAML_EXTERNAL_URL"]).toBe("https://abc.supatype.io/auth/v1")
124
+ expect(withKey["SUPATYPE_SAML_RELAY_STATE_VALIDITY_PERIOD"]).toBe("300s")
125
+ })
126
+
127
+ it("renders the next SAML key during a rotation, and only while SAML is on", () => {
128
+ // Self-host rotates with a second key in .env; Cloud held one key and could not rotate at all.
129
+ const on: AuthSettings = { auth: { sso: { saml: { enabled: true } } } }
130
+ const secrets = { [SAML_PRIVATE_KEY_SECRET]: "KEY", [SAML_NEXT_PRIVATE_KEY_SECRET]: "NEXT" }
131
+ expect(authSettingsToEnv(on, { ...ctx, secrets })["SUPATYPE_SAML_NEXT_PRIVATE_KEY"]).toBe("NEXT")
132
+ expect(authSettingsToEnv({}, { ...ctx, secrets })["SUPATYPE_SAML_NEXT_PRIVATE_KEY"]).toBe("")
133
+ expect(isAuthSecretKey(SAML_NEXT_PRIVATE_KEY_SECRET)).toBe(false)
134
+ })
135
+
136
+ it("never owns the platform's email limit", () => {
137
+ expect(AUTH_OWNED_KEYS).not.toContain("SUPATYPE_RATE_LIMIT_EMAIL_SENT")
138
+ expect(AUTH_OWNED_KEYS).not.toContain("SUPATYPE_RATE_LIMIT_HEADER")
139
+ })
140
+ })
141
+
142
+ describe("group settings validation", () => {
143
+ const check = (auth: object, target: "cloud" | "self-host" = "cloud"): string[] => validateAuthSettings({ auth }, target)
144
+
145
+ it("accepts a full set of valid groups", () => {
146
+ expect(
147
+ check({
148
+ hooks: {
149
+ customAccessToken: { uri: "https://fn.example.com/a", secrets: "env(A)" },
150
+ afterUserCreated: { uri: "pg-functions://postgres/public/after_user" },
151
+ },
152
+ captcha: { enabled: true, provider: "hcaptcha", secret: "env(CAPTCHA)" },
153
+ password: { minLength: 12, requiredCharacters: ["lower", "upper"], leakedPasswordCheck: true },
154
+ sessions: { timebox: 604800, inactivityTimeout: 86400, singlePerUser: true },
155
+ security: { refreshTokenRotation: true, refreshTokenReuseInterval: 10, manualLinking: true },
156
+ mfa: { totp: { enroll: true, verify: true }, phone: { enroll: false }, maxEnrolledFactors: 5 },
157
+ anonymous: { enabled: true },
158
+ phone: { enabled: true, provider: "vonage", vonage: { apiKey: "k", apiSecret: "env(V)", from: "Acme" } },
159
+ rateLimits: { otp: 20, mfa: 10 },
160
+ sso: { saml: { enabled: true, rateLimitAssertion: 20 } },
161
+ }),
162
+ ).toEqual([])
163
+ })
164
+
165
+ it("refuses a hook that is not https or a Postgres function, and http outside self-host localhost", () => {
166
+ expect(check({ hooks: { sendEmail: { uri: "ftp://x.example.com" } } })[0]).toMatch(/must be an https URL/)
167
+ expect(check({ hooks: { sendEmail: { uri: "http://localhost:54321/hook" } } }, "cloud")[0]).toMatch(/must be an https URL/)
168
+ expect(check({ hooks: { sendEmail: { uri: "http://localhost:54321/hook" } } }, "self-host")).toEqual([])
169
+ })
170
+
171
+ it("requires a uri while a hook is enabled", () => {
172
+ expect(check({ hooks: { sendEmail: { secrets: "env(X)" } } })[0]).toMatch(/uri is required/)
173
+ expect(check({ hooks: { sendEmail: { enabled: false } } })).toEqual([])
174
+ })
175
+
176
+ it("refuses a literal secret on both targets, and unknown fields", () => {
177
+ expect(check({ captcha: { enabled: true, secret: "literal" } }, "self-host")[0]).toMatch(/not hold the secret/)
178
+ expect(check({ hooks: { sendEmail: { uri: "https://x.example.com", secrets: GOOD_SECRET } } })[0]).toMatch(/not hold the secret/)
179
+ expect(check({ sessions: { timeout: 5 } })[0]).toMatch(/unknown field\(s\) timeout/)
180
+ expect(check({ mfa: { totp: { enrol: true } } })[0]).toMatch(/unknown field\(s\) enrol/)
181
+ })
182
+
183
+ it("keeps numbers and choices in range", () => {
184
+ expect(check({ password: { minLength: 3 } })[0]).toMatch(/minLength must be a whole number, 6 to 72/)
185
+ expect(check({ sessions: { timebox: 5 } })[0]).toMatch(/timebox/)
186
+ expect(check({ rateLimits: { otp: 0 } })[0]).toMatch(/rateLimits.otp/)
187
+ expect(check({ rateLimits: { emailSent: 5 } })[0]).toMatch(/unknown field\(s\) emailSent/)
188
+ expect(check({ captcha: { provider: "recaptcha" } })[0]).toMatch(/one of hcaptcha, turnstile/)
189
+ expect(check({ password: { requiredCharacters: ["emoji"] } })[0]).toMatch(/list of lower, upper, digit, symbol/)
190
+ })
191
+
192
+ it("refuses text that could end a quoted line early", () => {
193
+ expect(check({ phone: { twilio: { accountSid: 'AC"1' } } })[0]).toMatch(/cannot contain/)
194
+ expect(check({ phone: { twilio: { accountSid: "AC${X}" } } })[0]).toMatch(/cannot contain/)
195
+ })
196
+ })
197
+
198
+ describe("group secrets", () => {
199
+ const settings: AuthSettings = {
200
+ auth: {
201
+ hooks: { sendEmail: { uri: "https://x.example.com", secrets: "env(HOOK_SECRET)" } },
202
+ captcha: { enabled: true, secret: "env(CAPTCHA_SECRET)" },
203
+ phone: { provider: "messagebird", messagebird: { accessKey: "env(MB_KEY)" } },
204
+ },
205
+ }
206
+
207
+ it("lists each secret reference with its key", () => {
208
+ expect(authSecretRefs(settings)).toEqual([
209
+ { key: "hooks.sendEmail.secrets", envName: "HOOK_SECRET" },
210
+ { key: "captcha.secret", envName: "CAPTCHA_SECRET" },
211
+ { key: "phone.messagebird.accessKey", envName: "MB_KEY" },
212
+ ])
213
+ })
214
+
215
+ it("knows which stored secrets the settings use", () => {
216
+ expect(authSecretInUse(settings, "captcha.secret")).toBe(true)
217
+ expect(authSecretInUse(settings, "hooks.sendSms.secrets")).toBe(false)
218
+ expect(authSecretInUse(settings, "phone.twilio.authToken")).toBe(false)
219
+ expect(authSecretInUse({}, SAML_PRIVATE_KEY_SECRET)).toBe(false)
220
+ expect(authSecretInUse({ auth: { sso: { saml: { enabled: true } } } }, SAML_PRIVATE_KEY_SECRET)).toBe(true)
221
+ })
222
+
223
+ it("names the secrets an enabled feature cannot work without", () => {
224
+ expect(groupRequiredSecretKeys(settings).sort()).toEqual(["captcha.secret", "phone.messagebird.accessKey"])
225
+ expect(groupRequiredSecretKeys({ auth: { captcha: { enabled: false } } })).toEqual([])
226
+ })
227
+
228
+ it("names SES's two keys as required while SES is the mail provider", () => {
229
+ expect(groupRequiredSecretKeys({ email: { provider: "ses" } }).sort()).toEqual(["email.ses_access_key_id", "email.ses_secret_access_key"])
230
+ expect(groupRequiredSecretKeys({ email: { provider: "resend" } })).toEqual([])
231
+ })
232
+
233
+ it("holds the SES keys without giving the group renderers a variable or a reference for them", () => {
234
+ const ses = { email: { provider: "ses" as const, ses_access_key_id: "env(K)", ses_secret_access_key: "env(S)" } }
235
+ expect(GROUP_SECRET_KEYS).toEqual(expect.arrayContaining(["email.ses_access_key_id", "email.ses_secret_access_key"]))
236
+ expect(groupSecretRefs(ses).map((r) => r.key)).not.toContain("email.ses_access_key_id")
237
+ expect(GROUP_OWNED_KEYS.every((key) => typeof key === "string" && key.startsWith("SUPATYPE_"))).toBe(true)
238
+ expect(GROUP_OWNED_KEYS.some((key) => key.startsWith("SUPATYPE_SES_"))).toBe(false)
239
+ expect(Object.keys(groupsEnv(ses, ctx)).some((key) => key.startsWith("SUPATYPE_SES_"))).toBe(false)
240
+ expect(groupsSelfHostVars(ses).some((v) => v.key.startsWith("SUPATYPE_SES_"))).toBe(false)
241
+ })
242
+
243
+ it("accepts a Standard Webhooks hook secret and refuses anything else", () => {
244
+ expect(groupSecretFormatProblem("hooks.sendEmail.secrets", GOOD_SECRET)).toBeUndefined()
245
+ expect(groupSecretFormatProblem("hooks.sendEmail.secrets", `${GOOD_SECRET}|${GOOD_SECRET}`)).toBeUndefined()
246
+ expect(groupSecretFormatProblem("hooks.sendEmail.secrets", "plain")).toMatch(/v1,whsec_/)
247
+ expect(groupSecretFormatProblem("captcha.secret", "anything")).toBeUndefined()
248
+ })
249
+
250
+ it("makes the secrets settable, but never the platform's SAML key", () => {
251
+ expect(isAuthSecretKey("hooks.sendEmail.secrets")).toBe(true)
252
+ expect(isAuthSecretKey("phone.vonage.apiSecret")).toBe(true)
253
+ expect(isAuthSecretKey(SAML_PRIVATE_KEY_SECRET)).toBe(false)
254
+ })
255
+ })
256
+
257
+ describe("group settings as leaves", () => {
258
+ it("flattens and unflattens them, with a listed hook's enabled explicit", () => {
259
+ const settings: AuthSettings = {
260
+ auth: {
261
+ hooks: { sendEmail: { uri: "https://x.example.com", secrets: "env(S)" } },
262
+ sessions: { timebox: 3600 },
263
+ password: { requiredCharacters: ["digit"] },
264
+ },
265
+ }
266
+ const flat = flattenAuthSettings(settings)
267
+ expect(flat["auth.hooks.sendEmail.enabled"]).toBe(true)
268
+ expect(flat["auth.hooks.sendEmail.uri"]).toBe("https://x.example.com")
269
+ expect(flat["auth.sessions.timebox"]).toBe(3600)
270
+ expect(flat["auth.password.requiredCharacters"]).toEqual(["digit"])
271
+ expect(Object.keys(flat).some((k) => k.endsWith("secrets"))).toBe(false)
272
+ expect(unflattenAuthSettings(flat).auth?.sessions?.timebox).toBe(3600)
273
+ expect(unflattenAuthSettings(flat).auth?.hooks?.sendEmail?.uri).toBe("https://x.example.com")
274
+ })
275
+
276
+ it("accepts the new paths and refuses the platform-owned ones", () => {
277
+ expect(isAuthSettingPath("auth.mfa.totp.enroll")).toBe(true)
278
+ expect(isAuthSettingPath("auth.rateLimits.otp")).toBe(true)
279
+ expect(isAuthSettingPath("auth.rateLimits.emailSent")).toBe(false)
280
+ expect(isAuthSettingPath("auth.sso.saml.externalUrl")).toBe(false)
281
+ })
282
+ })
283
+
284
+ describe("groupsSelfHostVars", () => {
285
+ it("is empty for settings that set none of the groups", () => {
286
+ expect(groupsSelfHostVars({ auth: { siteUrl: "https://x.example.com", disableSignup: true } })).toEqual([])
287
+ })
288
+
289
+ it("renders only what is stated, a secret as the name of its variable, and leaves SAML to the CLI", () => {
290
+ const vars = groupsSelfHostVars({
291
+ auth: {
292
+ sessions: { singlePerUser: true },
293
+ captcha: { enabled: true, secret: "env(CAPTCHA)" },
294
+ hooks: { sendEmail: { uri: "https://x.example.com" } },
295
+ sso: { saml: { enabled: true } },
296
+ },
297
+ })
298
+ expect(vars).toContainEqual({ key: "SUPATYPE_SESSIONS_SINGLE_PER_USER", value: "true" })
299
+ expect(vars).toContainEqual({ key: "SUPATYPE_SECURITY_CAPTCHA_SECRET", fromEnv: "CAPTCHA" })
300
+ expect(vars).toContainEqual({ key: "SUPATYPE_HOOK_SEND_EMAIL_ENABLED", value: "true" })
301
+ expect(vars).toContainEqual({ key: "SUPATYPE_HOOK_SEND_EMAIL_URI", value: "https://x.example.com" })
302
+ expect(vars.some((v) => v.key.startsWith("SUPATYPE_SAML"))).toBe(false)
303
+ expect(vars.some((v) => v.key === "SUPATYPE_SESSIONS_TIMEBOX")).toBe(false)
304
+ })
305
+ })
306
+
307
+ describe("groupDefault", () => {
308
+ it("reports what the server runs with, not the raw fallback it is sent", () => {
309
+ expect(groupDefault("auth.rateLimits.otp")).toBe(30)
310
+ expect(groupDefault("auth.rateLimits.tokenRefresh")).toBe(150)
311
+ expect(groupDefault("auth.rateLimits.mfa")).toBe(15)
312
+ expect(groupDefault("auth.sso.saml.rateLimitAssertion")).toBe(15)
313
+ // The fallback sent is 0; the server raises anything below 6 to 6.
314
+ expect(groupDefault("auth.password.minLength")).toBe(6)
315
+ expect(groupDefault("auth.phone.otpLength")).toBe(6)
316
+ expect(groupDefault("auth.phone.otpExpiry")).toBe(60)
317
+ expect(groupDefault("auth.phone.maxFrequency")).toBe(60)
318
+ expect(groupDefault("auth.sso.saml.relayStateValidity")).toBe(120)
319
+ })
320
+
321
+ it("reports switches, choices and settings that have no value", () => {
322
+ expect(groupDefault("auth.captcha.enabled")).toBe(false)
323
+ expect(groupDefault("auth.security.refreshTokenRotation")).toBe(true)
324
+ expect(groupDefault("auth.mfa.totp.enroll")).toBe(true)
325
+ expect(groupDefault("auth.captcha.provider")).toBe("hcaptcha")
326
+ expect(groupDefault("auth.phone.provider")).toBeNull()
327
+ expect(groupDefault("auth.password.requiredCharacters")).toBeNull()
328
+ expect(groupDefault("auth.hooks.sendEmail.uri")).toBeNull()
329
+ // No limit is a hundred years in the file, but the default the user sees is none.
330
+ expect(groupDefault("auth.sessions.timebox")).toBeNull()
331
+ expect(groupDefault("auth.sessions.inactivityTimeout")).toBeNull()
332
+ })
333
+
334
+ it("is undefined for a path the table does not hold", () => {
335
+ expect(groupDefault("auth.siteUrl")).toBeUndefined()
336
+ })
337
+
338
+ it("has an answer for every table setting", () => {
339
+ const missing = GROUP_LEAF_PATHS.filter((p) => !/^auth.hooks.[A-Za-z]+.enabled$/.test(p) && groupDefault(p) === undefined)
340
+ expect(missing).toEqual([])
341
+ })
342
+ })
@@ -0,0 +1,327 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import {
3
+ AUTH_OWNED_KEYS,
4
+ AUTH_PROVIDER_NAMES,
5
+ authSecretInUse,
6
+ authSecretRefs,
7
+ authSettingPaths,
8
+ authSettingsToEnv,
9
+ envReferenceName,
10
+ flattenAuthSettings,
11
+ isAuthSecretKey,
12
+ parseAuthSettings,
13
+ isAuthSettingPath,
14
+ unflattenAuthSettings,
15
+ renderEnvFile,
16
+ validateAuthSettings,
17
+ type AuthRenderContext,
18
+ type AuthSettings,
19
+ } from "../src/auth-settings.js"
20
+
21
+ const ctx: AuthRenderContext = {
22
+ callbackBaseUrl: "https://abc.supatype.io",
23
+ siteUrl: "https://abc.supatype.io",
24
+ platformRedirectUrls: ["https://studio.supatype.com/**"],
25
+ secrets: {},
26
+ }
27
+
28
+ describe("authSettingsToEnv", () => {
29
+ it("writes every owned key even when settings are empty, so a removed value is unset", () => {
30
+ const env = authSettingsToEnv({}, ctx)
31
+ expect(Object.keys(env).sort()).toEqual([...AUTH_OWNED_KEYS].sort())
32
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_ENABLED"]).toBe("false")
33
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_SKIP_NONCE_CHECK"]).toBe("false")
34
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_CLIENT_ID"]).toBe("")
35
+ })
36
+
37
+ it("covers all 25 providers", () => {
38
+ expect(AUTH_PROVIDER_NAMES).toHaveLength(25)
39
+ const env = authSettingsToEnv({}, ctx)
40
+ for (const name of AUTH_PROVIDER_NAMES) {
41
+ expect(env[`SUPATYPE_EXTERNAL_${name.toUpperCase()}_ENABLED`]).toBe("false")
42
+ }
43
+ })
44
+
45
+ it("renders a configured provider with the callback under the callback base and its stored secret", () => {
46
+ const settings: AuthSettings = {
47
+ auth: { providers: { github: { clientId: "Iv1.abc", secret: "env(GITHUB_SECRET)" } } },
48
+ }
49
+ const env = authSettingsToEnv(settings, { ...ctx, secrets: { "providers.github.secret": "s3cret" } })
50
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_ENABLED"]).toBe("true")
51
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_CLIENT_ID"]).toBe("Iv1.abc")
52
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_SECRET"]).toBe("s3cret")
53
+ expect(env["SUPATYPE_EXTERNAL_GITHUB_REDIRECT_URI"]).toBe("https://abc.supatype.io/auth/v1/callback")
54
+ })
55
+
56
+ it("keeps a provider turned off when enabled is false", () => {
57
+ const env = authSettingsToEnv({ auth: { providers: { google: { enabled: false, clientId: "x" } } } }, ctx)
58
+ expect(env["SUPATYPE_EXTERNAL_GOOGLE_ENABLED"]).toBe("false")
59
+ })
60
+
61
+ it("always includes the platform redirect entries in the allow list, after the project's own", () => {
62
+ const env = authSettingsToEnv({ auth: { redirectUrls: ["https://app.example.com/**"] } }, ctx)
63
+ expect(env["SUPATYPE_URI_ALLOW_LIST"]).toBe("https://app.example.com/**,https://studio.supatype.com/**")
64
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_URI_ALLOW_LIST"]).toBe("https://studio.supatype.com/**")
65
+ })
66
+
67
+ it("takes the site URL from settings, else from the context", () => {
68
+ expect(authSettingsToEnv({ auth: { siteUrl: "https://app.example.com" } }, ctx)["SUPATYPE_SITE_URL"]).toBe(
69
+ "https://app.example.com",
70
+ )
71
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_SITE_URL"]).toBe("https://abc.supatype.io")
72
+ })
73
+
74
+ it("maps email and sign-up switches, with confirmations on unless turned off", () => {
75
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_MAILER_AUTOCONFIRM"]).toBe("false")
76
+ const off = authSettingsToEnv(
77
+ { auth: { email: { enabled: false, enableConfirmations: false }, disableSignup: true } },
78
+ ctx,
79
+ )
80
+ expect(off["SUPATYPE_EXTERNAL_EMAIL_ENABLED"]).toBe("false")
81
+ expect(off["SUPATYPE_MAILER_AUTOCONFIRM"]).toBe("true")
82
+ expect(off["SUPATYPE_DISABLE_SIGNUP"]).toBe("true")
83
+ })
84
+
85
+ it("renders smtp, with an integer port always present and the password from the stored secret", () => {
86
+ const settings: AuthSettings = {
87
+ email: {
88
+ provider: "smtp",
89
+ smtp: { host: "smtp.x.com", port: 2525, user: "u", pass: "env(SMTP_PASS)", sender_name: "Acme" },
90
+ },
91
+ }
92
+ const env = authSettingsToEnv(settings, { ...ctx, secrets: { "email.smtp.pass": "pw" } })
93
+ expect(env["SUPATYPE_MAILER_MAILER_PROVIDER"]).toBe("smtp")
94
+ expect(env["SUPATYPE_SMTP_HOST"]).toBe("smtp.x.com")
95
+ expect(env["SUPATYPE_SMTP_PORT"]).toBe("2525")
96
+ expect(env["SUPATYPE_SMTP_PASS"]).toBe("pw")
97
+ expect(env["SUPATYPE_SMTP_SENDER_NAME"]).toBe("Acme")
98
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_SMTP_PORT"]).toBe("587")
99
+ })
100
+
101
+ it("renders resend", () => {
102
+ const env = authSettingsToEnv(
103
+ { email: { provider: "resend", resend_api_key: "env(RESEND_KEY)", resend_from: "a@b.com" } },
104
+ { ...ctx, secrets: { "email.resend_api_key": "re_123" } },
105
+ )
106
+ expect(env["SUPATYPE_MAILER_MAILER_PROVIDER"]).toBe("resend")
107
+ expect(env["SUPATYPE_RESEND_API_KEY"]).toBe("re_123")
108
+ expect(env["SUPATYPE_RESEND_FROM"]).toBe("a@b.com")
109
+ })
110
+
111
+ it("uses the platform mail defaults when the project sets no provider", () => {
112
+ const env = authSettingsToEnv(
113
+ {},
114
+ {
115
+ ...ctx,
116
+ platformMail: {
117
+ host: "mail.supatype.io",
118
+ port: 587,
119
+ user: "p",
120
+ pass: "pp",
121
+ senderName: "Supatype",
122
+ adminEmail: "no-reply@auth.supatype.io",
123
+ },
124
+ },
125
+ )
126
+ expect(env["SUPATYPE_MAILER_MAILER_PROVIDER"]).toBe("smtp")
127
+ expect(env["SUPATYPE_SMTP_HOST"]).toBe("mail.supatype.io")
128
+ expect(env["SUPATYPE_SMTP_ADMIN_EMAIL"]).toBe("no-reply@auth.supatype.io")
129
+ })
130
+
131
+ it("never sets a platform-owned key", () => {
132
+ const env = authSettingsToEnv({}, ctx)
133
+ for (const key of ["SUPATYPE_JWT_SECRET", "SUPATYPE_DB_DATABASE_URL", "SUPATYPE_API_EXTERNAL_URL", "SUPATYPE_JWT_EXP"]) {
134
+ expect(Object.keys(env)).not.toContain(key)
135
+ expect(AUTH_OWNED_KEYS).not.toContain(key)
136
+ }
137
+ expect(Object.keys(env).filter((k) => k.startsWith("SUPATYPE_MAILER_URLPATHS_"))).toEqual([])
138
+ })
139
+ })
140
+
141
+ describe("validateAuthSettings", () => {
142
+ it("accepts the self-host config shape", () => {
143
+ const ok = { auth: { providers: { github: { clientId: "x", secret: "env(A)" } } } }
144
+ expect(validateAuthSettings(ok, "self-host")).toEqual([])
145
+ })
146
+
147
+ it("refuses a literal provider secret on both targets", () => {
148
+ const bad = { auth: { providers: { github: { secret: "literal" } } } }
149
+ expect(validateAuthSettings(bad, "cloud")[0]).toContain("auth.providers.github.secret")
150
+ expect(validateAuthSettings(bad, "self-host")[0]).toContain("auth.providers.github.secret")
151
+ })
152
+
153
+ it("accepts env() for smtp.pass, and refuses a literal for Cloud only", () => {
154
+ const ref = { email: { provider: "smtp", smtp: { pass: "env(SMTP_PASS)" } } }
155
+ expect(validateAuthSettings(ref, "cloud")).toEqual([])
156
+ const literal = { email: { provider: "smtp", smtp: { pass: "hunter2" } } }
157
+ expect(validateAuthSettings(literal, "self-host")).toEqual([])
158
+ expect(validateAuthSettings(literal, "cloud")[0]).toContain("email.smtp.pass")
159
+ })
160
+
161
+ it("refuses a literal resend key on Cloud", () => {
162
+ expect(validateAuthSettings({ email: { provider: "resend", resend_api_key: "re_x" } }, "cloud")[0]).toContain("resend_api_key")
163
+ })
164
+
165
+ it("leaves SES key presence to the caller, but still refuses a literal where a reference belongs", () => {
166
+ expect(validateAuthSettings({ email: { provider: "ses", ses_from: "a@b.test" } }, "cloud")).toEqual([])
167
+ expect(validateAuthSettings({ email: { provider: "ses" } }, "self-host")).toEqual([])
168
+ expect(validateAuthSettings({ email: { provider: "ses", ses_from: "a@b.test", ses_access_key_id: "literal" } }, "cloud")[0]).toContain("ses_access_key_id")
169
+ })
170
+
171
+ it("uses the SES keys only while SES is the provider", () => {
172
+ expect(authSecretInUse({ email: { provider: "ses" } }, "email.ses_access_key_id")).toBe(true)
173
+ expect(authSecretInUse({ email: { provider: "resend" } }, "email.ses_secret_access_key")).toBe(false)
174
+ })
175
+
176
+ it("takes SES on Cloud with the project's own key, and renders it for the server", () => {
177
+ // SES was refused on Cloud outright: the server only read ambient AWS credentials, which a
178
+ // hosted project does not have. It now reads SUPATYPE_SES_ACCESS_KEY_ID and its secret.
179
+ const ses = { email: { provider: "ses" as const, ses_from: "hi@acme.dev", ses_region: "eu-west-2", ses_access_key_id: 'env(SES_KEY)', ses_secret_access_key: 'env(SES_SECRET)' } }
180
+ expect(validateAuthSettings(ses, "cloud")).toEqual([])
181
+ expect(validateAuthSettings({ email: { ...ses.email, ses_secret_access_key: "literal" } }, "cloud")[0]).toContain("ses_secret_access_key")
182
+ expect(authSecretRefs(ses).map((r) => r.key)).toEqual(["email.ses_access_key_id", "email.ses_secret_access_key"])
183
+ const env = authSettingsToEnv(ses, { ...ctx, secrets: { "email.ses_access_key_id": "AKIA1", "email.ses_secret_access_key": "s3" } })
184
+ expect([env["SUPATYPE_SES_FROM"], env["SUPATYPE_SES_REGION"], env["SUPATYPE_SES_ACCESS_KEY_ID"], env["SUPATYPE_SES_SECRET_ACCESS_KEY"]]).toEqual(["hi@acme.dev", "eu-west-2", "AKIA1", "s3"])
185
+ // Every owned key is always written, so a project that leaves SES clears the stored key.
186
+ expect(authSettingsToEnv({}, ctx)["SUPATYPE_SES_SECRET_ACCESS_KEY"]).toBe("")
187
+ })
188
+
189
+ it("refuses unknown providers, unknown fields and bad URLs", () => {
190
+ expect(validateAuthSettings({ auth: { providers: { nope: {} } } }, "cloud")[0]).toContain("nope")
191
+ expect(validateAuthSettings({ auth: { providers: { github: { bogus: 1 } } } }, "cloud")[0]).toContain("bogus")
192
+ expect(validateAuthSettings({ auth: { siteUrl: "javascript:alert(1)" } }, "cloud")[0]).toContain("auth.siteUrl")
193
+ expect(validateAuthSettings({ auth: { redirectUrls: ["not a url"] } }, "cloud")[0]).toContain("auth.redirectUrls")
194
+ })
195
+
196
+ it("allows a custom-scheme redirect URL for an app, and still refuses schemes dangerous in a browser", () => {
197
+ const ok = ["myapp://login-callback/", "com.example.app:/oauth2redirect", "exp+myapp://**", "https://app.example.com/**"]
198
+ expect(validateAuthSettings({ auth: { redirectUrls: ok } }, "cloud")).toEqual([])
199
+ for (const bad of ["javascript:alert(1)", "data:text/html,x", "file:///etc/passwd", "vbscript:x", "JavaScript:alert(1)", "1app://x", "://x", "myapp:"]) {
200
+ expect(validateAuthSettings({ auth: { redirectUrls: [bad] } }, "cloud")[0]).toContain("auth.redirectUrls")
201
+ }
202
+ })
203
+
204
+ it("keeps the site URL and a provider's URLs to http(s)", () => {
205
+ expect(validateAuthSettings({ auth: { siteUrl: "myapp://home" } }, "cloud")[0]).toContain("auth.siteUrl")
206
+ expect(validateAuthSettings({ auth: { providers: { github: { redirectUri: "myapp://cb" } } } }, "cloud")[0]).toContain("redirectUri")
207
+ })
208
+
209
+ it("refuses a value that could end a quoted line early", () => {
210
+ expect(validateAuthSettings({ auth: { providers: { github: { clientId: "a\nb" } } } }, "cloud")[0]).toContain(
211
+ "auth.providers.github.clientId",
212
+ )
213
+ })
214
+ })
215
+
216
+ describe("authSecretRefs", () => {
217
+ it("lists each secret key with the env name it points at", () => {
218
+ const refs = authSecretRefs({
219
+ auth: { providers: { github: { secret: "env(GH)" }, google: { clientId: "x" } } },
220
+ email: { provider: "smtp", smtp: { pass: "env(SMTP_PASS)" } },
221
+ })
222
+ expect(refs).toEqual([
223
+ { key: "providers.github.secret", envName: "GH" },
224
+ { key: "email.smtp.pass", envName: "SMTP_PASS" },
225
+ ])
226
+ })
227
+ })
228
+
229
+ describe("renderEnvFile", () => {
230
+ it("writes sorted single-quoted lines, leaving $ and backslashes as they are", () => {
231
+ expect(renderEnvFile({ B: "2", A: "a $b \\ c" })).toBe("A='a $b \\ c'\nB='2'\n")
232
+ })
233
+
234
+ it("refuses a value with a control character or a single quote", () => {
235
+ expect(() => renderEnvFile({ A: "line\nbreak" })).toThrow(/A/)
236
+ expect(() => renderEnvFile({ A: "it's" })).toThrow(/A/)
237
+ })
238
+ })
239
+
240
+ describe("envReferenceName", () => {
241
+ it("reads env(NAME) and ignores literals", () => {
242
+ expect(envReferenceName("env(X_1)")).toBe("X_1")
243
+ expect(envReferenceName("literal")).toBeUndefined()
244
+ })
245
+ })
246
+
247
+ describe("flattenAuthSettings and unflattenAuthSettings", () => {
248
+ const settings: AuthSettings = {
249
+ auth: {
250
+ siteUrl: "https://app.example.com",
251
+ redirectUrls: ["https://app.example.com/**"],
252
+ email: { enableConfirmations: false },
253
+ providers: { github: { clientId: "Iv1", secret: "env(GH)" }, google: { enabled: false } },
254
+ },
255
+ email: { provider: "smtp", smtp: { host: "h", port: 25, pass: "env(P)" } },
256
+ }
257
+
258
+ it("makes one leaf per setting, with a provider's enabled always explicit and no secrets", () => {
259
+ expect(flattenAuthSettings(settings)).toEqual({
260
+ "auth.siteUrl": "https://app.example.com",
261
+ "auth.redirectUrls": ["https://app.example.com/**"],
262
+ "auth.email.enableConfirmations": false,
263
+ "auth.providers.github.enabled": true,
264
+ "auth.providers.github.clientId": "Iv1",
265
+ "auth.providers.google.enabled": false,
266
+ "email.provider": "smtp",
267
+ "email.smtp.host": "h",
268
+ "email.smtp.port": 25,
269
+ })
270
+ })
271
+
272
+ it("round-trips the leaves back into settings", () => {
273
+ const flat = flattenAuthSettings(settings)
274
+ expect(flattenAuthSettings(unflattenAuthSettings(flat))).toEqual(flat)
275
+ expect(unflattenAuthSettings(flat).auth?.providers?.github?.clientId).toBe("Iv1")
276
+ })
277
+
278
+ it("lists the paths a setting may have and refuses others", () => {
279
+ expect(isAuthSettingPath("auth.providers.github.clientId")).toBe(true)
280
+ expect(isAuthSettingPath("auth.providers.github.secret")).toBe(false)
281
+ expect(isAuthSettingPath("auth.providers.nope.enabled")).toBe(false)
282
+ expect(isAuthSettingPath("email.smtp.pass")).toBe(false)
283
+ expect(isAuthSettingPath("SUPATYPE_JWT_SECRET")).toBe(false)
284
+ })
285
+
286
+ it("knows the secret keys", () => {
287
+ expect(isAuthSecretKey("providers.github.secret")).toBe(true)
288
+ expect(isAuthSecretKey("email.smtp.pass")).toBe(true)
289
+ expect(isAuthSecretKey("providers.nope.secret")).toBe(false)
290
+ expect(isAuthSecretKey("jwt")).toBe(false)
291
+ })
292
+ })
293
+
294
+ describe("authSettingPaths", () => {
295
+ it("lists every path isAuthSettingPath accepts, and nothing else", () => {
296
+ const paths = authSettingPaths()
297
+ expect(paths.length).toBeGreaterThan(25 * 5)
298
+ expect(paths.every(isAuthSettingPath)).toBe(true)
299
+ expect(paths).toContain("auth.siteUrl")
300
+ expect(paths).toContain("auth.providers.zoom.enabled")
301
+ expect(new Set(paths).size).toBe(paths.length)
302
+ })
303
+ })
304
+
305
+ describe("parseAuthSettings", () => {
306
+ it("narrows valid settings and lists the problems of invalid ones", () => {
307
+ const ok = parseAuthSettings({ auth: { siteUrl: "https://a.com" } }, "cloud")
308
+ expect(ok).toEqual({ ok: true, settings: { auth: { siteUrl: "https://a.com" } } })
309
+ const bad = parseAuthSettings({ auth: { siteUrl: "nope" } }, "cloud")
310
+ expect(bad.ok).toBe(false)
311
+ expect(bad.ok ? [] : bad.problems[0]).toContain("auth.siteUrl")
312
+ })
313
+ })
314
+
315
+ describe("SES sender on Cloud", () => {
316
+ const keys = { ses_access_key_id: "env(SES_KEY)", ses_secret_access_key: "env(SES_SECRET)" }
317
+
318
+ it("names email.ses_from when Cloud is given SES without it", () => {
319
+ const problems = validateAuthSettings({ email: { provider: "ses", ...keys } }, "cloud")
320
+ expect(problems.join("\n")).toContain("email.ses_from")
321
+ })
322
+
323
+ it("takes SES with a sender on Cloud, and leaves self-host to its .env", () => {
324
+ expect(validateAuthSettings({ email: { provider: "ses", ses_from: "noreply@example.com", ...keys } }, "cloud")).toEqual([])
325
+ expect(validateAuthSettings({ email: { provider: "ses", ...keys } }, "self-host")).toEqual([])
326
+ })
327
+ })