-
Notifications
You must be signed in to change notification settings - Fork 971
/
Copy pathoperations.ts
3500 lines (3166 loc) · 115 KB
/
operations.ts
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
import { URLSearchParams } from "url";
import { decode as decodeJwt, sign as signJwt, JwtHeader } from "jsonwebtoken";
import * as express from "express";
import fetch from "node-fetch";
import AbortController from "abort-controller";
import { ExegesisContext } from "exegesis-express";
import {
toUnixTimestamp,
randomId,
isValidEmailAddress,
parseAbsoluteUri,
canonicalizeEmailAddress,
mirrorFieldTo,
authEmulatorUrl,
MakeRequired,
isValidPhoneNumber,
randomBase64UrlStr,
} from "./utils";
import { NotImplementedError, assert, BadRequestError, InternalError } from "./errors";
import { Emulators } from "../types";
import { EmulatorLogger } from "../emulatorLogger";
import {
ProjectState,
OobRequestType,
UserInfo,
ProviderUserInfo,
PROVIDER_PASSWORD,
PROVIDER_ANONYMOUS,
PROVIDER_PHONE,
SIGNIN_METHOD_EMAIL_LINK,
PROVIDER_CUSTOM,
OobRecord,
PROVIDER_GAME_CENTER,
SecondFactorRecord,
AgentProjectState,
TenantProjectState,
MfaConfig,
BlockingFunctionEvents,
} from "./state";
import { MfaEnrollments, Schemas } from "./types";
/**
* Create a map from IDs to operations handlers suitable for exegesis.
* @param state the state of the Auth Emulator
* @return operations, keyed by their operation id.
*/
export const authOperations: AuthOps = {
identitytoolkit: {
getProjects,
getRecaptchaParams,
accounts: {
createAuthUri,
delete: deleteAccount,
lookup,
resetPassword,
sendOobCode,
sendVerificationCode,
signInWithCustomToken,
signInWithEmailLink,
signInWithIdp,
signInWithPassword,
signInWithPhoneNumber,
signUp,
update: setAccountInfo,
mfaEnrollment: {
finalize: mfaEnrollmentFinalize,
start: mfaEnrollmentStart,
withdraw: mfaEnrollmentWithdraw,
},
mfaSignIn: {
start: mfaSignInStart,
finalize: mfaSignInFinalize,
},
},
projects: {
createSessionCookie,
queryAccounts,
getConfig,
updateConfig,
accounts: {
_: signUp,
delete: deleteAccount,
lookup,
query: queryAccounts,
sendOobCode,
update: setAccountInfo,
batchCreate,
batchDelete,
batchGet,
},
tenants: {
create: createTenant,
delete: deleteTenant,
get: getTenant,
list: listTenants,
patch: updateTenant,
createSessionCookie,
accounts: {
_: signUp,
batchCreate,
batchDelete,
batchGet,
delete: deleteAccount,
lookup,
query: queryAccounts,
sendOobCode,
update: setAccountInfo,
},
},
},
},
securetoken: {
token: grantToken,
},
emulator: {
projects: {
accounts: {
delete: deleteAllAccountsInProject,
},
config: {
get: getEmulatorProjectConfig,
update: updateEmulatorProjectConfig,
},
oobCodes: {
list: listOobCodesInProject,
},
verificationCodes: {
list: listVerificationCodesInProject,
},
},
},
};
/* Handlers */
const PASSWORD_MIN_LENGTH = 6;
// https://cloud.google.com/identity-platform/docs/use-rest-api#section-verify-custom-token
export const CUSTOM_TOKEN_AUDIENCE =
"https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";
const MFA_INELIGIBLE_PROVIDER = new Set([
PROVIDER_ANONYMOUS,
PROVIDER_PHONE,
PROVIDER_CUSTOM,
PROVIDER_GAME_CENTER,
]);
async function signUp(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1SignUpRequest"],
ctx: ExegesisContext
): Promise<Schemas["GoogleCloudIdentitytoolkitV1SignUpResponse"]> {
assert(!state.disableAuth, "PROJECT_DISABLED");
let provider: string | undefined;
const timestamp = new Date();
let updates: Omit<Partial<UserInfo>, "localId" | "providerUserInfo"> = {
lastLoginAt: timestamp.getTime().toString(),
};
if (ctx.security?.Oauth2) {
// Privileged request.
if (reqBody.idToken) {
assert(!reqBody.localId, "UNEXPECTED_PARAMETER : User ID");
}
if (reqBody.localId) {
// Fail fast if localId is taken (matching production behavior).
assert(!state.getUserByLocalId(reqBody.localId), "DUPLICATE_LOCAL_ID");
}
updates.displayName = reqBody.displayName;
updates.photoUrl = reqBody.photoUrl;
updates.emailVerified = reqBody.emailVerified || false;
if (reqBody.phoneNumber) {
assert(isValidPhoneNumber(reqBody.phoneNumber), "INVALID_PHONE_NUMBER : Invalid format.");
assert(!state.getUserByPhoneNumber(reqBody.phoneNumber), "PHONE_NUMBER_EXISTS");
updates.phoneNumber = reqBody.phoneNumber;
}
if (reqBody.disabled) {
updates.disabled = true;
}
} else {
assert(!reqBody.localId, "UNEXPECTED_PARAMETER : User ID");
if (reqBody.idToken || reqBody.password || reqBody.email) {
// Creating / linking email password account.
updates.displayName = reqBody.displayName;
updates.emailVerified = false;
assert(reqBody.email, "MISSING_EMAIL");
assert(reqBody.password, "MISSING_PASSWORD");
provider = PROVIDER_PASSWORD;
assert(state.allowPasswordSignup, "OPERATION_NOT_ALLOWED");
} else {
// Most attributes are ignored when creating anon user without privilege.
provider = PROVIDER_ANONYMOUS;
assert(state.enableAnonymousUser, "ADMIN_ONLY_OPERATION");
}
}
if (reqBody.email) {
assert(isValidEmailAddress(reqBody.email), "INVALID_EMAIL");
const email = canonicalizeEmailAddress(reqBody.email);
assert(!state.getUserByEmail(email), "EMAIL_EXISTS");
updates.email = email;
}
if (reqBody.password) {
assert(
reqBody.password.length >= PASSWORD_MIN_LENGTH,
`WEAK_PASSWORD : Password should be at least ${PASSWORD_MIN_LENGTH} characters`
);
updates.salt = "fakeSalt" + randomId(20);
updates.passwordHash = hashPassword(reqBody.password, updates.salt);
updates.passwordUpdatedAt = Date.now();
updates.validSince = toUnixTimestamp(new Date()).toString();
}
if (reqBody.mfaInfo) {
updates.mfaInfo = getMfaEnrollmentsFromRequest(state, reqBody.mfaInfo, {
generateEnrollmentIds: true,
});
}
if (state instanceof TenantProjectState) {
updates.tenantId = state.tenantId;
}
let user: UserInfo | undefined;
if (reqBody.idToken) {
({ user } = parseIdToken(state, reqBody.idToken));
}
let extraClaims;
if (!user) {
updates.createdAt = timestamp.getTime().toString();
const localId = reqBody.localId ?? state.generateLocalId();
if (reqBody.email && !ctx.security?.Oauth2) {
const userBeforeCreate = { localId, ...updates };
const blockingResponse = await fetchBlockingFunction(
state,
BlockingFunctionEvents.BEFORE_CREATE,
userBeforeCreate,
{ signInMethod: "password" }
);
updates = { ...updates, ...blockingResponse.updates };
}
user = state.createUserWithLocalId(localId, updates);
assert(user, "DUPLICATE_LOCAL_ID");
if (reqBody.email && !ctx.security?.Oauth2) {
if (!user.disabled) {
const blockingResponse = await fetchBlockingFunction(
state,
BlockingFunctionEvents.BEFORE_SIGN_IN,
user,
{ signInMethod: "password" }
);
updates = blockingResponse.updates;
extraClaims = blockingResponse.extraClaims;
user = state.updateUserByLocalId(user.localId, updates);
}
// User may have been disabled after either blocking function, but
// only throw after writing user to store
assert(!user.disabled, "USER_DISABLED");
}
} else {
user = state.updateUserByLocalId(user.localId, updates);
}
return {
kind: "identitytoolkit#SignupNewUserResponse",
localId: user.localId,
displayName: user.displayName,
email: user.email,
...(provider ? issueTokens(state, user, provider, { extraClaims }) : {}),
};
}
function lookup(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1GetAccountInfoRequest"],
ctx: ExegesisContext
): Schemas["GoogleCloudIdentitytoolkitV1GetAccountInfoResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
const seenLocalIds = new Set<string>();
const users: UserInfo[] = [];
function tryAddUser(maybeUser: UserInfo | undefined): void {
if (maybeUser && !seenLocalIds.has(maybeUser.localId)) {
users.push(maybeUser);
seenLocalIds.add(maybeUser.localId);
}
}
if (ctx.security?.Oauth2) {
if (reqBody.initialEmail) {
// TODO: This is now possible. See ProjectState.getUserByInitialEmail.
throw new NotImplementedError("Lookup by initialEmail is not implemented.");
}
for (const localId of reqBody.localId ?? []) {
tryAddUser(state.getUserByLocalId(localId));
}
for (const email of reqBody.email ?? []) {
tryAddUser(state.getUserByEmail(email));
}
for (const phoneNumber of reqBody.phoneNumber ?? []) {
tryAddUser(state.getUserByPhoneNumber(phoneNumber));
}
for (const { providerId, rawId } of reqBody.federatedUserId ?? []) {
if (!providerId || !rawId) {
continue;
}
tryAddUser(state.getUserByProviderRawId(providerId, rawId));
}
} else {
assert(reqBody.idToken, "MISSING_ID_TOKEN");
const { user } = parseIdToken(state, reqBody.idToken);
users.push(redactPasswordHash(user));
}
return {
kind: "identitytoolkit#GetAccountInfoResponse",
// Drop users property if no users are found. This is needed for Node.js
// Admin SDK: https://github.com/firebase/firebase-admin-node/issues/1078
users: users.length ? users : undefined,
};
}
function batchCreate(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1UploadAccountRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1UploadAccountResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
assert(reqBody.users?.length, "MISSING_USER_ACCOUNT");
if (reqBody.sanityCheck) {
if (state.oneAccountPerEmail) {
const existingEmails = new Set<string>();
for (const userInfo of reqBody.users) {
if (userInfo.email) {
assert(!existingEmails.has(userInfo.email), `DUPLICATE_EMAIL : ${userInfo.email}`);
existingEmails.add(userInfo.email);
}
}
}
// Check that there is no duplicate (providerId, rawId) tuple.
const existingProviderAccounts = new Set<string>();
for (const userInfo of reqBody.users) {
for (const { providerId, rawId } of userInfo.providerUserInfo ?? []) {
const key = `${providerId}:${rawId}`;
assert(
!existingProviderAccounts.has(key),
`DUPLICATE_RAW_ID : Provider id(${providerId}), Raw id(${rawId})`
);
existingProviderAccounts.add(key);
}
}
}
if (!reqBody.allowOverwrite) {
const existingLocalIds = new Set<string>();
for (const userInfo of reqBody.users) {
const localId = userInfo.localId || "";
assert(!existingLocalIds.has(localId), `DUPLICATE_LOCAL_ID : ${localId}`);
existingLocalIds.add(localId);
}
}
const errors: { index: number; message: string }[] = [];
for (let index = 0; index < reqBody.users.length; index++) {
const userInfo = reqBody.users[index];
try {
assert(userInfo.localId, "localId is missing");
const uploadTime = new Date();
const fields: Omit<Partial<UserInfo>, "localId"> = {
displayName: userInfo.displayName,
photoUrl: userInfo.photoUrl,
lastLoginAt: userInfo.lastLoginAt,
};
if (userInfo.tenantId) {
assert(
state instanceof TenantProjectState && state.tenantId === userInfo.tenantId,
"Tenant id in userInfo does not match the tenant id in request."
);
}
if (state instanceof TenantProjectState) {
fields.tenantId = state.tenantId;
}
// password
if (userInfo.passwordHash) {
// TODO: Check and block non-emulator hashes.
fields.passwordHash = userInfo.passwordHash;
fields.salt = userInfo.salt;
fields.passwordUpdatedAt = uploadTime.getTime();
} else if (userInfo.rawPassword) {
fields.salt = userInfo.salt || "fakeSalt" + randomId(20);
fields.passwordHash = hashPassword(userInfo.rawPassword, fields.salt);
fields.passwordUpdatedAt = uploadTime.getTime();
}
// custom attrs
if (userInfo.customAttributes) {
validateSerializedCustomClaims(userInfo.customAttributes);
fields.customAttributes = userInfo.customAttributes;
}
// federated
if (userInfo.providerUserInfo) {
fields.providerUserInfo = [];
for (const providerUserInfo of userInfo.providerUserInfo) {
const { providerId, rawId, federatedId } = providerUserInfo;
if (providerId === PROVIDER_PASSWORD || providerId === PROVIDER_PHONE) {
// These providers are handled automatically by create / update.
continue;
}
if (!rawId || !providerId) {
if (!federatedId) {
assert(false, "federatedId or (providerId & rawId) is required");
} else {
// TODO
assert(
false,
"((Parsing federatedId is not implemented in Auth Emulator; please specify providerId AND rawId as a workaround.))"
);
}
}
const existingUserWithRawId = state.getUserByProviderRawId(providerId, rawId);
assert(
!existingUserWithRawId || existingUserWithRawId.localId === userInfo.localId,
"raw id exists in other account in database"
);
fields.providerUserInfo.push({ ...providerUserInfo, providerId, rawId });
}
}
// phone number
if (userInfo.phoneNumber) {
assert(isValidPhoneNumber(userInfo.phoneNumber), "phone number format is invalid");
fields.phoneNumber = userInfo.phoneNumber;
}
fields.validSince = toUnixTimestamp(uploadTime).toString();
fields.createdAt = uploadTime.getTime().toString();
if (fields.createdAt && !isNaN(Number(userInfo.createdAt))) {
fields.createdAt = userInfo.createdAt;
}
if (userInfo.email) {
const email = userInfo.email;
assert(isValidEmailAddress(email), "email is invalid");
// For simplicity, Auth Emulator performs this check in all cases
// (unlike production which checks only if (reqBody.sanityCheck && state.oneAccountPerEmail)).
// We return a non-standard error message in other cases to clarify.
const existingUserWithEmail = state.getUserByEmail(email);
assert(
!existingUserWithEmail || existingUserWithEmail.localId === userInfo.localId,
reqBody.sanityCheck && state.oneAccountPerEmail
? "email exists in other account in database"
: `((Auth Emulator does not support importing duplicate email: ${email}))`
);
fields.email = canonicalizeEmailAddress(email);
}
fields.emailVerified = !!userInfo.emailVerified;
fields.disabled = !!userInfo.disabled;
// MFA
if (userInfo.mfaInfo && userInfo.mfaInfo.length > 0) {
fields.mfaInfo = [];
assert(fields.email, "Second factor account requires email to be presented.");
assert(fields.emailVerified, "Second factor account requires email to be verified.");
const existingIds = new Set<string>();
for (const enrollment of userInfo.mfaInfo) {
if (enrollment.mfaEnrollmentId) {
assert(!existingIds.has(enrollment.mfaEnrollmentId), "Enrollment id already exists.");
existingIds.add(enrollment.mfaEnrollmentId);
}
}
for (const enrollment of userInfo.mfaInfo) {
enrollment.mfaEnrollmentId = enrollment.mfaEnrollmentId || newRandomId(28, existingIds);
enrollment.enrolledAt = enrollment.enrolledAt || new Date().toISOString();
assert(enrollment.phoneInfo, "Second factor not supported.");
assert(isValidPhoneNumber(enrollment.phoneInfo), "Phone number format is invalid");
enrollment.unobfuscatedPhoneInfo = enrollment.phoneInfo;
fields.mfaInfo.push(enrollment);
}
}
if (state.getUserByLocalId(userInfo.localId)) {
assert(
reqBody.allowOverwrite,
"localId belongs to an existing account - can not overwrite."
);
}
state.overwriteUserWithLocalId(userInfo.localId, fields);
} catch (e: any) {
if (e instanceof BadRequestError) {
// Use friendlier messages for some codes, consistent with production.
let message = e.message;
if (message === "INVALID_CLAIMS") {
message = "Invalid custom claims provided.";
} else if (message === "CLAIMS_TOO_LARGE") {
message = "Custom claims provided are too large.";
} else if (message.startsWith("FORBIDDEN_CLAIM")) {
message = "Custom claims provided include a reserved claim.";
}
errors.push({
index,
message,
});
} else {
throw e;
}
}
}
return {
kind: "identitytoolkit#UploadAccountResponse",
error: errors,
};
}
function batchDelete(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1BatchDeleteAccountsRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1BatchDeleteAccountsResponse"] {
const errors: Required<
Schemas["GoogleCloudIdentitytoolkitV1BatchDeleteAccountsResponse"]["errors"]
> = [];
const localIds = reqBody.localIds ?? [];
assert(localIds.length > 0 && localIds.length <= 1000, "LOCAL_ID_LIST_EXCEEDS_LIMIT");
for (let index = 0; index < localIds.length; index++) {
const localId = localIds[index];
const user = state.getUserByLocalId(localId);
if (!user) {
continue;
} else if (!user.disabled && !reqBody.force) {
errors.push({
index,
localId,
message: "NOT_DISABLED : Disable the account before batch deletion.",
});
} else {
state.deleteUser(user);
}
}
return { errors: errors.length ? errors : undefined };
}
function batchGet(
state: ProjectState,
reqBody: unknown,
ctx: ExegesisContext
): Schemas["GoogleCloudIdentitytoolkitV1DownloadAccountResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
const maxResults = Math.min(Math.floor(ctx.params.query.maxResults) || 20, 1000);
const users = state.queryUsers(
{},
{ sortByField: "localId", order: "ASC", startToken: ctx.params.query.nextPageToken }
);
let newPageToken: string | undefined = undefined;
// As a non-standard behavior, passing in maxResults=-1 will return all users.
if (maxResults >= 0 && users.length >= maxResults) {
users.length = maxResults;
if (users.length) {
newPageToken = users[users.length - 1].localId;
}
}
return {
kind: "identitytoolkit#DownloadAccountResponse",
users,
nextPageToken: newPageToken,
};
}
function createAuthUri(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1CreateAuthUriRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1CreateAuthUriResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
const sessionId = reqBody.sessionId || randomId(27);
if (reqBody.providerId) {
throw new NotImplementedError("Sign-in with IDP is not yet supported.");
}
assert(reqBody.identifier, "MISSING_IDENTIFIER");
assert(reqBody.continueUri, "MISSING_CONTINUE_URI");
// TODO: What about non-email identifiers?
assert(isValidEmailAddress(reqBody.identifier), "INVALID_IDENTIFIER");
const email = canonicalizeEmailAddress(reqBody.identifier);
assert(parseAbsoluteUri(reqBody.continueUri), "INVALID_CONTINUE_URI");
const allProviders: string[] = [];
const signinMethods: string[] = [];
let registered = false;
const users = state.getUsersByEmailOrProviderEmail(email);
if (state.oneAccountPerEmail) {
if (users.length) {
registered = true;
users[0].providerUserInfo?.forEach(({ providerId }) => {
if (providerId === PROVIDER_PASSWORD) {
allProviders.push(providerId);
if (users[0].passwordHash) {
signinMethods.push(PROVIDER_PASSWORD);
}
if (users[0].emailLinkSignin) {
signinMethods.push(SIGNIN_METHOD_EMAIL_LINK);
}
} else if (providerId !== PROVIDER_PHONE) {
allProviders.push(providerId);
signinMethods.push(providerId);
}
});
}
} else {
// We only report if user has password provider sign-in methods. No IDP.
const user = users.find((u) => u.email);
if (user) {
registered = true;
if (user.passwordHash || user.emailLinkSignin) {
allProviders.push(PROVIDER_PASSWORD);
if (users[0].passwordHash) {
signinMethods.push(PROVIDER_PASSWORD);
}
if (users[0].emailLinkSignin) {
signinMethods.push(SIGNIN_METHOD_EMAIL_LINK);
}
}
}
}
return {
kind: "identitytoolkit#CreateAuthUriResponse",
registered,
allProviders,
sessionId,
signinMethods,
};
}
const SESSION_COOKIE_MIN_VALID_DURATION = 5 * 60; /* 5 minutes in seconds */
export const SESSION_COOKIE_MAX_VALID_DURATION = 14 * 24 * 60 * 60; /* 14 days in seconds */
function createSessionCookie(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1CreateSessionCookieRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1CreateSessionCookieResponse"] {
assert(reqBody.idToken, "MISSING_ID_TOKEN");
const validDuration = Number(reqBody.validDuration) || SESSION_COOKIE_MAX_VALID_DURATION;
assert(
validDuration >= SESSION_COOKIE_MIN_VALID_DURATION &&
validDuration <= SESSION_COOKIE_MAX_VALID_DURATION,
"INVALID_DURATION"
);
const { payload } = parseIdToken(state, reqBody.idToken);
const issuedAt = toUnixTimestamp(new Date());
const expiresAt = issuedAt + validDuration;
const sessionCookie = signJwt(
{
...payload,
iat: issuedAt,
exp: expiresAt,
iss: `https://session.firebase.google.com/${payload.aud}`,
},
"fake-secret",
{
// Generate a unsigned (insecure) JWT. Admin SDKs should treat this like
// a real token (if in emulator mode). This won't work in production.
algorithm: "none",
}
);
return { sessionCookie };
}
function deleteAccount(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1DeleteAccountRequest"],
ctx: ExegesisContext
): Schemas["GoogleCloudIdentitytoolkitV1DeleteAccountResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
let user: UserInfo;
if (ctx.security?.Oauth2) {
assert(reqBody.localId, "MISSING_LOCAL_ID");
const maybeUser = state.getUserByLocalId(reqBody.localId);
assert(maybeUser, "USER_NOT_FOUND");
user = maybeUser;
} else {
assert(reqBody.idToken, "MISSING_ID_TOKEN");
user = parseIdToken(state, reqBody.idToken).user;
}
state.deleteUser(user);
return {
kind: "identitytoolkit#DeleteAccountResponse",
};
}
function getProjects(
state: ProjectState
): Schemas["GoogleCloudIdentitytoolkitV1GetProjectConfigResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
assert(state instanceof AgentProjectState, "UNSUPPORTED_TENANT_OPERATION");
return {
projectId: state.projectNumber,
authorizedDomains: [
// This list is just a placeholder -- the JS SDK will NOT validate the
// domain at all when connecting to the emulator. Google-internal context:
// http://go/firebase-auth-emulator-dd#heading=h.3r9cilur7s46
"localhost",
],
};
}
function getRecaptchaParams(
state: ProjectState
): Schemas["GoogleCloudIdentitytoolkitV1GetRecaptchaParamResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
return {
kind: "identitytoolkit#GetRecaptchaParamResponse",
// These strings have the same length and character set as real tokens/keys
// but are clearly fake to human eyes. This should help troubleshooting
// issues caused by sending these to the real Recaptcha service backend.
// Clients, such as Firebase SDKs, MUST disable Recaptcha when communicating
// with the emulator. DO NOT rely on / parse the exact values below.
recaptchaStoken:
"This-is-a-fake-token__Dont-send-this-to-the-Recaptcha-service__The-Auth-Emulator-does-not-support-Recaptcha",
recaptchaSiteKey: "Fake-key__Do-not-send-this-to-Recaptcha_",
};
}
function queryAccounts(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1QueryUserInfoRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1QueryUserInfoResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
if (reqBody.expression?.length) {
throw new NotImplementedError("expression is not implemented.");
}
// returnUserInfo is by default true. Take this branch only on an explicit false.
if (reqBody.returnUserInfo === false) {
return {
recordsCount: state.getUserCount().toString(),
};
}
// In production, limit has an upper bound of 500 (which is also the default).
// https://cloud.google.com/identity-platform/docs/reference/rest/v1/projects.accounts/query
// To simplify implementation of both the Auth Emulator and clients, we do not
// support limit or offset. ALL users will be returned even if there are more
// than 500 of them. This is a willful violation of the API contract above.
if (reqBody.limit) {
throw new NotImplementedError("limit is not implemented.");
}
reqBody.offset = reqBody.offset || "0";
if (reqBody.offset !== "0") {
throw new NotImplementedError("offset is not implemented.");
}
if (!reqBody.order || reqBody.order === "ORDER_UNSPECIFIED") {
reqBody.order = "ASC";
}
if (!reqBody.sortBy || reqBody.sortBy === "SORT_BY_FIELD_UNSPECIFIED") {
reqBody.sortBy = "USER_ID";
}
let sortByField: "localId";
if (reqBody.sortBy === "USER_ID") {
sortByField = "localId";
} else {
throw new NotImplementedError("Only sorting by USER_ID is implemented.");
}
const users = state.queryUsers({}, { order: reqBody.order, sortByField });
return {
recordsCount: users.length.toString(),
userInfo: users,
};
}
/**
* Reset password for a user account.
*
* @param state the current project state
* @param reqBody request with oobCode and passwords
* @return the HTTP response body
*/
export function resetPassword(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1ResetPasswordRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1ResetPasswordResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
assert(state.allowPasswordSignup, "PASSWORD_LOGIN_DISABLED");
assert(reqBody.oobCode, "MISSING_OOB_CODE");
const oob = state.validateOobCode(reqBody.oobCode);
assert(oob, "INVALID_OOB_CODE");
if (reqBody.newPassword) {
assert(oob.requestType === "PASSWORD_RESET", "INVALID_OOB_CODE");
assert(
reqBody.newPassword.length >= PASSWORD_MIN_LENGTH,
`WEAK_PASSWORD : Password should be at least ${PASSWORD_MIN_LENGTH} characters`
);
state.deleteOobCode(reqBody.oobCode);
let user = state.getUserByEmail(oob.email);
assert(user, "INVALID_OOB_CODE");
const salt = "fakeSalt" + randomId(20);
const passwordHash = hashPassword(reqBody.newPassword, salt);
user = state.updateUserByLocalId(
user.localId,
{
emailVerified: true,
passwordHash,
salt,
passwordUpdatedAt: Date.now(),
validSince: toUnixTimestamp(new Date()).toString(),
},
{ deleteProviders: user.providerUserInfo?.map((info) => info.providerId) }
);
}
return {
kind: "identitytoolkit#ResetPasswordResponse",
requestType: oob.requestType,
// Do not reveal the email when inspecting an email sign-in oobCode.
// Instead, the client must provide email (e.g. by asking the user)
// when they call the emailLinkSignIn endpoint.
// See: https://firebase.google.com/docs/auth/web/email-link-auth#security_concerns
email: oob.requestType === "EMAIL_SIGNIN" ? undefined : oob.email,
};
}
function sendOobCode(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1GetOobCodeRequest"],
ctx: ExegesisContext
): Schemas["GoogleCloudIdentitytoolkitV1GetOobCodeResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
assert(
reqBody.requestType && reqBody.requestType !== "OOB_REQ_TYPE_UNSPECIFIED",
"MISSING_REQ_TYPE"
);
if (reqBody.returnOobLink) {
assert(ctx.security?.Oauth2, "INSUFFICIENT_PERMISSION");
}
if (reqBody.continueUrl) {
assert(
parseAbsoluteUri(reqBody.continueUrl),
"INVALID_CONTINUE_URI : ((expected an absolute URI with valid scheme and host))"
);
}
let email: string;
let mode: string;
switch (reqBody.requestType) {
case "EMAIL_SIGNIN":
assert(state.enableEmailLinkSignin, "OPERATION_NOT_ALLOWED");
mode = "signIn";
assert(reqBody.email, "MISSING_EMAIL");
email = canonicalizeEmailAddress(reqBody.email);
break;
case "PASSWORD_RESET":
mode = "resetPassword";
assert(reqBody.email, "MISSING_EMAIL");
email = canonicalizeEmailAddress(reqBody.email);
assert(state.getUserByEmail(email), "EMAIL_NOT_FOUND");
break;
case "VERIFY_EMAIL":
mode = "verifyEmail";
// Matching production behavior, reqBody.returnOobLink is used as a signal
// for Admin usage (instead of whether request is OAuth 2 authenticated.)
if (reqBody.returnOobLink && !reqBody.idToken) {
assert(reqBody.email, "MISSING_EMAIL");
email = canonicalizeEmailAddress(reqBody.email);
const maybeUser = state.getUserByEmail(email);
assert(maybeUser, "USER_NOT_FOUND");
} else {
// Get the user from idToken, reqBody.email is ignored.
const user = parseIdToken(state, reqBody.idToken || "").user;
assert(user.email, "MISSING_EMAIL");
email = user.email;
}
break;
default:
throw new NotImplementedError(reqBody.requestType);
}
if (reqBody.canHandleCodeInApp) {
EmulatorLogger.forEmulator(Emulators.AUTH).log(
"WARN",
"canHandleCodeInApp is unsupported in Auth Emulator. All OOB operations will complete via web."
);
}
const url = authEmulatorUrl(ctx.req as express.Request);
const oobRecord = createOobRecord(state, email, url, {
requestType: reqBody.requestType,
mode,
continueUrl: reqBody.continueUrl,
});
if (reqBody.returnOobLink) {
return {
kind: "identitytoolkit#GetOobConfirmationCodeResponse",
email,
oobCode: oobRecord.oobCode,
oobLink: oobRecord.oobLink,
};
} else {
logOobMessage(oobRecord);
return {
kind: "identitytoolkit#GetOobConfirmationCodeResponse",
email,
};
}
}
function sendVerificationCode(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1SendVerificationCodeRequest"]
): Schemas["GoogleCloudIdentitytoolkitV1SendVerificationCodeResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
assert(state instanceof AgentProjectState, "UNSUPPORTED_TENANT_OPERATION");
// reqBody.iosReceipt, iosSecret, and recaptchaToken are intentionally ignored.
// Production Firebase Auth service also throws INVALID_PHONE_NUMBER instead
// of MISSING_XXXX when phoneNumber is missing. Matching the behavior here.
assert(
reqBody.phoneNumber && isValidPhoneNumber(reqBody.phoneNumber),
"INVALID_PHONE_NUMBER : Invalid format."
);
const user = state.getUserByPhoneNumber(reqBody.phoneNumber);
assert(
!user?.mfaInfo?.length,
"UNSUPPORTED_FIRST_FACTOR : A phone number cannot be set as a first factor on an SMS based MFA user."
);
const { sessionInfo, phoneNumber, code } = state.createVerificationCode(reqBody.phoneNumber);
// Print out a developer-friendly log containing the link, in lieu of sending
// a real text message out to the phone number.
EmulatorLogger.forEmulator(Emulators.AUTH).log(
"BULLET",
`To verify the phone number ${phoneNumber}, use the code ${code}.`
);
return {
sessionInfo,
};
}
function setAccountInfo(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1SetAccountInfoRequest"],
ctx: ExegesisContext
): Schemas["GoogleCloudIdentitytoolkitV1SetAccountInfoResponse"] {
assert(!state.disableAuth, "PROJECT_DISABLED");
const url = authEmulatorUrl(ctx.req as express.Request);
return setAccountInfoImpl(state, reqBody, {
privileged: !!ctx.security?.Oauth2,
emulatorUrl: url,
});
}
/**
* Updates an account based on localId, idToken, or oobCode.
*
* @param state the current project state
* @param reqBody request with fields to update
* @param privileged whether request is OAuth2 authenticated. Affects validation
* @param emulatorUrl url to the auth emulator instance. Needed for sending OOB link for email reset
* @return the HTTP response body
*/
export function setAccountInfoImpl(
state: ProjectState,
reqBody: Schemas["GoogleCloudIdentitytoolkitV1SetAccountInfoRequest"],
{ privileged = false, emulatorUrl = undefined }: { privileged?: boolean; emulatorUrl?: URL } = {}
): Schemas["GoogleCloudIdentitytoolkitV1SetAccountInfoResponse"] {
// TODO: Implement these.
const unimplementedFields: (keyof typeof reqBody)[] = [
"provider",
"upgradeToFederatedLogin",