Coder Social home page Coder Social logo

anyfin / bankid Goto Github PK

View Code? Open in Web Editor NEW
60.0 24.0 26.0 210 KB

npm module to simplify integration with the Swedish Bank ID service for user authentication and signing processes.

Home Page: https://www.npmjs.com/package/bankid

License: MIT License

TypeScript 100.00%
bankid sweden javascript

bankid's Introduction

bankid

A npm module to simplify integration with the Swedish Bank ID service for user authentication and signing processes.

Installation

# If you prefer npm
npm install --save bankid
# If you prefer yarn
yarn install bankid

Usage V6

import { BankIdClientV6 } from "bankid";

const client = new BankIdClientV6({
  production: false,
});

const { autoStartToken, orderRef } = await client.authenticate({
  endUserIp: "127.0.0.1",
});

// Generate deep link from autoStarttoken and try to open BankID app
// See ./examples

client
  .awaitPendingCollect(orderRef)
  .then(res => {
    console.log(res.completionData)
  })

Acting on a session is done trough opening the app or trough scanning a QR Code, both examples are documented in detail in the examples directory

Usage V5

import { BankIdClient } from "bankid";

const client = new BankIdClient();
const pno = "YYYYMMDDXXXX";

client
  .authenticateAndCollect({
    personalNumber: pno,
    endUserIp: "127.0.0.1",
    userVisibleData: "Authentication request for my service",
  })
  .then(res => console.log(res.completionData))
  .catch(console.error);

As outlined in the relying party guidelines, there are four main methods (arguments marked with * are required)

  • authenticate({endUserIp*, personalNumber, requirement, userVisibleData, userVisibleDataFormat, userNonVisibleData})
  • sign({endUserIp*, personalNumber, requirement, userVisibleData*, userVisibleDataFormat, userNonVisibleData})
  • collect({orderRef*})
  • cancel({orderRef*})

Note that userVisibleData will be base64-encoded before sent to the BankID API.

Additionally, bankid provides convenience methods to combine auth / sign with periodic collection of the status until the process either failed or succeeded (as shown in the example code above):

  • authenticateAndCollect(...)
  • signAndCollect(...)

Full example not using the convenience methods:

import { BankIdClient } from "bankid";

const client = new BankIdClient();
const pno = "YYYYMMDDXXXX";
const message = "some message displayed to the user to sign";

client
  .sign({
    endUserIp: "127.0.0.1",
    personalNumber: pno,
    userVisibleData: message,
  })
  .then(res => {
    const timer = setInterval(() => {
      const done = () => clearInterval(timer);
      client
        .collect({ orderRef: res.orderRef })
        .then(res => {
          if (res.status === "complete") {
            console.log(res.completionData);
            done();
          } else if (res.status === "failed") {
            throw new Error(res.hintCode);
          }
        })
        .catch(err => {
          console.error(err);
          done();
        });
    }, 1000);
  })
  .catch(console.error);

Configuration

By default, bankid is instantiated with the following configuration pointing to the Bank ID Test Environment:

settings = {
  refreshInterval: 1000, // how often to poll status changes for authenticateAndCollect and signAndCollect
  production: false, // use test environment
  pfx: "PATH_TO_TEST_ENV_PFX", // test environment
  passphrase: "TEST_ENV_PASSPHRASE", // test environment
  ca: "CERTIFICATE", // dynamically set depending on the "production" setting unless explicitely provided
};

For production, you'll want to pass in your own pfx and passphrase instead:

import { BankIdClient } from "bankid";

const client = new BankIdClient({
  production: true,
  pfx: "PATH_TO_YOUR_PFX", // alternatively also accepts buffer
  passphrase: "YOUR_PASSPHRASE",
});

PFX path

When providing a pfx path, it is expected to be based on the current working directory from where the script is run:

.
├── certs
│   └── bankid.pfx
├── src
│   └── main.js

From the current directory you would run the script with node src/main.js and provide the pfx path:

import { BankIdClient } from "bankid";

const client = new BankIdClient({
  pfx: "certs/bankid.pfx",
});

Compatibility

In Node.js v17+, OpenSSL is upgraded from v1.1.1 to v3, introducing subtle breaking changes for this library that yield this error:

Error: unsupported
    at configSecureContext (node:internal/tls/secure-context:278:15)

This is due to the legacy algorithms used to generate BankID certificates - and to handle this (until BankID updates their default certificate formats) there are two solutions.

Manual certificate modernization (suggested)

First, ensure OpenSSL v3.x needs to be installed on your machine.

Then, you can run the following commands to get an updated certificate (new.pfx):

openssl pkcs12 -in old.pfx -nodes -legacy -out combined.pem
openssl pkcs12 -in combined.pem -export -out new.pfx

Enable legacy OpenSSL support

If for any reason you do not want to modify the certificates, you can also enable the legacy OpenSSL provider when running Node.js:

node --openssl-legacy-provider ...

Deploy/Publish

In order to deploy new versions, bump the version in package.json and create a new GitHub release.

GitHub Actions should automagically release it to npm. ✨

Ownership

Repo ownership: Jeff Trinidad - @jefftrinidad29
Last audit: 2023-04-27 by @jefftrinidad29

Audit Notes

27th April 2023 by @jefftrinidad29

  • Upgraded all non-critical dependencies
  • yarn audit fix

bankid's People

Contributors

a7ul avatar alepek avatar andreas-bergstrom avatar awesome-button avatar dependabot[bot] avatar fredrik avatar hyperborea avatar jakubhomoly avatar jefftrinidad29 avatar kimpers avatar linde12 avatar najamshehzad avatar nikvaessen avatar oliverjohns avatar pepf avatar spathon avatar spiatrenka avatar tobiastornros avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bankid's Issues

awaitPendingCollect

