How to polylfill Buffer for jsonwebtoken in Wepack 5 - jwt

I am upgrading to Webpack 5 and I have an issue with the package jsonwebtoken (https://github.com/auth0/node-jsonwebtoken) that needs Buffer (at https://github.com/auth0/node-jsonwebtoken/blob/master/sign.js#L91)
Since Webpack 5 polyfills are not included for nodejs functions and wen I try to use the function sign from jsonwebtoken it throws the following error :
message: "Buffer is not defined"
stack: "ReferenceError: Buffer is not defined↵
at module.exports (webpack-internal:///./node_modules/jsonwebtoken/sign.js:91:26)↵
To solve the issue I installed https://github.com/feross/buffer with
npm install buffer
and in my webpack config I added
resolve: {
fallback: {
"Buffer": require.resolve('buffer/'),
}
or
resolve: {
fallback: {
"buffer": require.resolve('buffer/'),
}
I also tried
resolve: {
fallback: {
"buffer": require.resolve('buffer/').Buffer,
}
But this last one produce a Webpack schema error :
configuration.resolve.fallback['Buffer'] should be one of these:
[non-empty string, ...] | false | non-empty string
-> New request.
Details:
* configuration.resolve.fallback['Buffer'] should be an array:
[non-empty string, ...]
-> Multiple alternative requests.
* configuration.resolve.fallback['Buffer'] should be false.
-> Ignore request (replace with empty module).
* configuration.resolve.fallback['Buffer'] should be a non-empty string.
-> New request.
at validate (/home/ant1/packcity/front-pmd/node_modules/webpack/node_modules/schema-utils/dist/validate.js:104:11)
Despite my trials it is not working and the error persists.
Did someone succeed in adding the polyfill for Buffer in their app bundled with Webpack ?
Any help would be really appreciated.

I just solved my issue by adding
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
As suggested here https://github.com/ipfs/js-ipfs/issues/3369#issuecomment-721975183

I found this question when having a similar issue with Gatsby. To fix, I added:
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
plugins: [
new webpack.ProvidePlugin({
Buffer: [require.resolve("buffer/"), "Buffer"],
}),
]
}
}
to my gatsby-node.js config.

I have solved it this way in Gatsby. I didn't have to install the buffer dependency. Just added this to my gatsby-node.js file.
exports.onCreateWebpackConfig = ({ actions, stage, plugins }) => {
if (stage === 'build-javascript' || stage === 'develop') {
actions.setWebpackConfig({
plugins: [plugins.provide({ Buffer: ['buffer/', 'Buffer'] })]
});
}
};

Related

How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')

I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.
Code
const addChoice = async (e) => {
try {
e.preventDefault();
const res = await fetch("/api/sendChoice", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
choiceSeq: choice,
checkSubmit: true,
}),
});
console.log(res);
router.push("/home");
} catch (error) {
console.log(error);
}
};
The error is happening at const res = await fetch("/api/sendChoice" ,{
In terminal server the error
error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'
In the inspect element the error is as
I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.
Some other related code from my project:
api/sendChoice
import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";
export default async function sendChoice(req, res) {
try {
const session = await getSession({ req });
await dbConnect();
if (!session) {
res.status(401).send("You are not signed in");
return;
}
if (req.method === "POST") {
console.log(req.body);
const { choiceSeq, checkSubmit } = req.body;
console.log(choiceSeq, checkSubmit);
const userId = session.user.id;
const nameP = session.user.name;
const choice = new Choice({
user: userId,
name: nameP,
choiceSeq,
checkSubmit,
});
await choice.save();
res.status(200).send("Choice saved");
} else {
res.status(400).send("Bad request");
}
}
catch (error) {
console.log(error);
}
}
The MongoDB schema
import mongoose, { Schema } from 'mongoose';
const ChoiceSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
name: {
type: String,
},
choiceSeq: {
type: Array,
default: [],
},
checkSubmit: {
type: Boolean,
}
});
mongoose.models = {};
export default mongoose.model('Choice', ChoiceSchema);
the latest update to version 17.5.0 is the one causing this error. You must reinstall node js to version 16.14.0 LTS. You should always work with LTS versions
This issue occured recently and apparently its happening with latest version of node.
issue link
So you can change the version of node to older version and it will be fixed. I am using node version v14.19.0
if you are using Docker then, giving a version will solve the problem.
before:
FROM node:alpine
now
FROM node:16.5.0-alpine
WORKDIR /app
COPY package.json .
RUN npm install --only=prod
COPY . .
CMD ["npm", "start"]
The latest release of Node.JS is what is causing this issue. In your package.json, make sure to set your engine to"engines": { "node": ">=0.12 < 17.5.0" } and you should be fine.
Also if you are using docker for deployment, make sure to change the version number in your dockerfile to be less that 17.5.0
Solution which worked well for me:)
Step 01: Open your terminal and copy paste below command.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | zsh
Wait patiently until its done.
Step 02: sudo vim ./zshrc
Step 03: Press I for Insert Mode and copy paste below command. Must be same in three lines.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion"
then press ESC key :wq (write and quite).
Step 04: brew install nvm
step 05: nvm install node (which will download latest version node)
step 06: nvm ls-remote (which make all the version available)
step 07: nvm install 14 (An Example)
step 08: nvm use 14 (this make it as default version)
source: https://github.com/nvm-sh/nvm
Try upgrading to v17.6.0. It solved the issue for me.
In My case eslint 8.9.0 was the culprit. Rollback fixed it.

An unexpected error occurred The plugins file is missing or invalid

