Encrypt pdf file using node-qpdf - node.js

I am trying to use node-qpdf
I just did simple:
Test.pdf is inside directory where index.js is
var qpdf = require('node-qpdf');
var options = {
keyLength: 128,
password: 'test123',
restrictions: {
print: 'low',
useAes: 'y'
}
}
var localFilePath ='Test.pdf';
var outputFilePath ='test';
qpdf.encrypt(localFilePath, options, outputFilePath);
I am getting error like:
Run: nodemon index.js
[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56
return callback(null, outputStream);
^
TypeError: callback is not a function
at Object.Qpdf.encrypt (C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56:16)
at Object.<anonymous> (C:\Users\Rad\Desktop\node-qpdf-master\test\index.js:13:6)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...

I think they haven't updated the docs, I read their codes, you must put outputFile and change your options into like this.
var options = {
keyLength: 256,
password: '12345',
outputFile: '<your output name file>',
restrictions: {
modify: 'none',
extract: 'n'
}
var doc = await qpdf.encrypt(`${fileLocation}.pdf`, options)

Related

Firbase/Heroku/Node JS - Firebase Invalid Credential / failed to parse service account json file / ENAMETOOLONG

I'm using github actions to deploy my first webapp via Heroku.
My code:
const fireBaseAdmin = require('firebase-admin');
if (!fireBaseAdmin)
throw new Error('The FIREBASE_SERVICE_ACCOUNT_CREDS environment variable was not found!');
fireBaseAdmin.initializeApp({
"credential": fireBaseAdmin.credential.cert(JSON.stringify({
"type": process.env.FIREBASE_TYPE,
"project_id": process.env.FIREBASE_PROJECT_ID,
"private_key_id": process.env.FIREBASE_PRIVATE_KEY_ID,
"private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
"client_email": process.env.FIREBASE_CLIENT_EMAIL,
"client_id": process.env.FIREBASE_CLIENT_ID,
"auth_uri": process.env.FIREBASE_AUTH_URI,
"token_uri": process.env.FIREBASE_TOKEN_URI,
"auth_provider_x509_cert_url": process.env.FIREBASE_AUTH_PROVIDER,
"client_x509_cert_url": process.env.FIREBASE_CLIENT
}))
});
module.exports = fireBaseAdmin;
Each of the .env variables are stored in Heroku's Config Vars.
Error log from Heroku (I stripped sensitive tokens/keys):
2021-08-17T11:16:53.818119+00:00 app[web.1]: /app/node_modules/firebase-admin/lib/credential/credential-internal.js:151
2021-08-17T11:16:53.818149+00:00 app[web.1]: throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error);
2021-08-17T11:16:53.818150+00:00 app[web.1]: ^
2021-08-17T11:16:53.818150+00:00 app[web.1]:
2021-08-17T11:16:53.818166+00:00 app[web.1]: FirebaseAppError: Failed to parse service account json file: Error: ENAMETOOLONG: name too long, open '{
"type":"service_account",
"project_id":"ec31",
"private_key_id":"2900d",
"private_key":"-----BEGIN PRIVATE KEY-----\nQ=\n-----END\nPRIVATE KEY-----\n",
"client_email":"firebase-adminsdk-.gserviceaccount.com",
"client_id":"10",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"ttps://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-o.gserviceaccount.com"
}'
2021-08-17T11:16:53.818167+00:00 app[web.1]: at FirebaseAppError.FirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:44:28)
2021-08-17T11:16:53.818168+00:00 app[web.1]: at FirebaseAppError.PrefixedFirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:90:28)
2021-08-17T11:16:53.818168+00:00 app[web.1]: at new FirebaseAppError (/app/node_modules/firebase-admin/lib/utils/error.js:125:28)
2021-08-17T11:16:53.818169+00:00 app[web.1]: at Function.ServiceAccount.fromPath (/app/node_modules/firebase-admin/lib/credential/credential-internal.js:151:19)
2021-08-17T11:16:53.818169+00:00 app[web.1]: at new ServiceAccountCredential (/app/node_modules/firebase-admin/lib/credential/credential-internal.js:67:28)
2021-08-17T11:16:53.818174+00:00 app[web.1]: at Object.exports.cert (/app/node_modules/firebase-admin/lib/credential/credential.js:34:54)
2021-08-17T11:16:53.818174+00:00 app[web.1]: at Object.<anonymous> (/app/firebase/index.js:25:42)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1072:14)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:937:32)
2021-08-17T11:16:53.818176+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:778:12)
2021-08-17T11:16:53.818176+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:961:19)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:92:18)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at Object.<anonymous> (/app/middlewares/auth.js:1:15)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1072:14)
2021-08-17T11:16:53.818178+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) {
2021-08-17T11:16:53.818178+00:00 app[web.1]: errorInfo: {
2021-08-17T11:16:53.818178+00:00 app[web.1]: code: 'app/invalid-credential',
2021-08-17T11:16:53.818190+00:00 app[web.1]: message: `Failed to parse service account json file: Error: ENAMETOOLONG: name too long, open '{
"type":"service_account",
"project_id":"e1",
"private_key_id":"2900",
"private_key":"-----BEGIN PRIVATE KEY-----\\nMIIEMoQ=\\n-----END\\nPRIVATE KEY-----\\n",
"client_email":"firebase-adminsdk-od.gserviceaccount.com",
"client_id":"1",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"ttps://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-o.gserviceaccount.com"
}'`
2021-08-17T11:16:53.818190+00:00 app[web.1]: },
2021-08-17T11:16:53.818190+00:00 app[web.1]: codePrefix: 'app'
2021-08-17T11:16:53.818191+00:00 app[web.1]: }
2021-08-17T11:16:53.947406+00:00 heroku[web.1]: Process exited with status 1
2021-08-17T11:16:54.345497+00:00 heroku[web.1]: State changed from starting to crashed
I've been attempted to update my code based on the various posts on Stack Overflow but I'm not having success with solving the error. Here's a short list of the post I've been referencing:
Deploying Firebase App with Service Account to Heroku (environment variables with dotenv)
Authenticating with the Firebase Admin SDK using environment variable
Node.js -Firebase Service Account Private Key won't parse
Firebase: Failed to parse service account: 'project_id' must be set
Any assistance would be greatly appreciated!
The cert() method expects either the path to serviceAccount.json file (string) or a ServiceAccount object. Here you are entering a string so it's expecting that to be the path to serviceAccount.json and not stringified credentials and hence you get the error FirebaseAppError: Failed to parse service account json file. Try this:
fireBaseAdmin.initializeApp({
credential: admin.credential.cert({
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_PROVIDER,
client_x509_cert_url: process.env.FIREBASE_CLIENT
}),
databaseURL: `https://${process.env.FIREBASE_PROJECT_ID}.firebaseio.com/`
})

