Introduction & Usage

Censor

A event & call interception library for javascript. Censor monkeypatches your custom handles to any existing object or class' functions, attributes and events.

Here is an example of intercepting all proceeding fetch requests and load events:

censor(window).whenCall("fetch", async (ctx) => {
  console.log(ctx.args) // Log the arguments passed to fetch

  var result = await ctx.pass() // Run the original fetch function
  console.log(result.status) // Log the result status

  return result // Pass the response
}).on("load", (ctx, event) => {
  console.log("loaded")  // Signifiy that the event was run
  return ctx.pass() // Run the original handler
})

 fetch("https://echo.zuplo.io").catch((error) => {
   console.error(error.message)
 })

Links

Installation

import { censor } from "https://cdn.jsdelivr.net/gh/thatrandomperson5/censorjs@master/release/censor.module.min.js"

or

<script src="https://cdn.jsdelivr.net/gh/thatrandomperson5/censorjs@master/release/censor.min.js"></script>

Usage

There are two main parts to the Censor process:

  • The censored instance or class (eg. WebSocket or window)
  • The censoring object (The CensorObject or CensorClass instance)

All censor handles applied via the censoring object will directly and permenantly affect the censored instance. You can think of the censoring object as a interface that allows for easy creation of censor handles, not directly connected to any handles themselves.

Instance vs. Class

Before you continue, you should know the difference between censoring a instance vs. a class. When you censor a instance, you replace current and future calls and triggers with glorified wrappers that handle it your way before passing back to the original. Censoring a class simply designates a initilization function so that when anyone creates a new instance of that class, it automatically comes with a censor on that instance. You can think of this as a "group" of sorts so that you can apply one set of handles to any object of your choice.

Basic Usage of the Censoring Object

The simplest, reccommended way of creating a censoring object is using the censor function.

var windowCensor = censor(window)
var webSocketCensor = censor(WebSocket)

You can also directly create the classes, but that makes inline chains more difficult (eg. censor(something).first().second())

var windowCensor = new CensorObject(window)
var webSocketCensor = new CensorClass(WebSocket)

Instance censors and class censors are implemented automatically, but class censors can also be set manually in the scope.

var webSocketCensor = censor(WebSocket, null, null) // Last null signifies that you are manually implementing it. 
WebSocket = webSocketCensor.genFunc() // Implement your class censoring 

Censoring Functions

Name Description Pass/Next Effect Step Graph
.whenCall(name, handle) Register a handle that is called instead whenever name is called. Call the original function behind name Outside Call -> Handle -> Original Function -> Handle Return
.whenAttr(name, handles) Sets a custom setter and getter for property with name. Get or set the property Outside Set/Get -> Handle -> Internal Get/Set -> Handle Return
.on(event, handle) A event intercepter that intercepts all event handles of the event event Call the original handle function. Event Triggered -> Handle -> Original Handle -> Handle Return
.whenCreate(handle) A instance creation interceptor (before other intercepters are added) Call the original new ClassName(...args) function. Creation Called -> Handle -> Constructor -> Handle Return -> Other Interception Added -> Return Final

Handles

Censor handles are constructed very similarly to the orignal handle/function with exception of the ctx object as the first object.

  • You have the option of making a handle a complete replacement of the original by not using ctx.
  • Your ways of interacting with the original are calling .next(...args) or .pass which passes argument automatically.

The general structure goes something like this:

(ctx) => {
  ctx.args.modify() // Change it to your wish
  var result = ctx.pass()
  result.modify() // Change the result
  return result;
}

Async

The whenCall function supports async handles. These will should be used when the original function is async and can be enabled by passing async (ctx, arg1) => {doSomething} as a handler.

Examples

Coming soon

Injection Tooling Examples

softRefresh example (installing eruda mobile console before anything else loaded)

softRefresh(
  () => {
    alert("Hello world")
    eruda.init()
  },
  {
    resources: ["https://cdn.jsdelivr.net/npm/eruda"],
  },
)

Original Tests

<script id="test1">
  function log(txt) {
    document.getElementById("outp").textContent += txt.toString() + "\n"
  }

  function test1() {
    censor(window, true).whenCall("fetch", async (ctx) => {
      log(ctx.args)
      var result = await ctx.pass()
      log(result.status)
      return result
    })

    window.fetch("https://echo.zuplo.io").catch((error) => {
      console.error(error.message)
    })

    document.getElementById("btn").onclick = () => {
      alert("Hello")
    }

    censor(document.getElementById("btn")).on("click", (ctx, event) => {
      log(ctx.args)
      return ctx.pass()
    })

    document.getElementById("btn").addEventListener("click", () => {
      log("EVENT CLICK")
    })
  }
  function test2() {
    var webSocketCensor = censor(WebSocket, "WebSocket")
    webSocketCensor.whenCall("send", (ctx, data) => {
      console.log(data)
      return ctx.pass()
    })

    webSocketCensor.on("message", (ctx, event) => {
      console.log(event.data)
      return ctx.pass()
    })

    let ws = new WebSocket("wss://echo.websocket.org/")
    ws.onopen = (event) => {
      ws.send("Here's some text that the server is urgently awaiting!")
    }
    ws.onmessage = (event) => {
      log(event.data)
    }
  }
  
  function test3() {
    var urlc = censor(URL)
    urlc.whenCreate((ctx) => {
      log(ctx.args)
      return ctx.pass()
    })
    let url = new URL("https://google.com")
  }
