Skip to content

Commit

Permalink
chore: run fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
negezor committed Apr 10, 2024
1 parent 9a180a4 commit d253574
Show file tree
Hide file tree
Showing 113 changed files with 1,673 additions and 2,381 deletions.
5 changes: 3 additions & 2 deletions packages/authorization/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export const CALLBACK_BLANK = 'https://oauth.vk.com/blank.html';
/**
* User-Agent for standalone auth
*/
export const DESKTOP_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36';
export const DESKTOP_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36';

/**
* Auth error codes
Expand All @@ -20,7 +21,7 @@ export enum AuthErrorCode {
USERNAME_OR_PASSWORD_IS_INCORRECT = 'USERNAME_OR_PASSWORD_IS_INCORRECT',
TOO_MUCH_TRIES = 'TOO_MUCH_TRIES',
WRONG_OTP = 'WRONG_OTP',
OTP_FORMAT_IS_INCORRECT = 'OTP_FORMAT_IS_INCORRECT'
OTP_FORMAT_IS_INCORRECT = 'OTP_FORMAT_IS_INCORRECT',
}

/**
Expand Down
4 changes: 1 addition & 3 deletions packages/authorization/src/errors/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ export class AuthorizationError extends VKError {
public constructor({ message, code, pageHtml }: IAuthorizationErrorOptions) {
super({ message, code });

this.pageHtml = isDebug
? pageHtml
: undefined;
this.pageHtml = isDebug ? pageHtml : undefined;
}
}
46 changes: 10 additions & 36 deletions packages/authorization/src/fetch-cookie.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
import createDebug from 'debug';
import { CookieJar } from 'tough-cookie';

import {
fetch,

RequestInfo,
RequestInit,
Response,
} from './fetch';
import { RequestInfo, RequestInit, Response, fetch } from './fetch';

export type Headers = Record<string, string>;

export type FetchWrapper = (
url: RequestInfo,
options?: RequestInit
) => Promise<Response>;
export type FetchWrapper = (url: RequestInfo, options?: RequestInit) => Promise<Response>;

export {
CookieJar,
RequestInfo,
RequestInit,
Response,
};
export { CookieJar, RequestInfo, RequestInit, Response };

const debug = createDebug('vk-io:util:fetch-cookie');

Expand All @@ -34,8 +20,7 @@ const findUserAgent = (headers?: Headers): string | undefined => {
return undefined;
}

const key = Object.keys(headers)
.find((header): boolean => userAgentRe.test(header));
const key = Object.keys(headers).find((header): boolean => userAgentRe.test(header));

if (!key) {
return undefined;
Expand All @@ -44,11 +29,8 @@ const findUserAgent = (headers?: Headers): string | undefined => {
return headers[key];
};

export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper => (
async function fetchCookie(
url: RequestInfo,
options: RequestInit = {},
): Promise<Response> {
export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper =>
async function fetchCookie(url: RequestInfo, options: RequestInit = {}): Promise<Response> {
const previousCookie = await jar.getCookieString(String(url));

const { headers = {} } = options as {
Expand All @@ -73,21 +55,15 @@ export const fetchCookieDecorator = (jar = new CookieJar()): FetchWrapper => (
return response;
}

await Promise.all(cookies.map((cookie: string): Promise<unknown> => (
jar.setCookie(cookie, response.url)
)));
await Promise.all(cookies.map((cookie: string): Promise<unknown> => jar.setCookie(cookie, response.url)));

return response;
}
);
};

export const fetchCookieFollowRedirectsDecorator = (jar?: CookieJar): FetchWrapper => {
const fetchCookie = fetchCookieDecorator(jar);

return async function fetchCookieFollowRedirects(
url: RequestInfo,
options: RequestInit = {},
): Promise<Response> {
return async function fetchCookieFollowRedirects(url: RequestInfo, options: RequestInit = {}): Promise<Response> {
const response = await fetchCookie(url, {
...options,

Expand All @@ -112,9 +88,7 @@ export const fetchCookieFollowRedirectsDecorator = (jar?: CookieJar): FetchWrapp

const userAgent = findUserAgent(options.headers as Headers);

const headers: Headers = userAgent !== undefined
? { 'User-Agent': userAgent }
: {};
const headers: Headers = userAgent !== undefined ? { 'User-Agent': userAgent } : {};

const redirectResponse = await fetchCookieFollowRedirects(location, {
method: 'GET',
Expand Down
5 changes: 2 additions & 3 deletions packages/authorization/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ export type RequestInfo = import('node-fetch').RequestInfo | URL;
export type RequestInit = import('node-fetch').RequestInit;
export type Response = import('node-fetch').Response;

export const fetch = (url: RequestInfo, init?: RequestInit): Promise<Response> => (
Promise.resolve(fetchPromise).then(fn => fn(url as string, init))
);
export const fetch = (url: RequestInfo, init?: RequestInit): Promise<Response> =>
Promise.resolve(fetchPromise).then(fn => fn(url as string, init));
22 changes: 8 additions & 14 deletions packages/authorization/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import type { load as cheerioLoad } from 'cheerio';

import { groupScopes, userScopes } from './constants';
import type { Response } from './fetch-cookie';
import { userScopes, groupScopes } from './constants';

export type CheerioStatic = ReturnType<typeof cheerioLoad>;

/**
* Returns the bit mask of the user permission by name
*/
export const getUserPermissionsByName = (rawScope: string | string[]): number => {
const scope = !Array.isArray(rawScope)
? rawScope.split(/,\s*/)
: rawScope;
const scope = !Array.isArray(rawScope) ? rawScope.split(/,\s*/) : rawScope;

let bitMask = 0;

Expand All @@ -30,9 +28,7 @@ export const getUserPermissionsByName = (rawScope: string | string[]): number =>
* Returns the bit mask of the group permission by name
*/
export const getGroupPermissionsByName = (rawScope: string | string[]): number => {
const scope = !Array.isArray(rawScope)
? rawScope.split(/,\s*/)
: rawScope;
const scope = !Array.isArray(rawScope) ? rawScope.split(/,\s*/) : rawScope;

let bitMask = 0;

Expand All @@ -47,18 +43,16 @@ export const getGroupPermissionsByName = (rawScope: string | string[]): number =
return bitMask;
};

export const getAllUserPermissions = (): number => (
getUserPermissionsByName([...userScopes.keys()])
);
export const getAllUserPermissions = (): number => getUserPermissionsByName([...userScopes.keys()]);

export const getAllGroupPermissions = (): number => (
getGroupPermissionsByName([...groupScopes.keys()])
);
export const getAllGroupPermissions = (): number => getGroupPermissionsByName([...groupScopes.keys()]);

/**
* Parse form
*/
export const parseFormField = ($: unknown): {
export const parseFormField = (
$: unknown,
): {
action: string;
fields: Record<string, string>;
} => {
Expand Down
1 change: 0 additions & 1 deletion packages/authorization/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export * from './open-api';
export {
AuthErrorCode,
officialAppCredentials,

userScopes,
groupScopes,
} from './constants';
17 changes: 5 additions & 12 deletions packages/authorization/src/open-api.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,27 @@
import { createHash } from 'crypto';

const openAPIProperties = [
'expire',
'secret',
'mid',
'sid',
];
const openAPIProperties = ['expire', 'secret', 'mid', 'sid'];

export interface IUserAuthorizedThroughOpenAPIOptions {
clientSecret: string;
params: Record<'expire' | 'mid' | 'secret' | 'sid' | 'sig', string>
params: Record<'expire' | 'mid' | 'secret' | 'sid' | 'sig', string>;
}

export const userAuthorizedThroughOpenAPI = ({
clientSecret,
params,
}: IUserAuthorizedThroughOpenAPIOptions):Promise<{ authorized: boolean }> => {
}: IUserAuthorizedThroughOpenAPIOptions): Promise<{ authorized: boolean }> => {
let sign = ([...openAPIProperties] as (keyof typeof params)[])
.sort()
.map(key => `${key}=${params[key]}`)
.join('');

sign += clientSecret;
sign = createHash('md5')
.update(sign)
.digest('hex');
sign = createHash('md5').update(sign).digest('hex');

const expire = Number(params.expire);

const isExpired = Number.isNaN(expire) || expire < (Date.now() / 1000);
const isExpired = Number.isNaN(expire) || expire < Date.now() / 1000;
const authorized = params.sig === sign && !isExpired;

return Promise.resolve({ authorized });
Expand Down
41 changes: 19 additions & 22 deletions packages/authorization/src/providers/account-verification.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,26 @@
import createDebug from 'debug';
import { load as cheerioLoad } from 'cheerio';
import { AbortController } from 'abort-controller';
import { load as cheerioLoad } from 'cheerio';
import createDebug from 'debug';

import { CaptchaType, type ICallbackServiceValidate, type CallbackService } from 'vk-io';
import { type CallbackService, CaptchaType, type ICallbackServiceValidate } from 'vk-io';

import type { Agent } from 'https';

import { AuthErrorCode, CALLBACK_BLANK, DESKTOP_USER_AGENT } from '../constants';
import { AuthorizationError } from '../errors';
import { type CheerioStatic, parseFormField, getFullURL } from '../helpers';
import {
CookieJar,

type FetchWrapper,
type RequestInfo,
type RequestInit,
type Response,

fetchCookieFollowRedirectsDecorator,
} from '../fetch-cookie';
import { DESKTOP_USER_AGENT, CALLBACK_BLANK, AuthErrorCode } from '../constants';
import { type CheerioStatic, getFullURL, parseFormField } from '../helpers';

const debug = createDebug('vk-io:authorization:account-verification');

const {
INVALID_PHONE_NUMBER,
AUTHORIZATION_FAILED,
FAILED_PASSED_CAPTCHA,
FAILED_PASSED_TWO_FACTOR,
} = AuthErrorCode;
const { INVALID_PHONE_NUMBER, AUTHORIZATION_FAILED, FAILED_PASSED_CAPTCHA, FAILED_PASSED_TWO_FACTOR } = AuthErrorCode;

/**
* Two-factor auth check action
Expand Down Expand Up @@ -226,11 +219,13 @@ export class AccountVerification {
debug('process two-factor handle');

if (this.twoFactorValidate) {
this.twoFactorValidate.reject(new AuthorizationError({
message: 'Incorrect two-factor code',
code: FAILED_PASSED_TWO_FACTOR,
pageHtml: $.html(),
}));
this.twoFactorValidate.reject(
new AuthorizationError({
message: 'Incorrect two-factor code',
code: FAILED_PASSED_TWO_FACTOR,
pageHtml: $.html(),
}),
);

this.twoFactorAttempts += 1;
}
Expand Down Expand Up @@ -341,10 +336,12 @@ export class AccountVerification {
*/
protected async processCaptchaForm(response: Response, $: CheerioStatic): Promise<Response> {
if (this.captchaValidate !== undefined) {
this.captchaValidate.reject(new AuthorizationError({
message: 'Incorrect captcha code',
code: FAILED_PASSED_CAPTCHA,
}));
this.captchaValidate.reject(
new AuthorizationError({
message: 'Incorrect captcha code',
code: FAILED_PASSED_CAPTCHA,
}),
);

this.captchaValidate = undefined;

Expand Down
Loading

0 comments on commit d253574

Please sign in to comment.