-
Notifications
You must be signed in to change notification settings - Fork 990
/
Copy pathaccountExporter.ts
223 lines (212 loc) · 6.73 KB
/
accountExporter.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
import { Writable } from "stream";
import * as os from "os";
import * as path from "path";
import { Client } from "./apiv2";
import { FirebaseError } from "./error";
import { googleOrigin } from "./api";
import * as utils from "./utils";
const apiClient = new Client({
urlPrefix: googleOrigin(),
});
// TODO: support for MFA at runtime was added in PR #3173, but this exporter currently ignores `mfaInfo` and loses the data on export.
const EXPORTED_JSON_KEYS = [
"localId",
"email",
"emailVerified",
"passwordHash",
"salt",
"displayName",
"photoUrl",
"lastLoginAt",
"createdAt",
"phoneNumber",
"disabled",
"customAttributes",
];
const EXPORTED_JSON_KEYS_RENAMING: Record<string, string> = {
lastLoginAt: "lastSignedInAt",
};
const EXPORTED_PROVIDER_USER_INFO_KEYS = [
"providerId",
"rawId",
"email",
"displayName",
"photoUrl",
];
const PROVIDER_ID_INDEX_MAP = new Map<string, number>([
["google.com", 7],
["facebook.com", 11],
["twitter.com", 15],
["github.com", 19],
]);
function escapeComma(str: string): string {
if (str.includes(",")) {
// Encapsulate the string with quotes if it contains a comma.
return `"${str}"`;
}
return str;
}
function convertToNormalBase64(data: string): string {
return data.replace(/_/g, "/").replace(/-/g, "+");
}
function addProviderUserInfo(providerInfo: any, arr: any[], startPos: number): void {
arr[startPos] = providerInfo.rawId;
arr[startPos + 1] = providerInfo.email || "";
arr[startPos + 2] = escapeComma(providerInfo.displayName || "");
arr[startPos + 3] = providerInfo.photoUrl || "";
}
function transUserToArray(user: any): any[] {
const arr = Array(27).fill("");
arr[0] = user.localId;
arr[1] = user.email || "";
arr[2] = user.emailVerified || false;
arr[3] = convertToNormalBase64(user.passwordHash || "");
arr[4] = convertToNormalBase64(user.salt || "");
arr[5] = escapeComma(user.displayName || "");
arr[6] = user.photoUrl || "";
for (let i = 0; i < (!user.providerUserInfo ? 0 : user.providerUserInfo.length); i++) {
const providerInfo = user.providerUserInfo[i];
if (providerInfo) {
const providerIndex = PROVIDER_ID_INDEX_MAP.get(providerInfo.providerId);
if (providerIndex) {
addProviderUserInfo(providerInfo, arr, providerIndex);
}
}
}
arr[23] = user.createdAt;
arr[24] = user.lastLoginAt;
arr[25] = user.phoneNumber;
arr[26] = user.disabled;
// quote entire custom claims object and escape inner quotes with quotes
arr[27] = user.customAttributes
? `"${user.customAttributes.replace(/(?<!\\)"/g, '""')}"`
: user.customAttributes;
return arr;
}
function transUserJson(user: any): any {
const newUser: any = {};
const pickedUser: Record<string, any> = {};
for (const k of EXPORTED_JSON_KEYS) {
pickedUser[k] = user[k];
}
for (const [key, value] of Object.entries(pickedUser)) {
const newKey = EXPORTED_JSON_KEYS_RENAMING[key] || key;
newUser[newKey] = value;
}
if (newUser.passwordHash) {
newUser.passwordHash = convertToNormalBase64(newUser.passwordHash);
}
if (newUser.salt) {
newUser.salt = convertToNormalBase64(newUser.salt);
}
if (user.providerUserInfo) {
newUser.providerUserInfo = [];
for (const providerInfo of user.providerUserInfo) {
if (PROVIDER_ID_INDEX_MAP.has(providerInfo.providerId)) {
const picked: Record<string, any> = {};
for (const k of EXPORTED_PROVIDER_USER_INFO_KEYS) {
picked[k] = providerInfo[k];
}
newUser.providerUserInfo.push(picked);
}
}
}
return newUser;
}
export function validateOptions(options: any, fileName: string): any {
const exportOptions: any = {};
if (fileName === undefined) {
throw new FirebaseError("Must specify data file");
}
const extName = path.extname(fileName.toLowerCase());
if (extName === ".csv") {
exportOptions.format = "csv";
} else if (extName === ".json") {
exportOptions.format = "json";
} else if (options.format) {
const format = options.format.toLowerCase();
if (format === "csv" || format === "json") {
exportOptions.format = format;
} else {
throw new FirebaseError("Unsupported data file format, should be csv or json");
}
} else {
throw new FirebaseError(
"Please specify data file format in file name, or use `format` parameter",
);
}
return exportOptions;
}
function createWriteUsersToFile(): (
userList: any[],
format: "csv" | "json",
writeStream: Writable,
) => void {
let jsonSep = "";
return (userList: any[], format: "csv" | "json", writeStream: Writable) => {
userList.map((user) => {
if (user.passwordHash && user.version !== 0) {
// Password isn't hashed by default Scrypt.
delete user.passwordHash;
delete user.salt;
}
if (format === "csv") {
writeStream.write(transUserToArray(user).join(",") + "," + os.EOL, "utf8");
} else {
writeStream.write(jsonSep + JSON.stringify(transUserJson(user), null, 2), "utf8");
jsonSep = "," + os.EOL;
}
});
};
}
export async function serialExportUsers(projectId: string, options: any): Promise<any> {
if (!options.writeUsersToFile) {
options.writeUsersToFile = createWriteUsersToFile();
}
const postBody: any = {
targetProjectId: projectId,
maxResults: options.batchSize,
};
if (options.nextPageToken) {
postBody.nextPageToken = options.nextPageToken;
}
if (!options.timeoutRetryCount) {
options.timeoutRetryCount = 0;
}
try {
const ret = await apiClient.post<any, { users: any[]; nextPageToken: string }>(
"/identitytoolkit/v3/relyingparty/downloadAccount",
postBody,
{
skipLog: { resBody: true }, // This contains a lot of PII - don't log it.
},
);
options.timeoutRetryCount = 0;
const userList = ret.body.users;
if (userList && userList.length > 0) {
options.writeUsersToFile(userList, options.format, options.writeStream);
utils.logSuccess("Exported " + userList.length + " account(s) successfully.");
// The identitytoolkit API do not return a nextPageToken value
// consistently when the last page is reached
if (!ret.body.nextPageToken) {
return;
}
options.nextPageToken = ret.body.nextPageToken;
return serialExportUsers(projectId, options);
}
} catch (err: any) {
// Calling again in case of error timedout so that script won't exit
if (err.original?.code === "ETIMEDOUT") {
options.timeoutRetryCount++;
if (options.timeoutRetryCount > 5) {
return err;
}
return serialExportUsers(projectId, options);
}
if (err instanceof FirebaseError) {
throw err;
} else {
throw new FirebaseError(`Failed to export accounts: ${err}`, { original: err });
}
}
}