Giter Site home page Giter Site logo

nfccard-tool's Introduction

nfccard-tool

The toolbox for reading and writing nfc cards. Parse card header, ndef message and records, prepare ndef records for writing...

Table of Contents

Install

npm:

npm install nfccard-tool --save

yarn:

yarn add nfccard-tool --save

Features

  • Parse a card header and wrap raw and human readable data in a object:
    • Locks states
    • Capability Container
      • Magic number
      • Spec version
      • Max NDEF length
      • Read and write accesses
    • NDEF message detection and length
  • Parse and prepare a NDEF message of types:
    • Text
    • Uri
    • Android App Record

Quick start examples (with the help of nfc-pcsc)

Read a card header and parse a NDEF message

npm run read-nfcpcsc

Write a NDEF message

npm run write-nfcpcsc

Usage

1 - Require the lib:

const ndef = require('nfccard-tool');

2 - Parse a card header:

With the card reader of your choice, read from block 0 until end of block 4. Which means a 20 bytes long read.

Note: before any NDEF parsing or preparing we need to parse the card header first using a read command.

// Starts reading in block 0 for 20 bytes long
const cardHeader = await reader.read(0, 20);

const tag = nfcCard.parseInfo(cardHeader);
console.log('tag info:', JSON.stringify(tag));

Which logs:

tag info:
{
    "headerValues":{
        "raw":{
            "Lock":{
                "LOCK0":0,
                "LOCK1":0
            },
            "capabilityContainer":{
                "MAGIC_NUMBER":225,
                "SPEC_VERSION":16,
                "MAX_NDEF_LENGTH":109,
                "READ_ACCESS":0,
                "WRITE_ACCESS":0
            },
            "NDEFMessageHeader":{
                "HAS_NDEF":3,
                "MESSAGE_LENGTH":86
            }
        },
        "string":{
            "Lock":{
                "LOCK0":"0",
                "LOCK1":"0"
            },
            "capabilityContainer":{
                "MAGIC_NUMBER":"E1",
                "SPEC_VERSION":"10",
                "MAX_NDEF_LENGTH":"6D",
                "READ_ACCESS":"0",
                "WRITE_ACCESS":"0"
            },
            "NDEFMessageHeader":{
                "HAS_NDEF":"3",
                "MESSAGE_LENGTH":"56"
            }
        }
    },
    "parsedHeader":{
        "isFormatedAsNDEF":true,
        "type2SpecVersion":"1.0",
        "maxNDEFMessageSize":872,
        "hasReadPermissions":true,
        "getReadPermissionsType":"HAS_READ_ACCESS",
        "hasWritePermissions":true,
        "writePermissionsType":"HAS_WRITE_ACCESS",
        "hasNDEFMessage":true,
        "NDEFMessageLength":86,
        "lengthToReadFromBlock4":88
    }

}

3 - Parse a NDEF message:

If card header parsing let us know there might be a NDEF message we can try to parse it:

// There might be a NDEF message and we are able to read the tag
if(nfcCard.isFormatedAsNDEF() && nfcCard.hasReadPermissions() && nfcCard.hasNDEFMessage()) {

  // Read the appropriate length to get the NDEF message as buffer
  const NDEFRawMessage = await reader.read(4, nfcCard.getNDEFMessageLengthToRead()); // starts reading in block 0 until 6

  // Parse the buffer as a NDEF raw message
  const NDEFMessage = nfcCard.parseNDEF(NDEFRawMessage);

  console.log('NDEFMessage:', NDEFMessage);

} else {
  console.log('Could not parse anything from this tag: \n The tag is either empty, locked, has a wrong NDEF format or is unreadable.')
}

4 - Prepare a NDEF message:

We can use the convenient method prepareBytesToWrite to get the appropriate Buffer we need to write a ndef message.

// 1 - READ HEADER

// Starts reading in block 0 until end of block 4
const cardHeader = await reader.read(0, 20);

const tag = nfcCard.parseInfo(cardHeader);
console.log('tag info:', JSON.stringify(tag));


// 2 - WRITE A NDEF MESSAGE AND ITS RECORDS

const message = [
  { type: 'text', text: 'I\'m a text message', language: 'en' },
  { type: 'uri', uri: 'https://github.com/somq' },
  { type: 'aar', packageName: 'https://github.com/somq' },
]

// Prepare the buffer to write on the card
const rawDataToWrite = nfcCard.prepareBytesToWrite(message);