Heroku Postgres: Unhandled rejection Error: self signed certificate

I'm trying to configure the PostgreSQL database with postgrator in node, using the connectionString in production. I've added the code for initialization in node
const postgrator = new Postgrator(migrationConfig);
postgrator.migrate('002', (err, migrations) => {
if (err) {
console.error(err);
} else {
console.log(migrations);
}
postgrator.endConnection();
});
const isDevelopment = process.env.NODE_ENV === 'development';
let migrationConfig;
if (isDevelopment) {
migrationConfig = {
"migrationDirectory": "migrations",
"driver": "pg",
"host": process.env.DEV_DB_HOST,
"port": process.env.DEV_DB_PORT,
"database": process.env.DEV_DB_DATABASE,
"username": process.env.DEV_DB_USER,
"password": process.env.DEV_DB_PASS,
"ssl": !isDevelopment,
}
} else {
migrationConfig = {
"migrationDirectory": "migrations",
"driver": "pg",
"connectionString": process.env.DATABASE_URL,
"ssl": true,
}
}
I'm not sure why I'm getting the self signed certificate error on production.
2020-10-18T10:04:49.845485+00:00 app[web.1]: > export NODE_ENV=production && nodemon src/server.js
2020-10-18T10:04:49.845485+00:00 app[web.1]:
2020-10-18T10:04:50.082326+00:00 app[web.1]: [nodemon] 2.0.4
2020-10-18T10:04:50.083611+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2020-10-18T10:04:50.084275+00:00 app[web.1]: [nodemon] watching path(s): *.*
2020-10-18T10:04:50.084383+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2020-10-18T10:04:50.085033+00:00 app[web.1]: [nodemon] starting `node src/server.js`
2020-10-18T10:04:50.489740+00:00 app[web.1]: Express is listening on port 48474
2020-10-18T10:04:50.535273+00:00 app[web.1]: Unhandled rejection Error: self signed certificate
2020-10-18T10:04:50.535275+00:00 app[web.1]: at TLSSocket.onConnectSecure (_tls_wrap.js:1502:34)
2020-10-18T10:04:50.535276+00:00 app[web.1]: at TLSSocket.emit (events.js:314:20)
2020-10-18T10:04:50.535276+00:00 app[web.1]: at TLSSocket._finishInit (_tls_wrap.js:937:8)
2020-10-18T10:04:50.535277+00:00 app[web.1]: at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:711:12)
2020-10-18T10:04:51.077573+00:00 heroku[web.1]: State changed from starting to up
I've upgraded the dyno to a paid service to activate the SSL, yet this error still continues to come up. I saw online suggestin to set rejectUnauthorized to false`, but postgrator does not provide that option. Even if I set it to the Postgres configuration the issue seems to still persist.
How do I fix this?

How to lint a typescript types file?

