bitwarden-estensione-browser/src/services/api.service.ts

516 lines
19 KiB
TypeScript
Raw Normal View History

2018-01-09 22:19:55 +01:00
import { ConstantsService } from './constants.service';
import { ApiService as ApiServiceAbstraction } from '../abstractions/api.service';
import { PlatformUtilsService } from '../abstractions/platformUtils.service';
import { TokenService } from '../abstractions/token.service';
import { EnvironmentUrls } from '../models/domain/environmentUrls';
import { CipherRequest } from '../models/request/cipherRequest';
import { FolderRequest } from '../models/request/folderRequest';
import { ImportDirectoryRequest } from '../models/request/importDirectoryRequest';
import { PasswordHintRequest } from '../models/request/passwordHintRequest';
import { RegisterRequest } from '../models/request/registerRequest';
import { TokenRequest } from '../models/request/tokenRequest';
import { TwoFactorEmailRequest } from '../models/request/twoFactorEmailRequest';
import { CipherResponse } from '../models/response/cipherResponse';
import { ErrorResponse } from '../models/response/errorResponse';
import { FolderResponse } from '../models/response/folderResponse';
import { IdentityTokenResponse } from '../models/response/identityTokenResponse';
import { IdentityTwoFactorResponse } from '../models/response/identityTwoFactorResponse';
2018-05-03 18:46:49 +02:00
import { ProfileResponse } from '../models/response/profileResponse';
import { SyncResponse } from '../models/response/syncResponse';
2018-01-09 22:19:55 +01:00
2018-01-31 20:27:11 +01:00
export class ApiService implements ApiServiceAbstraction {
2018-01-09 22:19:55 +01:00
urlsSet: boolean = false;
baseUrl: string;
identityBaseUrl: string;
deviceType: string;
2018-06-05 21:45:19 +02:00
isWebClient = false;
usingBaseUrl = false;
2018-01-09 22:19:55 +01:00
2018-03-21 16:19:05 +01:00
constructor(private tokenService: TokenService, private platformUtilsService: PlatformUtilsService,
2018-05-16 05:40:15 +02:00
private logoutCallback: (expired: boolean) => Promise<void>) {
2018-01-09 22:19:55 +01:00
this.deviceType = platformUtilsService.getDevice().toString();
2018-06-05 21:45:19 +02:00
this.isWebClient = platformUtilsService.identityClientId === 'web';
2018-01-09 22:19:55 +01:00
}
2018-01-09 22:23:27 +01:00
setUrls(urls: EnvironmentUrls): void {
2018-01-09 22:19:55 +01:00
this.urlsSet = true;
if (urls.base != null) {
2018-06-05 21:45:19 +02:00
this.usingBaseUrl = true;
2018-01-09 22:19:55 +01:00
this.baseUrl = urls.base + '/api';
this.identityBaseUrl = urls.base + '/identity';
return;
}
if (urls.api != null && urls.identity != null) {
this.baseUrl = urls.api;
this.identityBaseUrl = urls.identity;
return;
}
/* tslint:disable */
// Desktop
//this.baseUrl = 'http://localhost:4000';
//this.identityBaseUrl = 'http://localhost:33656';
// Desktop HTTPS
//this.baseUrl = 'https://localhost:44377';
//this.identityBaseUrl = 'https://localhost:44392';
// Desktop external
//this.baseUrl = 'http://192.168.1.3:4000';
//this.identityBaseUrl = 'http://192.168.1.3:33656';
// Preview
//this.baseUrl = 'https://preview-api.bitwarden.com';
//this.identityBaseUrl = 'https://preview-identity.bitwarden.com';
// Production
this.baseUrl = 'https://api.bitwarden.com';
this.identityBaseUrl = 'https://identity.bitwarden.com';
/* tslint:enable */
}
// Auth APIs
2018-02-02 04:55:49 +01:00
async postIdentityToken(request: TokenRequest): Promise<IdentityTokenResponse | IdentityTwoFactorResponse> {
2018-01-09 22:19:55 +01:00
const response = await fetch(new Request(this.identityBaseUrl + '/connect/token', {
2018-03-21 16:19:05 +01:00
body: this.qsStringify(request.toIdentityToken(this.platformUtilsService.identityClientId)),
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
cache: 'no-cache',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Accept': 'application/json',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
let responseJson: any = null;
const typeHeader = response.headers.get('content-type');
if (typeHeader != null && typeHeader.indexOf('application/json') > -1) {
responseJson = await response.json();
}
if (responseJson != null) {
if (response.status === 200) {
return new IdentityTokenResponse(responseJson);
} else if (response.status === 400 && responseJson.TwoFactorProviders2 &&
Object.keys(responseJson.TwoFactorProviders2).length) {
await this.tokenService.clearTwoFactorToken(request.email);
2018-02-02 04:55:49 +01:00
return new IdentityTwoFactorResponse(responseJson);
2018-01-09 22:19:55 +01:00
}
}
return Promise.reject(new ErrorResponse(responseJson, response.status, true));
}
async refreshIdentityToken(): Promise<any> {
try {
await this.doRefreshToken();
} catch (e) {
return Promise.reject(null);
}
}
// Two Factor APIs
async postTwoFactorEmail(request: TwoFactorEmailRequest): Promise<any> {
const response = await fetch(new Request(this.baseUrl + '/two-factor/send-email-login', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
// Account APIs
2018-05-03 18:46:49 +02:00
async getProfile(): Promise<ProfileResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/accounts/profile', {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-05-03 18:46:49 +02:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
}));
if (response.status === 200) {
const responseJson = await response.json();
return new ProfileResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
2018-01-09 22:19:55 +01:00
async getAccountRevisionDate(): Promise<number> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/accounts/revision-date', {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
}));
if (response.status === 200) {
return (await response.json() as number);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async postPasswordHint(request: PasswordHintRequest): Promise<any> {
const response = await fetch(new Request(this.baseUrl + '/accounts/password-hint', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async postRegister(request: RegisterRequest): Promise<any> {
const response = await fetch(new Request(this.baseUrl + '/accounts/register', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
// Folder APIs
async postFolder(request: FolderRequest): Promise<FolderResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/folders', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status === 200) {
const responseJson = await response.json();
return new FolderResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async putFolder(id: string, request: FolderRequest): Promise<FolderResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/folders/' + id, {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'PUT',
}));
if (response.status === 200) {
const responseJson = await response.json();
return new FolderResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async deleteFolder(id: string): Promise<any> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/folders/' + id, {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
method: 'DELETE',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
// Cipher APIs
async postCipher(request: CipherRequest): Promise<CipherResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/ciphers', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status === 200) {
const responseJson = await response.json();
return new CipherResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async putCipher(id: string, request: CipherRequest): Promise<CipherResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/ciphers/' + id, {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'PUT',
}));
if (response.status === 200) {
const responseJson = await response.json();
return new CipherResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async deleteCipher(id: string): Promise<any> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/ciphers/' + id, {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
method: 'DELETE',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
// Attachments APIs
async postCipherAttachment(id: string, data: FormData): Promise<CipherResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/ciphers/' + id + '/attachment', {
body: data,
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status === 200) {
const responseJson = await response.json();
return new CipherResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async deleteCipherAttachment(id: string, attachmentId: string): Promise<any> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/ciphers/' + id + '/attachment/' + attachmentId, {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
method: 'DELETE',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
// Sync APIs
async getSync(): Promise<SyncResponse> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/sync', {
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Device-Type': this.deviceType,
}),
}));
if (response.status === 200) {
const responseJson = await response.json();
return new SyncResponse(responseJson);
} else {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
async postImportDirectory(organizationId: string, request: ImportDirectoryRequest): Promise<any> {
const authHeader = await this.handleTokenState();
const response = await fetch(new Request(this.baseUrl + '/organizations/' + organizationId + '/import', {
body: JSON.stringify(request),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
headers: new Headers({
'Accept': 'application/json',
'Authorization': authHeader,
'Content-Type': 'application/json; charset=utf-8',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status !== 200) {
const error = await this.handleError(response, false);
return Promise.reject(error);
}
}
2018-01-09 22:19:55 +01:00
// Helpers
private async handleError(response: Response, tokenError: boolean): Promise<ErrorResponse> {
if ((tokenError && response.status === 400) || response.status === 401 || response.status === 403) {
2018-05-16 05:40:15 +02:00
await this.logoutCallback(true);
2018-01-09 22:19:55 +01:00
return null;
}
let responseJson: any = null;
const typeHeader = response.headers.get('content-type');
if (typeHeader != null && typeHeader.indexOf('application/json') > -1) {
responseJson = await response.json();
}
return new ErrorResponse(responseJson, response.status, tokenError);
}
private async handleTokenState(): Promise<string> {
2018-05-15 05:56:27 +02:00
let accessToken = await this.tokenService.getToken();
2018-01-09 22:19:55 +01:00
if (this.tokenService.tokenNeedsRefresh()) {
const tokenResponse = await this.doRefreshToken();
accessToken = tokenResponse.accessToken;
}
return 'Bearer ' + accessToken;
}
private async doRefreshToken(): Promise<IdentityTokenResponse> {
const refreshToken = await this.tokenService.getRefreshToken();
if (refreshToken == null || refreshToken === '') {
throw new Error();
}
2018-03-29 03:54:21 +02:00
const decodedToken = this.tokenService.decodeToken();
2018-01-09 22:19:55 +01:00
const response = await fetch(new Request(this.identityBaseUrl + '/connect/token', {
body: this.qsStringify({
grant_type: 'refresh_token',
2018-03-29 03:54:21 +02:00
client_id: decodedToken.client_id,
2018-01-09 22:19:55 +01:00
refresh_token: refreshToken,
}),
cache: 'no-cache',
2018-06-05 21:45:19 +02:00
credentials: this.getCredentials(),
2018-01-09 22:19:55 +01:00
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Accept': 'application/json',
'Device-Type': this.deviceType,
}),
method: 'POST',
}));
if (response.status === 200) {
const responseJson = await response.json();
const tokenResponse = new IdentityTokenResponse(responseJson);
await this.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken);
return tokenResponse;
} else {
const error = await this.handleError(response, true);
return Promise.reject(error);
}
}
private qsStringify(params: any): string {
return Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
2018-06-05 21:45:19 +02:00
private getCredentials(): RequestCredentials {
if (!this.isWebClient || this.usingBaseUrl) {
return 'include';
}
return undefined;
}
2018-01-09 22:19:55 +01:00
}