I do not have any idea why do I have this error. Everything seems ok. Can you please help me to solve this?
The plugins file is missing or invalid.
Your pluginsFile is set to /Users/gnematova/AMPautomation/AMPautomation/cypress/plugins/index.js, but either the file is missing, it contains a syntax error, or threw an error when required. The pluginsFile must be a .js, .ts, or .coffee file.
Or you might have renamed the extension of your pluginsFile. If that's the case, restart the test runner.
Please fix this, or set pluginsFile to false if a plugins file is not necessary for your project.
Error: Cannot find module 'cypress-cucumber-preprocessor'
Stack trace
plugins->index.js
const cucumber = require('cypress-cucumber-preprocessor').default;
/**
* #type {Cypress.PluginConfig}
*/
module.exports = (on, config) => {
require('cypress-mochawesome-reporter/plugin')(on);
on('file:preprocessor', cucumber());
on('before:browser:launch', (browser = {}, launchOptions) => {
console.log(launchOptions.args);
if (browser.family === 'chromium' && browser.name !== 'electron') {
launchOptions.args.push('--start-fullscreen');
launchOptions.args.push('--window-size=1400,1200');
}
if (browser.name === 'electron') {
launchOptions.preferences.fullscreen = true;
}
if (browser.name === 'chrome' && browser.isHeadless) {
launchOptions.args.push('--disable-gpu');
}
return launchOptions;
});
return config;
};

How do I solve the keycloak refresh /#state on my angular7 project - i'm using keycloak-angular

I have also tried all varying combinations for web origins and valid redirect URIs
I login via keycloak and it continuously redirects me back and forth between my localhost application and this url: http://localhost:4200/#state=166446fd-daf6-4b76-b595-583c01c663df&session_state=57ead1f3-bf41-4117-9ddf-75e37c9248e7&code=8692b58b-0868-4762-b82e-acde9911dd34.57ead1f3-bf41-4117-9ddf-75e37c9248e7.1e8b5b9d-b590-453e-b396-62b46c18cc9f
I have tried it on firefox and chrome but with the same issue - it seems to be looking for the keycloak.json file in the network tab even though I can login to the correct realm via keycloak
GET http://localhost:4200/keycloak.json 404 (Not Found)
scheduleTask # zone.js:2969
ERROR An error happened during Keycloak initialization. core.js:1601
Unhandled Promise rejection: An error happened during Keycloak initialization. ; Zone: ; Task: Promise.then ; Value: An error happened during Keycloak initialization. undefined
static init(): Promise<any> {
const keycloakAuth: any = Keycloak({
url: 'http://localhost:8080/auth',
realm: 'ContractPortal',
clientId: 'secretkey2',
'ssl-required': 'external',
'public-client': true
});
KeycloakService.auth.loggedIn = false;
return new Promise((resolve, reject) => {
keycloakAuth.init({onLoad: 'login-required'})
.success(() => {
console.log(keycloakAuth);
KeycloakService.auth.loggedIn = true;
KeycloakService.auth.authz = keycloakAuth;
KeycloakService.auth.logoutUrl = keycloakAuth.authServerUrl
+ '/realms/angular_keycloak/protocol/openid-connect/logout?redirect_uri='
+ document.baseURI;
resolve();
})
.error(() => {
reject();
});
});
}
it'd be great if one of you guys can point me in the right direction to solve this issue...
I have found another similar question to what I have asked link but not sure how to implement this solution! this is my provider setup -
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializer,
multi: true,
deps: [KeycloakService]
}
],
but OP puts the following in his provider
providers: [
KeyCloakService,
AssetService,
{
provide: LocationStrategy,
useClass: PathLocationStrategy
}
]
Please let me know if you require any other information
For anybody that ran into the same issue - I misunderstood the keycloak.json file and did not know where to get it - so I was exporting the complete json file from keycloak but THIS is not how you should get it!!
First you have to go to your realm > clients and click on installation
then download the keycloak OIDC json file
then place it next to the index.html file in your application
This solved my issue - hope it helps somebody else
I was researching on the internet and it is the same case, for me my angular page is reloading automatically in infnite loop
I did some changes in keycloak-init.ts file (please find following code and change checkLoginIframe from true to false)
Old Code: keycloak.init ({onLoad: 'login-required', "checkLoginIframe": true})
New Code: keycloak.init ({onLoad: 'login-required', "checkLoginIframe": false})
this.loadingService.isLoading$.pipe(delay(100)).subscribe((data => {
this.loading = data
}))
this.isLogging = await this.keycloak.isLoggedIn();
type roleUser = Array<{ id: number, text: string }>
if (this.isLogging) {
this.userProfile = await this.keycloak.loadUserProfile();
this.userRoles = await this.keycloak.getUserRoles();
}else {
// this.clearSession();
}
if you are using "this.keycloak.loadUserProfile()" Remove this "clear session"

sails helpers and machine spec

I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing

Webpack with Babel lazy load module using ES6 recommended Import() approach not working

I'm trying to do code splitting and lazy loading with webpack using the import() method
import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
I'm getting
'import' and 'export' may only appear at the top level
Note top level imports are working fine, i'm just getting an issue when I try and using the dynamic variant of import()
var path = require('path');
module.exports = {
entry: {
main: "./src/app/app.module.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name]-application.js"
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
]
},
resolve : {
modules : [
'node_modules',
'bower_components'
]
},
devtool : "source-map"
}
EDIT:
If I change it so the syntax reads, it works.... but the chunk comments don't work to label the bundle. I'm confused because the documentation says the the following is depreciated.
The use of System.import in webpack did not fit the proposed spec, so
it was deprecated in webpack 2.1.0-beta.28 in favor of import().
System.import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
You need the plugin syntax-dynamic-import to be able to use the import() function with Babel.
Install it with:
npm install --save-dev #babel/plugin-syntax-dynamic-import
And add it to your plugins:
{
presets: ['es2015'],
plugins: ['#babel/plugin-syntax-dynamic-import']
}