Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

twitter-openapi-typescript

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

twitter-openapi-typescript - npm Package Compare versions

Comparing version 0.0.5 to 0.0.6

18

dist/src/api.d.ts
import * as i from 'twitter-openapi-typescript-generated';
import { DefaultApiUtils, InitialStateApiUtils, PostApiUtils, TweetApiUtils, UserApiUtils, UserListApiUtils, V11GetApiUtils, V11PostApiUtils, V20GetApiUtils } from './apis';
import { DefaultFlag } from './types/flag';
type TwitterOpenApiParams = {
export type TwitterOpenApiParams = {
lang?: string;
fetchApi?: i.FetchAPI;
};
export type FetchApi = i.FetchAPI;
export type TwitterOpenApiCookie = {
name: string;
value: string;
};
export declare class TwitterOpenApi {
static hash: string;
static url: string;
static twitter: string;
static userAgent: string;
static bearer: string;
param: TwitterOpenApiParams;
fetchApi: FetchApi | undefined;
constructor(param?: TwitterOpenApiParams);
setFetchApi(fetchApi: FetchApi): void;
get fetchApi(): i.FetchAPI;
cookieDecode(cookie: string): TwitterOpenApiCookie[];
cookieEncode(cookie: TwitterOpenApiCookie[]): string;
getGuestSession(): Promise<TwitterOpenApiCookie[]>;
setCookies(context: i.RequestContext, cookies: TwitterOpenApiCookie[]): i.RequestContext;
getClient(): Promise<TwitterOpenApiClient>;
getClientFromCookies(ct0: string, authToken: string): Promise<TwitterOpenApiClient>;

@@ -33,3 +42,2 @@ }

}
export {};
//# sourceMappingURL=api.d.ts.map

@@ -38,2 +38,11 @@ "use strict";

};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -43,3 +52,3 @@ exports.TwitterOpenApiClient = exports.TwitterOpenApi = void 0;

