Repository navigation
Expand file tree
/
Copy pathadmin-import-users.test.ts
More file actions
934 lines (869 loc) · 40.1 KB
/
Copy pathadmin-import-users.test.ts
File metadata and controls
934 lines (869 loc) · 40.1 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { assertEngineUpdateDispatch } from '@objectstack/objectql';
import { RestServer } from '@objectstack/rest';
import { runAdminImportUsers, IMPORT_USERS_MAX_ROWS, type IdentityImportDeps } from './admin-import-users.js';
import { settleImportResetDelivery } from './account-invitation-marker.js';
import type { AdminActor } from './admin-user-endpoints.js';
const ACTOR: AdminActor = { id: 'admin-1', email: 'admin@example.com' };
const HERE = dirname(fileURLToPath(import.meta.url));
const IMPORT_USERS_SOURCE = readFileSync(resolve(HERE, 'admin-import-users.ts'), 'utf8');
function makeRequest(body: unknown): Request {
return new Request('http://localhost/api/v1/auth/admin/import-users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
}
function makeDeps(opts: {
existingUsers?: Array<Record<string, any>>;
phoneEnabled?: boolean;
emailAvailable?: boolean;
smsInviteAvailable?: boolean;
/** The send (inside the reset) fails — better-auth swallows it. */
resetFails?: boolean;
/** [#23598] The reset request itself refuses, before any send, with this message. */
resetRequestThrows?: string;
smsFails?: boolean;
/** [#23152] When set, the deps carry `consoleResetPasswordUrl` answering it. */
setPasswordPageUrl?: string;
} = {}) {
const existing = opts.existingUsers ?? [];
let nextId = 1;
const createUser = vi.fn(async ({ body }: any) => ({
user: { id: `u-${nextId++}`, email: body.email, name: body.name },
}));
// [#23598] better-auth's real shape: the reset runs `sendResetPassword`
// (whose body settles the import's receipt) inside `runInBackgroundOrAwait`,
// which CATCHES what the send throws, and answers `{ status: true }`
// regardless. A fake that throws on a failed send is the shape the real API
// never produces — it is what kept the import's dead failure path green.
const requestPasswordReset = vi.fn(async ({ body }: any) => {
if (opts.resetRequestThrows) throw new Error(opts.resetRequestThrows);
try {
await settleImportResetDelivery(body.email, undefined, async () => {
if (opts.resetFails) throw new Error('smtp down');
});
} catch {
/* better-auth: logger.error('Failed to run background task') */
}
return { status: true };
});
const find = vi.fn(async (_obj: string, q: any) => {
const where = q?.where ?? {};
return existing.filter((u) => Object.entries(where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return u[k] === v; }));
});
const update = vi.fn(async (_obj: string, data: any, options?: any) => {
assertEngineUpdateDispatch(data, options);
return {};
});
const insert = vi.fn(async () => ({}));
const warn = vi.fn();
const noteMustChangePasswordIssued = vi.fn();
const sendInviteSms = vi.fn(async () => {
if (opts.smsFails) throw new Error('sms provider down');
});
const deps: IdentityImportDeps = {
getAuthApi: async () => ({ createUser, requestPasswordReset }),
getDataEngine: () => ({ find, update, insert }),
phoneNumberEnabled: () => opts.phoneEnabled ?? false,
emailServiceAvailable: () => opts.emailAvailable ?? true,
smsInviteAvailable: () => opts.smsInviteAvailable ?? false,
sendInviteSms,
...(opts.setPasswordPageUrl !== undefined
? { consoleResetPasswordUrl: () => opts.setPasswordPageUrl! }
: {}),
noteMustChangePasswordIssued,
logger: { warn },
};
return { deps, createUser, requestPasswordReset, sendInviteSms, find, update, insert, warn, noteMustChangePasswordIssued };
}
/** Red line: no generated password may reach any persistence/log surface. */
function expectNoPasswordLeak(m: ReturnType<typeof makeDeps>, passwords: string[]) {
const surfaces = JSON.stringify([m.insert.mock.calls, m.update.mock.calls, m.warn.mock.calls]);
for (const pw of passwords) {
if (typeof pw === 'string' && pw.length > 0) expect(surfaces).not.toContain(pw);
}
}
describe('runAdminImportUsers — request validation', () => {
it('rejects an unknown passwordPolicy', async () => {
const m = makeDeps();
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'plaintext', format: 'json', rows: [] }),
ACTOR,
);
expect(res.status).toBe(400);
expect(m.createUser).not.toHaveBeenCalled();
});
it('defaults to the auto policy when passwordPolicy is omitted (#3236)', async () => {
const m = makeDeps(); // email service available, no SMS
const res = await runAdminImportUsers(
m.deps,
makeRequest({ format: 'json', rows: [{ email: 'a@b.co' }] }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.summary.passwordPolicy).toBe('auto');
// A deliverable email row is invited, not handed a temporary password.
expect(m.requestPasswordReset).toHaveBeenCalledTimes(1);
expect(data.rows[0].delivery).toBe('email');
expect(data.rows[0].temporaryPassword).toBeUndefined();
expect(data.summary.delivery).toEqual({ emailInvite: 1, smsInvite: 0, temporary: 0 });
});
it('rejects matchBy phone when the phoneNumber plugin is off', async () => {
const m = makeDeps({ phoneEnabled: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'temporary', mode: 'upsert', matchBy: 'phone', format: 'json', rows: [] }),
ACTOR,
);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('PHONE_NOT_ENABLED');
});
it('rejects the invite policy without an email service', async () => {
const m = makeDeps({ emailAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@b.co' }] }),
ACTOR,
);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('EMAIL_SERVICE_REQUIRED');
expect(m.createUser).not.toHaveBeenCalled();
});
it('rejects async: true explicitly (not silently)', async () => {
const m = makeDeps();
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'temporary', async: true, format: 'json', rows: [{ email: 'a@b.co' }] }),
ACTOR,
);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('ASYNC_NOT_SUPPORTED');
});
it('rejects payloads above the row cap with 413', async () => {
const m = makeDeps();
const rows = Array.from({ length: IMPORT_USERS_MAX_ROWS + 1 }, (_, i) => ({ email: `u${i}@x.co` }));
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'temporary', format: 'json', rows }),
ACTOR,
);
expect(res.status).toBe(413);
expect(m.createUser).not.toHaveBeenCalled();
});
});
describe('runAdminImportUsers — row validation (also on dryRun)', () => {
it('flags invite rows without a real email as INVITE_REQUIRES_EMAIL', async () => {
const m = makeDeps({ phoneEnabled: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'invite', dryRun: true, format: 'json',
rows: [
{ email: 'ok@x.co', name: 'OK' },
{ phone_number: '+8613800000000', name: 'PhoneOnly' },
{ name: 'Nobody' },
{ email: 'u-aaaaaaaaaaaaaaaaaaaa@placeholder.invalid' },
{ email: 'not-an-email' },
],
}),
ACTOR,
);
expect(res.status).toBe(200);
const rows = (res.body.data as any).rows;
expect(rows[0].action).toBe('created'); // dryRun projection
expect(rows[1].code).toBe('INVITE_REQUIRES_EMAIL');
expect(rows[2].code).toBe('NO_IDENTITY');
expect(rows[3].code).toBe('INVALID_EMAIL');
expect(rows[4].code).toBe('INVALID_EMAIL');
expect((res.body.data as any).summary.errors).toBe(4);
// dryRun writes nothing
expect(m.createUser).not.toHaveBeenCalled();
expect(m.update).not.toHaveBeenCalled();
expect(m.insert).not.toHaveBeenCalled();
});
it('flags phone columns when the plugin is off, and bad phone formats', async () => {
const m = makeDeps({ phoneEnabled: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'temporary', dryRun: true, format: 'json',
rows: [{ phone_number: '+8613800000000' }],
}),
ACTOR,
);
expect((res.body.data as any).rows[0].code).toBe('PHONE_NOT_ENABLED');
const m2 = makeDeps({ phoneEnabled: true });
const res2 = await runAdminImportUsers(
m2.deps,
makeRequest({
passwordPolicy: 'temporary', dryRun: true, format: 'json',
rows: [{ phone_number: 'junk' }],
}),
ACTOR,
);
expect((res2.body.data as any).rows[0].code).toBe('INVALID_PHONE');
});
});
describe('runAdminImportUsers — none policy (default: identity only, no credentials)', () => {
it('creates credential-less accounts: no password sent to better-auth, no stamps, no invitations', async () => {
const m = makeDeps({ phoneEnabled: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'none', format: 'json',
rows: [
{ email: 'a@x.co', name: 'A' },
{ phone_number: '+8613800000001', name: 'B' },
],
}),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(data.summary.passwordPolicy).toBe('none');
// better-auth receives NO password key at all → credential-less account.
for (const call of m.createUser.mock.calls) {
expect('password' in call[0].body).toBe(false);
}
// Phone-only row still gets a placeholder email.
expect(m.createUser.mock.calls[1][0].body.email).toMatch(/@placeholder\.invalid$/);
// No must_change_password stamps, no temporary passwords, no invitations.
expect(m.update.mock.calls.filter((c) => c[1]?.must_change_password === true).length).toBe(0);
expect(m.noteMustChangePasswordIssued).not.toHaveBeenCalled();
expect(data.rows.every((r: any) => r.temporaryPassword === undefined)).toBe(true);
expect(m.requestPasswordReset).not.toHaveBeenCalled();
expect(m.sendInviteSms).not.toHaveBeenCalled();
});
it('does not require an email or SMS service (unlike invite)', async () => {
const m = makeDeps({ emailAvailable: false, smsInviteAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'none', format: 'json', rows: [{ email: 'a@b.co' }] }),
ACTOR,
);
expect(res.status).toBe(200);
expect((res.body.data as any).summary.created).toBe(1);
});
});
describe('runAdminImportUsers — temporary policy', () => {
it('creates each row through better-auth, stamps must_change_password, returns per-row temp passwords once', async () => {
const m = makeDeps({ phoneEnabled: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'temporary', format: 'json',
rows: [
{ email: 'a@x.co', name: 'A' },
{ phone_number: '+8613800000001', name: 'B' },
],
}),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(m.createUser).toHaveBeenCalledTimes(2);
// Row 1: real email; row 2: placeholder that never contains the phone.
const sent1 = m.createUser.mock.calls[0][0].body;
const sent2 = m.createUser.mock.calls[1][0].body;
expect(sent1.email).toBe('a@x.co');
expect(typeof sent1.password).toBe('string');
expect(sent2.email).toMatch(/@placeholder\.invalid$/);
expect(sent2.email).not.toContain('138');
expect(sent2.data.phoneNumber).toBe('+8613800000001');
// must_change_password stamped per created user + gate cache primed.
const stamps = m.update.mock.calls.filter((c) => c[1]?.must_change_password === true);
expect(stamps.length).toBe(2);
expect(m.noteMustChangePasswordIssued).toHaveBeenCalled();
// Temp passwords: response-only, one per row, and they are the ones sent
// to better-auth for hashing.
const pw1 = data.rows[0].temporaryPassword;
const pw2 = data.rows[1].temporaryPassword;
expect(pw1).toBe(sent1.password);
expect(pw2).toBe(sent2.password);
expectNoPasswordLeak(m, [pw1, pw2]);
// No invitation emails under the temporary policy.
expect(m.requestPasswordReset).not.toHaveBeenCalled();
// Run-level audit row without password material.
const audit = m.insert.mock.calls.find((c) => c[0] === 'sys_audit_log');
expect(audit).toBeTruthy();
const meta = JSON.parse(audit![1].metadata);
expect(meta.event).toBe('user.import_run');
expect(meta.created).toBe(2);
});
});
describe('runAdminImportUsers — invite policy', () => {
it('creates with a throwaway password and requests a reset email per created row', async () => {
const m = makeDeps();
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'invite', format: 'json',
rows: [{ email: 'a@x.co' }, { email: 'b@x.co' }],
}),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(m.requestPasswordReset).toHaveBeenCalledTimes(2);
expect(m.requestPasswordReset.mock.calls.map((c) => c[0].body.email).sort()).toEqual(['a@x.co', 'b@x.co']);
// The throwaway password is not returned to the caller.
expect(data.rows[0].temporaryPassword).toBeUndefined();
// No must-change stamp for invite (users set their own password).
expect(m.update.mock.calls.filter((c) => c[1]?.must_change_password === true).length).toBe(0);
expectNoPasswordLeak(m, m.createUser.mock.calls.map((c) => c[0].body.password));
});
it('[#23152] names the Console set-password page as the reset redirectTo when the deps carry it', async () => {
const page = 'https://acme.example.com/_console/reset-password';
const m = makeDeps({ setPasswordPageUrl: page });
await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
expect(m.requestPasswordReset.mock.lastCall).toStrictEqual([{ body: { email: 'a@x.co', redirectTo: page } }]);
});
it('[#23152] without the member, the reset request is exactly { email } — no redirectTo key', async () => {
const m = makeDeps();
await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
expect(m.requestPasswordReset.mock.lastCall).toStrictEqual([{ body: { email: 'a@x.co' } }]);
});
it('keeps the row created (with INVITE_EMAIL_FAILED) when the email fails — no rollback', async () => {
const m = makeDeps({ resetFails: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
const data = res.body.data as any;
const row = data.rows[0];
// [#23598] Reported failed although better-auth swallowed the send's throw.
expect(row.delivery).toBeUndefined();
expect(row.code).toBe('INVITE_EMAIL_FAILED');
expect(row.error).toContain('smtp down');
expect(row.ok).toBe(false);
expect(row.action).toBe('created');
expect(data.summary.created).toBe(1);
expect(data.summary.errors).toBe(1);
expect(data.summary.delivery).toEqual({ emailInvite: 0, smsInvite: 0, temporary: 0 });
});
it('[#23598] a reset request that refuses before any send is a failed invitation too', async () => {
const m = makeDeps({ resetRequestThrows: 'Invalid redirectURL' });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
const data = res.body.data as any;
expect(data.rows[0]).toMatchObject({ ok: false, action: 'created', code: 'INVITE_EMAIL_FAILED' });
expect(data.rows[0].error).toContain('Invalid redirectURL');
expect(data.rows[0].delivery).toBeUndefined();
expect(data.summary.errors).toBe(1);
});
it('[#23598] a reset that answers without running the send is never reported delivered', async () => {
const m = makeDeps();
// better-auth answers `{ status: true }` without calling `sendResetPassword`
// for an address it finds no account behind.
m.requestPasswordReset.mockImplementation(async () => ({ status: true }));
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
const data = res.body.data as any;
expect(data.rows[0]).toMatchObject({ ok: false, action: 'created', code: 'INVITE_EMAIL_FAILED' });
expect(data.rows[0].error).toContain('never confirmed');
expect(data.rows[0].delivery).toBeUndefined();
expect(data.summary.errors).toBe(1);
expect(data.summary.delivery.emailInvite).toBe(0);
});
// #2780 — SMS invite variant for phone-only rows.
it('sends an SMS invite (not a reset email) to phone-only rows when SMS is available', async () => {
const m = makeDeps({ phoneEnabled: true, smsInviteAvailable: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'invite', format: 'json',
rows: [
{ email: 'a@x.co', name: 'Mail' },
{ phone_number: '+86 138 0000 0002', name: 'PhoneOnly' },
],
}),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
// Email row → reset email; phone-only row → invitation SMS to the
// NORMALIZED number, never a reset email to the placeholder address.
expect(m.requestPasswordReset).toHaveBeenCalledTimes(1);
expect(m.requestPasswordReset.mock.calls[0][0].body.email).toBe('a@x.co');
expect(m.sendInviteSms).toHaveBeenCalledTimes(1);
expect(m.sendInviteSms.mock.calls[0][0]).toBe('+8613800000002');
// The phone-only account got a placeholder email that never leaks the phone.
const phoneCreate = m.createUser.mock.calls.find((c) => c[0].body?.data?.phoneNumber);
expect(phoneCreate![0].body.email).toMatch(/@placeholder\.invalid$/);
// No temp passwords under invite.
expect(data.rows.every((r: any) => r.temporaryPassword === undefined)).toBe(true);
});
it('keeps the row created (with INVITE_SMS_FAILED) when the SMS fails — no rollback', async () => {
const m = makeDeps({ phoneEnabled: true, smsInviteAvailable: true, smsFails: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ phone_number: '+8613800000003' }] }),
ACTOR,
);
const data = res.body.data as any;
const row = data.rows[0];
// [#23598] The same stamp as a failed email: not delivered, not ok, counted.
expect(row.delivery).toBeUndefined();
expect(row.code).toBe('INVITE_SMS_FAILED');
expect(row.error).toContain('sms provider down');
expect(row.ok).toBe(false);
expect(row.action).toBe('created');
expect(data.summary.created).toBe(1);
expect(data.summary.errors).toBe(1);
expect(data.summary.delivery).toEqual({ emailInvite: 0, smsInvite: 0, temporary: 0 });
});
it('with SMS but no email service: phone-only rows invite, email rows fail per-row', async () => {
const m = makeDeps({ phoneEnabled: true, emailAvailable: false, smsInviteAvailable: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'invite', format: 'json',
rows: [
{ email: 'a@x.co' },
{ phone_number: '+8613800000004' },
],
}),
ACTOR,
);
expect(res.status).toBe(200); // not rejected outright — one channel works
const rows = (res.body.data as any).rows;
expect(rows[0].code).toBe('EMAIL_SERVICE_REQUIRED');
expect(rows[1].action).toBe('created');
expect(m.sendInviteSms).toHaveBeenCalledTimes(1);
expect(m.requestPasswordReset).not.toHaveBeenCalled();
});
it('still rejects invite outright when NEITHER email nor SMS is wired', async () => {
const m = makeDeps({ phoneEnabled: true, emailAvailable: false, smsInviteAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'invite', format: 'json', rows: [{ phone_number: '+8613800000005' }] }),
ACTOR,
);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('EMAIL_SERVICE_REQUIRED');
expect(m.createUser).not.toHaveBeenCalled();
});
});
// #3236 — `auto` prefers the invite path per row and only falls back to a
// temporary password for rows with no deliverable channel. Unlike `invite`, it
// never rejects the request for missing infrastructure.
describe('runAdminImportUsers — auto policy (default)', () => {
it('invites deliverable rows and falls back to temporary only for the unreachable ones — in ONE batch', async () => {
// Email service up, SMS down. Row 1: real email → email invite. Row 2:
// phone-only with no SMS → temporary fallback (the ONLY row that gets a
// shared secret). That per-row split is the whole point of #3236.
const m = makeDeps({ phoneEnabled: true, emailAvailable: true, smsInviteAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'auto', format: 'json',
rows: [
{ email: 'reachable@x.co', name: 'Mail' },
{ phone_number: '+8613800000001', name: 'PhoneOnly' },
],
}),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(data.summary.passwordPolicy).toBe('auto');
// Row 1 invited by email; no temporary password.
expect(m.requestPasswordReset).toHaveBeenCalledTimes(1);
expect(m.requestPasswordReset.mock.calls[0][0].body.email).toBe('reachable@x.co');
expect(data.rows[0].delivery).toBe('email');
expect(data.rows[0].temporaryPassword).toBeUndefined();
// Row 2 fell back to temporary: a returned password + must_change stamp.
expect(m.sendInviteSms).not.toHaveBeenCalled();
expect(typeof data.rows[1].temporaryPassword).toBe('string');
expect(data.rows[1].delivery).toBe('temporary');
const stamps = m.update.mock.calls.filter((c) => c[1]?.must_change_password === true);
expect(stamps.length).toBe(1);
expect(m.noteMustChangePasswordIssued).toHaveBeenCalled();
// Breakdown surfaced on the summary — one invite, one fallback.
expect(data.summary.delivery).toEqual({ emailInvite: 1, smsInvite: 0, temporary: 1 });
expectNoPasswordLeak(m, [data.rows[1].temporaryPassword]);
});
it('uses the SMS invite path for phone-only rows when SMS is wired', async () => {
const m = makeDeps({ phoneEnabled: true, emailAvailable: true, smsInviteAvailable: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'auto', format: 'json',
rows: [
{ email: 'a@x.co' },
{ phone_number: '+86 138 0000 0002' },
],
}),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
// Email row → reset email; phone-only row → SMS invite. No temp passwords.
expect(m.requestPasswordReset).toHaveBeenCalledTimes(1);
expect(m.sendInviteSms).toHaveBeenCalledTimes(1);
expect(m.sendInviteSms.mock.calls[0][0]).toBe('+8613800000002');
expect(data.rows.every((r: any) => r.temporaryPassword === undefined)).toBe(true);
expect(data.rows[0].delivery).toBe('email');
expect(data.rows[1].delivery).toBe('sms');
expect(data.summary.delivery).toEqual({ emailInvite: 1, smsInvite: 1, temporary: 0 });
});
it('never rejects for missing infrastructure — with no channels wired every row degrades to temporary', async () => {
const m = makeDeps({ phoneEnabled: true, emailAvailable: false, smsInviteAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'auto', format: 'json',
rows: [
{ email: 'a@x.co' },
{ phone_number: '+8613800000003' },
],
}),
ACTOR,
);
// Contrast with `invite`, which 400s here. `auto` provisions everyone.
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(m.requestPasswordReset).not.toHaveBeenCalled();
expect(m.sendInviteSms).not.toHaveBeenCalled();
expect(data.rows.every((r: any) => typeof r.temporaryPassword === 'string')).toBe(true);
expect(data.rows.every((r: any) => r.delivery === 'temporary')).toBe(true);
expect(data.summary.delivery).toEqual({ emailInvite: 0, smsInvite: 0, temporary: 2 });
expectNoPasswordLeak(m, data.rows.map((r: any) => r.temporaryPassword));
});
it('surfaces INVITE_EMAIL_FAILED (no rollback) when a chosen email invite fails', async () => {
const m = makeDeps({ resetFails: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'auto', format: 'json', rows: [{ email: 'a@x.co' }] }),
ACTOR,
);
const row = (res.body.data as any).rows[0];
expect(row.ok).toBe(false);
expect(row.action).toBe('created');
expect(row.code).toBe('INVITE_EMAIL_FAILED');
// [#23598] Nothing was delivered, so the row does not say `email`.
expect(row.delivery).toBeUndefined();
// A failed invite is NOT silently downgraded to a temporary password.
expect(row.temporaryPassword).toBeUndefined();
expect((res.body.data as any).summary.errors).toBe(1);
});
it('writes nothing on dryRun but still projects the per-row plan', async () => {
const m = makeDeps({ phoneEnabled: true, emailAvailable: true, smsInviteAvailable: false });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'auto', dryRun: true, format: 'json',
rows: [{ email: 'a@x.co' }, { phone_number: '+8613800000006' }],
}),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.createUser).not.toHaveBeenCalled();
expect(m.requestPasswordReset).not.toHaveBeenCalled();
expect(m.sendInviteSms).not.toHaveBeenCalled();
// dryRun does not deliver, so no per-row delivery is stamped.
expect((res.body.data as any).summary.delivery).toEqual({ emailInvite: 0, smsInvite: 0, temporary: 0 });
});
});
describe('runAdminImportUsers — upsert', () => {
it('matches by email: updates profile fields only, never credentials or email', async () => {
const m = makeDeps({
existingUsers: [{ id: 'u-old', email: 'a@x.co', name: 'Old Name' }],
});
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'temporary', mode: 'upsert', matchBy: 'email', format: 'json',
rows: [
{ email: 'a@x.co', name: 'New Name', password: 'Injected1!' }, // password column must be ignored
{ email: 'new@x.co', name: 'Fresh' },
],
}),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.updated).toBe(1);
expect(data.summary.created).toBe(1);
// The existing user was patched with name only — no email, no password.
const patch = m.update.mock.calls.find((c) => c[1]?.id === 'u-old');
expect(patch).toBeTruthy();
expect(patch![1]).toEqual({ id: 'u-old', name: 'New Name' });
// The updated row never went through createUser; the new row did.
expect(m.createUser).toHaveBeenCalledTimes(1);
expect(m.createUser.mock.calls[0][0].body.email).toBe('new@x.co');
// Updated (existing) users never get a temporary password back.
expect(data.rows[0].temporaryPassword).toBeUndefined();
expect(typeof data.rows[1].temporaryPassword).toBe('string');
});
it('matches by phone_number when enabled', async () => {
const m = makeDeps({
phoneEnabled: true,
existingUsers: [{ id: 'u-p', email: 'p@x.co', phone_number: '+8613800000009', name: 'P' }],
});
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'temporary', mode: 'upsert', matchBy: 'phone', format: 'json',
rows: [{ phone_number: '+86 138 0000 0009', name: 'P2' }],
}),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.updated).toBe(1);
expect(m.find).toHaveBeenCalledWith('sys_user', expect.objectContaining({
where: { phone_number: '+8613800000009' },
}));
});
it('skips upsert rows whose match key is blank instead of creating duplicates', async () => {
const m = makeDeps({ phoneEnabled: true });
const res = await runAdminImportUsers(
m.deps,
makeRequest({
passwordPolicy: 'temporary', mode: 'upsert', matchBy: 'phone', format: 'json',
rows: [{ email: 'email-only@x.co', name: 'NoPhone' }],
}),
ACTOR,
);
const row = (res.body.data as any).rows[0];
expect(row.action).toBe('skipped');
expect(m.createUser).not.toHaveBeenCalled();
});
});
describe('runAdminImportUsers — CSV payloads', () => {
it('accepts the same CSV shape as the generic import route', async () => {
const m = makeDeps();
const csv = 'email,name\nc1@x.co,C One\nc2@x.co,C Two\n';
const res = await runAdminImportUsers(
m.deps,
makeRequest({ passwordPolicy: 'temporary', csv }),
ACTOR,
);
const data = res.body.data as any;
expect(data.summary.created).toBe(2);
expect(m.createUser.mock.calls.map((c) => c[0].body.email).sort()).toEqual(['c1@x.co', 'c2@x.co']);
});
});
/**
* [#25078] Export → admin user import round trip, through the CSV text-cell rule.
*
* `@objectstack/rest`'s CSV export writes a text cell its consumer would
* interpret in a form that consumer reads as text, and its CSV import parse
* (`parseCsvToRows`, reached through `prepareImportRequest`) reverses exactly
* that. This door parses a `csv` body through that same `prepareImportRequest`,
* so a user list exported as CSV and imported back here must hand better-auth's
* `createUser` every stored name exactly.
*
* The file comes from the REAL export route of `@objectstack/rest`'s
* `RestServer`, over a protocol double serving a two-field `sys_user` schema and
* the rows below. The rule is pinned at its readers in `@objectstack/rest`
* (`csv-text-cell.test.ts`), and its other CSV doors in that package's
* `csv-text-cell-round-trip.test.ts`.
*/
describe('runAdminImportUsers — CSV export → import round trip (#25078)', () => {
/** Plain words after a trigger character: marked by the export. */
const MARKED = ['=Total', '+Name', '-Note', '@acme'];
/** Ordinary business values, and a user-authored name that begins with the mark itself. */
const UNMARKED = ['+86 138 0013 8000', '+1 555 010 0000', '-120.50', 'Acme Ltd', '120.50', "'Quoted"];
const NAMES = [...MARKED, ...UNMARKED];
async function exportUsersCsv(rows: Array<Record<string, string>>): Promise<string> {
const noop = () => {};
const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
const schema = { name: 'sys_user', fields: { email: { name: 'email', type: 'email' }, name: { name: 'name', type: 'text' } } };
const protocol = {
getMetaItem: vi.fn(async () => ({ type: 'object', name: 'sys_user', item: schema })),
findData: vi.fn(async () => ({ object: 'sys_user', records: rows, total: rows.length })),
};
const rest = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any);
(rest as any).resolveExecCtx = async () => ({ userId: ACTOR.id });
rest.registerRoutes();
const route: any = rest.getRoutes().find(
(r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/export',
);
expect(route).toBeDefined();
const chunks: string[] = [];
const res: any = {
write: (s: unknown) => { chunks.push(String(s)); return true; },
end: () => {},
header: () => res,
status: () => res,
json: () => res,
};
await route.handler({ params: { object: 'sys_user' }, query: { format: 'csv' } }, res);
return chunks.join('');
}
it('hands createUser every exported name exactly', async () => {
const rows = NAMES.map((name, i) => ({ email: `user${i + 1}@example.com`, name }));
const csv = await exportUsersCsv(rows);
// The file carried the marks, so the round trip below is not a pass-through.
expect(csv.split('\r\n')[0]).toBe('email,name');
for (const [i, v] of MARKED.entries()) expect(csv).toContain(`user${i + 1}@example.com,'${v}\r\n`);
expect(csv).toContain(',+86 138 0013 8000\r\n');
expect(csv).toContain(",'Quoted\r\n");
const m = makeDeps();
const res = await runAdminImportUsers(m.deps, makeRequest({ passwordPolicy: 'temporary', csv }), ACTOR);
expect(res.status).toBe(200);
expect((res.body.data as any).summary.created).toBe(NAMES.length);
const byEmail = new Map(m.createUser.mock.calls.map((c: any[]) => [c[0].body.email, c[0].body.name]));
expect(rows.map((r) => byEmail.get(r.email))).toEqual(NAMES);
});
});
/**
* [#17422] The IMPLEMENTOR half of #16952's contract.
*
* `ImportProtocolLike` types the three required members, but an EXPLICIT
* parameter annotation wins over a contextual type — so `findData(args: any)`
* opts this file back out of the contract while `tsc --noEmit` stays green.
* Measured on #17422 in this package: with the annotation restored, a probe
* reading the retired wire alias (`args.query?.$filter` — the pre-#16950 read
* whose `?? {}` default degraded the duplicate probe into match-everything)
* type-checks at exit 0; with the annotation gone the same probe is
* `TS2339 Property '$filter' does not exist on type 'QueryInput'`.
*
* ⇒ Nothing else in the repo can see that difference. The behavioural upsert
* tests above discriminate the CONSEQUENCE (ablated to the historical read,
* two of them go red) but not the opt-out itself: re-annotating the parameter
* leaves every one of them green and every gate green. This is that guard.
*/
describe('[#17422] the import protocol literal is typed BY `ImportProtocolLike`', () => {
it('binds the literal to the exported contract', () => {
expect(IMPORT_USERS_SOURCE).toContain('const protocol: ImportProtocolLike = {');
});
for (const member of ['findData', 'createData', 'updateData'] as const) {
it(`leaves \`${member}\`'s parameter unannotated, so the contract types it`, () => {
expect(IMPORT_USERS_SOURCE).toContain(`async ${member}(args) {`);
expect(IMPORT_USERS_SOURCE).not.toMatch(new RegExp(`async\\s+${member}\\s*\\(\\s*args\\s*:`));
});
}
});
/**
* [#22800] The identity import's lookup cells are judged like every other
* `runImport` caller's: the run protocol carries the declaration reader the
* import already holds (the one the parser reads `sys_user`'s fields through),
* so `servesReferenceTarget` (`@objectstack/core`, #22739) asks each lookup
* TARGET its declared exposure for `list` before a cell is matched against it.
*
* A target whose declaration refuses `list` answers as a target the caller
* cannot read: `reference_not_found` for a cell naming a record, a cell naming
* none and a pasted id alike, and nothing of the target is read. A serving
* target is unchanged. The import's reads run under the system identity, which
* is no exemption: the decision takes no caller.
*
* Fixture objects only. The decision's own matrix (every refusing and serving
* declaration, fail-closed) is pinned once, in
* `packages/core/src/utils/import-runner-reference-exposure.test.ts`; this
* block pins that THIS door asks it. The engine is `makeDeps`' pinned double,
* with only its `find` overridden to answer the fixture target.
*/
describe('[#22800] the identity import asks each lookup target its declared exposure, for list', () => {
const TARGET = 'fx_unit';
const RECORD = { id: 'fx_1', name: 'Existing' };
const LOOKUP = 'fx_unit_id';
/** The `sys_user` declaration the reader serves: two plain columns and one lookup into the fixture target. */
const SYS_USER = {
name: 'sys_user',
fields: {
email: { type: 'text', label: 'Email' },
name: { type: 'text', label: 'Name' },
[LOOKUP]: { type: 'lookup', label: 'Unit', reference: TARGET },
},
};
/** A cell naming the record, a cell naming none, and the record's id. */
const ROWS = [
{ email: 'a@fx.test', [LOOKUP]: 'Existing' },
{ email: 'b@fx.test', [LOOKUP]: 'Missing' },
{ email: 'c@fx.test', [LOOKUP]: 'fx_1' },
];
/** The target's declaration is `enable` (absent = no `enable` block); `reader: false` composes no declaration reader at all. */
function exposureDeps(enable: unknown, opts: { reader?: boolean } = {}) {
const m = makeDeps();
const engine = m.deps.getDataEngine()!;
const find = vi.fn(async (object: string, q: { where?: Record<string, unknown> }) => {
if (object !== TARGET) return engine.find(object, q);
const [[field, value]] = Object.entries(q.where ?? {});
return (RECORD as Record<string, unknown>)[field] === value ? [RECORD] : [];
});
const getMetaItem = vi.fn(async ({ name }: { type: string; name: string }) => {
if (name === 'sys_user') return { type: 'object', name, item: SYS_USER };
if (name === TARGET) return { type: 'object', name, item: { name, ...(enable === undefined ? {} : { enable }) } };
return { type: 'object', name, item: undefined };
});
const deps: IdentityImportDeps = {
...m.deps,
getDataEngine: () => ({ ...engine, find }),
...(opts.reader === false ? {} : { getMetaItem }),
};
return { ...m, deps, find, getMetaItem };
}
type RowVerdict = { ok: boolean; code?: string; field?: string };
const verdict = (r: RowVerdict) => ({ ok: r.ok, code: r.code, field: r.field });
const NOT_FOUND = { ok: false, code: 'reference_not_found', field: LOOKUP };
const OK = { ok: true, code: undefined, field: undefined };
const targetReads = (h: ReturnType<typeof exposureDeps>) => h.find.mock.calls.filter(([object]) => object === TARGET);
async function rowVerdicts(h: ReturnType<typeof exposureDeps>) {
const res = await runAdminImportUsers(h.deps, makeRequest({ passwordPolicy: 'none', format: 'json', rows: ROWS }), ACTOR);
expect(res.status).toBe(200);
return (res.body.data as { rows: RowVerdict[] }).rows.map(verdict);
}
for (const [label, enable] of [
['apiEnabled: false', { apiEnabled: false }],
['a whitelist granting get but not list', { apiMethods: ['get'] }],
] as const) {
it(`${label}: a match, a miss and an id all answer reference_not_found, and the target is never read`, async () => {
const h = exposureDeps(enable);
expect(await rowVerdicts(h)).toEqual([NOT_FOUND, NOT_FOUND, NOT_FOUND]);
expect(targetReads(h)).toEqual([]);
expect(h.createUser).not.toHaveBeenCalled();
});
}
for (const [label, enable] of [
['no enable block', undefined],
['a whitelist granting list', { apiMethods: ['list'] }],
] as const) {
it(`CONTROL ${label}: a match and an id resolve, a miss is reported, as before`, async () => {
const h = exposureDeps(enable);
expect(await rowVerdicts(h)).toEqual([OK, NOT_FOUND, OK]);
expect(targetReads(h).length).toBeGreaterThan(0);
expect(h.createUser).toHaveBeenCalledTimes(2);
});
}
it('the target is asked through the reader the import holds, once per import, by its own name', async () => {
const h = exposureDeps({ apiEnabled: false });
await rowVerdicts(h);
expect(h.getMetaItem.mock.calls.map(([ref]) => ref)).toEqual([
{ type: 'object', name: 'sys_user' },
{ type: 'object', name: TARGET },
]);
});
it('CONTROL without a declaration reader no cell is a reference: the target is neither asked nor read', async () => {
const h = exposureDeps({ apiEnabled: false }, { reader: false });
expect(await rowVerdicts(h)).toEqual([OK, OK, OK]);
expect(h.getMetaItem).not.toHaveBeenCalled();
expect(targetReads(h)).toEqual([]);
});
});