Best JavaScript code snippet using wpt
rsa.ts
Source:rsa.ts
1/* eslint-disable id-length, new-cap */2/**3 * JWK => PEM code borrowed from node-jwk (https://github.com/HyperBrain/node-jwk)4 * by Frank Schmid, licensed under Artistic-2.0 (https://opensource.org/licenses/Artistic-2.0).5 * Minor modifications to reduce lines and avoid the extra dependency.6 **/7import {Jwk} from '../types/types'8import {extractPemKey} from '../shared/pem'9import {10 PrivateKeyInfo,11 PublicKeyInfo,12 RSAPrivateKey,13 RSAPublicKey,14 RSAPublicKeyParams,15} from './asn1'16interface JwkData {17 id: number18 n: Buffer | null19 e: Buffer | null20 d: Buffer | null21 p: Buffer | null22 q: Buffer | null23 dp: Buffer | null24 dq: Buffer | null25 qi: Buffer | null26}27export function pemFromJwk(28 key: Jwk,29 targetType: 'private' | 'public'30): {pem: string; type: 'private' | 'public'} {31 const data = getJwkData(key)32 const isPrivate = Boolean(key.d)33 if (targetType === 'private' && !isPrivate) {34 throw new Error('Invalid private key - received a public key')35 }36 return targetType === 'private'37 ? {type: 'private', pem: RSAPrivateKey.encode(data, 'pem', {label: 'RSA PRIVATE KEY'})}38 : {type: 'public', pem: publicKeyFromJwk(data)}39}40export function jwkFromPem(pem: string): Jwk {41 const head = pem.slice(0, pem.indexOf('\n')).trim()42 const decoder = getDecoder(head)43 const body = extractPemKey(pem).replace(/[^\w\d+/=]+/g, '')44 return decoder(Buffer.from(body, 'base64'))45}46const zeroBuffer = Buffer.alloc(1, 0)47function unsigned(bignum: Buffer | null): Buffer | null {48 if (bignum === null || !Buffer.isBuffer(bignum)) {49 return bignum50 }51 if (bignum.readInt8(0) < 0) {52 return Buffer.concat([zeroBuffer, bignum], bignum.length + 1)53 }54 return bignum55}56function publicKeyFromJwk(data: JwkData): string {57 const keyParams = RSAPublicKeyParams.encode(data, 'der')58 const params = {59 header: {keyType: 'RSA'},60 content: {data: keyParams},61 }62 return RSAPublicKey.encode(params, 'pem', {label: 'PUBLIC KEY'})63}64function getJwkData(key: Jwk): JwkData {65 const n = key.n ? Buffer.from(key.n, 'base64') : null66 const e = key.e ? Buffer.from(key.e, 'base64') : null67 const d = key.d ? Buffer.from(key.d, 'base64') : null68 const p = key.p ? Buffer.from(key.p, 'base64') : null69 const q = key.q ? Buffer.from(key.q, 'base64') : null70 const dp = key.dp ? Buffer.from(key.dp, 'base64') : null71 const dq = key.dq ? Buffer.from(key.dq, 'base64') : null72 const qi = key.qi ? Buffer.from(key.qi, 'base64') : null73 return {74 id: 0,75 n: unsigned(n),76 e: unsigned(e),77 d: unsigned(d),78 p: unsigned(p),79 q: unsigned(q),80 dp: unsigned(dp),81 dq: unsigned(dq),82 qi: unsigned(qi),83 }84}85function decodeRsaPublic(buffer: Buffer): Jwk {86 const key = RSAPublicKeyParams.decode(buffer, 'der')87 const e = pad(key.e.toString(16))88 return {89 kty: 'RSA',90 n: bn2base64url(key.n),91 e: hex2b64url(e),92 }93}94function decodeRsaPrivate(buffer: Buffer): Jwk {95 const key = RSAPrivateKey.decode(buffer, 'der')96 const e = pad(key.e.toString(16))97 return {98 kty: 'RSA',99 n: bn2base64url(key.n),100 e: hex2b64url(e),101 d: bn2base64url(key.d),102 p: bn2base64url(key.p),103 q: bn2base64url(key.q),104 dp: bn2base64url(key.dp),105 dq: bn2base64url(key.dq),106 qi: bn2base64url(key.qi),107 }108}109function decodePublic(buffer: Buffer): Jwk {110 const info = PublicKeyInfo.decode(buffer, 'der')111 return decodeRsaPublic(info.publicKey.data)112}113function decodePrivate(buffer: Buffer): Jwk {114 const info = PrivateKeyInfo.decode(buffer, 'der')115 return decodeRsaPrivate(info.privateKey)116}117function bn2base64url(bn: number): string {118 return hex2b64url(pad(bn.toString(16)))119}120function pad(hex: string): string {121 return hex.length % 2 === 1 ? `0${hex}` : hex122}123function urlize(base64: string): string {124 // eslint-disable-next-line no-div-regex125 return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')126}127function hex2b64url(str: string): string {128 return urlize(Buffer.from(str, 'hex').toString('base64'))129}130function getDecoder(header: string): (buffer: Buffer) => Jwk {131 const match = /^-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----$/.exec(header)132 if (!match) {133 throw new Error('Unrecognized PEM key type')134 }135 const isRSA = Boolean(match[1])136 const isPrivate = match[2] === 'PRIVATE'137 if (isPrivate) {138 return isRSA ? decodeRsaPrivate : decodePrivate139 }140 return isRSA ? decodeRsaPublic : decodePublic...
auth0Authorizer.ts
Source:auth0Authorizer.ts
1import { CustomAuthorizerEvent, CustomAuthorizerResult } from 'aws-lambda'2import 'source-map-support/register'3import { verify, decode } from 'jsonwebtoken'4import { createLogger } from '../../utils/logger'5import Axios from 'axios'6import { Jwt } from '../../auth/Jwt'7import { JwtPayload } from '../../auth/JwtPayload'8import * as jwkToPem from 'jwk-to-pem'9const logger = createLogger('auth')10// TODO: Provide a URL that can be used to download a certificate that can be used11// to verify JWT token signature.12// To get this URL you need to go to an Auth0 page -> Show Advanced Settings -> Endpoints -> JSON Web Key Set13const jwksUrl = 'https://sunhorus.auth0.com/.well-known/jwks.json'14// const config = {15// method: 'get',16// url: jwksUrl,17// headers: {}18// };19export const handler = async (20 event: CustomAuthorizerEvent21): Promise<CustomAuthorizerResult> => {22 logger.info('Authorizing a user', event.authorizationToken)23 try {24 const jwtToken = await verifyToken(event.authorizationToken)25 logger.info('User was authorized', jwtToken)26 return {27 principalId: jwtToken.sub,28 policyDocument: {29 Version: '2012-10-17',30 Statement: [31 {32 Action: 'execute-api:Invoke',33 Effect: 'Allow',34 Resource: '*'35 }36 ]37 }38 }39 } catch (e) {40 logger.error('User not authorized', { error: e.message })41 return {42 principalId: 'user',43 policyDocument: {44 Version: '2012-10-17',45 Statement: [46 {47 Action: 'execute-api:Invoke',48 Effect: 'Deny',49 Resource: '*'50 }51 ]52 }53 }54 }55}56async function verifyToken(authHeader: string): Promise<JwtPayload> {57 const token = getToken(authHeader)58 const jwt: Jwt = decode(token, { complete: true }) as Jwt59 if (!jwt)60 throw new Error('token provided is invalid')61 // TODO: Implement token verification62 // You should implement it similarly to how it was implemented for the exercise for the lesson 563 // You can read more about how to do this here: https://auth0.com/blog/navigating-rs256-and-jwks/64 const response = await Axios(jwksUrl);65 const jwkData = response.data;66 const signingKey = jwkData['keys'].find(key => key['kid'] === jwt['header']['kid']);67 if (!signingKey) {68 throw new Error('Invalid Signing key');69 }70 return verify(token, jwkToPem(signingKey), { algorithms: ['RS256'] }) as JwtPayload;71}72function getToken(authHeader: string): string {73 if (!authHeader) throw new Error('No authentication header')74 if (!authHeader.toLowerCase().startsWith('bearer '))75 throw new Error('Invalid authentication header')76 const split = authHeader.split(' ')77 const token = split[1]78 return token...
authorizer.js
Source:authorizer.js
1const jwt = require('jsonwebtoken');2const NodeCache = require('node-cache');3const axios = require('axios');4const authorizerCache = new NodeCache({ stdTTL: 60 * 60 }); // 1 hour TTL5class Authorizer {6 opts = {};7 constructor({ url, path = '.well-known/jwks.json', key = 'data.publicKey' }) {8 this.opts.url = url;9 this.opts.path = path;10 this.opts.key = key;11 }12 verify = async ({ token }) => {13 let publicKey = await this.getPublicKey();14 console.log({ token, publicKey });15 try {16 return await jwt.verify(token, publicKey);17 } catch (err) {18 console.log(err);19 return null;20 }21 };22 extractKeyFromJson = ({ json, key }) => {23 if (!key.length) return json;24 let toPopKey = key.shift();25 return this.extractKeyFromJson({ json: json[toPopKey], key });26 };27 getPublicKey = async () => {28 const CACHE_KEY = 'authorizerPublicKey';29 let publicKey = authorizerCache.get(CACHE_KEY);30 if (!publicKey) {31 let jwkData = (32 await axios.get(33 (this.opts.url.endsWith('/') ? this.opts.url : this.opts.url + '/') +34 this.opts.path35 )36 ).data;37 publicKey = this.extractKeyFromJson({38 json: jwkData,39 key: this.opts.key.split('.'),40 });41 authorizerCache.set(CACHE_KEY, publicKey);42 }43 return publicKey.toString('ssh');44 };45 middleware = async (req, res, next) => {46 try {47 let authHeader = req.headers['authorization'] || '';48 if (typeof authHeader !== 'undefined' && authHeader.includes('Bearer ')) {49 authHeader = authHeader.replace('Bearer ', '');50 const decode = await this.verify({ token: authHeader });51 if (!decode) {52 throw Error('Invalid access token');53 }54 req.user = decode;55 return next();56 } else {57 throw Error('Authorization header not passed');58 }59 } catch (err) {60 console.log('Error in authorizer fn', err);61 return res.status(401).json({62 responseStatus: 'UNAUTHORIZED',63 message: err.message,64 success: false,65 error: {},66 });67 }68 };69}...
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.jwkData(function(data) {4 console.log(data);5});6var wptools = require('wptools');7var page = wptools.page('Barack Obama');8page.jwkData(function(data) {9 console.log(data);10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.jwkData(function(data) {14 console.log(data);15});16var wptools = require('wptools');17var page = wptools.page('Barack Obama');18page.jwkData(function(data) {19 console.log(data);20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.jwkData(function(data) {24 console.log(data);25});26var wptools = require('wptools');27var page = wptools.page('Barack Obama');28page.jwkData(function(data) {29 console.log(data);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.jwkData(function(data) {34 console.log(data);35});36var wptools = require('wptools');37var page = wptools.page('Barack Obama');38page.jwkData(function(data) {39 console.log(data);40});41var wptools = require('wptools');42var page = wptools.page('Barack Obama');43page.jwkData(function(data) {44 console.log(data);45});
Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Albert Einstein');3wp.jwkData(function(err, data) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(data);9 }10});11var wptools = require('wptools');12var wp = wptools.page('Albert Einstein');13wp.jwkData(function(err, data) {14 if (err) {15 console.log(err);16 }17 else {18 console.log(data);19 }20});21var wptools = require('wptools');22var wp = wptools.page('Albert Einstein');23wp.jwkData(function(err, data) {24 if (err) {25 console.log(err);26 }27 else {28 console.log(data);29 }30});31var wptools = require('wptools');32var wp = wptools.page('Albert Einstein');33wp.jwkData(function(err, data) {34 if (err) {35 console.log(err);36 }37 else {38 console.log(data);39 }40});41var wptools = require('wptools');42var wp = wptools.page('Albert Einstein');43wp.jwkData(function(err, data) {44 if (err) {45 console.log(err);46 }47 else {48 console.log(data);49 }50});51var wptools = require('wptools');52var wp = wptools.page('Albert Einstein');53wp.jwkData(function(err, data) {54 if (err) {55 console.log(err);56 }57 else {58 console.log(data);59 }60});61var wptools = require('wptools');62var wp = wptools.page('Albert Einstein');63wp.jwkData(function(err, data) {64 if (err) {65 console.log(err);66 }
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Albert Einstein');3wiki.jwkData(function(err, data) {4 console.log(data);5});6var wptools = require('wptools');7var wiki = wptools.page('Albert Einstein');8wiki.jwkData(function(err, data) {9 console.log(data);10});11var wptools = require('wptools');12var wiki = wptools.page('Albert Einstein');13wiki.jwkData(function(err, data) {14 console.log(data);15});16var wptools = require('wptools');17var wiki = wptools.page('Albert Einstein');18wiki.jwkData(function(err, data) {19 console.log(data);20});21var wptools = require('wptools');22var wiki = wptools.page('Albert Einstein');23wiki.jwkData(function(err, data) {24 console.log(data);25});26var wptools = require('wptools');27var wiki = wptools.page('Albert Einstein');28wiki.jwkData(function(err, data) {29 console.log(data);30});31var wptools = require('wptools');32var wiki = wptools.page('Albert Einstein');33wiki.jwkData(function(err, data) {34 console.log(data);35});36var wptools = require('wptools');37var wiki = wptools.page('Albert Einstein');38wiki.jwkData(function(err, data) {39 console.log(data);40});41var wptools = require('wptools');42var wiki = wptools.page('Albert Einstein');43wiki.jwkData(function(err, data) {44 console.log(data);45});
Using AI Code Generation
1const wptools = require('wptools');2const wpt = new wptools('Albert Einstein');3wpt.jwkData(function(err, data) {4 if (err) {5 return console.log(err);6 }7 console.log(data);8});9const wptools = require('wptools');10const wpt = new wptools('Albert Einstein');11wpt.jwkData(function(err, data) {12 if (err) {13 return console.log(err);14 }15 console.log(data);16});17const wptools = require('wptools');18const wpt = new wptools('Albert Einstein');19wpt.jwkData(function(err, data) {20 if (err) {21 return console.log(err);22 }23 console.log(data);24});25const wptools = require('wptools');26const wpt = new wptools('Albert Einstein');27wpt.jwkData(function(err, data) {28 if (err) {29 return console.log(err);30 }31 console.log(data);32});33const wptools = require('wptools');34const wpt = new wptools('Albert Einstein');35wpt.jwkData(function(err, data) {36 if (err) {37 return console.log(err);38 }39 console.log(data);40});41const wptools = require('wptools');42const wpt = new wptools('Albert Einstein');43wpt.jwkData(function(err, data) {44 if (err) {45 return console.log(err);46 }47 console.log(data);48});49const wptools = require('wptools');50const wpt = new wptools('Albert Einstein');51wpt.jwkData(function(err, data) {52 if (err) {53 return console.log(err);54 }55 console.log(data);56});
Using AI Code Generation
1var wptools = require('wptools');2var jwkData = wptools.jwkData;3var jwk = jwkData('Albert Einstein');4jwk.then(function(data) {5 console.log(data);6});7var wptools = require('wptools');8var jwkData = wptools.jwkData;9var jwk = jwkData('Albert Einstein');10jwk.then(function(data) {11 console.log(data);12});13var wptools = require('wptools');14var jwkData = wptools.jwkData;15var jwk = jwkData('Albert Einstein');16jwk.then(function(data) {17 console.log(data);18});19var wptools = require('wptools');20var jwkData = wptools.jwkData;21var jwk = jwkData('Albert Einstein');22jwk.then(function(data) {23 console.log(data);24});25var wptools = require('wptools');26var jwkData = wptools.jwkData;27var jwk = jwkData('Albert Einstein');28jwk.then(function(data) {29 console.log(data);30});31var wptools = require('wptools');32var jwkData = wptools.jwkData;33var jwk = jwkData('Albert Einstein');34jwk.then(function(data) {35 console.log(data);36});37var wptools = require('wptools');38var jwkData = wptools.jwkData;39var jwk = jwkData('Albert Einstein');40jwk.then(function(data) {41 console.log(data);42});43var wptools = require('wptools');44var jwkData = wptools.jwkData;45var jwk = jwkData('Albert Einstein');
Using AI Code Generation
1const wptools = require('wptools');2const wpt = wptools();3jwkData.then((data) => {4 console.log(data);5});6const wptools = require('wptools');7const wpt = wptools();8jwkData.then((data) => {9 console.log(data);10});11const wptools = require('wptools');12const wpt = wptools();13jwkData.then((data) => {14 console.log(data);15});16const wptools = require('wptools');17const wpt = wptools();18jwkData.then((data) => {19 console.log(data);20});21const wptools = require('wptools');22const wpt = wptools();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!