Repository navigation
Expand file tree
/
Copy pathaudience-posture.ts
More file actions
760 lines (731 loc) · 37.6 KB
/
Copy pathaudience-posture.ts
File metadata and controls
760 lines (731 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Audience posture — the SINGLE owner of "who may become a user of this
* environment" (#11739 / epic #11723; vocabulary and completeness predicates
* declared in `@objectstack/spec/system` `AudienceConfigSchema`).
*
* ## The one enforcement point
*
* Enforcement rides better-auth 1.7.1's `user.validateUserInfo` gate — the
* vendor's own admission seam, invoked by `internalAdapter.createUser` for
* EVERY creation path (measured against the installed dist: sign-up.mjs passes
* `{method:'email-password'}`, link-account.mjs `{method:'oauth'|'sso-*'}`,
* admin routes `{method:'admin'}`, @better-auth/scim `{method:'scim'}`,
* magic-link / email-otp / phone-number / anonymous each their own). A
* rejection surfaces as a 403 `APIError` whose `code` is OURS, and browser
* OAuth flows redirect to the error URL carrying the same code. The gate
* fails CLOSED by vendor construction (a throwing hook rejects provisioning).
* This module owns the DECISION (`decideAudienceAdmission`, a pure function
* the test matrix drives); auth-manager owns the wiring and the I/O
* (bootstrap probe, invitation lookup, permission-set resolution).
*
* ## What is gated, and what deliberately is not
*
* The posture governs SELF-registration — a person becoming a user by their
* own act. Three creation classes ({@link classifyCreationMethod}):
*
* - `self-serve` (POSTURE-GATED): email/password sign-up, social-provider
* OAuth JIT (`socialProviders` — a public IdP account is not an operator
* act), magic-link, email-otp, phone-number, anonymous, siwe, and ANY
* unrecognized method (fail closed: a future plugin's creation path is
* gated until deliberately classified).
* - `operator` (never gated): `admin` (create-user / bulk import) and `scim`
* (IdP-driven provisioning) — these ARE the invite/provisioning mechanisms
* the closed postures point operators at.
* - `provider`: JIT provisioning through an OPERATOR-REGISTERED identity
* authority — `sso-oidc` / `sso-saml` (@better-auth/sso providers;
* registration is platform-admin-only, #10009) and `oauth` whose providerId
* is a configured `oidcProviders` entry (enterprise SSO incl. the cloud
* platform IdP, whose OP side additionally enforces app-assignment, D5.1).
* Never gated under `email_domain` or `open`, and an `oidcProviders` entry is
* never gated at all. Under `invite_only` an `@better-auth/sso` provider
* (`AudienceAdmissionInput.ssoProvider`) admits a person with no account and
* no invitation ONLY when that provider's `allowJit` toggle is on (maintainer
* ruling A, record 6718355623): `invite_only` means by invitation, and the
* enterprise combo "self-registration closed + IdP JIT on" is stated per
* provider instead of implied by registering one. Off by default, so an
* unknown SSO user is refused `SELF_REGISTRATION_CLOSED` like any
* uninvited sign-up; the invitation and bootstrap carve-outs below apply.
*
* Only `action: 'create-user'` is judged: `link-account` and provider
* `sign-in` concern an EXISTING user's identity, not audience admission.
*
* ## The invitation carve-out
*
* `invite_only` means BY INVITATION — not "no new users". better-auth's
* organization invitation flow requires the invitee to hold an account before
* `accept-invitation`, and for a brand-new invitee that account comes from the
* self-serve sign-up route. So a self-serve creation holding a PENDING,
* unexpired `sys_invitation` row is admitted under every posture (under
* `email_domain` an explicit invitation also trumps the domain list — an
* operator inviting an external contractor must not dead-end them), except a
* social-provider creation whose address the provider did not verify under a
* posture whose admission rests on the address (below), and except a creation
* the posture's own rule already admits ({@link isAdmittedByPostureRule}): that
* one is a self-registrant, invitation or not, so it asks for the declared
* self-registration set and is refused with the uninvited sign-up when the set
* cannot be resolved — the invitation does not admit it without the grant.
* Without this carve-out the posture would be "admin-create only" and the
* invitation surface would be dead for new users — the invite dead-end class.
*
* What "holding" means is {@link invitationProofFor}'s answer. Under
* `invite_only` a self-serve sign-up is admitted only by the invitation it
* presents: an email-and-password sign-up presents the invitation's id (the
* one its accept link carries, `presented-invitation.ts`), and an address
* alone is refused like any uninvited sign-up. A creation whose own flow
* proved the mailbox (magic link, email OTP), or whose identity provider
* verified the address, is matched by address. `open` and `email_domain`
* match every creation by address.
*
* Admission by an invitation alone grants the account and nothing more
* ({@link isAdmittedByInvitationAlone}): under `invite_only`, and under
* `email_domain` for an address off the list, the sign-up receives no
* self-registration permission set, is not bound into the deployment's
* organization while its address is unverified, and joins by accepting the
* invitation. A sign-up the posture's own rule admits — any address under
* `open`, an address on the list under `email_domain` — is admitted by that
* rule, invitation or not ({@link isAdmittedByPostureRule}): it receives the
* declared set and binds as an uninvited one does, and the invitation still
* places it as the invitation names once it accepts.
*
* ## A social provider's word on the address
*
* Under a posture whose admission rests on the address — `email_domain`
* always, `open` while email verification is in force
* ({@link resolveEmailVerificationRequirement}) — a self-serve creation through
* a social provider is admitted only when the provider verified the address
* (`emailVerified` `true`). Otherwise {@link decideAudienceAdmission} refuses it
* `SELF_REGISTRATION_CLOSED`, as `invite_only` refuses it through the
* invitation proof: no account row, no session, no membership, and a pending
* invitation addressed to it does not admit it either. The rule is keyed on the
* creation class, so a social provider configured later is covered without
* being named; the `provider` class (an operator-registered identity
* authority) and the bootstrap carve-out are unaffected. Under `open` with the
* deployment's verification declared off, the creation is admitted as before.
*
* ## Pinned domain-matching rules (`email_domain`)
*
* An unpinned matcher is where this class of gate leaks, so the rules are
* stated and test-locked ({@link emailDomainAllowed}):
*
* 1. The candidate domain is everything after the LAST `@` of the address;
* an address with no `@`, or an empty remainder, has no domain and never
* matches (placeholder addresses for phone-only users land here).
* 2. Comparison is case-insensitive on both sides.
* 3. A list entry matches by EXACT equality — subdomains are NOT implied
* (`user@mail.acme.com` is not admitted by `acme.com`; declare
* `mail.acme.com` too) and wildcards are refused at declaration.
* 4. `+tag` local-part suffixes are irrelevant — matching never reads the
* local part, so `user+anything@acme.com` matches like `user@acme.com`.
* 5. No punycode/IDN normalization is applied: the declared entry and the
* address's domain are compared as lowercased strings. Declare an
* internationalized domain in the exact form addresses carry it.
*
* ## Fail postures, mirrored from the MembershipPolicy precedent (#5205)
*
* An off-vocabulary posture at admission time is REFUSED with
* `AUTH_CONFIG_ERROR` — a verdict distinct from `SELF_REGISTRATION_CLOSED`
* ("a valid posture said no") because sending the debugger to re-read a
* setting that looks exactly as they left it is the recorded failure mode. A
* declared permission set that cannot be resolved refuses admission the same
* way, for every sign-up the posture's rule admits, invited or not: admitting
* a self-registrant WITHOUT the declared grant would be the
* ADR-0078 "declared but inert" defect at runtime, and fail-open is the one
* direction this gate must never take.
*/
import { isCloudManaged } from '@objectstack/core';
import { MCP_AGENT_PERMISSION_SETS } from '@objectstack/spec/ai';
import {
AUDIENCE_POSTURES,
SystemUserId,
isAudiencePosture,
audiencePermitsSelfRegistration,
type AudienceConfig,
type AudiencePosture,
type EmailAndPasswordConfig,
} from '@objectstack/spec/system';
/** Wire code for "a valid posture closed self-registration" (ADR-0112 ledger). */
export const SELF_REGISTRATION_CLOSED = 'SELF_REGISTRATION_CLOSED';
/** Wire code for "the address's domain is off the email_domain allowlist" (ADR-0112 ledger). */
export const EMAIL_DOMAIN_NOT_ALLOWED = 'EMAIL_DOMAIN_NOT_ALLOWED';
/** Wire code for "the audience configuration itself is unusable" (registered pre-existing). */
export const AUDIENCE_CONFIG_ERROR = 'AUTH_CONFIG_ERROR';
/** The audience declaration as the live config resolves it. */
export interface ResolvedAudience {
posture: AudiencePosture;
allowedEmailDomains: readonly string[];
selfRegistrationPermissionSet?: string;
/**
* Present when the RAW posture was off-vocabulary (reachable only by
* mutating config past the entry validation). `posture` is then coerced to
* `invite_only` for DISPLAY surfaces; the admission path refuses with
* `AUTH_CONFIG_ERROR` instead of trusting the coercion (fail closed, and
* the refusal names the offending value — never "policy said no").
*/
invalid?: { raw: string };
}
/** Bounded, type-safe description of a rejected value (the #5205 pattern). */
export function describeAudiencePosture(value: unknown): string {
if (typeof value === 'string') {
return value.length > 64 ? `'${value.slice(0, 64)}…' (truncated)` : `'${value}'`;
}
if (value === null) return 'null';
if (value === undefined) return 'undefined';
return `[${typeof value}]`;
}
/**
* Resolve the raw authored `audience` config to the shape every consumer
* reads. Undeclared ⇒ `invite_only` (maintainer ruling 2026-08-24, epic
* #11723 — no legacy/undeclared limbo). Never throws: entry refusal is
* {@link assertAudienceConfig}'s job; this only marks an off-vocabulary
* posture `invalid` so consumers fail closed rather than fail open.
*/
export function resolveAudience(raw: AudienceConfig | undefined): ResolvedAudience {
const rawPosture = (raw as { posture?: unknown } | undefined)?.posture;
const domains = Array.isArray(raw?.allowedEmailDomains) ? raw.allowedEmailDomains : [];
const set =
typeof raw?.selfRegistrationPermissionSet === 'string' && raw.selfRegistrationPermissionSet
? raw.selfRegistrationPermissionSet
: undefined;
if (rawPosture === undefined || rawPosture === null) {
return { posture: 'invite_only', allowedEmailDomains: domains, selfRegistrationPermissionSet: set };
}
if (!isAudiencePosture(rawPosture)) {
return {
posture: 'invite_only',
allowedEmailDomains: domains,
selfRegistrationPermissionSet: set,
invalid: { raw: describeAudiencePosture(rawPosture) },
};
}
return { posture: rawPosture, allowedEmailDomains: domains, selfRegistrationPermissionSet: set };
}
/**
* [#20389] Who declared the standing `emailAndPassword.requireEmailVerification`.
*
* - `deployment`: the deployment's own configuration — the manager's
* constructor config (stack config / host preset), host code calling
* `applyConfigPatch()`, or an `OS_AUTH_REQUIRE_EMAIL_VERIFICATION` env
* override arriving through the settings namespace.
* - `console`: a value an administrator STORED in the `auth` settings
* namespace at runtime.
*
* Only posture `open` reads it: there an explicit `false` is the deployment's
* opt-out, which the console can agree with but never make.
*/
export type VerificationDeclarant = 'deployment' | 'console';
/**
* [#20389] THE effective email-verification requirement for a posture and a
* declared `requireEmailVerification` — the one function the better-auth
* wiring (`createAuthInstance`) and the advertisement (`getPublicConfig`) both
* read, so the two cannot disagree.
*
* - `email_domain`: always ON. The domain allowlist is the only gate there, so
* an unverified sign-up is colleague impersonation (an explicit `false` is
* refused at entry by {@link assertAudienceConfig}).
* - `open`: ON unless the deployment declared it OFF with an explicit `false`
* (absent or `true` keeps the forced-on default).
* - `invite_only`: the declared value, default OFF.
*
* Callers must have passed the declaration through {@link assertAudienceConfig}:
* this resolves, it does not judge who declared the value.
*/
export function resolveEmailVerificationRequirement(
posture: AudiencePosture,
declared: boolean | undefined,
): boolean {
if (posture === 'email_domain') return true;
if (posture === 'open') return declared !== false;
return declared ?? false;
}
/**
* [#20389] The boot warning for posture `open` running with email verification
* explicitly off. It names the posture and the consequence, and is logged once
* per boot by `AuthPlugin` after the settings namespace is applied.
*/
export const OPEN_POSTURE_VERIFICATION_OFF_WARNING =
"[auth] audience posture 'open' is running with email verification explicitly OFF " +
'(emailAndPassword.requireEmailVerification: false, or OS_AUTH_REQUIRE_EMAIL_VERIFICATION=false). ' +
'Anyone can register an address they do not control and is signed in at once; an organization ' +
'invitation sent to that address still waits for the address to be verified. Keep this to a deployment ' +
'with no mail transport that trusts its sign-ups, such as a pre-production environment; remove the ' +
'explicit false to force verification back on.';
/**
* Entry validation — REFUSES an unusable audience declaration at the point it
* enters the manager (constructor and `applyConfigPatch`), loudly, with the
* remedy in the message. Mirrors `AudienceConfigSchema`'s predicates (the
* schema guards the authoring surface; the runtime receives plain objects),
* refuses one value the schema does not — an MCP agent ceiling set as the
* self-registration set ([ADR-0090 D10]: a self-registrant is a person, and an
* agent ceiling is not a person's set) — and adds the one cross-field invariant
* the schema cannot see, on
* `emailAndPassword.requireEmailVerification` (verification is FORCED on by
* the wiring under both self-registration postures unless noted):
*
* - `email_domain` ⇒ must not be explicitly `false` — refused: an unverified
* allowlisted-domain signup is colleague impersonation and makes the
* domain gate decorative.
* - `open` ⇒ an explicit `false` is honoured when the DEPLOYMENT declared it
* (#20389: a pre-production deployment with no mail transport otherwise
* dead-ends every sign-up at the verify page), and refused when only the
* console stored it (`verificationDeclaredBy: 'console'`).
*
* On a cloud-managed environment (`isCloudManaged()`, `@objectstack/core`)
* every posture but `invite_only` is refused: the vocabulary is unchanged, the
* refusal is the runtime's.
*/
export function assertAudienceConfig(
raw: AudienceConfig | undefined,
emailAndPassword: EmailAndPasswordConfig | undefined,
options: { verificationDeclaredBy?: VerificationDeclarant } = {},
): void {
if (raw === undefined || raw === null) return;
const fail = (message: string): never => {
throw new Error(`[audience] invalid audience configuration: ${message}`);
};
const rawPosture = (raw as { posture?: unknown }).posture;
if (rawPosture !== undefined && !isAudiencePosture(rawPosture)) {
fail(
`posture ${describeAudiencePosture(rawPosture)} is not a recognized audience posture — ` +
`expected one of: ${AUDIENCE_POSTURES.join(', ')}. Refused, never coerced: an unrecognised value must not fall through to a more permissive posture than the one intended.`,
);
}
const posture: AudiencePosture = (rawPosture as AudiencePosture | undefined) ?? 'invite_only';
// [#25083] A cloud-managed environment never opens self-registration: the
// organisation that hosts it invites its people in the cloud. Refused rather
// than coerced, so a declared `open` never reads as in force — at
// construction the refusal stops the boot, and on a merged patch the
// standing posture keeps ruling.
if (posture !== 'invite_only' && isCloudManaged()) {
fail(
`posture '${posture}' opens self-registration, which a cloud-managed environment (OS_CLOUD_MANAGED) never offers: ` +
"the organisation that hosts it invites its people in the cloud. Use posture 'invite_only' (the default), or remove the posture.",
);
}
const domains = raw.allowedEmailDomains;
if (domains !== undefined && !Array.isArray(domains)) {
fail('allowedEmailDomains must be an array of bare domain names');
}
if (posture === 'email_domain') {
if (!domains || domains.length === 0) {
fail(
"posture 'email_domain' requires a non-empty allowedEmailDomains list — declare the domains, " +
"or use posture 'invite_only'.",
);
}
} else if (domains !== undefined) {
fail(
`allowedEmailDomains is only read under posture 'email_domain' — under '${posture}' it is declared ` +
'but inert (ADR-0078) and reads as a wall that does not exist. Remove it, or set posture to email_domain.',
);
}
if (domains) {
const seen = new Set<string>();
for (const entry of domains) {
if (typeof entry !== 'string' || !isDeclarableEmailDomain(entry)) {
fail(
`allowedEmailDomains entry ${describeAudiencePosture(entry)} is not a bare domain name ` +
'(expected e.g. "acme.com" — no scheme, no "@", no wildcard, at least one dot).',
);
}
const lowered = entry.toLowerCase();
if (seen.has(lowered)) fail(`allowedEmailDomains entry '${entry}' is duplicated (matching is case-insensitive)`);
seen.add(lowered);
}
}
const set = raw.selfRegistrationPermissionSet;
if (audiencePermitsSelfRegistration(posture)) {
if (typeof set !== 'string' || set.length === 0) {
fail(
`posture '${posture}' permits self-registration, so selfRegistrationPermissionSet must DECLARE the ` +
'permission set a self-registrant receives (the implicit member_default fallback is retired; ' +
'declaring member_default explicitly is allowed).',
);
}
if (set === 'admin_full_access') {
fail(
"selfRegistrationPermissionSet must not be 'admin_full_access' — a platform-admin grant to every " +
'self-registrant is never a declarable audience.',
);
}
// [ADR-0090 D10] A self-registrant is a person, and an agent ceiling is not
// a person's set: the declaration that names the set refuses one.
if (typeof set === 'string' && (MCP_AGENT_PERMISSION_SETS as readonly string[]).includes(set)) {
fail(
`selfRegistrationPermissionSet must not be '${set}' — it is the permission ceiling of an AI assistant ` +
'connected over MCP, which the assistant receives from the access its user consented to, never from an ' +
'assignment, and a self-registrant is a person. Declare a permission set meant for people.',
);
}
if (emailAndPassword?.requireEmailVerification === false) {
if (posture === 'email_domain') {
fail(
`posture '${posture}' opens self-registration, which FORCES email verification on — ` +
'emailAndPassword.requireEmailVerification: false contradicts it and is refused ' +
'(an unverified allowlisted-domain signup is colleague impersonation). ' +
"Remove the explicit false, or close the posture to 'invite_only'.",
);
}
if ((options.verificationDeclaredBy ?? 'deployment') === 'console') {
fail(
`posture '${posture}' FORCES email verification on unless the DEPLOYMENT turns it off — ` +
'a requireEmailVerification: false stored in the auth settings console cannot, and is refused. ' +
'Set OS_AUTH_REQUIRE_EMAIL_VERIFICATION=false (or emailAndPassword.requireEmailVerification: false ' +
"in the stack config) to opt out, remove the stored value, or close the posture to 'invite_only'.",
);
}
}
} else if (set !== undefined) {
fail(
"selfRegistrationPermissionSet is only read under a posture that permits self-registration — under " +
`'${posture}' it is declared but inert (ADR-0078). Remove it, or open the posture deliberately.`,
);
}
}
/** Declaration-side domain shape (mirrors the spec schema's regex). */
const DECLARABLE_DOMAIN = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)+$/;
export function isDeclarableEmailDomain(entry: string): boolean {
return DECLARABLE_DOMAIN.test(entry);
}
/**
* Pinned rule 1: the candidate domain is everything after the LAST `@`,
* lowercased; no `@` / empty remainder ⇒ `null` (never matches).
*/
export function extractEmailDomain(email: unknown): string | null {
if (typeof email !== 'string') return null;
const at = email.lastIndexOf('@');
if (at < 0) return null;
const domain = email.slice(at + 1).trim().toLowerCase();
return domain.length > 0 ? domain : null;
}
/** Pinned rules 2–5: exact, case-insensitive, per-entry equality. */
export function emailDomainAllowed(email: unknown, allowedDomains: readonly string[]): boolean {
const domain = extractEmailDomain(email);
if (!domain) return false;
for (const entry of allowedDomains) {
if (typeof entry === 'string' && entry.toLowerCase() === domain) return true;
}
return false;
}
/**
* THE bootstrap population predicate — "does this environment already have a
* HUMAN user?" — owned once, here, and asked by every consumer of the
* first-run bypass.
*
* ## Humans, not rows (the canonical answer)
*
* The bootstrap bypass counts **non-system humans**, never "any `sys_user`
* row". Three call sites ask this same question and they must agree:
*
* - the audience gate's bootstrap bypass (`isBootstrapCreation`);
* - plugin-auth's dev-admin seed, whose own precondition has always filtered
* `usr_system` / `role === 'system'` before deciding to seed;
* - plugin-security's first-user detection, which prints "no human users yet
* — first sign-up will be promoted to platform admin" off the identical
* filter and then promotes that sign-up.
*
* If the audience gate counted ANY row while those two counted humans, the
* two would disagree on exactly one population: a database still carrying the
* legacy `usr_system` service row (`SystemUserId.SYSTEM` — no longer
* provisioned, but present in every DB an older runtime created). There,
* plugin-security would announce "no human users yet" and stand ready to
* promote the first sign-up while the audience gate refused that very
* sign-up with `SELF_REGISTRATION_CLOSED` — a fresh-looking install locked
* out of itself, which is the one outcome the bypass exists to prevent.
* Humans is therefore canonical, and the disagreement is closed by both
* plugin-auth call sites reading THIS function rather than re-spelling the
* filter.
*
* ## Why the filter runs in JS and not in the where-clause
*
* A store-side `role != 'system'` drops rows whose `role` is NULL under SQL
* three-valued logic — i.e. it would hide ordinary humans, the direction that
* fails open. The rows are read unfiltered and judged here.
*/
export function isHumanUserRow(row: unknown): boolean {
if (!row || typeof row !== 'object') return false;
const user = row as { id?: unknown; role?: unknown };
if (user.id === SystemUserId.SYSTEM) return false;
if (user.role === 'system') return false;
return true;
}
/**
* How the incoming creation reached the platform, from the vendor-supplied
* `source` (see the module doc for why each class lands where it does).
*/
export type AudienceCreationClass = 'operator' | 'provider' | 'self-serve';
const OPERATOR_METHODS: ReadonlySet<string> = new Set(['admin', 'scim']);
const PROVIDER_METHODS: ReadonlySet<string> = new Set(['sso-oidc', 'sso-saml']);
export function classifyCreationMethod(
source: { method?: unknown; oauth?: { providerId?: unknown } } | undefined,
opts: { enterpriseOAuthProviderIds: ReadonlySet<string> },
): AudienceCreationClass {
const method = typeof source?.method === 'string' ? source.method : '';
if (OPERATOR_METHODS.has(method)) return 'operator';
if (PROVIDER_METHODS.has(method)) return 'provider';
if (method === 'oauth') {
const providerId = source?.oauth?.providerId;
if (typeof providerId === 'string' && opts.enterpriseOAuthProviderIds.has(providerId)) {
return 'provider';
}
return 'self-serve';
}
// Known self-serve methods AND any unrecognized method: posture-gated
// (fail closed — an unclassified future creation path must not bypass the
// audience wall silently).
return 'self-serve';
}
export type AudienceAdmission =
| { admit: true; grantPermissionSet: boolean }
| { admit: false; code: string; message: string };
export interface AudienceAdmissionInput {
audience: ResolvedAudience;
creationClass: AudienceCreationClass;
/** The would-be user's email, as the creation path carries it. */
email: string | undefined;
/**
* The creation holds a pending, unexpired `sys_invitation` row, by the proof
* {@link invitationProofFor} asks of it.
*/
hasPendingInvitation: boolean;
/**
* No user exists yet — the first-run owner wizard / seeded admin creating
* the very first account. Mirrors the `disableSignUp` bootstrap bypass: a
* fresh install must never lock its operator out.
*/
isBootstrap: boolean;
/**
* Present when a `provider`-class creation came through a registered
* `@better-auth/sso` provider (`sso-oidc` / `sso-saml`): that provider's
* `allowJit` toggle (`sso-sign-in-options.ts`). Absent for every other
* creation, an `oidcProviders` entry included.
*/
ssoProvider?: { allowJit: boolean };
/** The vendor's `source.method` for the creation (`oauth` for a social provider). */
method?: unknown;
/**
* What the creation's identity provider said of the address, as the vendor
* hands it (`user.emailVerified`). Verified only when it is `true`.
*/
emailVerified?: unknown;
/**
* The deployment's declared `emailAndPassword.requireEmailVerification`,
* resolved here by {@link resolveEmailVerificationRequirement}, the resolver
* the better-auth wiring and the public config read. Absent resolves to the
* posture's default, so under `open` email verification is in force unless
* the deployment declared an explicit `false`.
*/
declaredEmailVerification?: boolean;
}
/**
* A self-serve creation through a social provider: `oauth` whose providerId is
* not an operator-registered `oidcProviders` entry ({@link classifyCreationMethod}
* classes those `provider`). It is told by the creation class and method, not
* by a list of providers, so a social provider configured later is covered
* without being named.
*/
function isSocialProviderCreation(creationClass: AudienceCreationClass, method: unknown): boolean {
return creationClass === 'self-serve' && method === 'oauth';
}
/**
* Whether a valid posture's admission of a self-serve creation rests on its
* address: `email_domain` always, and `open` while email verification is in
* force. Under either, a self-serve creation through a social provider is
* admitted only when the provider verified the address
* ({@link decideAudienceAdmission}). Under `invite_only` the invitation proof
* already asks it of an OAuth creation ({@link invitationProofFor}).
*/
function admissionRestsOnAddress(audience: ResolvedAudience, declaredEmailVerification: boolean | undefined): boolean {
if (audience.invalid) return false;
if (audience.posture === 'email_domain') return true;
if (audience.posture === 'open') return resolveEmailVerificationRequirement('open', declaredEmailVerification);
return false;
}
/**
* What a creation must show for the invitation carve-out to answer for it:
*
* - `presented` — the request presents the invitation itself, its id, and
* that row is pending, unexpired and addressed to the creation's email
* (`isPresentedInvitationPending`);
* - `address` — a pending, unexpired invitation is addressed to the
* creation's email (`AuthManager#hasPendingInvitationFor`);
* - `none` — no invitation admits it.
*/
export type InvitationProof = 'presented' | 'address' | 'none';
/**
* Which {@link InvitationProof} the carve-out asks of a creation. Under a
* valid `invite_only` posture a self-serve email-and-password sign-up must
* present the invitation, and a self-serve OAuth creation is matched by
* address only when the identity provider verified it (`emailVerified`
* `true`). Magic link and email OTP create an account only after the mailbox
* answered, so they keep the address match, as does every other method (a
* phone or anonymous creation carries no invited address to match), the
* `provider` class, and every creation under `open` and `email_domain`.
*/
export function invitationProofFor(input: {
audience: ResolvedAudience;
creationClass: AudienceCreationClass;
method: unknown;
emailVerified: unknown;
}): InvitationProof {
const { audience, creationClass, method, emailVerified } = input;
if (audience.invalid || audience.posture !== 'invite_only' || creationClass !== 'self-serve') return 'address';
if (method === 'email-password') return 'presented';
if (method === 'oauth') return emailVerified === true ? 'address' : 'none';
return 'address';
}
/**
* Whether an admitted self-serve sign-up was admitted by its invitation alone,
* so the membership settle does not bind it into the deployment's
* organization while its address is unverified (`settleMembership`,
* `auth-manager-membership-admission.ts`). It joins by accepting the
* invitation, which needs a verified address and writes the role the issuer
* chose. An invitation proves no mailbox: under `invite_only` its id is
* carried by the accept link and by a copied link, and under `email_domain`
* the address match reads only the address the sign-up typed.
*
* - `invite_only`: the sign-up presented the invitation, which is pending,
* unexpired and addressed to it ({@link invitationProofFor} `presented`).
* - `email_domain`: the sign-up's address is off the allowlist, and a pending
* invitation addressed to it admitted it. An address on the list is admitted
* by the domain rule, invitation or not ({@link isAdmittedByPostureRule}),
* binds as before and receives the declared self-registration set.
* - `open`, an off-vocabulary posture, and every creation that is not
* self-serve: never.
*/
export function isAdmittedByInvitationAlone(input: {
audience: ResolvedAudience;
creationClass: AudienceCreationClass;
email: string | undefined;
proof: InvitationProof;
hasPendingInvitation: boolean;
}): boolean {
const { audience, creationClass, email, proof, hasPendingInvitation } = input;
if (!hasPendingInvitation || audience.invalid || creationClass !== 'self-serve') return false;
// `open`, and `email_domain` on the allowlist: admitted by the posture's rule.
if (isAdmittedByPostureRule(audience, email)) return false;
if (audience.posture === 'invite_only') return proof === 'presented';
return audience.posture === 'email_domain';
}
/**
* Whether a valid posture's own rule admits a self-serve creation by its
* address, with no invitation: `open` admits every address, `email_domain` an
* address on the allowlist ({@link emailDomainAllowed}), and `invite_only`
* none. The one classification both readers of an invitation share: a
* sign-up the rule admits is admitted by that rule, invitation or not, so the
* admission verdict grants it the declared self-registration set
* ({@link decideAudienceAdmission}) and the membership settle binds it at
* creation ({@link isAdmittedByInvitationAlone}).
*/
function isAdmittedByPostureRule(audience: ResolvedAudience, email: string | undefined): boolean {
if (audience.invalid) return false;
if (audience.posture === 'open') return true;
if (audience.posture === 'email_domain') return emailDomainAllowed(email, audience.allowedEmailDomains);
return false;
}
/** The refusal message for an unknown user arriving through an SSO provider under `invite_only`. */
const SSO_JIT_CLOSED_MESSAGE =
'This single sign-on provider does not create accounts for people who were not invited ' +
'(audience posture invite_only). Ask an administrator for an invitation, or ask them to turn on ' +
'just-in-time provisioning (allowJit) for this provider.';
/** The refusal message for a social-provider creation whose address the provider did not verify. */
const socialAddressUnverifiedMessage = (posture: AudiencePosture): string =>
'This sign-in provider has not verified the email address, and this environment creates an account through ' +
`a social sign-in only for a verified address (audience posture ${posture}). ` +
'Verify the address with the provider and sign in again.';
/**
* THE admission decision — pure, so the posture × method matrix is a table of
* direct calls. Order: creation-class exemptions → bootstrap → vocabulary
* guard (fail closed) → the social-provider address rule → the posture's own
* rule ({@link isAdmittedByPostureRule}, with the self-registration grant) →
* the invitation carve-out (no grant) → the posture's refusal.
*
* The social-provider address rule: under a posture whose admission rests on
* the address ({@link admissionRestsOnAddress}: `email_domain` always, `open`
* while email verification is in force), a self-serve creation through a
* social provider is admitted only when the provider verified the address.
* Otherwise it is refused `SELF_REGISTRATION_CLOSED`, as `invite_only` refuses
* it, and nothing is written: no account row, no session, no membership. A
* pending invitation does not admit it either — the invitation is matched by
* that same address. The `operator` and `provider` classes, and the bootstrap
* carve-out, stay ahead of the rule.
*/
export function decideAudienceAdmission(input: AudienceAdmissionInput): AudienceAdmission {
const { audience, creationClass, email, hasPendingInvitation, isBootstrap, ssoProvider } = input;
if (creationClass === 'operator') {
return { admit: true, grantPermissionSet: false };
}
if (creationClass === 'provider') {
// An SSO provider under a VALID `invite_only` posture admits an unknown
// user only by its `allowJit` toggle, an invitation, or the bootstrap
// carve-out (module doc, `provider`). Every other provider creation, and
// every other posture, admits as before.
const gated = ssoProvider !== undefined && !ssoProvider.allowJit && !audience.invalid && audience.posture === 'invite_only';
if (!gated || isBootstrap || hasPendingInvitation) return { admit: true, grantPermissionSet: false };
return { admit: false, code: SELF_REGISTRATION_CLOSED, message: SSO_JIT_CLOSED_MESSAGE };
}
if (isBootstrap) {
return { admit: true, grantPermissionSet: false };
}
if (audience.invalid) {
return {
admit: false,
code: AUDIENCE_CONFIG_ERROR,
message:
`audience posture ${audience.invalid.raw} is not a recognized value (expected one of: ` +
`${AUDIENCE_POSTURES.join(', ')}) — self-registration is refused until the configuration is fixed. ` +
'This is a configuration error, not a policy refusal.',
};
}
if (
isSocialProviderCreation(creationClass, input.method) &&
input.emailVerified !== true &&
admissionRestsOnAddress(audience, input.declaredEmailVerification)
) {
return { admit: false, code: SELF_REGISTRATION_CLOSED, message: socialAddressUnverifiedMessage(audience.posture) };
}
if (isAdmittedByPostureRule(audience, email)) {
// The posture's own rule first: `open`, and `email_domain` for an address
// on the allowlist, admit the sign-up by that rule, invitation or not, so
// it receives the declared self-registration set. A pending invitation
// still places it as the invitation names once it accepts. The membership
// settle reads the same classification (`isAdmittedByInvitationAlone`).
return { admit: true, grantPermissionSet: true };
}
if (hasPendingInvitation) {
// An explicit invitation is a stronger operator act than any posture —
// it admits the invitee's own account creation under invite_only AND
// trumps the email_domain allowlist (module doc: the invite dead-end).
// Admitted by the invitation alone, the sign-up gets the account and no
// self-registration grant.
return { admit: true, grantPermissionSet: false };
}
switch (audience.posture) {
case 'invite_only':
return {
admit: false,
code: SELF_REGISTRATION_CLOSED,
message:
'Self-registration is closed (audience posture invite_only). ' +
'Ask an administrator for an invitation.',
};
case 'email_domain':
// An address on the allowlist was admitted by the posture's rule above.
return {
admit: false,
code: EMAIL_DOMAIN_NOT_ALLOWED,
message:
'Self-registration is limited to approved email domains, and this address ' +
'is not on the list. Use your organization email, or ask an administrator for an invitation.',
};
default: {
// `open` was admitted by the posture's rule above, so this is
// unreachable for a well-typed posture; keep the fail-closed floor.
return {
admit: false,
code: AUDIENCE_CONFIG_ERROR,
message: `audience posture ${describeAudiencePosture(audience.posture)} is not a recognized value.`,
};
}
}
}