Using randomUUID() in Zapier to generate UUID - node.js

I'm using Zapier's code module to write some Nodejs to generate a UUID.
I know that I can use node's crypto "library" because I've used it in the past to hash some text (MD5) to send to an API endpoint. I also know that I can use the crypto function randomInt.
For example, the following will correctly without errors return a number in the stated range:
const crypto = require('crypto');
let num = crypto.randomInt(1, 7);
output = [{id: num}];
When I try to use the randomUUID function (documentation), like the following, I get the error "TypeError: crypto.randomUUID is not a function" from Zapier:
const crypto = require('crypto');
let uuid = crypto.randomUUID();
output = [{id: uuid}];
I almost gave up there, but tried one last weird thing:
const crypto = require('crypto');
let uuid = crypto.randomUUID; //changed this
output = [{id: uuid}];
Note that I removed the () and this didn't throw an error and returned something like:
LT6TvivKgpFu5Yk3OvQmti1Hq1aNy5ZM
That looks a lot like a proper UUID since it has the right number of characters, but not the expected hyphens like (for example) 88368f2a-d5db-47d8-a05f-534fab0a0045
So, two questions:
Why is Zapier saying that randomUUID() is not a function? Does it not support this or am I coding something weirdly wrong or not requiring something needed? Is there a different way to do this?
When I use randomUUID (no ()) is this actually a reliable UUID?
EDIT: more info from Zapier, they are saying that their logs show that the code step cannot find module 'uuid'

When I use randomUUID (no ()) is this actually a reliable UUID?
The value you're getting there is not a reliable UUID. UUIDs will contain only 0-9a-f characters, the example you have there doesn't match.
Sorry I can't help you with what's going wrong with the other part! You could maybe try something like this
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
to make sure the crypto package is actually available and there's not some error being silently suppressed? You may also want to check the version, as randomUUID() appears to have been added in v14.17.0
Also nit but should probably be const uuid = crypto.randomUUID(); instead of let ;)

Related

Node js - Issue with my syntax in require(module) . When to use {} and when not to use {} in require('module')

I have a query with the syntax in the require statement. Please refere the sample code below.
const nodemailer = require("nodemailer");
const {google} =require('googleapis');
const {OAuth2}=google.auth;
Some times , I see sample codes which use
const {<variable>} = require('moduleName')
Other times, I see like below
const <variable> = require('moduleName')
What is the difference between them?
Thanks in Advance.
Grateful to the Developers Community.
So, you use { } in this context when you want to do object destructuring to get a property from the exported object and create a module-level variable with that same name.
This:
const { google } = require('googleapis');
is a shortcut for this:
const __g = require('googleapis');
const google = __g.google;
So, within this context, you use the { google } only when you want the .google property from the imported module.
If you want the entire module handle such as this:
const nodemailer = require("nodemailer");
then, you don't use the { }. The only way to know which one you want for any given module is to consult the documentation for the module, the code for the module or examples of how to use the module. It depends entirely upon what the module exports and whether you want the top level export object or you want a property of that object.
It's important to realize that the { } used with require() is not special syntax associated with require(). This is normal object destructuring assignment, the same as if you did this:
// define some object
const x = { greeting: "hello" };
// use object destructuring assignment to create a new variable
// that contains the property of an existing object
const { greeting } = x;
console.log(greeting); // "hello
When you import the function with {}, it means you just import one function that available in the package. Maybe you have've seen:
const {googleApi, googleAir, googleWater} = require("googleapis")
But, when you not using {}, it means you import the whole package, just write:
const google = require("googleapis")
So, let say when you need googleApi in your code. You can call it:
google.googleApi

Can't use crypto in NPM dependency in Electron app