// Write the buffer on the card starting at block 4
const preparationWrite = await reader.write(4, rawDataToWrite.preparedData);

// Success !
if (preparationWrite) {
  console.log('Data have been written successfully.')
}

Which logs:

NDEFMessage:
[
  { NDEFLibRecord:
     { LanguageCode: null,
       text: null,
       _typeNameFormat: 1,
       _type: [Array],
       _id: [],
       _payload: [Array] },
    type: 'text',
    text: 'I\'m a text message',
    language: 'en' },
  { NDEFLibRecord:
     { RawUri: [],
       Uri: '',
       _typeNameFormat: 1,
       _type: [Array],
       _id: [],
       _payload: [Array],
       type: 'U' },
    type: 'uri',
    uri: 'https://github.com/somq' },
  { NDEFLibRecord:
     { packageName: '',
       _typeNameFormat: 4,
       _type: [Array],
       _id: [],
       _payload: [Array],
       type: 'android.com:pkg' },
    type: 'aar',
    packageName: 'https://github.com/somq' }
]

API

Methods

// Magic number
nfcCard.isFormatedAsNDEF();

// Type 2 Tag Specification version, eg. 1.0
nfcCard.getType2SpecVersion();

// Max NDEF size for the current tag
nfcCard.getMaxNDEFMessageLength();

// Read locked ?
nfcCard.hasReadPermissions();

// Read types: HAS_READ_ACCESS, RFU, PROPRIETARY, UNKNOWN
nfcCard.getReadPermissionsType();

// Write locked ?
nfcCard.hasWritePermissions();

// Write types: HAS_READ_ACCESS, RFU, PROPRIETARY, UNKNOWN
nfcCard.getWritePermissionsType();

// NDEF message flag is present ?
nfcCard.hasNDEFMessage();

// NDEF message length on exists on the tag
nfcCard.getNDEFMessageLength();

tag object

{
    "headerValues":{
        "raw":{ // Raw buffer values
            "Lock":{
                "LOCK0":0, // Lock 0 status - block 2, byte 2
                "LOCK1":0 // Lock 1 status - block 2, byte 3
            },
            "capabilityContainer":{
                "MAGIC_NUMBER":225, // magic number - block 3, byte 0 (CC0)
                "SPEC_VERSION":16, // type 2 spec version - block 3, byte 1 (CC1)
                "MAX_NDEF_LENGTH":109, // max ndef message length - block 3, byte 2 (CC2)
                "READ_ACCESS":0, // read access - block 3, byte 3 (CC3)
                "WRITE_ACCESS":0 // write access - block 3, byte 3 (CC3)
            },
            "NDEFMessageHeader":{
                "HAS_NDEF":3, // NDEF header 0 - block 4, byte 0
                "MESSAGE_LENGTH":86 // NDEF header 1 - block 4, byte 1
            }
        },
        "string":{ // Hex string values
            "Lock":{
                "LOCK0":"0",
                "LOCK1":"0"
            },
            "capabilityContainer":{
                "MAGIC_NUMBER":"E1",
                "SPEC_VERSION":"10",
                "MAX_NDEF_LENGTH":"6D",
                "READ_ACCESS":"0",
                "WRITE_ACCESS":"0"
            },
            "NDEFMessageHeader":{
                "HAS_NDEF":"3",
                "MESSAGE_LENGTH":"56"
            }
        }
    },
    "parsedHeader":{
        "isFormatedAsNDEF":true, // magic number - block 3, byte 0 (CC0)
        "type2SpecVersion":"1.0", // type 2 spec version - block 3, byte 1 (CC1)
        "maxNDEFMessageSize":872, // max ndef message length - block 3, byte 2
        "hasReadPermissions":true, // read access - block 3, byte 3 (CC3)
        "getReadPermissionsType":"HAS_READ_ACCESS",
        "hasWritePermissions":true, // write access - block 3, byte 3 (CC3)
        "writePermissionsType":"HAS_WRITE_ACCESS",
        "hasNDEFMessage":true, // NDEF header 0 - block 4, byte 0
        "NDEFMessageLength":86, // NDEF header 1 - block 4, byte 1
        "lengthToReadFromBlock4":88 // NDEFMessageLength + 2
    }

}

Compatibility

Only a part of Type 2 tag specification is implemented.

This lib does not support yet:

  • Dynamical memory structure
  • Lock preparing
  • ... some are probably missing