var apis_1 = require("./apis");
var TwitterOpenApi = /** @class */ (function () {
var TwitterOpenApi = exports.TwitterOpenApi = /** @class */ (function () {
function TwitterOpenApi(param) {

@@ -49,42 +58,123 @@ if (param === void 0) { param = {}; }

}
TwitterOpenApi.prototype.setFetchApi = function (fetchApi) {
this.fetchApi = fetchApi;
Object.defineProperty(TwitterOpenApi.prototype, "fetchApi", {
get: function () {
return this.param.fetchApi || fetch;
},
enumerable: false,
configurable: true
});
TwitterOpenApi.prototype.cookieDecode = function (cookie) {
return cookie
.split(', ')
.map(function (cookie) { return cookie.split(';')[0]; })
.filter(function (cookie) { return cookie.indexOf('=') != -1; })
.map(function (cookie) { return cookie.split('='); })
.map(function (_b) {
var name = _b[0], value = _b[1];
return ({
name: name,
value: value,
});
});
};
TwitterOpenApi.prototype.cookieEncode = function (cookie) {
return cookie.map(function (cookie) { return "".concat(cookie.name, "=").concat(cookie.value); }).join('; ');
};
TwitterOpenApi.prototype.getGuestSession = function () {
return __awaiter(this, void 0, void 0, function () {
var response, chars, csrfToken, cookies, html, re, script;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.fetchApi(TwitterOpenApi.twitter, { method: 'GET', redirect: 'manual' })];
case 1:
response = _b.sent();
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
csrfToken = __spreadArray([], Array(32), true).reduce(function (a) { return a + chars[Math.floor(Math.random() * chars.length)]; }, '');
cookies = this.cookieDecode(response.headers.get('set-cookie'));
cookies.push({ name: 'ct0', value: csrfToken });
return [4 /*yield*/, this.fetchApi(TwitterOpenApi.twitter, {
method: 'GET',
headers: { Cookie: this.cookieEncode(cookies) },
}).then(function (response) { return response.text(); })];
case 2:
html = _b.sent();
re = new RegExp('<script nonce="([a-zA-Z0-9]{48})">(document.cookie="(.*?)";)+<\\/script>');
script = html.match(re)[0];
script
.split('document.cookie="')
.slice(1)
.map(function (e) { return e.replace('</script>', '').replace('";', ''); })
.map(function (e) { return _this.cookieDecode(e)[0]; })
.filter(function (e) { return cookies.findIndex(function (c) { return c.name == e.name; }) == -1; })
.forEach(function (e) { return cookies.push(e); });
return [2 /*return*/, cookies];
}
});
});
};
TwitterOpenApi.prototype.setCookies = function (context, cookies) {
if (context.init.headers) {
var headers = context.init.headers;
headers['cookie'] = this.cookieEncode(cookies);
}
return context;
};
TwitterOpenApi.prototype.getClient = function () {
return __awaiter(this, void 0, void 0, function () {
var cookies, config, flag, _b, _c;
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, this.getGuestSession()];
case 1:
cookies = _d.sent();
config = {
fetchApi: this.fetchApi,
middleware: [{ pre: function (context) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_b) {
return [2 /*return*/, this.setCookies(context, cookies)];
}); }); } }],
apiKey: function (key) {
var _b, _c, _d;
return {
'user-agent': TwitterOpenApi.userAgent,
'x-twitter-client-language': (_b = _this.param.lang) !== null && _b !== void 0 ? _b : 'en',
'x-twitter-active-user': 'yes',
'x-csrf-token': (_c = cookies.find(function (cookie) { return cookie.name === 'ct0'; })) === null || _c === void 0 ? void 0 : _c.value,
'x-guest-token': (_d = cookies.find(function (cookie) { return cookie.name === 'gt'; })) === null || _d === void 0 ? void 0 : _d.value,
}[key];
},
accessToken: TwitterOpenApi.bearer,
};
flag = this.fetchApi(TwitterOpenApi.url, { method: 'GET' }).then(function (res) { return res.json(); });
_b = TwitterOpenApiClient.bind;
_c = [void 0, new i.Configuration(config)];
return [4 /*yield*/, flag];
case 2: return [2 /*return*/, new (_b.apply(TwitterOpenApiClient, _c.concat([_d.sent()])))()];
}
});
});
};
TwitterOpenApi.prototype.getClientFromCookies = function (ct0, authToken) {
return __awaiter(this, void 0, void 0, function () {
var config, flag, _b, _c;
var cookies, config, flag, _b, _c;
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
case 0: return [4 /*yield*/, this.getGuestSession()];
case 1:
cookies = _d.sent();
[
{ name: 'auth_token', value: authToken },
{ name: 'ct0', value: ct0 },
]
.filter(function (e) { return cookies.findIndex(function (c) { return c.name == e.name; }) == -1; })
.forEach(function (e) { return cookies.push(e); });
config = {
fetchApi: this.fetchApi || fetch,
middleware: [
{
pre: function (context) { return __awaiter(_this, void 0, void 0, function () {
var cookie, headers;
return __generator(this, function (_b) {
cookie = [
{
name: 'auth_token',
value: authToken,
},
{
name: 'ct0',
value: ct0,
},
]
.map(function (cookie) { return "".concat(cookie.name, "=").concat(cookie.value); })
.join('; ');
if (context.init.headers) {
headers = context.init.headers;
headers['cookie'] = cookie;
}
return [2 /*return*/, context];
});
}); },
},
],
fetchApi: this.param.fetchApi || fetch,
middleware: [{ pre: function (context) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_b) {
return [2 /*return*/, this.setCookies(context, cookies)];
}); }); } }],
apiKey: function (key) {
var _b;
var _b, _c;
return {

@@ -95,3 +185,3 @@ 'user-agent': TwitterOpenApi.userAgent,

'x-twitter-auth-type': 'OAuth2Session',
'x-csrf-token': ct0,
'x-csrf-token': (_c = cookies.find(function (cookie) { return cookie.name === 'ct0'; })) === null || _c === void 0 ? void 0 : _c.value,
}[key];

@@ -101,9 +191,7 @@ },

};
flag = config
.fetchApi(TwitterOpenApi.url, { method: 'GET' })
.then(function (res) { return res.json(); });
flag = this.fetchApi(TwitterOpenApi.url, { method: 'GET' }).then(function (res) { return res.json(); });
_b = TwitterOpenApiClient.bind;
_c = [void 0, new i.Configuration(config)];
return [4 /*yield*/, flag];
case 1: return [2 /*return*/, new (_b.apply(TwitterOpenApiClient, _c.concat([_d.sent()])))()];
case 2: return [2 /*return*/, new (_b.apply(TwitterOpenApiClient, _c.concat([_d.sent()])))()];
}

@@ -117,2 +205,3 @@ });

TwitterOpenApi.url = "https://raw.githubusercontent.com/fa0311/twitter-openapi/".concat(_a.hash, "/src/config/placeholder.json");
TwitterOpenApi.twitter = 'https://twitter.com/home';
TwitterOpenApi.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36';

