Repository navigation
Expand file tree
/
Copy pathaudience-posture.test.ts
More file actions
1341 lines (1227 loc) · 64.4 KB
/
Copy pathaudience-posture.test.ts
File metadata and controls
1341 lines (1227 loc) · 64.4 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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// [#11739] Audience posture — the declared answer to "who may become a user of
// this environment", enforced at better-auth's `user.validateUserInfo` seam.
//
// Three layers, matching the module split:
//
// 1. PURE decision matrix — `decideAudienceAdmission` / `classifyCreationMethod`
// drive the full posture × creation-method table as direct calls, including
// the paths an HTTP harness cannot cheaply reach (SSO JIT, SCIM, unknown
// methods).
// 2. ENTRY validation — `assertAudienceConfig` at the constructor and
// `applyConfigPatch`: off-vocabulary postures, inert declarations
// (ADR-0078), the open-with-verification-off contradiction.
// 3. END of the chain (the #4785 lesson: assert the outcome, not the middle) —
// a real better-auth pipeline over the in-memory engine: refusals carry the
// REGISTERED code + 403 status on the wire, admissions mint accounts, and
// an admitted self-registrant really receives the declared permission set
// (`sys_user_permission_set` row), because a declaration nothing lands is
// the ADR-0078 defect this card closes.
import { describe, it, expect, vi } from 'vitest';
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql';
import { ERROR_CODE_LEDGER } from '@objectstack/spec/api';
import { MCP_AGENT_PERMISSION_SETS } from '@objectstack/spec/ai';
import { AuthManager } from './auth-manager';
// The SSO discovery egress guard the source loads with a dynamic import, paid
// here, during collection (check-test-source-alias, "The source reach").
import '@objectstack/core/egress';
import { bindTestSecurityCatalog, catalogFromTables } from './__tests__/security-catalog.testkit.js';
import {
assertAudienceConfig,
classifyCreationMethod,
decideAudienceAdmission,
emailDomainAllowed,
extractEmailDomain,
invitationProofFor,
isAdmittedByInvitationAlone,
resolveAudience,
resolveEmailVerificationRequirement,
SELF_REGISTRATION_CLOSED,
EMAIL_DOMAIN_NOT_ALLOWED,
AUDIENCE_CONFIG_ERROR,
type ResolvedAudience,
} from './audience-posture';
// ── In-memory IDataEngine (the #3585 / session-of-record harness shape) ──────
const createMemoryEngine = () => {
const tables = new Map<string, any[]>();
const rows = (name: string) => {
if (!tables.has(name)) tables.set(name, []);
return tables.get(name)!;
};
const eq = (a: any, b: any) =>
a instanceof Date || b instanceof Date
? new Date(a as any).getTime() === new Date(b as any).getTime()
: a === b;
const matches = (row: any, where: Record<string, any> = {}) =>
Object.entries(where).every(([k, v]) => {
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
const actual = row[k];
if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {
if ('$ne' in v) return !eq(actual, v.$ne);
if ('$in' in v) return (v.$in as any[]).some((x) => eq(actual, x));
if ('$gt' in v) return actual > v.$gt;
if ('$gte' in v) return actual >= v.$gte;
if ('$lt' in v) return actual < v.$lt;
if ('$lte' in v) return actual <= v.$lte;
}
return eq(actual, v);
});
const project = (row: any, fields?: string[]) => {
if (!Array.isArray(fields) || fields.length === 0) return { ...row };
const out: any = {};
for (const f of ['id', ...fields]) if (f in row) out[f] = row[f];
return out;
};
let seq = 0;
return {
tables,
async insert(name: string, data: any) {
const row = { id: data.id ?? `row_${++seq}`, ...data };
rows(name).push(row);
return { ...row };
},
async findOne(name: string, q: any = {}) {
assertEngineFindOnePredicate(name, q);
const row = rows(name).find((r) => matches(r, q.where));
return row ? project(row, q.fields) : null;
},
async find(name: string, q: any = {}) {
let out = rows(name).filter((r) => matches(r, q.where));
if (q.offset) out = out.slice(q.offset);
// Presence, not truthiness: `limit: 0` is a request for NOTHING, and `0`
// is falsy — `if (q.limit)` answers it with every matched row.
if (typeof q.limit === 'number') out = out.slice(0, q.limit);
return out.map((r) => project(r, q.fields));
},
async count(name: string, q: any = {}) {
return rows(name).filter((r) => matches(r, q.where)).length;
},
async update(name: string, patch: any, options?: any) {
assertEngineUpdateDispatch(patch, options);
const row = rows(name).find((r) => r.id === patch.id);
if (!row) return null;
Object.assign(row, patch);
return { ...row };
},
async delete(name: string, q: any = {}) {
assertEngineDeleteDispatch(q);
const table = rows(name);
const keep = table.filter((r) => !matches(r, q.where));
tables.set(name, keep);
return table.length - keep.length;
},
};
};
const SECRET = 'test-secret-at-least-32-chars-long!!';
const PASSWORD = 'S3cure!Passw0rd-4785';
/**
* [ADR-0131 D3/D4] The sets the fixture's `sys_permission_set` rows name are
* catalog definitions too — the admission asks the catalog whether a set
* grants, and the grant names it (ADR-0131 D4).
*/
const bindRowCatalog = (engine: any) =>
bindTestSecurityCatalog(engine, () => catalogFromTables({ sys_permission_set: engine.tables.get('sys_permission_set') }));
/**
* [ADR-0131 D3] The self-registration grant is written WITH a membership. The
* end-of-chain cases that assert the grant lands at sign-up run `single`: the
* reconciler binds the Default Organization in the same `user.create.after`
* hook, and the grant is owned by it. The walled half (no membership yet, the
* grant held as a claim until the first one) is pinned in
* `self-registration-grant-first-membership.test.ts`.
*/
const SINGLE_TENANCY = () => ({ defaultOrgId: async () => 'org_default' });
const makeManager = (engine: any, config: Record<string, unknown> = {}) =>
new AuthManager({
secret: SECRET,
baseUrl: 'http://localhost:3000',
dataEngine: bindRowCatalog(engine),
...config,
} as any);
const signUp = (manager: AuthManager, email: string, invitationId?: string) =>
manager.handleRequest(
new Request('http://localhost:3000/api/v1/auth/sign-up/email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password: PASSWORD, name: 'Audience Test', invitationId }),
}),
);
/**
* A magic-link creation asked of the real admission gate: a door that keeps
* the address match under `invite_only` (`invitationProofFor`), so it is the
* door the address probe's own pins drive. `undefined` admits.
*/
const magicLinkCreation = (manager: AuthManager, email: string) =>
(manager as any).validateAudienceAdmission({
user: { email },
source: { action: 'create-user', method: 'magic-link' },
});
/** Seed one existing user so the zero-user bootstrap bypass is OFF. */
const seedExistingUser = (engine: any) => {
engine.tables.set('sys_user', [
{
id: 'usr_existing',
email: 'owner@example.com',
name: 'Owner',
email_verified: true,
created_at: new Date(),
updated_at: new Date(),
},
]);
};
const seedPermissionSet = (engine: any, name: string, extra: Record<string, unknown> = {}) => {
engine.tables.set('sys_permission_set', [
...(engine.tables.get('sys_permission_set') ?? []),
{ id: `ps_${name}`, name, label: name, active: true, ...extra },
]);
};
/** Seed a pending invitation and answer its id, which a sign-up presents. */
const seedPendingInvitation = (engine: any, email: string, extra: Record<string, unknown> = {}): string => {
const id = `inv_${Math.random().toString(36).slice(2, 8)}`;
engine.tables.set('sys_invitation', [
...(engine.tables.get('sys_invitation') ?? []),
{
id,
email,
status: 'pending',
organization_id: 'org_1',
expires_at: new Date(Date.now() + 60_000),
...extra,
},
]);
return id;
};
const audience = (over: Partial<ResolvedAudience> = {}): ResolvedAudience => ({
posture: 'invite_only',
allowedEmailDomains: [],
...over,
});
// ─────────────────────────────────────────────────────────────────────────────
describe('pinned domain matching (#11739)', () => {
it('rule 1: the domain is everything after the LAST @; no @ / empty ⇒ no match ever', () => {
expect(extractEmailDomain('user@acme.com')).toBe('acme.com');
expect(extractEmailDomain('we"ird@user@acme.com')).toBe('acme.com');
expect(extractEmailDomain('no-at-sign')).toBeNull();
expect(extractEmailDomain('trailing@')).toBeNull();
expect(extractEmailDomain(undefined)).toBeNull();
expect(emailDomainAllowed('no-at-sign', ['acme.com'])).toBe(false);
});
it('rule 2: case-insensitive on both sides', () => {
expect(emailDomainAllowed('user@ACME.com', ['acme.com'])).toBe(true);
expect(emailDomainAllowed('user@acme.com', ['AcMe.CoM'])).toBe(true);
});
it('rule 3: exact equality — subdomains are NOT implied, in either direction', () => {
expect(emailDomainAllowed('user@mail.acme.com', ['acme.com'])).toBe(false);
expect(emailDomainAllowed('user@acme.com', ['mail.acme.com'])).toBe(false);
expect(emailDomainAllowed('user@mail.acme.com', ['mail.acme.com'])).toBe(true);
// A suffix that is not a label boundary must not match either.
expect(emailDomainAllowed('user@evilacme.com', ['acme.com'])).toBe(false);
});
it('rule 4: +tag local parts are irrelevant (matching never reads the local part)', () => {
expect(emailDomainAllowed('user+anything@acme.com', ['acme.com'])).toBe(true);
expect(emailDomainAllowed('user+tag@other.com', ['acme.com'])).toBe(false);
});
it('placeholder / phone-style addresses carry no matchable domain', () => {
expect(emailDomainAllowed('', ['acme.com'])).toBe(false);
});
});
describe('creation-method classification (#11739)', () => {
const enterprise = { enterpriseOAuthProviderIds: new Set(['okta', 'objectstack-cloud']) };
it('operator methods are never posture-gated: admin, scim', () => {
expect(classifyCreationMethod({ method: 'admin' }, enterprise)).toBe('operator');
expect(classifyCreationMethod({ method: 'scim' }, enterprise)).toBe('operator');
});
it('operator-registered identity authorities are provider class: sso-oidc, sso-saml, enterprise oauth', () => {
expect(classifyCreationMethod({ method: 'sso-oidc' }, enterprise)).toBe('provider');
expect(classifyCreationMethod({ method: 'sso-saml' }, enterprise)).toBe('provider');
expect(classifyCreationMethod({ method: 'oauth', oauth: { providerId: 'okta' } }, enterprise)).toBe('provider');
expect(
classifyCreationMethod({ method: 'oauth', oauth: { providerId: 'objectstack-cloud' } }, enterprise),
).toBe('provider');
});
it('self-serve methods are posture-gated: email-password, social oauth, magic-link, email-otp, phone, anonymous, siwe', () => {
for (const method of ['email-password', 'magic-link', 'email-otp', 'phone-number', 'anonymous', 'siwe']) {
expect(classifyCreationMethod({ method }, enterprise)).toBe('self-serve');
}
expect(classifyCreationMethod({ method: 'oauth', oauth: { providerId: 'google' } }, enterprise)).toBe('self-serve');
});
it('an UNRECOGNIZED method is self-serve — fail closed, a future creation path must not bypass the wall', () => {
expect(classifyCreationMethod({ method: 'future-thing' }, enterprise)).toBe('self-serve');
expect(classifyCreationMethod({}, enterprise)).toBe('self-serve');
expect(classifyCreationMethod(undefined, enterprise)).toBe('self-serve');
});
});
describe('admission decision matrix (#11739): posture × creation class', () => {
const base = { email: 'user@acme.com', hasPendingInvitation: false, isBootstrap: false };
it.each([
['invite_only', 'operator'],
['invite_only', 'provider'],
['email_domain', 'operator'],
['email_domain', 'provider'],
['open', 'operator'],
['open', 'provider'],
] as const)('%s admits the %s class (admin-create / SSO JIT are operator-sanctioned)', (posture, cls) => {
const verdict = decideAudienceAdmission({
...base,
audience: audience({ posture, allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [] }),
creationClass: cls,
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
});
it('invite_only refuses self-serve with SELF_REGISTRATION_CLOSED', () => {
const verdict = decideAudienceAdmission({ ...base, audience: audience(), creationClass: 'self-serve' });
expect(verdict.admit).toBe(false);
if (!verdict.admit) expect(verdict.code).toBe(SELF_REGISTRATION_CLOSED);
});
it('invite_only admits a self-serve creation holding a pending invitation (the carve-out)', () => {
const verdict = decideAudienceAdmission({
...base,
hasPendingInvitation: true,
audience: audience(),
creationClass: 'self-serve',
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
});
it('email_domain admits on-list self-serve WITH the permission-set grant, refuses off-list with EMAIL_DOMAIN_NOT_ALLOWED', () => {
const aud = audience({
posture: 'email_domain',
allowedEmailDomains: ['acme.com'],
selfRegistrationPermissionSet: 'portal_user',
});
expect(decideAudienceAdmission({ ...base, audience: aud, creationClass: 'self-serve' })).toEqual({
admit: true,
grantPermissionSet: true,
});
const refused = decideAudienceAdmission({
...base,
email: 'user@other.com',
audience: aud,
creationClass: 'self-serve',
});
expect(refused.admit).toBe(false);
if (!refused.admit) expect(refused.code).toBe(EMAIL_DOMAIN_NOT_ALLOWED);
});
it('an explicit invitation trumps the email_domain allowlist (no invite dead-end for external invitees)', () => {
const verdict = decideAudienceAdmission({
...base,
email: 'contractor@external.com',
hasPendingInvitation: true,
audience: audience({ posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'portal_user' }),
creationClass: 'self-serve',
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
});
// A sign-up the posture's own rule admits is admitted by that rule,
// invitation or not, and receives the declared set; one admitted by its
// invitation alone gets the account and no grant.
it.each([
['email_domain', 'on the allowlist', 'colleague@acme.com', true, { admit: true, grantPermissionSet: true }],
['email_domain', 'on the allowlist', 'colleague@acme.com', false, { admit: true, grantPermissionSet: true }],
['email_domain', 'off the allowlist', 'contractor@external.com', true, { admit: true, grantPermissionSet: false }],
['open', 'any address', 'anyone@external.com', true, { admit: true, grantPermissionSet: true }],
['open', 'any address', 'anyone@external.com', false, { admit: true, grantPermissionSet: true }],
['invite_only', 'any address', 'anyone@external.com', true, { admit: true, grantPermissionSet: false }],
] as const)('%s, an address %s (%s), invited %s: %o', (posture, _where, email, invited, expected) => {
const verdict = decideAudienceAdmission({
...base,
email,
hasPendingInvitation: invited,
audience: audience({
posture,
allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [],
selfRegistrationPermissionSet: posture === 'invite_only' ? undefined : 'portal_user',
}),
creationClass: 'self-serve',
});
expect(verdict).toEqual(expected);
});
it('open admits self-serve with the grant', () => {
const verdict = decideAudienceAdmission({
...base,
audience: audience({ posture: 'open', selfRegistrationPermissionSet: 'portal_user' }),
creationClass: 'self-serve',
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: true });
});
it('bootstrap (zero users) admits self-serve under every posture — a fresh install never locks its operator out', () => {
for (const posture of ['invite_only', 'email_domain', 'open'] as const) {
const verdict = decideAudienceAdmission({
email: 'owner@anything.com',
hasPendingInvitation: false,
isBootstrap: true,
audience: audience({
posture,
allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [],
selfRegistrationPermissionSet: posture === 'invite_only' ? undefined : 'portal_user',
}),
creationClass: 'self-serve',
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
}
});
it('an off-vocabulary posture refuses with AUTH_CONFIG_ERROR — a verdict distinct from "policy said no" (#5205)', () => {
const verdict = decideAudienceAdmission({
...base,
audience: audience({ invalid: { raw: "'inviteOnly'" } }),
creationClass: 'self-serve',
});
expect(verdict.admit).toBe(false);
if (!verdict.admit) {
expect(verdict.code).toBe(AUDIENCE_CONFIG_ERROR);
expect(verdict.message).toContain("'inviteOnly'");
expect(verdict.message).toContain('configuration error');
}
});
// Ruling record 6718355623: an SSO provider (`ssoProvider` present) under
// invite_only admits an unknown user only by its allowJit toggle, an
// invitation or the bootstrap carve-out.
it('invite_only refuses an SSO-provider creation with allowJit off: SELF_REGISTRATION_CLOSED', () => {
const verdict = decideAudienceAdmission({ ...base, audience: audience(), creationClass: 'provider', ssoProvider: { allowJit: false } });
expect(verdict.admit).toBe(false);
if (!verdict.admit) expect(verdict.code).toBe(SELF_REGISTRATION_CLOSED);
});
it('invite_only admits an SSO-provider creation with allowJit on, an invitation, or at bootstrap, never with the grant', () => {
const aud = audience();
for (const input of [
{ ssoProvider: { allowJit: true } },
{ ssoProvider: { allowJit: false }, hasPendingInvitation: true },
{ ssoProvider: { allowJit: false }, isBootstrap: true },
]) {
expect(decideAudienceAdmission({ ...base, audience: aud, creationClass: 'provider', ...input })).toEqual({
admit: true,
grantPermissionSet: false,
});
}
});
it('CONTROL: email_domain and open admit an SSO-provider creation with allowJit off, as before', () => {
for (const posture of ['email_domain', 'open'] as const) {
const verdict = decideAudienceAdmission({
...base,
email: 'someone@elsewhere.com',
audience: audience({ posture, allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [], selfRegistrationPermissionSet: 'portal_user' }),
creationClass: 'provider',
ssoProvider: { allowJit: false },
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
}
});
it('CONTROL: an off-vocabulary posture admits an SSO-provider creation as before (it is judged only under a valid invite_only)', () => {
const verdict = decideAudienceAdmission({
...base,
audience: audience({ invalid: { raw: "'inviteOnly'" } }),
creationClass: 'provider',
ssoProvider: { allowJit: false },
});
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
});
it('the three refusal codes are DISTINCT and the two new ones are registered in the ADR-0112 ledger', () => {
expect(SELF_REGISTRATION_CLOSED).not.toBe(EMAIL_DOMAIN_NOT_ALLOWED);
expect(SELF_REGISTRATION_CLOSED).not.toBe(AUDIENCE_CONFIG_ERROR);
const registered = (ERROR_CODE_LEDGER as Record<string, readonly string[]>)['@objectstack/plugin-auth'];
expect(registered).toContain(SELF_REGISTRATION_CLOSED);
expect(registered).toContain(EMAIL_DOMAIN_NOT_ALLOWED);
expect(registered).toContain(AUDIENCE_CONFIG_ERROR);
});
});
describe('resolveAudience (#11739)', () => {
it('undeclared ⇒ invite_only (the ruled default — no legacy limbo)', () => {
expect(resolveAudience(undefined).posture).toBe('invite_only');
expect(resolveAudience({}).posture).toBe('invite_only');
});
it('marks an off-vocabulary posture invalid and coerces DISPLAY to the safe end, never the open one', () => {
const resolved = resolveAudience({ posture: 'inviteOnly' } as any);
expect(resolved.posture).toBe('invite_only');
expect(resolved.invalid?.raw).toBe("'inviteOnly'");
});
});
describe('entry validation: assertAudienceConfig (#11739)', () => {
it('accepts an undeclared audience and every well-formed declaration', () => {
expect(() => assertAudienceConfig(undefined, undefined)).not.toThrow();
expect(() => assertAudienceConfig({ posture: 'invite_only' }, undefined)).not.toThrow();
expect(() =>
assertAudienceConfig(
{ posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'portal_user' },
undefined,
),
).not.toThrow();
expect(() =>
assertAudienceConfig({ posture: 'open', selfRegistrationPermissionSet: 'member_default' }, undefined),
).not.toThrow();
});
it('refuses an off-vocabulary posture loudly, naming the value and the vocabulary', () => {
expect(() => assertAudienceConfig({ posture: 'inviteOnly' } as any, undefined)).toThrow(
/'inviteOnly'.*invite_only, email_domain, open/s,
);
});
it('refuses email_domain without a non-empty, well-formed, duplicate-free domain list', () => {
expect(() =>
assertAudienceConfig({ posture: 'email_domain', selfRegistrationPermissionSet: 'p' }, undefined),
).toThrow(/non-empty allowedEmailDomains/);
expect(() =>
assertAudienceConfig(
{ posture: 'email_domain', allowedEmailDomains: [], selfRegistrationPermissionSet: 'p' },
undefined,
),
).toThrow(/non-empty allowedEmailDomains/);
expect(() =>
assertAudienceConfig(
{ posture: 'email_domain', allowedEmailDomains: ['@acme.com'], selfRegistrationPermissionSet: 'p' },
undefined,
),
).toThrow(/not a bare domain name/);
expect(() =>
assertAudienceConfig(
{ posture: 'email_domain', allowedEmailDomains: ['acme.com', 'ACME.COM'], selfRegistrationPermissionSet: 'p' },
undefined,
),
).toThrow(/duplicated/);
});
it('refuses inert declarations (ADR-0078): domains outside email_domain, permission set under invite_only', () => {
expect(() =>
assertAudienceConfig({ posture: 'invite_only', allowedEmailDomains: ['acme.com'] }, undefined),
).toThrow(/inert/);
expect(() =>
assertAudienceConfig(
{ posture: 'open', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'p' },
undefined,
),
).toThrow(/inert/);
expect(() =>
assertAudienceConfig({ posture: 'invite_only', selfRegistrationPermissionSet: 'p' }, undefined),
).toThrow(/inert/);
});
it('requires the self-registrant permission set for self-registration-permitting postures, and refuses admin_full_access', () => {
expect(() => assertAudienceConfig({ posture: 'open' }, undefined)).toThrow(/selfRegistrationPermissionSet/);
expect(() =>
assertAudienceConfig({ posture: 'open', selfRegistrationPermissionSet: 'admin_full_access' }, undefined),
).toThrow(/admin_full_access/);
});
it.each(MCP_AGENT_PERMISSION_SETS)('refuses the agent ceiling set %s as the self-registration permission set, under each self-registration posture', (name) => {
const domains = { allowedEmailDomains: ['acme.com'] };
for (const audience of [{ posture: 'open' as const }, { posture: 'email_domain' as const, ...domains }]) {
expect(
() => assertAudienceConfig({ ...audience, selfRegistrationPermissionSet: name }, undefined),
audience.posture,
).toThrow(
new RegExp(`^\\[audience\\] invalid audience configuration: selfRegistrationPermissionSet must not be '${name}' — it is the permission ceiling of an AI assistant connected over MCP`),
);
}
});
it('control: a permission set meant for people stays a declarable self-registration set', () => {
for (const set of ['member_default', 'portal_user']) {
expect(() => assertAudienceConfig({ posture: 'open', selfRegistrationPermissionSet: set }, undefined), set).not.toThrow();
}
});
it('email_domain: an explicit verification-off stays refused, from ANY declarant (the domain list is the only gate there)', () => {
const emailDomain = {
posture: 'email_domain' as const,
allowedEmailDomains: ['acme.com'],
selfRegistrationPermissionSet: 'p',
};
for (const verificationDeclaredBy of [undefined, 'deployment', 'console'] as const) {
expect(
() => assertAudienceConfig(emailDomain, { requireEmailVerification: false }, { verificationDeclaredBy }),
`declared by ${verificationDeclaredBy ?? 'default'}`,
).toThrow(
/^\[audience\] invalid audience configuration: posture 'email_domain' opens self-registration, which FORCES email verification on — emailAndPassword\.requireEmailVerification: false contradicts it and is refused \(an unverified allowlisted-domain signup is colleague impersonation\)/,
);
}
// Explicit true and undefined are both fine — the wiring forces true.
expect(() => assertAudienceConfig(emailDomain, { requireEmailVerification: true })).not.toThrow();
expect(() => assertAudienceConfig(emailDomain, undefined)).not.toThrow();
});
it("open: an explicit verification-off is the DEPLOYMENT's to declare — honoured from it, refused from the console", () => {
const open = { posture: 'open' as const, selfRegistrationPermissionSet: 'p' };
// The deployment's own configuration (also the default declarant) is honoured.
expect(() => assertAudienceConfig(open, { requireEmailVerification: false })).not.toThrow();
expect(() =>
assertAudienceConfig(open, { requireEmailVerification: false }, { verificationDeclaredBy: 'deployment' }),
).not.toThrow();
// A value only the settings console stored cannot make the opt-out.
expect(() =>
assertAudienceConfig(open, { requireEmailVerification: false }, { verificationDeclaredBy: 'console' }),
).toThrow(
/^\[audience\] invalid audience configuration: posture 'open' FORCES email verification on unless the DEPLOYMENT turns it off/,
);
// Explicit true and undefined stay fine from either declarant.
for (const verificationDeclaredBy of ['deployment', 'console'] as const) {
expect(() => assertAudienceConfig(open, { requireEmailVerification: true }, { verificationDeclaredBy })).not.toThrow();
expect(() => assertAudienceConfig(open, undefined, { verificationDeclaredBy })).not.toThrow();
}
// invite_only is untouched: a console-stored false there was never a contradiction.
expect(() =>
assertAudienceConfig({ posture: 'invite_only' }, { requireEmailVerification: false }, { verificationDeclaredBy: 'console' }),
).not.toThrow();
});
it('resolveEmailVerificationRequirement: email_domain always on, open on unless declared false, invite_only follows the declaration', () => {
for (const declared of [undefined, true, false]) {
expect(resolveEmailVerificationRequirement('email_domain', declared), `email_domain/${declared}`).toBe(true);
}
expect(resolveEmailVerificationRequirement('open', undefined)).toBe(true);
expect(resolveEmailVerificationRequirement('open', true)).toBe(true);
expect(resolveEmailVerificationRequirement('open', false)).toBe(false);
expect(resolveEmailVerificationRequirement('invite_only', undefined)).toBe(false);
expect(resolveEmailVerificationRequirement('invite_only', true)).toBe(true);
expect(resolveEmailVerificationRequirement('invite_only', false)).toBe(false);
});
it('the constructor runs the same assertion (boot refusal, not a first-signup 403)', () => {
expect(() => makeManager(createMemoryEngine(), { audience: { posture: 'bogus' } })).toThrow(/bogus/);
expect(() =>
makeManager(createMemoryEngine(), { audience: { posture: 'email_domain', allowedEmailDomains: [] as string[] } }),
).toThrow(/allowedEmailDomains/);
// The constructor config IS the deployment's declaration: open + false boots…
expect(() =>
makeManager(createMemoryEngine(), {
audience: { posture: 'open', selfRegistrationPermissionSet: 'p' },
emailAndPassword: { requireEmailVerification: false },
}),
).not.toThrow();
// …and email_domain + false still refuses the boot.
expect(() =>
makeManager(createMemoryEngine(), {
audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'p' },
emailAndPassword: { requireEmailVerification: false },
}),
).toThrow(/posture 'email_domain' opens self-registration, which FORCES email verification on/);
});
it('applyConfigPatch refuses an invalid merged result and the standing config keeps ruling', () => {
const manager = makeManager(createMemoryEngine(), {
audience: { posture: 'open', selfRegistrationPermissionSet: 'portal_user' },
});
expect(() => manager.applyConfigPatch({ audience: { posture: 'email_domain' } } as any)).toThrow(
/allowedEmailDomains/,
);
expect(manager.getAudience().posture).toBe('open');
// A verification-off value only the console stored, beside a standing open
// posture, is the contradiction: refused, and verification stays on.
expect(() =>
manager.applyConfigPatch(
{ emailAndPassword: { requireEmailVerification: false } } as any,
{ requireEmailVerificationFrom: 'console' },
),
).toThrow(/posture 'open' FORCES email verification on unless the DEPLOYMENT turns it off/);
expect(manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(true);
});
it('applyConfigPatch: a deployment-declared opt-out under open is honoured, and the console may only AGREE with it', () => {
const manager = makeManager(createMemoryEngine(), {
audience: { posture: 'open', selfRegistrationPermissionSet: 'portal_user' },
});
// Host code (the default declarant) is the deployment.
manager.applyConfigPatch({ emailAndPassword: { requireEmailVerification: false } } as any);
expect(manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(false);
// The console restating the same false agrees with the deployment.
expect(() =>
manager.applyConfigPatch(
{ emailAndPassword: { requireEmailVerification: false } } as any,
{ requireEmailVerificationFrom: 'console' },
),
).not.toThrow();
// Once the deployment re-declares verification ON, a console false is refused again.
manager.applyConfigPatch({ emailAndPassword: { requireEmailVerification: true } } as any);
expect(() =>
manager.applyConfigPatch(
{ emailAndPassword: { requireEmailVerification: false } } as any,
{ requireEmailVerificationFrom: 'console' },
),
).toThrow(/unless the DEPLOYMENT turns it off/);
expect(manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(true);
});
it('applyConfigPatch: opening the posture over a console-stored false is refused — that false never becomes an opt-out', () => {
const manager = makeManager(createMemoryEngine()); // undeclared ⇒ invite_only
// Legal under invite_only, where nothing forces verification.
manager.applyConfigPatch(
{ emailAndPassword: { requireEmailVerification: false } } as any,
{ requireEmailVerificationFrom: 'console' },
);
expect(() =>
manager.applyConfigPatch({ audience: { posture: 'open', selfRegistrationPermissionSet: 'p' } } as any),
).toThrow(/unless the DEPLOYMENT turns it off/);
expect(manager.getAudience().posture).toBe('invite_only');
});
it('applyConfigPatch: under email_domain not even the deployment can turn verification off', () => {
const manager = makeManager(createMemoryEngine(), {
audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'p' },
});
expect(() =>
manager.applyConfigPatch({ emailAndPassword: { requireEmailVerification: false } } as any),
).toThrow(/posture 'email_domain' opens self-registration, which FORCES email verification on/);
expect(manager.getPublicConfig().emailPassword.requireEmailVerification).toBe(true);
});
});
describe('end of the chain: better-auth pipeline over the memory engine (#11739)', () => {
it('bootstrap: the very first signup is admitted under the default (undeclared ⇒ invite_only)', async () => {
const engine = createMemoryEngine();
const manager = makeManager(engine);
const res = await signUp(manager, 'first@anything.com');
expect(res.status).toBeLessThan(300);
expect(engine.tables.get('sys_user')?.length).toBe(1);
});
it('undeclared audience: a SECOND self-serve signup is refused 403 SELF_REGISTRATION_CLOSED', async () => {
const engine = createMemoryEngine();
const manager = makeManager(engine);
await signUp(manager, 'first@anything.com');
const res = await signUp(manager, 'second@anything.com');
expect(res.status).toBe(403);
const body = await res.json();
expect(body.code).toBe(SELF_REGISTRATION_CLOSED);
expect(String(body.message)).toContain('Self-registration is closed');
// The refusal really refused — no second user row landed.
expect(engine.tables.get('sys_user')?.length).toBe(1);
});
it('invite_only: the pending invitation a sign-up presents admits it (address in any case), an expired one does not', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
const manager = makeManager(engine);
// better-auth 1.7.1 normalizes BOTH sides before this gate ever runs:
// `organization/invite-member` lowercases the address it stores, and
// `internalAdapter.createUser` lowercases the registrant's before calling
// `validateUserInfo`. So the row holds the normalized form, and the
// case-insensitivity the invitee experiences is that the address THEY type
// may carry any case at all.
const bob = seedPendingInvitation(engine, 'bob@acme.com');
const admitted = await signUp(manager, 'Bob@Acme.com', bob);
expect(admitted.status).toBeLessThan(300);
const late = seedPendingInvitation(engine, 'late@acme.com', { expires_at: new Date(Date.now() - 60_000) });
const refused = await signUp(manager, 'late@acme.com', late);
expect(refused.status).toBe(403);
expect((await refused.json()).code).toBe(SELF_REGISTRATION_CLOSED);
});
// ── [#11770] The page boundary of the pending-invitation probe ────────────
//
// The carve-out's first spelling read `{ status: 'pending' }` with
// `limit: 200` and matched the address in JS, so an invitee outside that
// first page was refused `SELF_REGISTRATION_CLOSED` under the `invite_only`
// default — the invitation lane silently failing for the TAIL of a large
// rollout. The suite covered expiry and case-insensitivity but never crossed
// a page, which is precisely why the ceiling was invisible.
it('invite_only: an invitation past the page boundary still admits — a 500-person rollout has no silent tail (#11770)', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
const manager = makeManager(engine);
// A 500-employee onboarding, with the target seeded LAST so it sits far
// outside the first page of any read that pages the pending POPULATION.
for (let i = 0; i < 500; i++) seedPendingInvitation(engine, `colleague${i}@acme.com`);
seedPendingInvitation(engine, 'last.hire@acme.com');
const pending = engine.tables.get('sys_invitation') ?? [];
expect(pending.length).toBe(501);
// The fixture really crosses the old boundary — assert the placement
// rather than trusting the loop above to have produced it.
expect(pending.findIndex((r: any) => r.email === 'last.hire@acme.com')).toBeGreaterThan(200);
expect(await magicLinkCreation(manager, 'last.hire@acme.com')).toBeUndefined();
});
it('the probe reads sys_invitation NARROWED by email — the work never depends on how many invitations exist (#11770)', async () => {
const readsForPopulation = async (otherPending: number) => {
const engine = createMemoryEngine();
seedExistingUser(engine);
const manager = makeManager(engine);
for (let i = 0; i < otherPending; i++) seedPendingInvitation(engine, `colleague${i}@acme.com`);
seedPendingInvitation(engine, 'targeted@acme.com');
const reads: any[] = [];
const find = engine.find.bind(engine);
engine.find = async (name: string, q: any = {}) => {
if (name === 'sys_invitation') reads.push(q);
return find(name, q);
};
expect(await magicLinkCreation(manager, 'targeted@acme.com')).toBeUndefined();
return reads;
};
const small = await readsForPopulation(1);
const large = await readsForPopulation(400);
// Every read carries BOTH predicates. Without the email predicate the only
// way to stay correct is to walk the whole pending population, which is an
// unbounded read on the self-serve sign-up path.
expect(small.length).toBeGreaterThan(0);
for (const q of [...small, ...large]) {
expect(q.where?.status).toBe('pending');
expect(q.where?.email).toBe('targeted@acme.com');
expect(q.offset ?? 0).toBe(0); // one page settled it, either way
}
// 2 pending rows or 401 — identical work.
expect(large.length).toBe(small.length);
});
it('a case-folding collation may answer with a differently-cased row (matched) but never a different address (#11770)', async () => {
// Some collations answer `email = 'x'` case-insensitively — and MySQL's
// default folds accents with it. The JS re-check is what keeps the probe's
// answer identical across drivers: a case-only difference still matches,
// an accent-only difference must not.
const foldingEngine = (stored: string) => {
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPendingInvitation(engine, stored);
const find = engine.find.bind(engine);
engine.find = async (name: string, q: any = {}) => {
if (name !== 'sys_invitation') return find(name, q);
// The store ignores the email predicate entirely — the widest a
// folding collation could plausibly be.
const where: Record<string, unknown> = { ...(q.where ?? {}) };
delete where.email;
return find(name, { ...q, where });
};
return engine;
};
const cased = foldingEngine('Bob@Acme.com');
expect(await magicLinkCreation(makeManager(cased), 'bob@acme.com')).toBeUndefined();
const accented = foldingEngine('bób@acme.com');
const refused = await magicLinkCreation(makeManager(accented), 'bob@acme.com');
expect(refused?.error).toBe(SELF_REGISTRATION_CLOSED);
});
it('email_domain: on-list admitted AND the declared permission set really lands; off-list refused with EMAIL_DOMAIN_NOT_ALLOWED', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPermissionSet(engine, 'portal_user');
const manager = makeManager(engine, {
getTenancy: SINGLE_TENANCY,
audience: {
posture: 'email_domain',
allowedEmailDomains: ['acme.com'],
selfRegistrationPermissionSet: 'portal_user',
},
});
const admitted = await signUp(manager, 'User+tag@ACME.com');
expect(admitted.status).toBeLessThan(300);
// declared = enforced: the grant row exists, bound to the created user.
await vi.waitFor(() => {
const grants = engine.tables.get('sys_user_permission_set') ?? [];
expect(grants.length).toBe(1);
expect(grants[0].permission_set).toBe('portal_user');
const created = (engine.tables.get('sys_user') ?? []).find((u: any) => u.email === 'user+tag@acme.com');
expect(grants[0].user_id).toBe(created?.id);
// ADR-0131 D3: owned by the membership it travels with.
expect(grants[0].organization_id).toBe('org_default');
});
const refused = await signUp(manager, 'user@mail.acme.com'); // subdomain: NOT implied
expect(refused.status).toBe(403);
const body = await refused.json();
expect(body.code).toBe(EMAIL_DOMAIN_NOT_ALLOWED);
expect((engine.tables.get('sys_user') ?? []).some((u: any) => u.email === 'user@mail.acme.com')).toBe(false);
});
it('[ADR-0131 D4] the self-registration grant names its set alone — with ZERO sys_permission_set rows', async () => {
// The fake engine stores exactly the payload the writer sends — no platform
// hook stands behind it here — so this pins the writer's own payload. No
// set row is seeded: the set is the catalog's (ADR-0131 D3), and the grant
// names it (D4).
const engine = createMemoryEngine();
seedExistingUser(engine);
const manager = makeManager(engine, {
getTenancy: SINGLE_TENANCY,
audience: { posture: 'open', selfRegistrationPermissionSet: 'portal_user' },
});
bindTestSecurityCatalog(engine, { permissions: [{ name: 'portal_user' }] });
const admitted = await signUp(manager, 'joiner@anywhere.com');
expect(admitted.status).toBeLessThan(300);
await vi.waitFor(() => {
const grants = engine.tables.get('sys_user_permission_set') ?? [];
expect(grants.length).toBe(1);
expect(grants[0].permission_set).toBe('portal_user');
expect(grants[0].permission_set_id).toBeUndefined();
expect(engine.tables.get('sys_permission_set') ?? []).toEqual([]);
});
});
it('email_domain forces email verification on: the wired flag, the public config, and the minted session agree', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPermissionSet(engine, 'portal_user');
const manager = makeManager(engine, {
audience: {
posture: 'email_domain',
allowedEmailDomains: ['acme.com'],
selfRegistrationPermissionSet: 'portal_user',
},
});
// Public surface mirrors the forcing (nothing set requireEmailVerification).
const pub = manager.getPublicConfig();
expect(pub.emailPassword.requireEmailVerification).toBe(true);
expect((pub.features as any).audiencePosture).toBe('email_domain');
// And better-auth really runs with it: the admitted signup creates the
// user but does NOT auto-sign-in an unverified account.
const res = await signUp(manager, 'user@acme.com');
expect(res.status).toBeLessThan(300);
const body = await res.json().catch(() => ({}));
expect(body?.token ?? null).toBeNull();
});
it('a DANGLING declared permission set refuses admission with AUTH_CONFIG_ERROR — never an ungranted admit', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
// NOTE: no sys_permission_set row named 'ghost' is seeded.
const manager = makeManager(engine, {
audience: { posture: 'open', selfRegistrationPermissionSet: 'ghost' },
});
const res = await signUp(manager, 'user@anywhere.com');
expect(res.status).toBe(403);
const body = await res.json();
expect(body.code).toBe(AUDIENCE_CONFIG_ERROR);
expect(String(body.message)).toContain("'ghost'");
expect((engine.tables.get('sys_user') ?? []).length).toBe(1);
});
it('[ADR-0131 D3] a declared set the activation ledger switches OFF refuses admission — never an ungranted admit', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPermissionSet(engine, 'member_default');
engine.tables.set('sys_metadata_activation', [
{ id: 'act_member', metadata_type: 'permission', name: 'member_default', package_id: 'pkg', active: false },
]);
const manager = makeManager(engine, {
audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' },
});
const res = await signUp(manager, 'user@anywhere.com');
expect(res.status).toBe(403);
expect((await res.json()).code).toBe(AUDIENCE_CONFIG_ERROR);
expect((engine.tables.get('sys_user') ?? []).length).toBe(1);
});
// An invited sign-up the posture's own rule admits is a self-registrant: it
// asks for the declared set like an uninvited one, so a set that cannot be
// resolved refuses it too. The invitation does not admit it without the grant.
it.each([
['open', 'missing', { posture: 'open' }, 'invited@anywhere.com'],
['open', 'switched off', { posture: 'open' }, 'invited@anywhere.com'],
['email_domain (on the allowlist)', 'missing', { posture: 'email_domain', allowedEmailDomains: ['acme.com'] }, 'invited@acme.com'],
['email_domain (on the allowlist)', 'switched off', { posture: 'email_domain', allowedEmailDomains: ['acme.com'] }, 'invited@acme.com'],
] as const)('%s: an invited sign-up whose declared set is %s is refused AUTH_CONFIG_ERROR, like an uninvited one', async (_posture, state, posture, email) => {
const engine = createMemoryEngine();
seedExistingUser(engine);
if (state === 'switched off') {
seedPermissionSet(engine, 'member_default');
engine.tables.set('sys_metadata_activation', [
{ id: 'act_member', metadata_type: 'permission', name: 'member_default', package_id: 'pkg', active: false },
]);
}
seedPendingInvitation(engine, email);
const set = state === 'missing' ? 'ghost' : 'member_default';
const manager = makeManager(engine, { audience: { ...posture, selfRegistrationPermissionSet: set } });
const res = await signUp(manager, email);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.code).toBe(AUDIENCE_CONFIG_ERROR);
expect(String(body.message)).toContain(`'${set}'`);
expect((engine.tables.get('sys_user') ?? []).length).toBe(1);
});
it('CONTROL: email_domain, an invited sign-up OFF the allowlist is admitted by its invitation alone, asking for no set, so a missing set does not refuse it', async () => {
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPendingInvitation(engine, 'contractor@external.com');
const manager = makeManager(engine, {
audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'ghost' },
});
const res = await signUp(manager, 'contractor@external.com');
expect(res.status, await res.clone().text()).toBeLessThan(300);
expect((engine.tables.get('sys_user') ?? []).length).toBe(2);
expect(engine.tables.get('sys_user_permission_set') ?? []).toEqual([]);
});
it('[ADR-0131 D3] the set ROW\'s `active` switches nothing: a row flagged off still admits and grants', async () => {
// The resolver reads no catalog row, so the row flag is not a deactivation.
const engine = createMemoryEngine();
seedExistingUser(engine);
seedPermissionSet(engine, 'member_default', { active: false });
const manager = makeManager(engine, {
getTenancy: SINGLE_TENANCY,
audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' },