are there any ways to lint or otherwise debug a types file?
I have a index.d.ts file of all my types, but it seems to crash my app at startup.
using tsc with some basic options works fine
using tslint works fine.
but when running with the webpack compiler I get the following error.
the file contents are a lot but basically like the below.
I had some issues with exporting enums before but basically not getting any actual errors I can understand.
// we SEND to Boto
export enum MsgTypeOut {
TEXT = 0,
IMAGE = 1,
URL_LINK = 2,
FILE = 3,
}
export interface BotoTextMsg {
chatId: string
messageType: MsgTypeOut.TEXT
token?: string
payload: {
text: string
}
}
nodemon:watch early exit on watch, still watching (1) +14s
/Users/dc/dev/tix/recobot/stack/backend/server.js:2663
throw new Error("Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.\n at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)\n at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)");
^
Error: Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.
at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)
at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:2663:7)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:2551:19)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:867:16)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1306:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1343:30)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:1028:15)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:63:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:66:10)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
[nodemon] app crashed - waiting for file changes before starting...
webpack config is pretty much vanilla based on create-react-app.
const fs = require("fs")
// const path = require("path")
const NodemonPlugin = require("nodemon-webpack-plugin");
const nodeModules = {};
fs.readdirSync("node_modules")
.filter(function (x) {
return [".bin"].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = "commonjs " + mod;
});
module.exports = {
entry: "./server/server.ts",
output: {
filename: "server.js",
// path: path.join(__dirname, "/build"),
},
externals: nodeModules,
// needed to fix https://github.com/webpack/webpack/issues/1599
node: {
__dirname: true
},
module: {
loaders: [
{
loader: "ts-loader",
test: /\.tsx?$/,
},
],
},
plugins: [new NodemonPlugin()],
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
},
target: "node",
};
For anyone watching, the error is related to importing enums.
You can export an enum from a types.d.ts file... but it won't import and blows up in this weird way.
https://lukasbehal.com/2017-05-22-enums-in-declaration-files/
How to refer to Typescript enum in d.ts file, when using AMD?

Cannot find module

I have a class that I have created and put it in a custom folder in the src folder. It is not a nestjs module nor a provider just a helper class that I can instantiate and use. However when I run the app I got the following error:
npm run start:dev
> rent-go#1.0.0 start:dev /Users/arsenegandote/Applications/js/rent-go
> nodemon
[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /Users/arsenegandote/Applications/js/rent-go/src/**/*
[nodemon] starting `ts-node -r tsconfig-paths/register src/main.ts`
Error: Cannot find module './json.result.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:603:15)
at Function.Module._resolveFilename (/Users/arsenegandote/Applications/js/rent-go/node_modules/tsconfig-paths/lib/register.js:75:40)
at Function.Module._load (internal/modules/cjs/loader.js:529:25)
at Module.require (internal/modules/cjs/loader.js:658:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/arsenegandote/Applications/js/rent-go/src/lib/api.controller.ts:1:1)
at Module._compile (internal/modules/cjs/loader.js:722:30)
at Module.m._compile (/Users/arsenegandote/Applications/js/rent-go/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:733:10)
at Object.require.extensions.(anonymous function) [as .ts] (/Users/arsenegandote/Applications/js/rent-go/node_modules/ts-node/src/index.ts:442:12)
[nodemon] app crashed - waiting for file changes before starting...](url)
This is the generic class I am instantiating in a controller:
export class JsonResult<T> {
readonly status: string;
readonly data: T;
constructor(status: string, data: T) {
this.status = status;
this.data = data;
}
}
And my controller implements this abstract class:
export abstract class ApiController {
failed(): void {
throw new HttpException(
{
status: ApiStatus.FAILED,
data: {},
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
notFound(): void {
throw new HttpException(
{
status: HttpStatus.NOT_FOUND,
data: [],
},
HttpStatus.NOT_FOUND,
);
}
badRequest(message: string): void {
throw new HttpException(
{
status: HttpStatus.BAD_REQUEST,
data: {
message,
},
},
HttpStatus.BAD_REQUEST,
);
}
success<T>(data: T): JsonResult<T> {
return new JsonResult<T>(ApiStatus.SUCCESS, data);
}
}
Error: Cannot find module './json.result.js'
The error means that your file cannot be found. Make sure your import path is correct.

Elmongo plugin for full text search

I'm trying to use the Elmongo plugin for Node.js and I'm having some trouble with the plugin. Here is my code:
var mongoose = require('mongoose');
var elmongo = require('elmongo');
var Schema = mongoose.Schema;
var twitterSchema = new Schema ({
id: {type: Number, index: {unique: true, dropDups: true}},
created_at: Date,
user: [{
id: Number,
name: String,
screen_name: String,
location: String
}],
text: String,
keywords: []
});
twitterSchema.plugin(elmongo);
var Tweets = mongoose.model('Tweets', twitterSchema);
twitterSchema.sync(function(err, numSynced){
console.log("number of tweets synced: " + numSynced);
});
twitterSchema.search({query: 'flu'}, function(err, results){
console.log('search results: ' + results);
});
exports.Document = function(db) {
return db.model('Tweets');
};
The error message I'm getting is:
module.js:340
throw err;
^
Error: Cannot find module 'elmongo'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/Documents/UCIMedCenterProject/MedStream-feature.sentiment-analysis/models.js:2:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
I looked up some of the errors and what I get is that I need to reinstall the module, but that didn't work either. Any help?
You should install this module in your project directory (go to your project directory in command line and then run "npm install elmongo")
You should check inside node_modules folder if any folder with name elmongo is present. If not try installing the module again.
Try installing as administrator.
sudo npm install elmongo

Resources