Is it intended behaviour that awaitPendingCollect does not return a proper status when the orderRef has been canceled?

Add support for Markdown formatting (userVisibleDataFormat)

BankID added an optional userVisibleDataFormat parameter to allow Markdown syntax in userVisibleData

Relevant documentation:
image

Sign request example (source):

{
"personalNumber":"190000000000",
"endUserIp": "194.168.2.25",
"userVisibleData": "IFRoaXMgaXMgYSBzYW1wbGUgdGV4dCB0byBiZSBzaWduZWQ=",
"userVisibleDataFormat": "simpleMarkdownV1"
}

Regarding PDF File Contract Sign

Dear Sir/Mam,

I am using this code authentication for personal number and its is working fine in test net.

Code:
const BankId = require("bankid");

const bankid = new BankId();
const pno = "YYYYMMDD-XXXX";
const message = "some message displayed to the user to sign";

bankid
.sign("127.0.0.1", pno, message)
.then(res => {
const timer = setInterval(() => {
const done = () => clearInterval(timer);

  bankid
    .collect(res.orderRef)
    .then(res => {
      if (res.status === "complete") {
        console.log(res.completionData);
        done();
      } else if (res.status === "failed") {
        throw new Error(res.hintCode);
      }
    })
    .catch(err => {
      console.error(err);
      done();
    });
}, 1000);

})
.catch(console.error);
But Now i Want to implement the upload file in pdf format and check it is correct or not though bank id app.

I am using this code in nodes.js. So please tell me the solution . Because i am trying for a month but not got any solution.

Thanks

Can you specify a timeout?

Is there a way to specify a timeout? If not, what is the default timeout if any?

I'm not seeing anything obvious whilst browsing the code other than the REQUEST_TIMEOUT response code, which is seemingly defined but not referenced.

We have a fairly short timeout per default of six seconds for our Lambdas and on occasion requests will take longer than that.

ca & pfx types don't match runtime validation

The BankIdClientSettings.pfx and BankIdClientSettings.ca options have the following type: string | Buffer | undefined but during runtime it is expected to be string | Buffer

We need to check that the path isn't undefined before passing it to fs.readFileSync, alternatively update the typescript definition.

I think that allowing undefined is good, because then you could do e.g.:

const client = new BankIdClient({
    production: process.env.NODE_ENV === 'prod',
    pfx: process.env.BANKID_PFX_PATH,
    passphrase: process.env.BANKID_PASSPHRASE,
});

rather than something like

const client = new BankIdClient({
    production: process.env.NODE_ENV === 'prod',
    ...(process.env.NODE_ENV === 'prod' && {
        pfx: process.env.BANKID_PFX_PATH,
        passphrase: process.env.BANKID_PASSPHRASE,
    }),
});

pfx problem

Hi, I just get this when I try to give path to the downloaded .pfx cert?
any idea how to link to .pfx file?

fs.js:663
return binding.open(pathModule.toNamespacedPath(path),
ENOENT: no such file or directory, open '....pfx'

invalidParameters

I have set every as documented in the readme file, it was working before but now I am getting this error invalid parameters. What could be the issue?

This library requires legacy openssl support

BankID certificates are encrypted using the RC2-40-CBC algorithm, which was probably dropped in OpenSSL 3.

As Node 17 switched to openssl 3, and bankid certificates use the RC2 algorithm, a node application using this library must be started with node-options="--openssl-legacy-provider".

I think an average developer expects this library to work out-of the box with the certificate they get from BankID.

Maybe we should mention this option is required in our README?

We use axios, which uses follow-redirects, so the symptom the developer will experience is:

 Error: unsupported
    at configSecureContext (node:internal/tls/secure-context:278:15)
    at Object.createSecureContext (node:_tls_common:116:3)
    at Object.connect (node:_tls_wrap:1718:48)
    at Agent.createConnection (node:https:169:22)
    at Agent.createSocket (node:_http_agent:342:26)
    at Agent.addRequest (node:_http_agent:289:10)
    at new ClientRequest (node:_http_client:337:16)
    at Object.request (node:https:377:10)
    at RedirectableRequest._performRequest (/app/node_modules/bankid/node_modules/follow-redirects/index.js:273:24)
    at new RedirectableRequest (/app/node_modules/bankid/node_modules/follow-redirects/index.js:61:8)

Cancel and awaitPendingCollect

Is there a reason to why no proper status is returned from awaitPendingCollect when cancelling the orderRef?

Right now it will just reject with an error and nothing else.

QR support

Hi, have you considered implementing support for qrStartSecrets and qrStartSecrets?

Unsupported

I'm getting unsupported from my endpoints. I tried using this basic example however it didn't work -

const BankId = require("bankid");

const client = new BankId.BankIdClient();
const pno = "YYYYMMDDXXXX";

client
  .authenticateAndCollect({
    personalNumber: pno,
    endUserIp: "127.0.0.1",
  })
  .then(res => console.log(res.completionData))
  .catch(console.error);

Do you guys know if there has been any updates to the bankid API?

TypeError: fs.readFileSync is not a function on initiating new BankId instance in React app

Hello!

I just scaffolded a react app and trying to use this package.

I added the sample code and I get the following error when new BankId() tries to execute:

Selection_077

The code I am using:

import React from "react";

const BankId = require('bankid');

const App = () => {
  const bankid = new BankId();
  const pno = "19681110-0871";
  const handleClick = () => {
    return bankid
      .authenticateAndCollect("127.0.0.1", pno)
      .then(res => console.log(res.completionData))
      .catch(console.error);
  };
  return (
    <div>
      <h1>BankId Test</h1>
      <button onClick={handleClick}>Autenticate!</button>
    </div>
  );
};

export default App;

Can you help me debug this?
Thanks!
Greg

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.