Troubleshoot

Error: path\node_modules@pokusew\pcsclite\build\Release\ pcsclite.node

npm rebuild

Third party

We are natively using ndef-lib for parsing but you could give a try at https://github.com/TapTrack/NdefJS or have a deep look at https://github.com/googlearchive/chrome-nfc

If you are looking for a nfc tag reading library take a look at https://github.com/pokusew/nfc-pcsc

License

MIT ยฉ somq

nfccard-tool's People

Contributors

somq avatar

Stargazers

 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

nfccard-tool's Issues

Unable to read: Tag is either empty, locked, has a wrong NDEF format

Thank you for the great project!

I have a Mifare Ultralight - NTAG213 tag with 1 Text NDEF record (Format: NFC Well Known 0x01), and I'm able to read it with no problem with the NFC Tools iOS App.

I'm running the read example on this repo, and I'm getting "hasNDEFMessage": false in the header and the following error:

Could not parse anything from this tag: 
 The tag is either empty, locked, has a wrong NDEF format or is unreadable.

Which is strange because I'm positive that there is 1 Text NDEF encoded. I can confirm the data format is NFC Forum Type 2.

What am I doing wrong?

Any help is appreciated ๐Ÿ™

Here's the tag info.

tag info: {
  "headerValues": {
    "raw": {
      "Lock": {
        "LOCK0": 0,
        "LOCK1": 0
      },
      "capabilityContainer": {
        "MAGIC_NUMBER": 225,
        "SPEC_VERSION": 16,
        "MAX_NDEF_LENGTH": 18,
        "READ_ACCESS": 0,
        "WRITE_ACCESS": 0
      },
      "NDEFMessageHeader": {
        "HAS_NDEF": 1,
        "MESSAGE_LENGTH": 3
      }
    },
    "string": {
      "Lock": {
        "LOCK0": "0",
        "LOCK1": "0"
      },
      "capabilityContainer": {
        "MAGIC_NUMBER": "E1",
        "SPEC_VERSION": "10",
        "MAX_NDEF_LENGTH": "12",
        "READ_ACCESS": "0",
        "WRITE_ACCESS": "0"
      },
      "NDEFMessageHeader": {
        "HAS_NDEF": "1",
        "MESSAGE_LENGTH": "3"
      }
    }
  },
  "parsedHeader": {
    "isFormatedAsNDEF": true,
    "type2SpecVersion": "1.0",
    "maxNDEFMessageSize": 144,
    "hasReadPermissions": true,
    "getReadPermissionsType": "HAS_READ_ACCESS",
    "hasWritePermissions": true,
    "writePermissionsType": "HAS_WRITE_ACCESS",
    "hasNDEFMessage": false,
    "NDEFMessageLength": 3,
    "lengthToReadFromBlock4": 5
  }
}

Error when reading card

Hi,

Tried running npm run read-nfcpcsc but it returns me this error:


D:\Sort\project\node-nfc\nfccard-tool\examples\read-nfc-pcsc.js:12
  reader.on('card', async card => {
                    ^^^^^
SyntaxError: missing ) after argument list
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Any idea how can I fix this? Or maybe it's a bug? Thanks!

Error writing short text

Hello,

When I write a short text message (<9 characters) to a NFC tag, I get this error when I read the tag and try to parse it:

Uncaught (in promise) NdefExceptionMessages.ExMessageBeginMissing

I think the error come from the method prepareBytesToWrite, because I don't have any problem when I try to parse short messages encoded in a NDEF format by another program.

Failure TypeError: Cannot read properties of undefined (reading 'toString')

I got error like in title.

I am simple using it like this:

reader
      .read(4, 16, 16)
      .then((cardHeader) => {
        return nfcCard.parseInfo(cardHeader);
      })
at Object.decimalToHexString (C:\Users\Radoslaw\Desktop\nfc-pcsc-master\nfc-pcsc-master\node_modules\nfccard-tool\lib\utils.js:56:21)
    at nfcCardTool.getHeaderRawValues (C:\Users\Radoslaw\Desktop\nfc-pcsc-master\nfc-pcsc-master\node_modules\nfccard-tool\lib\nfccard-tool.js:57:25)
    at nfcCardTool.parseInfo (C:\Users\Radoslaw\Desktop\nfc-pcsc-master\nfc-pcsc-master\node_modules\nfccard-tool\lib\nfccard-tool.js:274:32)

Card is Mifare classic.

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.