Создания OAuth на javascript, html и typescript

28 декабря, 21:43 Технологии 4421 0

Короче я подумал про OAuth и решил эго создать на Java Script и давайте начнем

 

1. Создания OAuth

Ну чтож поехали. Для начала создаэм генератор Ray ID

Вот код етого генератора

/**  

* Return a random value to Ray ID  

*/

function random() {

   const array = new Uint32Array(1);

   crypto.getRandomValues(array);

   const ray_id = array[0] % 100000 + 1;

   return ray_id;

}

var ray_id = random();

(function() {

 

   let pre = document.createElement('pre');

   pre.className = "ray";

   pre.innerHTML = `${ray_id}`;

 

   document.body.append(pre);

})();

 

2. Создаэм сканнер

Теперь создаэм сканер вот его код

function scan(type = '', time = new Date().setTime()) {

   if (type == 'ddos') {

       if (time > 0) {

           return 0

       } else {

           let rel = document.createElement('meta');

           rel.httpEquiv = 'refresh';

           rel.content = 5;

 

           document.head.append(rel);

           return 1;

       }

   }

   return new Date().getTime();

}

 

И создаэм функцию inner_scan далее она нам понадобится

function innerScan() {

   if (ray_id > 0) {

       return true;

   }

   return false;

}

 

3. Сканнер

Теперь создаэм все необходимоэ для работи етого кода:

let scan_inner = innerScan();

let ret = scan('ddos', new Date().setTime(10000));

if (scan_inner == true) {

   scan('ddos', new Date().setTime(10000));

   let go = document.createElement('meta');

   go.httpEquiv = 'refresh';

   go.content = '0; url=http://вашсайт.домен/страница';

   if (ret == 1) {

       document.head.append(go);

   }

   document.head.append(go);

} else if (scan_inner == false) {

   let error = document.createElement('pre')

   error.className = 'error'

   error.innerHTML = '<strong>Error of scanning. Please reload this page</strong>'

 

   document.body.append(error);

}

 

4.Протокол OAuth

Для OAuth нужен протокол поетому создаэм его

let OAuth_Protocol = generateOAuth("OAuth2P", 867487867454584956862452957386288574, 1, false);

/**

* This function generate `OAuth2` protocol.

* @param {*} type this parameter set protocol type

* @param {*} sha256 this parameter set UUID to protocol

* @param {*} id this parameter set ID in protocol

* @param {*} cert this parameter set generation protocol certificate

*/

function generateOAuth(type = "", sha256 = 0, id = 0, cert = false) {

   if (type == "OAuth2P" || sha256 != 0 || id != 0) {

       if (cert == true) {

           generateOAuthCertificate(".crt", "OAuth" + sha256);

           let crt = generateOAuthCertificate(".crt", "OAuth" + sha256);

           let OAuth2 = type + ":" + sha256 + id + "Proto" + crt;

           return OAuth2;

       } else {

           let OAuth = type + ":" + sha256 + id + "Proto";

           return OAuth;

       }

   } else if (type == "OAuth2D" || sha256 != 0 || id != 0) {

       if (cert == true) {

           generateOAuthCertificate(".dec", "OAuth" + sha256);

           let crt = generateOAuthCertificate(".crt", "OAuth" + sha256);

           let OAuth2 = type + ":" + sha256 + id + "Proto" + crt;

           return OAuth2;

       } else {

           let OAuth = type + ":" + sha256 + id + "Proto";

           return OAuth;

       }

   }

   return "";

}

/**

* This function generate `certificate` to protocol

* @param {*} type set certificate type

* @param {*} owner set certificate owner

*/

