-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathapp-check-api-client-internal.ts
More file actions
292 lines (271 loc) · 9.6 KB
/
app-check-api-client-internal.ts
File metadata and controls
292 lines (271 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*!
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { App } from '../app';
import { FirebaseApp } from '../app/firebase-app';
import {
HttpRequestConfig, HttpClient, RequestResponseError, AuthorizedHttpClient, RequestResponse
} from '../utils/api-request';
import { PrefixedFirebaseError } from '../utils/error';
import * as utils from '../utils/index';
import * as validator from '../utils/validator';
import { AppCheckToken, AppCheckTokenOptions } from './app-check-api'
// App Check backend constants
const FIREBASE_APP_CHECK_V1_API_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1/projects/{projectId}/apps/{appId}:exchangeCustomToken';
const ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1beta/projects/{projectId}:verifyAppCheckToken';
const FIREBASE_APP_CHECK_CONFIG_HEADERS = {
'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`
};
/**
* Class that facilitates sending requests to the Firebase App Check backend API.
*
* @internal
*/
export class AppCheckApiClient {
private readonly httpClient: HttpClient;
private projectId?: string;
constructor(private readonly app: App) {
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'First argument passed to admin.appCheck() must be a valid Firebase app instance.');
}
this.httpClient = new AuthorizedHttpClient(app as FirebaseApp);
}
/**
* Exchange a signed custom token to App Check token
*
* @param customToken - The custom token to be exchanged.
* @param appId - The mobile App ID.
* @returns A promise that fulfills with a `AppCheckToken`.
*/
public exchangeToken(
customToken: string,
appId: string,
options?: AppCheckTokenOptions
): Promise<AppCheckToken> {
if (!validator.isNonEmptyString(appId)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`appId` must be a non-empty string.');
}
if (!validator.isNonEmptyString(customToken)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`customToken` must be a non-empty string.');
}
if (typeof options?.limitedUse !== 'undefined' && !validator.isBoolean(options.limitedUse)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`limitedUse` must be a boolean value.');
}
if (typeof options?.jti !== 'undefined') {
if (!validator.isString(options.jti)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`jti` must be a string value.');
}
if (options.jti !== '' && !options.limitedUse) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`jti` cannot be specified without setting `limitedUse` to `true`.');
}
}
return this.getUrl(appId)
.then((url) => {
const request: HttpRequestConfig = {
method: 'POST',
url,
headers: FIREBASE_APP_CHECK_CONFIG_HEADERS,
data: {
customToken,
...(options?.limitedUse !== undefined && { limitedUse: options.limitedUse }),
...(options?.jti !== undefined && { jti: options.jti }),
}
};
return this.httpClient.send(request);
})
.then((resp) => {
return this.toAppCheckToken(resp);
})
.catch((err) => {
throw this.toFirebaseError(err);
});
}
public verifyReplayProtection(token: string): Promise<boolean> {
if (!validator.isNonEmptyString(token)) {
throw new FirebaseAppCheckError(
'invalid-argument',
'`token` must be a non-empty string.');
}
return this.getVerifyTokenUrl()
.then((url) => {
const request: HttpRequestConfig = {
method: 'POST',
url,
headers: FIREBASE_APP_CHECK_CONFIG_HEADERS,
data: { app_check_token: token }
};
return this.httpClient.send(request);
})
.then((resp) => {
if (typeof resp.data.alreadyConsumed !== 'undefined'
&& !validator.isBoolean(resp.data?.alreadyConsumed)) {
throw new FirebaseAppCheckError(
'invalid-argument', '`alreadyConsumed` must be a boolean value.');
}
return resp.data.alreadyConsumed || false;
})
.catch((err) => {
throw this.toFirebaseError(err);
});
}
private getUrl(appId: string): Promise<string> {
return this.getProjectId()
.then((projectId) => {
const urlParams = {
projectId,
appId,
};
const baseUrl = utils.formatString(FIREBASE_APP_CHECK_V1_API_URL_FORMAT, urlParams);
return utils.formatString(baseUrl);
});
}
private getVerifyTokenUrl(): Promise<string> {
return this.getProjectId()
.then((projectId) => {
const urlParams = {
projectId
};
const baseUrl = utils.formatString(ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT, urlParams);
return utils.formatString(baseUrl);
});
}
private getProjectId(): Promise<string> {
if (this.projectId) {
return Promise.resolve(this.projectId);
}
return utils.findProjectId(this.app)
.then((projectId) => {
if (!validator.isNonEmptyString(projectId)) {
throw new FirebaseAppCheckError(
'unknown-error',
'Failed to determine project ID. Initialize the '
+ 'SDK with service account credentials or set project ID as an app option. '
+ 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.');
}
this.projectId = projectId;
return projectId;
});
}
private toFirebaseError(err: RequestResponseError): PrefixedFirebaseError {
if (err instanceof PrefixedFirebaseError) {
return err;
}
const response = err.response;
if (!response.isJson()) {
return new FirebaseAppCheckError(
'unknown-error',
`Unexpected response with status: ${response.status} and body: ${response.text}`);
}
const error: Error = (response.data as ErrorResponse).error || {};
let code: AppCheckErrorCode = 'unknown-error';
if (error.status && error.status in APP_CHECK_ERROR_CODE_MAPPING) {
code = APP_CHECK_ERROR_CODE_MAPPING[error.status];
}
const message = error.message || `Unknown server error: ${response.text}`;
return new FirebaseAppCheckError(code, message);
}
/**
* Creates an AppCheckToken from the API response.
*
* @param resp - API response object.
* @returns An AppCheckToken instance.
*/
private toAppCheckToken(resp: RequestResponse): AppCheckToken {
const token = resp.data.token;
// `ttl` is a string with the suffix "s" preceded by the number of seconds,
// with nanoseconds expressed as fractional seconds.
const ttlMillis = this.stringToMilliseconds(resp.data.ttl);
return {
token,
ttlMillis
}
}
/**
* Converts a duration string with the suffix `s` to milliseconds.
*
* @param duration - The duration as a string with the suffix "s" preceded by the
* number of seconds, with fractional seconds. For example, 3 seconds with 0 nanoseconds
* is expressed as "3s", while 3 seconds and 1 nanosecond is expressed as "3.000000001s",
* and 3 seconds and 1 microsecond is expressed as "3.000001s".
*
* @returns The duration in milliseconds.
*/
private stringToMilliseconds(duration: string): number {
if (!validator.isNonEmptyString(duration) || !duration.endsWith('s')) {
throw new FirebaseAppCheckError(
'invalid-argument', '`ttl` must be a valid duration string with the suffix `s`.');
}
const seconds = duration.slice(0, -1);
return Math.floor(Number(seconds) * 1000);
}
}
interface ErrorResponse {
error?: Error;
}
interface Error {
code?: number;
message?: string;
status?: string;
}
export const APP_CHECK_ERROR_CODE_MAPPING: { [key: string]: AppCheckErrorCode } = {
ABORTED: 'aborted',
INVALID_ARGUMENT: 'invalid-argument',
INVALID_CREDENTIAL: 'invalid-credential',
INTERNAL: 'internal-error',
PERMISSION_DENIED: 'permission-denied',
UNAUTHENTICATED: 'unauthenticated',
NOT_FOUND: 'not-found',
UNKNOWN: 'unknown-error',
};
export type AppCheckErrorCode =
'aborted'
| 'invalid-argument'
| 'invalid-credential'
| 'internal-error'
| 'permission-denied'
| 'unauthenticated'
| 'not-found'
| 'app-check-token-expired'
| 'unknown-error';
/**
* Firebase App Check error code structure. This extends PrefixedFirebaseError.
*
* @param code - The error code.
* @param message - The error message.
* @constructor
*/
export class FirebaseAppCheckError extends PrefixedFirebaseError {
constructor(code: AppCheckErrorCode, message: string) {
super('app-check', code, message);
/* tslint:disable:max-line-length */
// Set the prototype explicitly. See the following link for more details:
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
/* tslint:enable:max-line-length */
(this as any).__proto__ = FirebaseAppCheckError.prototype;
}
}