@@ -122,3 +211,2 @@ TwitterOpenApi.bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';

}());
exports.TwitterOpenApi = TwitterOpenApi;
var TwitterOpenApiClient = /** @class */ (function () {

@@ -125,0 +213,0 @@ function TwitterOpenApiClient(config, flag) {

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ export { DefaultApiUtils } from './defaultApi';

@@ -0,0 +0,0 @@ "use strict";

export declare class InitialStateApiUtils {
}
//# sourceMappingURL=initialStateApi.d.ts.map

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ export * from './apis';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

@@ -0,0 +0,0 @@ "use strict";

export * from './api';
export * from './type';
//# sourceMappingURL=index.d.ts.map

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=type.js.map

@@ -0,0 +0,0 @@ export type DefaultFlag = {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=flag.js.map

@@ -0,0 +0,0 @@ export type ApiUtilsHeader = {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=header.js.map

@@ -0,0 +0,0 @@ export * from './flag';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import { ApiUtilsHeader } from './';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=response.js.map

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=timeline.js.map

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=tweet.js.map

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=user_list.js.map

@@ -0,0 +0,0 @@ import * as i from 'twitter-openapi-typescript-generated';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=user.js.map
{
"name": "twitter-openapi-typescript",
"version": "0.0.5",
"version": "0.0.6",
"description": "Implementation of Twitter internal API in TypeScript",

@@ -24,3 +24,3 @@ "scripts": {

"dependencies": {
"twitter-openapi-typescript-generated": "^0.0.3"
"twitter-openapi-typescript-generated": "^0.0.5"
},

@@ -35,3 +35,3 @@ "devDependencies": {

"eslint": "^8.0.0",
"eslint-config-standard-with-typescript": "^34.0.0",
"eslint-config-standard-with-typescript": "^35.0.0",
"eslint-plugin-import": "^2.25.0",

@@ -44,4 +44,4 @@ "eslint-plugin-n": "^15.0.0",

"ts-jest": "^28.0.0",
"typescript": "^4.0"
"typescript": "^5.1"
}
}

@@ -1,3 +0,5 @@

# twitter-openapi-typescript@0.0.5
# twitter-openapi-typescript
## Setup
```sh

@@ -7,9 +9,9 @@ npm i twitter-openapi-typescript

## Usage
```typescript
import { TwitterOpenApi } from "twitter-openapi-typescript";
import fetch from "node-fetch";
const api = new TwitterOpenApi();
api.setFetchApi(fetch as any);
const client = await api.getClientFromCookies('<csrf toke here>', '<auth token here>'); // option
const client = await api.getClient();
const response = await client.getUserApi().getUserByScreenName({ screenName: 'elonmusk' });

@@ -19,1 +21,19 @@ console.log(response.data.legacy.screenName);

```
### Node.js
```typescript
import fetch from "node-fetch";
const api = new TwitterOpenApi({ fetchApi: fetch as any });
```
### Login
```typescript
const client = await api.getClientFromCookies('<csrf toke here>', '<auth token here>');
```
### List of APIs
You should read the Test case.
<https://github.com/fa0311/twitter-openapi-typescript/tree/master/twitter-openapi-typescript/test/api>

@@ -15,7 +15,11 @@ import * as i from 'twitter-openapi-typescript-generated';

type TwitterOpenApiParams = {
export type TwitterOpenApiParams = {
lang?: string;
fetchApi?: i.FetchAPI;
};
export type FetchApi = i.FetchAPI;
export type TwitterOpenApiCookie = {
name: string;
value: string;
};

@@ -25,2 +29,4 @@ export class TwitterOpenApi {

static url = `https://raw.githubusercontent.com/fa0311/twitter-openapi/${this.hash}/src/config/placeholder.json`;
static twitter = 'https://twitter.com/home';
static userAgent =

@@ -32,4 +38,2 @@ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36';

fetchApi: FetchApi | undefined;
constructor(param: TwitterOpenApiParams = {}) {

@@ -39,33 +43,87 @@ this.param = param;

setFetchApi(fetchApi: FetchApi) {
this.fetchApi = fetchApi;
get fetchApi(): i.FetchAPI {
return this.param.fetchApi || fetch;
}
cookieDecode(cookie: string): TwitterOpenApiCookie[] {
return cookie
.split(', ')
.map((cookie) => cookie.split(';')[0])
.filter((cookie) => cookie.indexOf('=') != -1)
.map((cookie) => cookie.split('='))
.map(([name, value]) => ({
name: name,
value: value,
}));
}
cookieEncode(cookie: TwitterOpenApiCookie[]): string {
return cookie.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ');
}
async getGuestSession(): Promise<TwitterOpenApiCookie[]> {
const response = await this.fetchApi(TwitterOpenApi.twitter, { method: 'GET', redirect: 'manual' });
const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
const csrfToken = [...Array(32)].reduce((a) => a + chars[Math.floor(Math.random() * chars.length)], '');
const cookies = this.cookieDecode(response.headers.get('set-cookie')!);
cookies.push({ name: 'ct0', value: csrfToken });
const html = await this.fetchApi(TwitterOpenApi.twitter, {
method: 'GET',
headers: { Cookie: this.cookieEncode(cookies) },
}).then((response) => response.text());
const re = new RegExp('<script nonce="([a-zA-Z0-9]{48})">(document.cookie="(.*?)";)+<\\/script>');
const script = html.match(re)[0];
script
.split('document.cookie="')
.slice(1)
.map((e) => e.replace('</script>', '').replace('";', ''))
.map((e) => this.cookieDecode(e)[0])
.filter((e) => cookies.findIndex((c) => c.name == e.name) == -1)
.forEach((e) => cookies.push(e));
return cookies;
}
setCookies(context: i.RequestContext, cookies: TwitterOpenApiCookie[]): i.RequestContext {
if (context.init.headers) {
const headers = context.init.headers as i.HTTPHeaders;
headers['cookie'] = this.cookieEncode(cookies);
}
return context;
}
async getClient(): Promise<TwitterOpenApiClient> {
const cookies: TwitterOpenApiCookie[] = await this.getGuestSession();
const config: i.ConfigurationParameters = {
fetchApi: this.fetchApi,
middleware: [{ pre: async (context) => this.setCookies(context, cookies) }],
apiKey: (key) => {
return {
'user-agent': TwitterOpenApi.userAgent,
'x-twitter-client-language': this.param.lang ?? 'en',
'x-twitter-active-user': 'yes',
'x-csrf-token': cookies.find((cookie) => cookie.name === 'ct0')?.value,
'x-guest-token': cookies.find((cookie) => cookie.name === 'gt')?.value,
}[key]!;
},
accessToken: TwitterOpenApi.bearer,
};
const flag = this.fetchApi(TwitterOpenApi.url, { method: 'GET' }).then((res) => res.json()) as Promise<DefaultFlag>;
return new TwitterOpenApiClient(new i.Configuration(config), await flag);
}
async getClientFromCookies(ct0: string, authToken: string): Promise<TwitterOpenApiClient> {
const cookies: TwitterOpenApiCookie[] = await this.getGuestSession();
[
{ name: 'auth_token', value: authToken },
{ name: 'ct0', value: ct0 },
]
.filter((e) => cookies.findIndex((c) => c.name == e.name) == -1)
.forEach((e) => cookies.push(e));
const config: i.ConfigurationParameters = {
fetchApi: this.fetchApi || fetch,
middleware: [
{
pre: async (context) => {
const cookie = [
{
name: 'auth_token',
value: authToken,
},
{
name: 'ct0',
value: ct0,
},
]
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join('; ');
if (context.init.headers) {
const headers = context.init.headers as i.HTTPHeaders;
headers['cookie'] = cookie;
}
return context;
},
},
],
fetchApi: this.param.fetchApi || fetch,
middleware: [{ pre: async (context) => this.setCookies(context, cookies) }],
apiKey: (key) => {

@@ -77,3 +135,3 @@ return {

'x-twitter-auth-type': 'OAuth2Session',
'x-csrf-token': ct0,
'x-csrf-token': cookies.find((cookie) => cookie.name === 'ct0')?.value,
}[key]!;

@@ -83,5 +141,3 @@ },

};
const flag = config
.fetchApi(TwitterOpenApi.url, { method: 'GET' })
.then((res) => res.json()) as Promise<DefaultFlag>;
const flag = this.fetchApi(TwitterOpenApi.url, { method: 'GET' }).then((res) => res.json()) as Promise<DefaultFlag>;
return new TwitterOpenApiClient(new i.Configuration(config), await flag);

@@ -88,0 +144,0 @@ }

import { getClient, logger } from '@test/init';
import { printTweet } from '@test/util';

@@ -4,0 +3,0 @@ test('getProfileSpotlightsQuery', async () => {

@@ -30,6 +30,6 @@ import { TwitterOpenApi } from '@/api';

export const getClient = async () => {
const api = new TwitterOpenApi();
api.setFetchApi(fetch as any);
const api = new TwitterOpenApi({ fetchApi: fetch as any });
const client = await api.getClientFromCookies(ct0, authToken);
// const client = await api.getClient();
return client;
};

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