function generateOAuthCertificate(type = "", owner = "") {

   if (type == ".crt" || owner != "") {

       let cert = document.createElement('script')

       cert.type = "ssl/crt";

       cert.async = true;

       cert.defer = "OAuth2 Proto"

       cert.innerHTML = `

       var certificate = '74566959406867448759867877646786476984764674674986457647637540385496847209540673985834095HUMt8498yttu84yheog8y87yg87niy87gy4g874yng87gtg8ieyfo8it7END${owner};

       function export() {

           return certificate;

       }

       console.log(export());

       `

       document.body.append(cert)

       return `74566959406867448759867877646786476984764674674986457647637540385496847209540673985834095HUMt8498yttu84yheog8y87yg87niy87gy4g874yng87gtg8ieyfo8it7END${owner}`;

   } else if (type == ".dec" || owner != "") {

       let cert = document.createElement('script')

       cert.type = "ssl/crt";

       cert.async = true;

       cert.defer = "OAuth2 Proto"

       cert.innerHTML = `

       var certificate = '10101010101101010011110101001010101010101101010101011011101010010101010101010101010101010101010101010100110000011010101010101001100010110010101010END${owner};

       function export() {

           return certificate;

       }

       console.log(export());

       `

       document.body.append(cert)

       return `10101010101101010011110101001010101010101101010101011011101010010101010101010101010101010101010101010100110000011010101010101001100010110010101010END${owner}`;

   }

}

5. OAuth Запроси

Ну чтож мы имеем код для OAuth. Теперь создаэм OAuth запроси, но прежде вставте етот код

/* ----------------------------------------OAuth Protocol 1.1---------------------------------------- */

 

var OAUTH_PROTOCOL_OK = 200;

var OAUTH_PROTOCOL_ERROR = 404;

var OAUTH_PROTOCOL_UNDEFINED = 401;

var OAUTH_PROTOCOL_NOT_GEN = 402;

var OAUTH_PROTOCOL_LOAD = 201;

var OAUTH_PROTOCOL_SUCCESS = 202;

var OAUTH_PROTOCOL_SCAN = 301;

var RAYID_ERROR = 403;

var RAYID_SUCCESS = 205;

 

function protocolFilter() {

   if (OAuth_Protocol != "") {

       return OAUTH_PROTOCOL_OK;

   } else {

       return OAUTH_PROTOCOL_ERROR;

   }

}

А теперь к делу. Создаем OAuth запрос

// OAuth Request

import "./lib.oauth"

let oauth = new OAuth();

oauth.open('GET', 'http://вашсайт.домен/api.php', true);

oauth.onreadystatechange = function() {

   if (oauth.readyState === 4) {

       if (oauth.status === 200) {

           console.log(xhr.responseText);

       } else {

           console.log('Request failed with status ' + oauth.status);

       }

   }

};

oauth.send();

И мы можем заметить из import "./lib.oauth" ето не встроеная библиотека поетому создаэм библиотека вот код:

ВНИМАНИЯ! Етот код вставляйте в файл lib.oauth.d.ts

/**

* Creates a new OAuth.

*/

interface OAuth extends OAuthEventTarget {

   /**

    * This function return this interface

    */

   isEmpty(): OAuthConstructor;

 

   /**

    * Calls the OAuth, substituting the specified object for the this value of the OAuth,

    * and the specified array for the arguments of the OAuth.

    * @param thisArg The object to be used as the this object.

    * @param argArray A set of arguments to be passed to the OAuth.

    */

   apply(this: OAuth, thisArg: any, argArray?: any) : any;

 

   /**

    * Calls a method of an object, substituting another object for the current object.

    * @param thisArg The object to be used as the current object.

    * @param argArray A list of arguments to be passed to the method.

    */

   call(this: OAuth, thisArg: any, ...argArray: any[]): any;

 

   /**

    * For a given OAuth, creates a bound OAuth that has the same body as the original OAuth.

    * The this object of the bound OAuth is associated with the specified object, and has the specified initial parameters.

    * @param thisArg An object to which the this keyword can refer inside the new OAuth.

    * @param argArray A list of arguments to be passed to the new OAuth.

    */

   bind(this: OAuth, thisArg: any, ...argArray: any[]): any;

 

   /** Returns a string representation of a function. */

   toString(): string;

 

   onreadystatechange: ((this: OAuth, ev: Event) => any) | null;

 

   /**

    * Returns client's state.

    */

