Skip to content

Commit

Permalink
refactor and clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
KTNG-3 committed Apr 23, 2024
1 parent aebd17f commit f2e5872
Show file tree
Hide file tree
Showing 96 changed files with 1,061 additions and 1,654 deletions.
6 changes: 0 additions & 6 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,11 @@
"semi": "warn",
"new-cap": "warn",
"spaced-comment": "warn",
"require-jsdoc": "warn",
"brace-style": "warn",
"curly": "warn",
"guard-for-in": "warn",
"no-empty-pattern": "warn",
"no-new-wrappers": "warn",
"valid-jsdoc": ["warn", {
"requireParamDescription": true,
"requireReturnDescription": false,
"requireReturn": true
}],
"valid-typeof": "warn"
},
"settings": {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"devDependencies": {
"@types/jest": "^29.5.12",
"@types/node": "^20.12.7",
"@typescript-eslint/eslint-plugin": "^7.7.0",
"@typescript-eslint/parser": "^7.7.0",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"dotenv": "^16.4.5",
"eslint": "^8.57.0",
"jest": "29.7.0",
Expand Down
23 changes: 21 additions & 2 deletions packages/@valapi/auth/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
# 5.0.0

**Change**

- ~~`AuthInstance.fromJSON(user)`~~
- **-->** `new AuthInstance(user?)`
- **-->** `new Auth({ user })`

### Typescript

**Change**

- ~~`UserAuthInfo`~~ **-->** `AuthUserInfo`
- ~~`AuthConfig`~~ **-->** `Config`
- ~~`AuthPromiseResponse`~~ **-->** `PromiseResponse`
- ~~`AuthResponse`~~ **-->** `Response`
- ~~`AuthRequestPlatform`~~ **-->** `ClientPlatform`
- ~~`AuthRequestConfig`~~ **-->** `RequestConfig`

# 5.0.0-alpha.0

**Add**
Expand Down Expand Up @@ -29,7 +48,7 @@
- `User`
- `AuthCore.authenticationInfo`

static
_static_

- `AuthClient.fromCookie()`
- `AuthClient.fromJSON()`
Expand Down Expand Up @@ -98,7 +117,7 @@ static
- `AuthCore.getExpirationDate()`
- `Cookie.authorize()`

static
_static_

- `AuthCore.expires_in`
- `AuthCore.token_type`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,25 @@
import type { Region } from "@valapi/lib";
import { Auth, type UserAuthInfo } from "../index";

import { CookieJar } from "tough-cookie";

import { env } from "node:process";
import { randomBytes } from "node:crypto";

describe("auth.login", () => {
const auth = new Auth();
import type { Region } from "@valapi/lib";

test("new client", () => {
expect(auth.toJSON()).toMatchObject<UserAuthInfo>({
cookie: new CookieJar().serializeSync(),
isMultifactor: false,
access_token: "",
id_token: "",
session_state: "",
entitlements_token: ""
});
import { Auth } from "../index";

expect(auth.subject).toBe("");
});
describe("auth.client", () => {
const auth = new Auth();

test("empty refresh", async () => {
test("empty_reauth", async () => {
await expect(auth.reauthorize()).rejects.toThrow();
});

test("user auth", async () => {
test("login", async () => {
await auth.login(<string>env.VAL_USER, <string>env.VAL_PASS);

expect(auth.isMultifactor).toBe(false);
expect(auth.isAuthenticated).toBe(true);
});

test("user auth error", async () => {
test("error", async () => {
const errorAuth = new Auth({
platform: {
platformChipset: "",
Expand All @@ -46,16 +33,17 @@ describe("auth.login", () => {
await expect(errorAuth.login(randomBytes(10).toString("hex"), randomBytes(15).toString("hex"))).rejects.toThrow();
});

test("user region", async () => {
test("region", async () => {
await expect(auth.regionTokenization()).resolves.toBe(<Region.ID>env.VAL_REGION);
});

test("cookie auth", async () => {
const cookieAuth = new Auth();
cookieAuth.fromJSON({
...new Auth().toJSON(),
...{
cookie: auth.cookie.toJSON()
test("reauth", async () => {
const cookieAuth = new Auth({
user: {
...new Auth().toJSON(),
...{
cookie: auth.cookie.toJSON()
}
}
});

Expand Down
28 changes: 22 additions & 6 deletions packages/@valapi/auth/src/__tests__/core.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import { CookieJar } from "tough-cookie";

import { AuthInstance } from "@valapi/auth";
import type { AuthUserInfo } from "@valapi/auth";

describe("auth.core", () => {
const auth = new AuthInstance();

describe("auth.client", () => {
const myClient = new AuthInstance();
test("new", () => {
expect(auth.toJSON()).toMatchObject<AuthUserInfo>({
cookie: new CookieJar().serializeSync(),
isMultifactor: false,
access_token: "",
id_token: "",
session_state: "",
entitlements_token: ""
});

expect(auth.subject).toBe("");
expect(auth.isAuthenticated).toBe(false);
});

test("save class", () => {
const constClient = new AuthInstance();
constClient.fromJSON(myClient.toJSON());
test("save", () => {
const exportAuth = new AuthInstance(auth.toJSON());

expect(myClient.toJSON()).toStrictEqual(constClient.toJSON());
expect(exportAuth.toJSON()).toStrictEqual(auth.toJSON());
});
});
41 changes: 21 additions & 20 deletions packages/@valapi/auth/src/client/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { ValError } from "@valapi/lib";
import type { Region } from "@valapi/lib";

import { AuthRequest } from "./AuthRequest";
import type { AuthPromiseResponse, AuthResponse, AuthRequestConfig } from "./AuthRequest";
import type { PromiseResponse, Response, RequestConfig } from "./AuthRequest";
import { AuthInstance } from "./AuthInstance";
import type { UserAuthInfo } from "./AuthInstance";
import type { AuthUserInfo } from "./AuthInstance";

export type AuthRequestResponse =
type AuthRequestResponse =
| {
type: "error";
error: string;
Expand Down Expand Up @@ -40,32 +40,40 @@ export type AuthRequestResponse =
country: string;
};

export interface EntitlementsTokenResponse {
interface EntitlementsTokenResponse {
entitlements_token?: string;
}

export interface RegionTokenResponse {
interface RegionTokenResponse {
token: string;
affinities: {
pbe: Region.ID;
live: Region.ID;
};
}

export type AuthConfig = Omit<AuthRequestConfig, "cookie">;
export interface Config extends Omit<RequestConfig, "cookie"> {
user?: AuthUserInfo;
}

export class Auth extends AuthInstance {
public readonly request: AuthRequest;

constructor(config: AuthConfig = {}) {
super();
public constructor(config: Config = {}) {
super(config.user);

this.request = new AuthRequest({
...config,
...{
cookie: this.cookie
}
});

if (this.isAuthenticated) {
this.request.headers.setAuthorization(`Bearer ${this.access_token}`);
this.request.headers.set("X-Riot-Entitlements-JWT", this.entitlements_token);
}
this.request.headers.set("Cookie", this.cookie.getSetCookieStringsSync("https://auth.riotgames.com"));
}

private analyzeCookie(key: string) {
Expand All @@ -80,7 +88,7 @@ export class Auth extends AuthInstance {
this.request.headers.set("Cookie", this.cookie.getSetCookieStringsSync("https://auth.riotgames.com"));
}

protected async authorize(): AuthPromiseResponse<AuthRequestResponse> {
protected async authorize(): PromiseResponse<AuthRequestResponse> {
const response = await this.request.post<AuthRequestResponse>("https://auth.riotgames.com/api/v1/authorization", {
client_id: "play-valorant-web-prod",
nonce: "1",
Expand Down Expand Up @@ -111,6 +119,7 @@ export class Auth extends AuthInstance {
// URI
if (response.data.type === "response") {
this.uriTokenization(response.data.response.parameters.uri);
await this.entitlementsTokenization();

return;
}
Expand All @@ -126,7 +135,7 @@ export class Auth extends AuthInstance {
const response = await this.authorize();
this.analyzeCookie("asid");

const TokenResponse: AuthResponse<AuthRequestResponse> = await this.request.put("https://auth.riotgames.com/api/v1/authorization", {
const TokenResponse: Response<AuthRequestResponse> = await this.request.put("https://auth.riotgames.com/api/v1/authorization", {
type: "auth",
username: username,
password: password,
Expand Down Expand Up @@ -169,7 +178,7 @@ export class Auth extends AuthInstance {
}

protected async entitlementsTokenization() {
const response: AuthResponse<EntitlementsTokenResponse> = await this.request.post("https://entitlements.auth.riotgames.com/api/token/v1");
const response: Response<EntitlementsTokenResponse> = await this.request.post("https://entitlements.auth.riotgames.com/api/token/v1");

if (!response.data.entitlements_token) {
throw new ValError({
Expand All @@ -185,18 +194,10 @@ export class Auth extends AuthInstance {
}

public async regionTokenization(): Promise<Region.ID> {
const response: AuthResponse<RegionTokenResponse> = await this.request.put("https://riot-geo.pas.si.riotgames.com/pas/v1/product/valorant", {
const response: Response<RegionTokenResponse> = await this.request.put("https://riot-geo.pas.si.riotgames.com/pas/v1/product/valorant", {
id_token: this.id_token
});

return response.data.affinities.live;
}

public fromJSON(user: UserAuthInfo): void {
super.fromJSON(user);

this.request.headers.setAuthorization(`Bearer ${this.access_token}`);
this.request.headers.set("X-Riot-Entitlements-JWT", this.entitlements_token);
this.request.headers.set("Cookie", this.cookie.getSetCookieStringsSync("https://auth.riotgames.com"));
}
}
40 changes: 25 additions & 15 deletions packages/@valapi/auth/src/client/AuthInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CookieJar } from "tough-cookie";

import { ValEncryption } from "@valapi/lib";

export interface UserAuthInfo {
export interface AuthUserInfo {
cookie: CookieJar.Serialized;
isMultifactor: boolean;
access_token: string;
Expand All @@ -11,14 +11,15 @@ export interface UserAuthInfo {
entitlements_token: string;
}

export interface UserTokenParse {
interface UserTokenParse {
sub: string;
exp: number;
}

export class AuthInstance implements Omit<UserAuthInfo, "cookie"> {
export class AuthInstance implements Omit<AuthUserInfo, "cookie"> {
public cookie: CookieJar = new CookieJar();
public isMultifactor: boolean = false;

public access_token: string = "";
public id_token: string = "";
public session_state: string = "";
Expand All @@ -27,6 +28,26 @@ export class AuthInstance implements Omit<UserAuthInfo, "cookie"> {
public subject: string = "";
public expirationDate: Date = new Date(-1);

public get isAuthenticated() {
return new Date() < this.expirationDate && Boolean(this.id_token) && Boolean(this.entitlements_token);
}

public constructor(user?: AuthUserInfo) {
if (!user) {
return;
}

this.cookie = CookieJar.deserializeSync(user.cookie);
this.isMultifactor = user.isMultifactor;

this.access_token = user.access_token;
this.id_token = user.id_token;
this.session_state = user.session_state;
this.entitlements_token = user.entitlements_token;

this.getTokenInfo();
}

protected getTokenInfo() {
if (!this.access_token) {
return;
Expand All @@ -38,7 +59,7 @@ export class AuthInstance implements Omit<UserAuthInfo, "cookie"> {
this.expirationDate = new Date(parseToken.exp * 1000);
}

public toJSON(): UserAuthInfo {
public toJSON(): AuthUserInfo {
return {
cookie: this.cookie.serializeSync(),
isMultifactor: this.isMultifactor,
Expand All @@ -48,15 +69,4 @@ export class AuthInstance implements Omit<UserAuthInfo, "cookie"> {
entitlements_token: this.entitlements_token
};
}

public fromJSON(user: UserAuthInfo) {
this.cookie = CookieJar.deserializeSync(user.cookie);
this.isMultifactor = user.isMultifactor;
this.access_token = user.access_token;
this.id_token = user.id_token;
this.session_state = user.session_state;
this.entitlements_token = user.entitlements_token;

this.getTokenInfo();
}
}
Loading

0 comments on commit f2e5872

Please sign in to comment.