wechaty-puppet-service
Version:
Puppet Service for Wechaty
81 lines • 2.99 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.authImplToken = void 0;
const wechaty_puppet_1 = require("wechaty-puppet");
const grpc_js_js_1 = require("./grpc-js.js");
const mokey_patch_header_authorization_js_1 = require("./mokey-patch-header-authorization.js");
/**
* Huan(202108): Monkey patch to support
* copy `:authority` from header to metadata
*/
(0, mokey_patch_header_authorization_js_1.monkeyPatchMetadataFromHttp2Headers)(grpc_js_js_1.Metadata);
/**
* Huan(202108): wrap handle calls with authorization
*
* See:
* https://grpc.io/docs/guides/auth/#with-server-authentication-ssltls-and-a-custom-header-with-token
*/
const authWrapHandlerToken = (validToken) => (handler) => {
wechaty_puppet_1.log.verbose('wechaty-puppet-service', 'auth/auth-impl-token.ts authWrapHandlerToken(%s)(%s)', validToken, handler.name);
return function (call, cb) {
// console.info('wrapAuthHandler internal')
const authorization = call.metadata.get('authorization')[0];
// console.info('authorization', authorization)
let errMsg = '';
if (typeof authorization === 'string') {
if (authorization.startsWith('Wechaty ')) {
const token = authorization.substring(8 /* 'Wechaty '.length */);
if (token === validToken) {
return handler(call, cb);
}
else {
errMsg = `Invalid Wechaty TOKEN "${token}"`;
}
}
else {
const type = authorization.split(/\s+/)[0];
errMsg = `Invalid authorization type: "${type}"`;
}
}
else {
errMsg = 'No Authorization found.';
}
/**
* Not authorized
*/
const error = new grpc_js_js_1.StatusBuilder()
.withCode(grpc_js_js_1.GrpcStatus.UNAUTHENTICATED)
.withDetails(errMsg)
.withMetadata(call.metadata)
.build();
if (cb) {
/**
* Callback:
* handleUnaryCall
* handleClientStreamingCall
*/
cb(error);
}
else if ('emit' in call) {
/**
* Stream:
* handleServerStreamingCall
* handleBidiStreamingCall
*/
call.emit('error', error);
}
else {
throw new Error('no callback and call is not emit-able');
}
};
};
const authImplToken = (validToken) => (serviceImpl) => {
wechaty_puppet_1.log.verbose('wechaty-puppet-service', 'authImplToken()');
for (const [key, val] of Object.entries(serviceImpl)) {
// any: https://stackoverflow.com/q/59572522/1123955
serviceImpl[key] = authWrapHandlerToken(validToken)(val);
}
return serviceImpl;
};
exports.authImplToken = authImplToken;
//# sourceMappingURL=auth-impl-token.js.map
;