   readonly readyState: number;  

 

   /**

    * Returns the response body.

    */

   readonly response: any;

 

   /**

    * Returns response as text.

    *  

    * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text".

    */

   readonly responseText: string;

 

   /**

    * Returns the response type.

    *  

    * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text".

    *  

    * When set: setting to "document" is ignored if current global object is not a Window object.

    *  

    * When set: throws an "InvalidStateError" DOMException if state is loading or done.

    *  

    * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object.

    */

   responseType: OAuthResponseType;

 

   readonly responseURL: string;

 

   readonly status: number;

 

   readonly statusText: string;

 

   /**

    * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and this's synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method).

    *  

    * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object.

    */

   timeout: number;

 

   /**

    * Returns the associated OAuthUpload object. It can be used to gather transmission information when data is transferred to a server.

    */

   readonly upload: OAuthUpload;

 

   /**

    * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.

    *

    * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set.

    */

   withCredentials: boolean;

 

   /**

    * Cancels any network activity.

    */

   abort(): void;

   getAllResponseHeaders(): string;

   getResponseHeader(name: string): string | null;

 

   /**

    * Sets the request method, request URL, and synchronous flag.

    *

    * Throws a "SyntaxError" DOMException if either method is not a valid method or url cannot be parsed.

    *

    * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`.

    *

    * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string.

    */

   open(method: string, url: string | URL): void;

   open(method: string, url: string | URL, async: boolean, username?: string | null, password?: string | null): void;

 

   /**

    * Acts as if the `Content-Type` header value for a response is mime. (It does not change the header.)

    *

    * Throws an "InvalidStateError" DOMException if state is loading or done.

    */

   overrideMimeType(mime: string): void;

 

   /**

    * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.

    *

    * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set.

    */

   send(body?: Document | OAuthBodyInit | null): void;

 

   /**

    * Combines a header in author request headers.

    *

    * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set.

    *

    * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value.

    */

   setRequestHeader(name: string, value: string): void;

 

   readonly UNSENT: 0;

   readonly OPENED: 1;

   readonly HEADERS_RECEIVED: 2;

   readonly LOADING: 3;

   readonly DONE: 4;

