New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

workers-firebase

Package Overview
Dependencies
Maintainers
2
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

workers-firebase - npm Package Compare versions

Comparing version 0.1.1 to 0.1.2

.prettierrc.cjs

6

dist/auth/auth.d.ts
import { FirebaseService } from '../service';
import type { Settings } from '../types';
import type { AccountQuery, AccountQueryResult, SignInResponse, Tokens, User } from './types';
export declare type GetUsersOptions = {
uids?: string[];
emails?: string[];
};
export declare class Auth extends FirebaseService {

@@ -17,3 +21,3 @@ getToken: (claims?: object) => Promise<string>;

getUser(idTokenOrUID: string): Promise<User>;
getUsers(uids: string[]): Promise<User[]>;
getUsers(options: GetUsersOptions): Promise<User[]>;
updateUser(idTokenOrUID: string, updates: any): Promise<Tokens>;

@@ -20,0 +24,0 @@ updatePassword(idTokenOrUID: string, password: string): Promise<Tokens>;

52

dist/auth/auth.js

@@ -5,2 +5,3 @@ import jwt from '@tsndr/cloudflare-worker-jwt';

const uidLength = 28;
const oauthScope = 'https://www.googleapis.com/auth/identitytoolkit';
export class Auth extends FirebaseService {

@@ -25,6 +26,3 @@ constructor(settings, apiKey) {

const jsonWebKey = await getPublicKey(kid);
if (alg !== 'RS256' ||
!jsonWebKey ||
payload.iss !==
`https://securetoken.google.com/${this.settings.projectId}`)
if (alg !== 'RS256' || !jsonWebKey || payload.iss !== `https://securetoken.google.com/${this.settings.projectId}`)
throw new Error('JWT invalid');

@@ -87,17 +85,21 @@ const key = await crypto.subtle.importKey('jwk', jsonWebKey, importAlgorithm, false, ['verify']);

async getUser(idTokenOrUID) {
if (idTokenOrUID.length === uidLength)
return (await this.signInWithCustomToken(await this.createCustomToken(idTokenOrUID))).user;
const response = await this.userRequest('POST', 'accounts:lookup', {
idToken: idTokenOrUID,
});
let response;
if (idTokenOrUID.length === uidLength) {
response = await this.request('POST', 'accounts:lookup', { localId: [idTokenOrUID] }, oauthScope);
}
else {
response = await this.userRequest('POST', 'accounts:lookup', { idToken: idTokenOrUID });
}
return convertUserData(response.users[0]);
}
async getUsers(uids) {
async getUsers(options) {
const { uids, emails } = options;
const response = await this.request('POST', 'accounts:lookup', {
localId: uids,
}, 'https://www.googleapis.com/auth/identitytoolkit');
email: emails,
}, oauthScope);
// may not be returned in the same order, we will sort it
const map = new Map();
response.users.forEach((data) => map.set(data.localId, convertUserData(data)));
return uids.map((uid) => map.get(uid));
response.users.forEach((data) => map.set(uids ? data.localId : data.email, convertUserData(data)));
return (uids || emails).map(lookup => map.get(lookup));
}

@@ -126,6 +128,3 @@ async updateUser(idTokenOrUID, updates) {

async updatePassword(idTokenOrUID, password) {
if (!idTokenOrUID ||
typeof idTokenOrUID !== 'string' ||
!password ||
typeof password !== 'string') {
if (!idTokenOrUID || typeof idTokenOrUID !== 'string' || !password || typeof password !== 'string') {
throw new Error('INVALID_DATA');

@@ -143,7 +142,8 @@ }

async deleteUser(idTokenOrUID) {
if (idTokenOrUID.length === uidLength)
idTokenOrUID = await this.getUserToken(idTokenOrUID);
await this.userRequest('POST', 'accounts:delete', {
idToken: idTokenOrUID,
});
if (idTokenOrUID.length === uidLength) {
await this.request('POST', 'accounts:delete', { localId: idTokenOrUID }, oauthScope);
}
else {
await this.userRequest('POST', 'accounts:delete', { idToken: idTokenOrUID });
}
}

@@ -182,4 +182,3 @@ async sendVerification(idTokenOrUID) {

async getUserToken(uid) {
return (await this.signInWithCustomToken(await this.createCustomToken(uid)))
.tokens.idToken;
return (await this.signInWithCustomToken(await this.createCustomToken(uid))).tokens.idToken;
}

@@ -243,7 +242,4 @@ }

static stringify(a) {
return btoa(String.fromCharCode.apply(0, a))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
}

@@ -26,2 +26,53 @@ export interface TokenPayload {

}
export interface FirebaseProviderUserInfo {
providerId: string;
displayName: string;
photoUrl: string;
federatedId: string;
email: string;
rawId: string;
screenName: string;
phoneNumber: string;
}
export interface FirebaseEmailInfo {
emailAddress: string;
}
export interface FirebaseMfaEnrollment {
mfaEnrollmentId: string;
displayName: string;
enrolledAt: string;
phoneInfo: string;
totpInfo: {};
emailInfo: FirebaseEmailInfo;
unobfuscatedPhoneInfo: string;
}
export interface FirebaseUserInfo {
localId: string;
email: string;
displayName: string;
language: string;
photoUrl: string;
timeZone: string;
dateOfBirth: string;
passwordHash: string;
salt: string;
version: number;
emailVerified: boolean;
passwordUpdatedAt: number;
providerUserInfo: FirebaseProviderUserInfo[];
validSince: string;
disabled: boolean;
lastLoginAt: string;
createdAt: string;
screenName: string;
customAuth: boolean;
rawPassword: string;
phoneNumber: string;
customAttributes: string;
emailLinkSignin: boolean;
tenantId: string;
mfaInfo: FirebaseMfaEnrollment[];
initialEmail: string;
lastRefreshAt: string;
}
export interface Tokens {

@@ -28,0 +79,0 @@ idToken: string;

@@ -32,10 +32,2 @@ import { StatusError } from './status-error';

}
console.log('fetch:', `${this.apiUrl}${path}?${searchParams}`, {
method,
body: JSON.stringify(body),
headers: {
Authorization,
'Content-Type': 'application/json',
},
});
const response = await fetch(`${this.apiUrl}${path}?${searchParams}`, {

@@ -42,0 +34,0 @@ method,

{
"name": "workers-firebase",
"version": "0.1.1",
"version": "0.1.2",
"scripts": {

@@ -5,0 +5,0 @@ "start": "tsc --watch",

@@ -7,2 +7,3 @@ import jwt from '@tsndr/cloudflare-worker-jwt';

AccountQueryResult,
FirebaseUserInfo,
SignInFirebaseResponse,

@@ -17,2 +18,7 @@ SignInResponse,

const uidLength = 28;
const oauthScope = 'https://www.googleapis.com/auth/identitytoolkit';
export type GetUsersOptions = {
uids?: string[];
emails?: string[];
};

@@ -23,16 +29,9 @@ export class Auth extends FirebaseService {

constructor(settings: Settings, apiKey: string) {
super(
'auth',
'https://identitytoolkit.googleapis.com/v1',
settings,
apiKey
);
super('auth', 'https://identitytoolkit.googleapis.com/v1', settings, apiKey);
}
async verify(token: string) {
if (typeof token !== 'string')
throw new Error('JWT token must be a string');
if (typeof token !== 'string') throw new Error('JWT token must be a string');
const tokenParts = token.split('.');
if (tokenParts.length !== 3)
throw new Error('JWT token must consist of 3 parts');
if (tokenParts.length !== 3) throw new Error('JWT token must consist of 3 parts');
const {

@@ -44,21 +43,8 @@ header: { alg, kid },

if (!importAlgorithm) throw new Error('JWT algorithm not found');
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000))
throw 'JWT token not yet valid';
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000))
throw 'JWT token expired';
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) throw 'JWT token not yet valid';
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) throw 'JWT token expired';
const jsonWebKey = await getPublicKey(kid);
if (
alg !== 'RS256' ||
!jsonWebKey ||
payload.iss !==
`https://securetoken.google.com/${this.settings.projectId}`
)
if (alg !== 'RS256' || !jsonWebKey || payload.iss !== `https://securetoken.google.com/${this.settings.projectId}`)
throw new Error('JWT invalid');
const key = await crypto.subtle.importKey(
'jwk',
jsonWebKey,
importAlgorithm,
false,
['verify']
);
const key = await crypto.subtle.importKey('jwk', jsonWebKey, importAlgorithm, false, ['verify']);
const verified = await crypto.subtle.verify(

@@ -74,13 +60,6 @@ importAlgorithm,

async signInWithEmailAndPassword(
email: string,
password: string
): Promise<SignInResponse> {
async signInWithEmailAndPassword(email: string, password: string): Promise<SignInResponse> {
email = email && email.toLowerCase();
const data = { email, password, returnSecureToken };
const result: SignInFirebaseResponse = await this.userRequest(
'POST',
'accounts:signInWithPassword',
data
);
const result: SignInFirebaseResponse = await this.userRequest('POST', 'accounts:signInWithPassword', data);
const tokens = convertSignInResponse(result);

@@ -92,7 +71,3 @@ const user = await this.getUser(tokens.idToken);

// 0auth signing
async signInWithIdp(
credentials: string,
requestUri: string,
returnIdpCredential = false
): Promise<SignInResponse> {
async signInWithIdp(credentials: string, requestUri: string, returnIdpCredential = false): Promise<SignInResponse> {
const data = {

@@ -104,7 +79,3 @@ postBody: credentials,

};
const result: SignInFirebaseResponse = await this.userRequest(
'POST',
'accounts:signInWithIdp',
data
);
const result: SignInFirebaseResponse = await this.userRequest('POST', 'accounts:signInWithIdp', data);
const tokens = convertSignInResponse(result);

@@ -118,7 +89,3 @@

const data = { token, returnSecureToken };
const result: SignInFirebaseResponse = await this.userRequest(
'POST',
'accounts:signInWithCustomToken',
data
);
const result: SignInFirebaseResponse = await this.userRequest('POST', 'accounts:signInWithCustomToken', data);
const tokens = convertSignInResponse(result);

@@ -131,6 +98,3 @@ const user = await this.getUser(tokens.idToken);

const data = { grant_type: 'refresh_token', refresh_token: refreshToken };
const result: TokenResponse = await POST(
`https://securetoken.googleapis.com/v1/token?key=${this.apiKey}`,
data
);
const result: TokenResponse = await POST(`https://securetoken.googleapis.com/v1/token?key=${this.apiKey}`, data);
const tokens: Tokens = {

@@ -158,22 +122,26 @@ idToken: result.id_token,

async getUser(idTokenOrUID: string) {
if (idTokenOrUID.length === uidLength)
return (
await this.signInWithCustomToken(
await this.createCustomToken(idTokenOrUID)
)
).user;
const response: any = await this.userRequest('POST', 'accounts:lookup', {
idToken: idTokenOrUID,
});
let response: { users: FirebaseUserInfo[] };
if (idTokenOrUID.length === uidLength) {
response = await this.request('POST', 'accounts:lookup', { localId: [idTokenOrUID] }, oauthScope);
} else {
response = await this.userRequest('POST', 'accounts:lookup', { idToken: idTokenOrUID });
}
return convertUserData(response.users[0]);
}
async getUsers(uids: string[]) {
const response: any = await this.request('POST', 'accounts:lookup', {
localId: uids,
}, 'https://www.googleapis.com/auth/identitytoolkit');
async getUsers(options: GetUsersOptions) {
const { uids, emails } = options;
const response: any = await this.request(
'POST',
'accounts:lookup',
{
localId: uids,
email: emails,
},
oauthScope
);
// may not be returned in the same order, we will sort it
const map = new Map<string, User>();
response.users.forEach((data: any) => map.set(data.localId, convertUserData(data)));
return uids.map((uid) => map.get(uid));
response.users.forEach((data: any) => map.set(uids ? data.localId : data.email, convertUserData(data)));
return (uids || emails).map(lookup => map.get(lookup));
}

@@ -191,4 +159,3 @@

}
if (idTokenOrUID.length === uidLength)
idTokenOrUID = await this.getUserToken(idTokenOrUID);
if (idTokenOrUID.length === uidLength) idTokenOrUID = await this.getUserToken(idTokenOrUID);
const { name, email, photoUrl } = updates;

@@ -202,7 +169,3 @@ updates = {

};
const result = (await this.userRequest(
'POST',
'accounts:update',
updates
)) as SignInFirebaseResponse;
const result = (await this.userRequest('POST', 'accounts:update', updates)) as SignInFirebaseResponse;
return convertSignInResponse(result);

@@ -212,12 +175,6 @@ }

async updatePassword(idTokenOrUID: string, password: string) {
if (
!idTokenOrUID ||
typeof idTokenOrUID !== 'string' ||
!password ||
typeof password !== 'string'
) {
if (!idTokenOrUID || typeof idTokenOrUID !== 'string' || !password || typeof password !== 'string') {
throw new Error('INVALID_DATA');
}
if (idTokenOrUID.length === uidLength)
idTokenOrUID = await this.getUserToken(idTokenOrUID);
if (idTokenOrUID.length === uidLength) idTokenOrUID = await this.getUserToken(idTokenOrUID);
const result = (await this.userRequest('POST', 'accounts:update', {

@@ -232,12 +189,11 @@ password,

async deleteUser(idTokenOrUID: string) {
if (idTokenOrUID.length === uidLength)
idTokenOrUID = await this.getUserToken(idTokenOrUID);
await this.userRequest('POST', 'accounts:delete', {
idToken: idTokenOrUID,
});
if (idTokenOrUID.length === uidLength) {
await this.request('POST', 'accounts:delete', { localId: idTokenOrUID }, oauthScope);
} else {
await this.userRequest('POST', 'accounts:delete', { idToken: idTokenOrUID });
}
}
async sendVerification(idTokenOrUID: string) {
if (idTokenOrUID.length === uidLength)
idTokenOrUID = await this.getUserToken(idTokenOrUID);
if (idTokenOrUID.length === uidLength) idTokenOrUID = await this.getUserToken(idTokenOrUID);
const data = { requestType: 'VERIFY_EMAIL', idToken: idTokenOrUID };

@@ -265,7 +221,3 @@ await this.userRequest('POST', 'accounts:sendOobCode', data);

async queryAccounts(options: AccountQuery): Promise<AccountQueryResult> {
const result: any = await this.userRequest(
'POST',
`projects/${this.settings.projectId}/accounts:query`,
options
);
const result: any = await this.userRequest('POST', `projects/${this.settings.projectId}/accounts:query`, options);
return {

@@ -283,4 +235,3 @@ count: parseInt(result.recordsCount),

async getUserToken(uid: string) {
return (await this.signInWithCustomToken(await this.createCustomToken(uid)))
.tokens.idToken;
return (await this.signInWithCustomToken(await this.createCustomToken(uid))).tokens.idToken;
}

@@ -303,3 +254,3 @@ }

function convertUserData(user: any): User {
function convertUserData(user: FirebaseUserInfo): User {
let claims: Record<string, any> = {};

@@ -341,10 +292,5 @@

);
const age = parseInt(
response.headers.get('Cache-Control').replace(/^.*max-age=(\d+).*$/, '$1')
);
const age = parseInt(response.headers.get('Cache-Control').replace(/^.*max-age=(\d+).*$/, '$1'));
setTimeout(() => (publicKeys = undefined), age * 1000);
publicKeys = ((await response.json()) as any).keys.reduce(
(map, key) => (map[key.kid] = key) && map,
{}
);
publicKeys = ((await response.json()) as any).keys.reduce((map, key) => (map[key.kid] = key) && map, {});
}

@@ -357,5 +303,4 @@ return publicKeys[kid];

return new Uint8Array(
Array.prototype.map.call(
atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')),
(c: string) => c.charCodeAt(0)
Array.prototype.map.call(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')), (c: string) =>
c.charCodeAt(0)
)

@@ -365,7 +310,4 @@ );

static stringify(a: string) {
return btoa(String.fromCharCode.apply(0, a))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
}

@@ -31,2 +31,63 @@ export interface TokenPayload {

export interface FirebaseProviderUserInfo {
providerId: string;
displayName: string;
photoUrl: string;
federatedId: string;
email: string;
rawId: string;
screenName: string;
phoneNumber: string;
}
export interface FirebaseEmailInfo {
emailAddress: string;
}
export interface FirebaseMfaEnrollment {
mfaEnrollmentId: string;
displayName: string;
enrolledAt: string;
// Union field mfa_value can be only one of the following:
phoneInfo: string;
totpInfo: {};
emailInfo: FirebaseEmailInfo;
// End of list of possible types for union field mfa_value.
// Union field unobfuscated_mfa_value can be only one of the following:
unobfuscatedPhoneInfo: string;
// End of list of possible types for union field unobfuscated_mfa_value.
}
export interface FirebaseUserInfo {
localId: string;
email: string;
displayName: string;
language: string;
photoUrl: string;
timeZone: string;
dateOfBirth: string;
passwordHash: string;
salt: string;
version: number;
emailVerified: boolean;
passwordUpdatedAt: number;
providerUserInfo: FirebaseProviderUserInfo[];
validSince: string;
disabled: boolean;
lastLoginAt: string;
createdAt: string;
screenName: string;
customAuth: boolean;
rawPassword: string;
phoneNumber: string;
customAttributes: string;
emailLinkSignin: boolean;
tenantId: string;
mfaInfo: FirebaseMfaEnrollment[];
initialEmail: string;
lastRefreshAt: string;
}
export interface Tokens {

@@ -72,6 +133,3 @@ idToken: string; // A Firebase Auth ID token for the authenticated user.

export type AccountQueryOrder = 'ORDER_UNSPECIFIED' | 'ASC' | 'DESC';
export type AccountQueryExpression =
| { email: string }
| { userId: string }
| { phoneNumber: string };
export type AccountQueryExpression = { email: string } | { userId: string } | { phoneNumber: string };

@@ -78,0 +136,0 @@ export interface AccountQuery {

@@ -58,10 +58,2 @@ import { StatusError } from './status-error';

}
console.log('fetch:', `${this.apiUrl}${path}?${searchParams}`, {
method,
body: JSON.stringify(body),
headers: {
Authorization,
'Content-Type': 'application/json',
},
});
const response = await fetch(`${this.apiUrl}${path}?${searchParams}`, {

@@ -68,0 +60,0 @@ method,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc