showdownjs / showdown

A bidirectional Markdown to HTML to Markdown converter written in Javascript
http://www.showdownjs.com/
MIT License
14.26k stars 1.56k forks source link

Inclusion suggestion #859

Closed falseywinchnet closed 2 years ago

falseywinchnet commented 3 years ago

I had to do a lot of work to get my cloudflare worker to run, but once I did, it was pretty sweet. I have some code suggestions to include. I found an example of how to get google OAUTH working and I worked up the code to make it function for pushing files to google storage via the JSON protocol.

The following code is used

`async function handleRequest(request) {

try{

// Function to encode an object with base64 function objectToBase64url(object) { return arrayBufferToBase64Url( new TextEncoder().encode(JSON.stringify(object)), ) };

// Function to encode array buffer with base64 function arrayBufferToBase64Url(buffer) { return btoa(String.fromCharCode(...new Uint8Array(buffer))) .replace(/=/g, '') .replace(/+/g, '-') .replace(/\//g, '_') };

// Function to convert string to array buffer function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = new Uint8Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; };

// // Step 1 - Form the JWT header and encode to base64 const GOOGLE_JWT_HEADER = objectToBase64url({ // RSA SHA-256 algorithm is mandatory for Google alg: 'RS256', // JWT token format is mandatory for Google typ: 'JWT' });

// // Step 2 - Form the JWT claim set and encode to base64

// Define the time the assertion was issued let assertiontime = Math.round(Date.now() / 1000)

// Define the expiration time of the assertion, maximum 1 hour let expirytime = assertiontime + 3600

// JWT claim payload const GOOGLE_JWT_CLAIMSET = objectToBase64url({ // Service account email address from https://console.cloud.google.com // This should be defined as a secret rather than hardcoded!! 'iss': 'email@domain.tld', // A listing of available scopes is provided here: // https://developers.google.com/identity/protocols/oauth2/scopes 'scope': 'https://www.googleapis.com/auth/devstorage.read_write', 'aud': 'https://oauth2.googleapis.com/token', 'exp': expirytime, 'iat': assertiontime });

// Combine the JWT header + claim and convert to byte array for signing const GOOGLE_JWT_COMBINED = str2ab( "{" + GOOGLE_JWT_HEADER + "}.{" + GOOGLE_JWT_CLAIMSET + "}" );

const private_key_raw = '-----BEGIN PRIVATE KEY-----\nput the private key from your .json from google from the service account here\n-----END PRIVATE KEY-----\n'; //Note that you first have to activate the service account from the commmand line, finish the oauth steps, enable some APIs, and wait a few hours.

// Tidy up the key ahead of importing var private_key_clean = private_key_raw.replace('-----BEGIN PRIVATE KEY-----', ''); var private_key_clean = private_key_clean.replace('-----END PRIVATE KEY-----', ''); var private_key_clean = private_key_clean.replace(/(\r\n|\n|\r)/gm, "");

// base64 decode the string to get the binary data var private_key_binary = atob(private_key_clean);

// convert from a binary string to an ArrayBuffer var private_key_binary = str2ab(private_key_binary);

// Import the private key into the crypto store const SIGNING_KEY = await crypto.subtle.importKey( "pkcs8", private_key_binary, { name: "RSASSA-PKCS1-V1_5", hash: {name: "SHA-256"} }, false, ["sign"] );

// Sign the GOOGLE_JWT_HEADER and GOOGLE_JWT_CLAIMSET const rawToken = await crypto.subtle.sign( { name: 'RSASSA-PKCS1-V1_5' }, SIGNING_KEY, GOOGLE_JWT_COMBINED );

// Convert the signature to Base64URL format const GOOGLE_JWT_SIGNED = arrayBufferToBase64Url(rawToken);

// Combine the headers with signature var combined_headers_signed = "{" + GOOGLE_JWT_HEADER + "}.{" + GOOGLE_JWT_CLAIMSET + "}.{"

// // Step 4 - Send the request

// Create payload const GOOGLE_JWT_PAYLOAD = "grant_type=" + "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + combined_headers_signed;

// Make the OAUTH request const response = await fetch('https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'no-cache', 'Host': 'oauth2.googleapis.com' }, body: GOOGLE_JWT_PAYLOAD });

// Grab the JSON from the response const oauth = await response.json();

arrayofinfo = [ 1,2,3];

// Capture the access token const GOOGLE_OAUTH_ACCESS_TOKEN = oauth.access_token;

const URL = "https://storage.googleapis.com/upload/storage/v1/b/BUCKETNAME/o?uploadtype=media&name=" + Date.now().toString() + ".json"; / The following fetch requires between 12 and 30ms to complete. It requires the cloudflare unbounded worker 90% of the time. /

const mailman = await fetch(URL, { method: 'POST', headers : { "Authorization" : Bearer ${GOOGLE_OAUTH_ACCESS_TOKEN}, "Content-Type" : "application/json;charset=UTF-8" }, body: JSON.stringify(arrayofinfo) });

await Promise .all() .then(() => { }) .catch(error => { }); } //the promise structure is needed for the await to finish.

return Response.redirect("https://google.com", 307);

} catch (err) { console.log(err) } };

addEventListener('fetch', async event => { event.respondWith(handleRequest(event.request)) }) `

SyntaxRules commented 2 years ago

I'm not sure what your are suggesting @falseywinchnet. I may have missed it, but your code doesn't seem to reference ShowdownJS at all.

falseywinchnet commented 2 years ago

Devyn I didn't comment on your repo. I don't know why my commentary was moved to your repo. I commented on the cloudflare workers system making a suggestion for a code example inclusion. The code example I wrote was for a fully functional low latency async cloudflare worker to push data to a google bucket.

On Wed, Nov 10, 2021 at 12:02 AM Devyn S @.***> wrote:

Closed #859 https://github.com/showdownjs/showdown/issues/859.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/showdownjs/showdown/issues/859#event-5594724902, or unsubscribe https://github.com/notifications/unsubscribe-auth/AUYJQQ6WPMKQKOVLTGKGT5DULIDHBANCNFSM5AAR5KJA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.