   addEventListener<K extends keyof OAuthEventMap>(type: K, listener: (this: OAuth, ev: OAuthEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

   addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

   removeEventListener<K extends keyof OAuthEventMap>(type: K, listener: (this: OAuth, ev: OAuthEventMap[K]) => any, options?: boolean | EventListenerOptions): void;

   removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;

   prototype: any;

   readonly lenght: number;

 

   // Non-standard extensions

   arguments: any;

   caller: OAuth;

   task: OAuth;

}

 

interface OAuthUpload extends OAuthEventTarget {

   addEventListener<K extends keyof OAuthEventTargetEventMap>(type: K, listener: (this: OAuthUpload, ev: OAuthEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

   addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

   removeEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: OAuthUpload, ev: OAuthEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;

   removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;

}

 

interface OAuthConstructor {

   /**

    * Creates a new OAuthes

    * @param args A list of arguments the oauth accepts.

    */

   new (...args: string[]): OAuth;

   (...args: string[]): OAuth;

   readonly prototype: OAuth;

}

 

declare var OAuth: OAuthConstructor;

 

interface OAuthEventMap extends OAuthEventTargetEventMap {

   "readystatechange": Event;

}

 

interface OAuthEventTargetEventMap {

   "abort": ProgressEvent<OAuthEventTarget>;

   "error": ProgressEvent<OAuthEventTarget>;

   "load": ProgressEvent<OAuthEventTarget>;

   "loadend": ProgressEvent<OAuthEventTarget>;

   "loadstart": ProgressEvent<OAuthEventTarget>;

   "progress": ProgressEvent<OAuthEventTarget>;

   "timeout": ProgressEvent<OAuthEventTarget>;

}

 

interface OAuthEventTarget extends EventTarget {

   onabort: ((this: OAuth, ev: ProgressEvent) => any) | null;

   onerror: ((this: OAuth, ev: ProgressEvent) => any) | null;

   onload: ((this: OAuth, ev: ProgressEvent) => any) | null;

   onloadend: ((this: OAuth, ev: ProgressEvent) => any) | null;

   onloadstart: ((this: OAuth, ev: ProgressEvent) => any) | null;

   onprogress: ((this: OAuth, ev: ProgressEvent) => any) | null;

   ontimeout: ((this: OAuth, ev: ProgressEvent) => any) | null;

   addEventListener<K extends keyof OAuthEventTargetEventMap>(type: K, listener: (this: OAuthEventTarget, ev: OAuthEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

   addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

   removeEventListener<K extends keyof OAuthEventTargetEventMap>(type: K, listener: (this: OAuthEventTarget, ev: OAuthEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;

   removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;

}

 

interface OAuthEventTargetEventMap {

   "abort": ProgressEvent<OAuthEventTarget>;

   "error": ProgressEvent<OAuthEventTarget>;

   "load": ProgressEvent<OAuthEventTarget>;

   "loadend": ProgressEvent<OAuthEventTarget>;

   "loadstart": ProgressEvent<OAuthEventTarget>;

   "progress": ProgressEvent<OAuthEventTarget>;

   "timeout": ProgressEvent<OAuthEventTarget>;

}

 

declare var OAuthEventTarget: {

   prototype: OAuthEventTarget;

   new(): OAuthEventTarget;

}

 

type OAuthBodyInit = Blob | BufferSource | FormData | URLSearchParams | string;

type OAuthResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";

6. Страница

Теперь мы имеем готовий OAuth но нам надо его запустить, для етого создаэм файл index.html и вставляеи в него етот код

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta http-equiv="X-UA-Compatible" content="IE=7">

   <meta name="description" content="This is confirm page">

   <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

   <meta name="keywords" content="Confirm Page">

   <meta name="robots" content="nocache">

   <meta http-equiv="refresh" content="5">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <!-- Это наш скрипт с OAuth -->

   <script src="oauth-2.0.js" async crossorigin></script>

   <title>Please wait...</title>

   <style>

       .ray {

           position: relative;

           top: 300px;

           left: 340px;

           font-size: 14px;

       }

       .ray_text {

           position: relative;

           top: 331px;

           left: 275px;

       }

   </style>

   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

   <script>

       var activeRequests = 0;

       var maxRequests = 10;

 

       function makeRequest() {

           if (activeRequests < maxRequests) {

               activeRequests++;

               // executing AJAX-request

               $.ajax({

                   url: 'nreum.ua',

                   success: function(data) {

               },

               error: function() {

 

               },

               complete: function() {

                   activeRequests--;

               }

               });

           } else {

               // Server overload. Canceling all requests

               console.log('[Server/OAUTH]: Server overload. Canceling all requests');

           }

       }

       makeRequest();

   </script>

   <script>

       // Allowed IP Address List

       const allowedIPs = ['176.108.106.48'];

 

       // Creating Server

       const server = (req, res) => {

           // Get client IP address

           const clientIP = req.socket.remoteAddress;

 

           if (allowedIPs.includes(clientIP)) {

               // Allowed IP address, process the request

           } else {

               res.statusCode = 401;

               res.end('Unauthorized');

           }

       };

   </script>

</head>

<body>

   <center>

       <h1>ServerPanel 4.5 OAuth Client</h1>

       <br>

       <pre><p>

           We are currently checking to see if this site could have been hacked by a client.

           Do not reload the site while the scan is in progress!

       </p></pre>

   </center>

   <p class="ray_text">Ray ID:</p>

</body>

</html>

По желанию код OAuth можно улудшить

 

НУ чтож это все я надеюсь что етая тема била полезная для тебя.

 

Кстати код етого проекта находится здесь:
https://gitlab.com/aternoserror103/oauth-typescript/-/tree/main

Там улудшений lib.oauth.d.ts из 839 строками кода.

0 комментариев
Сортировка:
Добавить комментарий

IT Новости

Смотреть все