I'm building an Electron app (with Ionic) to digitally sign PDFs with p12 certificates using node-signpdf (https://www.npmjs.com/package/node-signpdf). I've had problems which I solved by using require ('electron').remote for example for fs.
I've also installed the same node version in my OS (MacOS Catalina) as the same one that electron is using (Node v12.4.0).
The problem is that one of the NPM dependencies uses crypto and it shows as undefined with the next error:
HomePage.html:39 ERROR TypeError: _crypto.randomBytes is not a function
at Object.ctx.seedFileSync (prng.js:340)
at _reseedSync (prng.js:210)
at Object.ctx.generateSync (prng.js:163)
at Object.ctx.generate (prng.js:80)
at Object.ctx.getBytes (random.js:92)
at _modPow (rsa.js:431)
at Object.push../node_modules/node-forge/lib/rsa.js.pki.rsa.encrypt (rsa.js:501)
at Object.key.sign (rsa.js:1245)
at addSignerInfos (pkcs7.js:534)
at Object.sign (pkcs7.js:377)
What I can see is that node-signpdf uses node-forge as a dependency, and node-forge loads crypto inside prng.js this way:
var _crypto = null;
if(forge.util.isNodejs && !forge.options.usePureJavaScript &&
!process.versions['node-webkit']) {
_crypto = require('crypto');
}
I've tried changing that part of the code to use crypto-js or browserfy-crypto (this last one doesn't even build and hasn't been updated in years), but I keep getting the error shown above.
EDIT 1:
This is how I'm implementing the signature in my service:
public signFile(pathToFile: string, pathToCert: string): void {
const fs = (<any>window).require('fs');
let certBuffer = fs.readFileSync(pathToCert);
let fileBuffer = fs.readFileSync(pathToFile);
fileBuffer = plainAddPlaceholder({
pdfBuffer: fileBuffer,
reason: 'I have reviewed it.',
signatureLength: 1612,
});
const signedPdf = signer.sign(fileBuffer, certBuffer, {passphrase: 'qwertyui'});
}
The code adds the placeholder to add the signature, the problem comes in signer.sign
EDIT 2:
When I run the app if I type in console: require ('crypto') I see the methods, so it looks like it's loaded in the global scope, the problem seems to be in the NPM dependency of node-forge.
EDIT 3:
I've changed require('crypto') to window.require('crypto') and started working. But I think I'll have to make postinstall script to modify it.
Is there a better way?
-
How can I make this crypto thing work? I ran out of ideas. Maybe you can spare some?
Thanks for your time!

Different result in NodeJS calculating MD5 hash using crypo

I am trying to get the MD5 has from a number in NodeJS using crypto but I am getting a different hash returned then I get from site where I can calculate the has.
According to http://onlinemd5.com/ the MD5 has for 1092000 is AF118C8D2A0D27A1D49582FDF6339B7C.
When I try to calculate the hash for that number in NodeJS it gives me a different result (ac4d61a5b76c96b00235a124dfd1bfd1). My code:
const crypto = require('crypto');
const num = 1092000;
const hash = crypto.createHash('md5').update(toString(num)).digest('hex');
console.log(hash);
If you convert it to a string normally it works:
const hash = crypto.createHash('md5').update(String(num)).digest('hex'); // or num.toString()
See the difference:
toString(num) = [object Undefined]
(1092000).toString() = "1092000"
If you console.log(this) in a Node env by default you will see that it is:
this = {} typeof = 'object'
this in a Node env is pointing at module.exports so you're calling this toString on the Object.prototype which is not the right thing to do a string conversion on anything other than module.exports.

How can i use ‚momentjs‘ in a ‚binary-parser‘ formatter?

Can anybody help me please. How can i use moment in a formatter?
i think this is not a problem from node or binary parser. it is my understanding i think.
const Parser = require("binary-parser").Parser;
const moment = require('moment');
let time = function(timestamp) {
return moment(timestamp, 'YYMMDDHHmmssSS').format('YYYY-MM-DD HH:mm:ss.SS');
};
let Telegram = new Parser()
.string('timestamp', {encoding: 'hex', length: 7, formatter: time});
The Exception is:
evalmachine.:9
return moment(timestamp, 'YYMMDDHHmmssSS').format('YYYY-MM-DD HH:mm:ss.SS');
^
ReferenceError: moment is not defined
at Parser. (evalmachine.:9:2)
...
I think the Problem is that Parser don't know moment. But how can i realize that?
i have tried to import moment directly in the binary-parser module. But it doesn't working.
If i run moment outside of Parser then it is working.
Maybe anybody can help me.
The formatter function runs without the momentjs context. I am guessing because of the way it consumes the formatter property. In the code found here, the code is:
if (this.code.formatter) {
... (ctx, varName, this.options.formatter)
Because of the funny way the this keyword works, it's bound to the object (options) and because that declaration does not contain momentjs, it says that it is not defined.
You can get a better understanding of this by looking at line 735:
ctx.pushCode("{0} = ({1}).call(this, {0});", varName, formatter);
It's bound to the current object.
P.S.: I copied the code and pasted it on Node.js and it's working perfectly. ^That is a possible explanation.

What does utils.generateToken(64) do?

var token = utils.generateToken(64);
I have a vague idea what it might be for but I wanted to know specifically just to be sure.
I didn't find anything in what's supposed to be the official doc
That function will generate a unique id for you, the function can written like this:
Reference here
var uid = require('uid2');
function generateToken(number) {
return uid(number);
}
you need package uid2 to run that function
npm install uid2
Read here to know how it work:
https://github.com/coreh/uid2/blob/master/index.js

Resources