Sandbox execution of JavaScript with vm2 (#463)

* Sandbox execution of JavaScript with vm2

* Encode js to base64

This prevents executing code in the global context by inserting extra
backticks i.e. eval_in_node('`+console.log(process.env)+`').

* Include node_modules/ in python module

* Set NODE_PATH so embedded node_modules is found
master
Jordan Cannon 2020-08-21 02:43:42 -05:00 committed by GitHub
parent dc1763a7d6
commit 9e254ccd2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 892 additions and 5 deletions

View File

@ -19,7 +19,7 @@ class Streamango(BaseExtractor):
r'<script type="text/javascript">([^"]+)var srces', res.text)[0]
src = re.findall(
r'src:d\(([^"]+?)\)', res.text)[0]
js = "window = {}; \n" + js + f"console.log(window.d({src}))"
js = "window = {}; \n" + js + f"window.d({src})"
logger.debug(f"Evaling: {js}")
output = eval_in_node(js)
stream = "https:" + output

1
anime_downloader/node_modules/.bin/vm2 generated vendored Symbolic link
View File

@ -0,0 +1 @@
../vm2/bin/vm2

1
anime_downloader/node_modules/vm2/.eslintignore generated vendored Normal file
View File

@ -0,0 +1 @@
/test.js

19
anime_downloader/node_modules/vm2/.eslintrc.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
module.exports = {
env: {
es6: true,
node: true
},
extends: [
'integromat'
],
parserOptions: {
"ecmaVersion": 2017,
"ecmaFeatures": {
"globalReturn": true
}
},
globals: {
},
rules: {
}
};

142
anime_downloader/node_modules/vm2/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,142 @@
v3.9.2 (2020-04-29)
-------------------
[new] Added NodeVM options to pass argv & env to process object (XmiliaH)
[fix] Fixed breakouts in NodeVM (XmiliaH)
[fix] Made async check more robust (XmiliaH)
v3.9.1 (2020-03-29)
-------------------
[fix] Require helpers statically in main (XmiliaH)
[fix] Fix for non-configurable property access (XmiliaH)
v3.9.0 (2020-03-21)
-------------------
[new] Added vm.Script `lineOffset` and `columnOffset` options (azu)
[new] Allow to specify a compiler per VMScript (XmiliaH)
[new] Add option to disable async (XmiliaH)
[new] Added allot of jsdoc (XmiliaH)
[fix] Fix access to frozen or unconfigurable properties (XmiliaH)
[fix] Double wrap Objects to prevent breakout via inspect (XmiliaH)
[fix] Compile now compiles VM code (XmiliaH)
v3.8.4 (2019-09-13)
-------------------
[fix] Do not allow precompiling VMScript (XmiliaH)
[fix] Security fixes (XmiliaH)
v3.8.3 (2019-07-31)
-------------------
[fix] Security fixes
v3.8.2 (2019-06-13)
-------------------
[fix] toString() on builtin objects
v3.8.1 (2019-05-02)
-------------------
[fix] Module resolver fixes
[fix] require('events') works correctly in Node 12
[fix] SyntaxError not being instanceOf Error
v3.8.0 (2019-04-21)
-------------------
[new] Allow prohibiting access to eval/wasm in sandbox context
[new] Allow transitive external dependencies in sandbox context (Idan Attias)
[new] Allow using wildcards in module-names passed using the external attribute (Harel Moshe)
[fix] Default to index.js when specified "main" does not exist (Harel Moshe)
[fix] Security fixes
v3.7.0 (2019-04-15)
-------------------
[new] Add require.resolve (Idan Attias)
[new] Support multiple root paths (Idan Attias)
v3.6.11 (2019-04-08)
-------------------
[fix] Contextification of EvalError and URIError
[fix] Security fixes
v3.6.10 (2019-01-28)
-------------------
[fix] Add missing console.debug function in NodeVM
[fix] Security fixes
v3.6.9 (2019-01-26)
-------------------
[fix] Security fixes
v3.6.8 (2019-01-26)
-------------------
[fix] Security fixes
v3.6.7 (2019-01-26)
-------------------
[fix] Security fixes
v3.6.6 (2019-01-01)
-------------------
[fix] Security fixes
v3.6.5 (2018-12-31)
-------------------
[fix] Security fixes
v3.6.4 (2018-10-17)
-------------------
[fix] Added new to vmwerror when trying to load coffeescipt but can't (dotconnor)
[fix] Add arguments to process.nextTick proxy (Patrick Engström)
v3.6.3 (2018-08-06)
-------------------
[fix] Security fixes
v3.6.2 (2018-07-05)
-------------------
[fix] Security fixes
v3.6.1 (2018-06-27)
-------------------
[fix] Security fixes
v3.6.0 (2018-05-11)
-------------------
[new] Support for custom source extensions
[new] WIP support for disallowing Promise
[fix] Prevent slow unsafe alloc for Buffers
[fix] Refactors around defaults
[fix] Types definition update
v3.5.2 (2017-10-04)
-------------------
[fix] Prevent slow unsafe alloc for Buffers
v3.5.1 (2017-10-04)
-------------------
[fix] Prevent unsafe alloc for Buffers
v3.5.0 (2017-08-31)
-------------------
[new] Allow a custom compiler to recieve the filetype (Orta Therox)
[new] Allow in-sandbox requires to also get called through the compiler (Orta Therox)
[new] Support whitelisting modules inside a VM (Orta Therox)
[new] Add TypeScript definition (Orta Therox)
v3.4.0 (2017-03-28)
-------------------
[new] Added experimental VM.protect method
v3.3.1 (2017-03-27)
-------------------
[new] Added VM.freeze method
v3.2.0 (2017-02-10)
-------------------
[new] Added support for pre-compiled scripts via VMScript
v3.1.0 (2016-09-03)
-------------------
[new] Added option wrapper (Alizain Feerasta)
v3.0.1 (2016-07-20)
-------------------
Initial release