</script>
<pre><code id="outp"></code></pre>
<button id="btn">Button</button>

API

All functions, variables and classes and their types.

Other documentation versions can be found here.

The main module of the Censor library. Contains all core features.

Censor
Example
censor(window).whenCall("fetch", async (ctx) => {
  console.log(ctx.args) // Log the arguments passed to fetch
  var result = await ctx.pass() // Run the original fetch function
  console.log(result.status) // Log the result status
  return result // Pass the response
}).on("load", (ctx, event) => {
  console.log("loaded")  // Signifiy that the event was run
  return ctx.pass() // Run the original handler
})

 fetch("https://echo.zuplo.io").catch((error) => {
   console.error(error.message)
 })

PropertyDescription

src/censor.js

See mozilla documentation.

PropertyDescription

Type: Object

Properties
configurable (bool?)
enumerable (bool?)
value (any?)
writable (bool?)
get (function (): void?)
set (function (any): void?)

CensorContext

src/censor.js

A class for providing context and interaction within the Censor handle.

new CensorContext(parent: CensorObject, name: string)
Parameters
parent (CensorObject) The connected Censor object.
name (string) The name of the attribute, function, or event that is currently connected.
Instance Members
▸ args
▸ parent
▸ callback
▸ subject
▸ next(args)
▸ pass()
▸ expandUpon()

CensorCallContext

src/censor.js

A class for providing context and interaction within the Censor handle.

new CensorCallContext()

Extends CensorContext

Deprecated: since 0.1.1

genericHandle

src/censor.js

The main callback function type. Note that the effects of .pass()/.next() change based om where the context was assigned from. (See Pass/NextEffect)

genericHandle(ctx: (CensorContext | CensorCallContext), var_args: ...any): any

Type: Function

Parameters
ctx ((CensorContext | CensorCallContext)) The passed context.
var_args (...any) Any number of arguments passed to the context.
Returns
any: The result you want to be passed to the original.

CensorObject

src/censor.js

The main Censor class. Applies censor effects to any object, and effects are independent of the Censor class object.

new CensorObject(object: Object)
Parameters
object (Object) The base object.
Static Members
▸ typeCheck(obj, typ)
▸ getPropertyDescriptor(obj, name, maxdepth)
Instance Members
▸ object
▸ call(name, args)
▸ getAttr(name)
▸ setAttr(name, asgn)
▸ whenCall(name, handle)
▸ whenAttr(name, handles)
▸ on(event, handle)

CensorClass

src/censor.js

Very similar to CensorObject, used to censor uninitiated classes on initiation. whenCall, whenAttr and on are all directly equivilent to their CensorObject counterparts.

new CensorClass(cls: function (...any): Object, accessName: (string | null), implementOn: (Object | null))
Parameters
cls (function (...any): Object) The class descriptor function.
accessName ((string | null) = null) The name this class is accessed by publicly. (For example, WebSocket is internally named E , so this would be needed)
implementOn ((Object | null) = window) The object to automatically implement the result genFunc() onto.
Instance Members
▸ name
▸ whenCreate(handle)
▸ apply(obj)
▸ genFunc()

Properly censor the given object if able

censor(obj: any, options: ...any): (CensorObject | CensorClass)
Parameters
obj (any) The object given as a base.
options (...any) Options to pass to the Censor constructor.
Returns
(CensorObject | CensorClass): The Censor object used to apply handles.

The link to the censor CDN, can be used in options.resources

censorResource

Type: string

A hash function taken from here

cyrb53
Parameters
str (string) The string to hash
seed (number = 0) The seed to base the hash
Returns
number: The hash

softRefreshCallback

src/injection-tooling.js

The callback type for softRefresh

softRefreshCallback(pass: Object?)

Type: Function

Parameters
pass (Object?) An object you can pass to the callback through the pass option

Refresh a webpage with a handle the executes before any original code execution.

softRefresh(handle: softRefreshCallback, options: Object): Promise
Parameters
handle (softRefreshCallback) The handle to execute.
options (Object = {}) The options object.
Name Description
options.pass Object? A json serializable object to pass to the handle after load.
options.resources Array<(URL | string)>? A list of links to libraries or other resources you want avalible in your handle.
options.processer function (Document)? Any custom operations on the document before the soft refresh.
options.useCurrentState bool? Use current html instead of fetching default.
Returns
Promise: The promise that resolves the function.