9
anime_downloader/node_modules/vm2/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2014-2020 Patrik Simek and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

389
anime_downloader/node_modules/vm2/README.md generated vendored Normal file
View File

@ -0,0 +1,389 @@
# vm2 [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Package Quality][quality-image]][quality-url] [![Travis CI][travis-image]][travis-url] [![Known Vulnerabilities][snyk-image]][snyk-url]
vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. Securely!
**Features**
* Runs untrusted code securely in a single process with your code side by side
* Full control over sandbox's console output
* Sandbox has limited access to process's methods
* Sandbox can require modules (builtin and external)
* You can limit access to certain (or all) builtin modules
* You can securely call methods and exchange data and callbacks between sandboxes
* Is immune to all known methods of attacks
* Transpilers support
**How does it work**
* It uses internal VM module to create secure context
* It uses [Proxies](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) to prevent escaping the sandbox
* It overrides builtin require to control access to modules
**What is the difference between Node's vm and vm2?**
Try it yourself:
```javascript
const vm = require('vm');
vm.runInNewContext('this.constructor.constructor("return process")().exit()');
console.log('Never gets executed.');
```
```javascript
const {VM} = require('vm2');
new VM().run('this.constructor.constructor("return process")().exit()');
// Throws ReferenceError: process is not defined
```
## Installation
**IMPORTANT**: Requires Node.js 6 or newer.
npm install vm2
## Quick Example
```javascript
const {VM} = require('vm2');
const vm = new VM();
vm.run(`process.exit()`); // TypeError: process.exit is not a function
```
```javascript
const {NodeVM} = require('vm2');
const vm = new NodeVM({
require: {
external: true
}
});
vm.run(`
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error(error);
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
`, 'vm.js');
```
## Documentation
* [VM](#vm)
* [NodeVM](#nodevm)
* [VMScript](#vmscript)
* [Error handling](#error-handling)
* [Debugging a sandboxed code](#debugging-a-sandboxed-code)
* [Read-only objects](#read-only-objects-experimental)
* [Protected objects](#protected-objects-experimental)
* [Cross-sandbox relationships](#cross-sandbox-relationships)
* [CLI](#cli)
* [2.x to 3.x changes](https://github.com/patriksimek/vm2/wiki/2.x-to-3.x-changes)
* [1.x and 2.x docs](https://github.com/patriksimek/vm2/wiki/1.x-and-2.x-docs)
* [Contributing](https://github.com/patriksimek/vm2/wiki/Contributing)
## VM
VM is a simple sandbox, without `require` feature, to synchronously run an untrusted code. Only JavaScript built-in objects + Buffer are available. Scheduling functions (`setInterval`, `setTimeout` and `setImmediate`) are not available by default.
**Options:**
* `timeout` - Script timeout in milliseconds.
* `sandbox` - VM's global object.
* `compiler` - `javascript` (default) or `coffeescript` or custom compiler function. The library expects you to have coffee-script pre-installed if the compiler is set to `coffeescript`.
* `eval` - If set to `false` any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError` (default: `true`).
* `wasm` - If set to `false` any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError` (default: `true`).
* `fixAsync` - If set to `true` any attempt to run code using async will throw a `VMError` (default: `false`).
**IMPORTANT**: Timeout is only effective on synchronous code you run through `run`. Timeout is NOT effective on any method returned by VM. There're some situations when timeout doesn't work - see [#244](https://github.com/patriksimek/vm2/pull/244).
```javascript
const {VM} = require('vm2');
const vm = new VM({
timeout: 1000,
sandbox: {}
});
vm.run("process.exit()"); // throws ReferenceError: process is not defined
```
You can also retrieve values from VM.
```javascript
let number = vm.run("1337"); // returns 1337
```
**TIP**: See tests for more usage examples.
## NodeVM
Unlike `VM`, `NodeVM` lets you require modules same way like in regular Node's context.
**Options:**
* `console` - `inherit` to enable console, `redirect` to redirect to events, `off` to disable console (default: `inherit`).
* `sandbox` - VM's global object.
* `compiler` - `javascript` (default) or `coffeescript` or custom compiler function (which receives the code, and it's filepath). The library expects you to have coffee-script pre-installed if the compiler is set to `coffeescript`.
* `eval` - If set to `false` any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError` (default: `true`).
* `wasm` - If set to `false` any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError` (default: `true`).
* `sourceExtensions` - Array of file extensions to treat as source code (default: `['js']`).
* `require` - `true` or object to enable `require` method (default: `false`).
* `require.external` - `true`, an array of allowed external modules or an object (default: `false`).
* `require.external.modules` - Array of allowed external modules. Also supports wildcards, so specifying `['@scope/*-ver-??]`, for instance, will allow using all modules having a name of the form `@scope/something-ver-aa`, `@scope/other-ver-11`, etc.
* `require.external.transitive` - Boolean which indicates if transitive dependencies of external modules are allowed (default: `false`).
* `require.builtin` - Array of allowed builtin modules, accepts ["*"] for all (default: none).
* `require.root` - Restricted path(s) where local modules can be required (default: every path).
* `require.mock` - Collection of mock modules (both external or builtin).
* `require.context` - `host` (default) to require modules in host and proxy them to sandbox. `sandbox` to load, compile and require modules in sandbox. Builtin modules except `events` always required in host and proxied to sandbox.
* `require.import` - Array of modules to be loaded into NodeVM on start.
* `require.resolve` - An additional lookup function in case a module wasn't found in one of the traditional node lookup paths.
* `nesting` - `true` to enable VMs nesting (default: `false`).
* `wrapper` - `commonjs` (default) to wrap script into CommonJS wrapper, `none` to retrieve value returned by the script.
* `argv` - Array to be passed to `process.argv`.
* `env` - Object to be passed to `process.env`.
**IMPORTANT**: Timeout is not effective for NodeVM so it is not immune to `while (true) {}` or similar evil.
**REMEMBER**: The more modules you allow, the more fragile your sandbox becomes.
```javascript
const {NodeVM} = require('vm2');
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs', 'path'],
root: "./",
mock: {
fs: {
readFileSync() { return 'Nice try!'; }
}
}
}
});
// Sync
let functionInSandbox = vm.run("module.exports = function(who) { console.log('hello '+ who); }");
functionInSandbox('world');
// Async
let functionWithCallbackInSandbox = vm.run("module.exports = function(who, callback) { callback('hello '+ who); }");
functionWithCallbackInSandbox('world', (greeting) => {
console.log(greeting);
});
```
When `wrapper` is set to `none`, `NodeVM` behaves more like `VM` for synchronous code.
```javascript
assert.ok(vm.run('return true') === true);
```
**TIP**: See tests for more usage examples.
### Loading modules by relative path
To load modules by relative path, you must pass full path of the script you're running as a second argument of vm's `run` method. Filename then also shows up in any stack traces produced from the script.
```javascript
vm.run("require('foobar')", "/data/myvmscript.js");
```
## VMScript
You can increase performance by using pre-compiled scripts. The pre-compiled VMScript can be run later multiple times. It is important to note that the code is not bound to any VM (context); rather, it is bound before each run, just for that run.
```javascript
const {VM, VMScript} = require('vm2');
const vm = new VM();
const script = new VMScript("Math.random()");
console.log(vm.run(script));
console.log(vm.run(script));
```
Works for both `VM` and `NodeVM`.
```javascript
const {NodeVM, VMScript} = require('vm2');
const vm = new NodeVM();
const script = new VMScript("module.exports = Math.random()");
console.log(vm.run(script));
console.log(vm.run(script));
```
Code is compiled automatically first time you run it. You can compile the code anytime with `script.compile()`. Once the code is compiled, the method has no effect.
## Error handling
Errors in code compilation and synchronous code execution can be handled by `try`/`catch`. Errors in asynchronous code execution can be handled by attaching `uncaughtException` event handler to Node's `process`.
```javascript
try {
var script = new VMScript("Math.random()").compile();
} catch (err) {
console.error('Failed to compile script.', err);
}
try {
vm.run(script);
} catch (err) {
console.error('Failed to execute script.', err);
}
process.on('uncaughtException', (err) => {
console.error('Asynchronous error caught.', err);
})
```
## Debugging a sandboxed code
You can debug/inspect code running in the sandbox as if it was running in a normal process.
- You can use breakpoints (requires you to specify a script file name)
- You can use `debugger` keyword.
- You can use step-in to step inside the code running in the sandbox.
**Example**
/tmp/main.js:
```javascript
const {VM, VMScript} = require('.');
const fs = require('fs');
const file = `${__dirname}/sandbox.js`;
// By providing a file name as second argument you enable breakpoints
const script = new VMScript(fs.readFileSync(file), file);
new VM().run(script);
```
/tmp/sandbox.js
```javascript
const foo = 'ahoj';
// Debugger keyword works just fine anywhere.
// Even without specifying a file name to the VMScript object.
debugger;
```
## Read-only objects (experimental)
To prevent sandboxed script to add/change/delete properties to/from the proxied objects, you can use `freeze` methods to make the object read-only. This is only effective inside VM. Frozen objects are affected deeply. Primitive types can not be frozen.
**Example without using `freeze`:**
```javascript
const util = {
add: (a, b) => a + b
}
const vm = new VM({
sandbox: {util}
});
vm.run('util.add = (a, b) => a - b');
console.log(util.add(1, 1)); // returns 0
```
**Example with using `freeze`:**
```javascript
const vm = new VM(); // Objects specified in sandbox can not be frozen.
vm.freeze(util, 'util'); // Second argument adds object to global.
vm.run('util.add = (a, b) => a - b'); // Fails silently when not in strict mode.
console.log(util.add(1, 1)); // returns 2
```
**IMPORTANT:** It is not possible to freeze objects that has already been proxied to the VM.
## Protected objects (experimental)
Unlike `freeze`, this method allows sandboxed script to add/modify/delete properties on object with one exception - it is not possible to attach functions. Sandboxed script is therefore not able to modify methods like `toJSON`, `toString` or `inspect`.
**IMPORTANT:** It is not possible to protect objects that has already been proxied to the VM.
## Cross-sandbox relationships
```javascript
const assert = require('assert');
const {VM} = require('vm2');
const sandbox = {
object: new Object(),
func: new Function(),
buffer: new Buffer([0x01, 0x05])
}
const vm = new VM({sandbox});
assert.ok(vm.run(`object`) === sandbox.object);
assert.ok(vm.run(`object instanceof Object`));
assert.ok(vm.run(`object`) instanceof Object);
assert.ok(vm.run(`object.__proto__ === Object.prototype`));
assert.ok(vm.run(`object`).__proto__ === Object.prototype);
assert.ok(vm.run(`func`) === sandbox.func);
assert.ok(vm.run(`func instanceof Function`));
assert.ok(vm.run(`func`) instanceof Function);
assert.ok(vm.run(`func.__proto__ === Function.prototype`));
assert.ok(vm.run(`func`).__proto__ === Function.prototype);
assert.ok(vm.run(`new func() instanceof func`));
assert.ok(vm.run(`new func()`) instanceof sandbox.func);
assert.ok(vm.run(`new func().__proto__ === func.prototype`));
assert.ok(vm.run(`new func()`).__proto__ === sandbox.func.prototype);
assert.ok(vm.run(`buffer`) === sandbox.buffer);
assert.ok(vm.run(`buffer instanceof Buffer`));
assert.ok(vm.run(`buffer`) instanceof Buffer);
assert.ok(vm.run(`buffer.__proto__ === Buffer.prototype`));
assert.ok(vm.run(`buffer`).__proto__ === Buffer.prototype);
assert.ok(vm.run(`buffer.slice(0, 1) instanceof Buffer`));
assert.ok(vm.run(`buffer.slice(0, 1)`) instanceof Buffer);
```
## CLI
Before you can use vm2 in command line, install it globally with `npm install vm2 -g`.
```
$ vm2 ./script.js
```
## Known Issues
* It is not possible to define class that extends proxied class.
## Deployment
1. Update the CHANGELOG
2. Update the `package.json` version number
3. Commit the changes
4. Run `npm publish`
## Sponsors
[![Integromat][integromat-image]][integromat-url]
[npm-image]: https://img.shields.io/npm/v/vm2.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/vm2
[downloads-image]: https://img.shields.io/npm/dm/vm2.svg?style=flat-square
[downloads-url]: https://www.npmjs.com/package/vm2
[quality-image]: http://npm.packagequality.com/shield/vm2.svg?style=flat-square
[quality-url]: http://packagequality.com/#?package=vm2
[travis-image]: https://img.shields.io/travis/patriksimek/vm2/master.svg?style=flat-square&label=unit
[travis-url]: https://travis-ci.org/patriksimek/vm2
[snyk-image]: https://snyk.io/test/github/patriksimek/vm2/badge.svg
[snyk-url]: https://snyk.io/test/github/patriksimek/vm2
[integromat-image]: https://static.integromat.com/logo/45_text.png
[integromat-url]: https://www.integromat.com

3
anime_downloader/node_modules/vm2/bin/vm2 generated vendored Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env node
require(__dirname +'/../lib/cli.js');

198
anime_downloader/node_modules/vm2/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,198 @@
import {EventEmitter} from 'events';
/**
* Require options for a VM
*/
export interface VMRequire {
/** Array of allowed builtin modules, accepts ["*"] for all (default: none) */
builtin?: string[];
/*
* `host` (default) to require modules in host and proxy them to sandbox. `sandbox` to load, compile and
* require modules in sandbox. Builtin modules except `events` always required in host and proxied to sandbox
*/
context?: "host" | "sandbox";
/** `true`, an array of allowed external modules or an object with external options (default: `false`) */
external?: boolean | string[] | { modules: string[], transitive: boolean };
/** Array of modules to be loaded into NodeVM on start. */
import?: string[];
/** Restricted path(s) where local modules can be required (default: every path). */
root?: string | string[];
/** Collection of mock modules (both external or builtin). */
mock?: any;
/* An additional lookup function in case a module wasn't found in one of the traditional node lookup paths. */
resolve?: (moduleName: string, parentDirname: string) => string;
}
/**
* A custom compiler function for all of the JS that comes
* into the VM
*/
type CompilerFunction = (code: string, filename: string) => string;
/**
* Options for creating a VM
*/
export interface VMOptions {
/**
* `javascript` (default) or `coffeescript` or custom compiler function (which receives the code, and it's filepath).
* The library expects you to have coffee-script pre-installed if the compiler is set to `coffeescript`.
*/
compiler?: "javascript" | "coffeescript" | CompilerFunction;
/** VM's global object. */
sandbox?: any;
/**
* Script timeout in milliseconds. Timeout is only effective on code you run through `run`.
* Timeout is NOT effective on any method returned by VM.
*/
timeout?: number;
/**
* If set to `false` any calls to eval or function constructors (`Function`, `GeneratorFunction`, etc) will throw an
* `EvalError` (default: `true`).
*/
eval?: boolean;
/**
* If set to `false` any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError` (default: `true`).
*/
wasm?: boolean;
/**
* If set to `true` any attempt to run code using async will throw a `VMError` (default: `false`).
*/
fixAsync?: boolean;
}
/**
* Options for creating a NodeVM
*/
export interface NodeVMOptions extends VMOptions {
/** `inherit` to enable console, `redirect` to redirect to events, `off` to disable console (default: `inherit`). */
console?: "inherit" | "redirect" | "off";
/** `true` or an object to enable `require` optionss (default: `false`). */
require?: true | VMRequire;
/** `true` to enable VMs nesting (default: `false`). */
nesting?: boolean;
/** `commonjs` (default) to wrap script into CommonJS wrapper, `none` to retrieve value returned by the script. */
wrapper?: "commonjs" | "none";
/** File extensions that the internal module resolver should accept. */
sourceExtensions?: string[];
/**
* Array of arguments passed to `process.argv`.
* This object will not be copied and the script can change this object.
*/
argv?: string[];
/**
* Environment map passed to `process.env`.
* This object will not be copied and the script can change this object.
*/
env?: any;
}
/**
* VM is a simple sandbox, without `require` feature, to synchronously run an untrusted code.
* Only JavaScript built-in objects + Buffer are available. Scheduling functions
* (`setInterval`, `setTimeout` and `setImmediate`) are not available by default.
*/
export class VM {
constructor(options?: VMOptions);
/** Direct access to the global sandbox object */
readonly sandbox: any;
/** Timeout to use for the run methods */
timeout?: number;
/** Runs the code */
run(js: string, path?: string): any;
/** Runs the VMScript object */
run(script: VMScript): any;
/** Runs the code in the specific file */
runFile(filename: string): any;
/** Loads all the values into the global object with the same names */
setGlobals(values: any): this;
/** Make a object visible as a global with a specific name */
setGlobal(name: string, value: any): this;
/** Get the global object with the specific name */
getGlobal(name: string): any;
/** Freezes the object inside VM making it read-only. Not available for primitive values. */
freeze(object: any, name?: string): any;
/** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values */
protect(object: any, name?: string): any;
}
/**
* A VM with behavior more similar to running inside Node.
*/
export class NodeVM extends EventEmitter implements VM {
constructor(options?: NodeVMOptions);
/** Require a module in VM and return it's exports. */
require(module: string): any;
/**
* Create NodeVM and run code inside it.
*
* @param {string} script Javascript code.
* @param {string} [filename] File name (used in stack traces only).
* @param {Object} [options] VM options.
*/
static code(script: string, filename?: string, options?: NodeVMOptions): any;
/**
* Create NodeVM and run script from file inside it.
*
* @param {string} [filename] File name (used in stack traces only).
* @param {Object} [options] VM options.
*/
static file(filename: string, options?: NodeVMOptions): any;
/** Direct access to the global sandbox object */
readonly sandbox: any;
/** Only here because of implements VM. Does nothing. */
timeout?: number;
/** Runs the code */
run(js: string, path?: string): any;
/** Runs the VMScript object */
run(script: VMScript): any;
/** Runs the code in the specific file */
runFile(filename: string): any;
/** Loads all the values into the global object with the same names */
setGlobals(values: any): this;
/** Make a object visible as a global with a specific name */
setGlobal(name: string, value: any): this;
/** Get the global object with the specific name */
getGlobal(name: string): any;
/** Freezes the object inside VM making it read-only. Not available for primitive values. */
freeze(object: any, name?: string): any;
/** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values */
protect(object: any, name?: string): any;
}
/**
* You can increase performance by using pre-compiled scripts.
* The pre-compiled VMScript can be run later multiple times. It is important to note that the code is not bound
* to any VM (context); rather, it is bound before each run, just for that run.
*/
export class VMScript {
constructor(code: string, path: string, options?: {
lineOffset?: number;
columnOffset?: number;
compiler?: "javascript" | "coffeescript" | CompilerFunction;
});
constructor(code: string, options?: {
filename?: string,
lineOffset?: number;
columnOffset?: number;
compiler?: "javascript" | "coffeescript" | CompilerFunction;
});
readonly code: string;
readonly filename: string;
readonly lineOffset: number;
readonly columnOffset: number;
readonly compiler: "javascript" | "coffeescript" | CompilerFunction;
/**
* Wraps the code
* @deprecated
*/
wrap(prefix: string, postfix: string): this;
/** Compiles the code. If called multiple times, the code is only compiled once. */
compile(): this;
}
/** Custom Error class */
export class VMError extends Error {}

3
anime_downloader/node_modules/vm2/index.js generated vendored Normal file
View File

@ -0,0 +1,3 @@
if (parseInt(process.versions.node.split('.')[0]) < 6) throw new Error('vm2 requires Node.js version 6 or newer.');
module.exports = require('./lib/main');

72
anime_downloader/node_modules/vm2/package.json generated vendored Normal file
View File

@ -0,0 +1,72 @@
{
"_args": [
[
"vm2@3.9.2",
"/home/jordan/src/anime-downloader"
]
],
"_from": "vm2@3.9.2",
"_id": "vm2@3.9.2",
"_inBundle": false,
"_integrity": "sha512-nzyFmHdy2FMg7mYraRytc2jr4QBaUY3TEGe3q3bK8EgS9WC98wxn2jrPxS/ruWm+JGzrEIIeufKweQzVoQEd+Q==",
"_location": "/vm2",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "vm2@3.9.2",
"name": "vm2",
"escapedName": "vm2",
"rawSpec": "3.9.2",
"saveSpec": null,
"fetchSpec": "3.9.2"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/vm2/-/vm2-3.9.2.tgz",
"_spec": "3.9.2",
"_where": "/home/jordan/src/anime-downloader",
"author": {
"name": "Patrik Simek",
"url": "https://patriksimek.cz"
},
"bin": {
"vm2": "bin/vm2"
},
"bugs": {
"url": "https://github.com/patriksimek/vm2/issues"
},
"dependencies": {},
"description": "vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. Securely!",
"devDependencies": {
"eslint": "^5.16.0",
"eslint-config-integromat": "^1.5.0",
"mocha": "^6.2.2"
},
"engines": {
"node": ">=6.0"
},
"homepage": "https://github.com/patriksimek/vm2#readme",
"keywords": [
"sandbox",
"prison",
"jail",
"vm",
"alcatraz",
"contextify"
],
"license": "MIT",
"main": "index.js",
"name": "vm2",
"repository": {
"type": "git",
"url": "git+https://github.com/patriksimek/vm2.git"
},
"scripts": {
"pretest": "eslint .",
"test": "mocha test"
},
"types": "index.d.ts",
"version": "3.9.2"
}

13
anime_downloader/package-lock.json generated Normal file
View File

@ -0,0 +1,13 @@
{
"name": "anime-downloader",
"version": "4.4.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"vm2": {
"version": "3.9.2",
"resolved": "https://registry.npmjs.org/vm2/-/vm2-3.9.2.tgz",
"integrity": "sha512-nzyFmHdy2FMg7mYraRytc2jr4QBaUY3TEGe3q3bK8EgS9WC98wxn2jrPxS/ruWm+JGzrEIIeufKweQzVoQEd+Q=="
}
}
}

View File

@ -0,0 +1,26 @@
{
"name": "anime-downloader",
"version": "4.4.2",
"description": "A simple but powerful anime downloader and streamer.",
"main": "index.js",
"directories": {
"doc": "docs",
"test": "tests"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vn-ki/anime-downloader.git"
},
"author": "",
"license": "Unlicense",
"bugs": {
"url": "https://github.com/vn-ki/anime-downloader/issues"
},
"homepage": "https://github.com/vn-ki/anime-downloader#readme",
"dependencies": {
"vm2": "^3.9.2"
}
}

View File

@ -117,6 +117,6 @@ def decrypt(encrypted, passphrase):
def get_cookie(soup):
js = soup.select_one('script').text
js = "location = {'reload': ()=>true};document = {}; \n" + js + f"console.log(document.cookie)"
js = "location = {'reload': ()=>true};document = {}; \n" + js + f"document.cookie"
cookie = eval_in_node(js).strip()
return cookie

View File

@ -15,6 +15,7 @@ import coloredlogs
import pickle
import tempfile
import requests
import base64
from tabulate import tabulate
from uuid import uuid4
from secrets import choice
@ -391,10 +392,15 @@ def get_hcaptcha_cookies(url):
def deobfuscate_packed_js(packedjs):
return eval_in_node('eval=console.log; ' + packedjs)
def eval_in_node(js: str):
# TODO: This should be in util
output = subprocess.check_output(['node', '-e', js])
js = base64.b64encode(js.encode('utf-8')).decode()
sandboxedScript ="""
const {VM} = require('vm2');
const js = Buffer.from('%s','base64').toString()
console.log(new VM().run(js))
"""%js
node_path = path.join(path.dirname(__file__), 'node_modules')
output = subprocess.check_output(['node', '-e', sandboxedScript], env={'NODE_PATH': node_path})
return output.decode('utf-8')
def open_magnet(magnet):

View File

@ -38,6 +38,11 @@ setup(
'httpretty'
],
},
package_data={
# setuptools doesn't support recursive globbing so we need patterns
# for each depth
'anime_downloader': ['node_modules/**/*', 'node_modules/**/**/*']
},
long_description=long_description,
long_description_content_type='text/markdown',
entry_points='''