smartcard
╭────────────────────────────────────────╮
│ │
│ ╭───────────╮ │
│ │ ▄▄▄ ▄▄▄▄▄ │ │
│ │ ███ ▄▄▄▄▄ │ │
│ │ ▀▀▀ ▀▀▀▀▀ │ │
│ ╰───────────╯ │
│ │
│ ░░░░░░░░░░░░ │
│ ░░░░░░░░░░░░ │
╰────────────────────────────────────────╯
Stable PC/SC smart card bindings for Node.js.
Works with Node.js 18+ without recompilation. Built on N-API for long-term stability.
Getting Started
1. Install the package
npm install smartcard
macOS/Windows: Ready to go - no additional setup needed.
Linux:
# Install PC/SC libraries
sudo apt-get install libpcsclite-dev pcscd # Debian/Ubuntu
sudo dnf install pcsc-lite-devel pcsc-lite # Fedora/RHEL
# Start the daemon
sudo systemctl start pcscd
3. Connect a reader and run your first script
const { Devices } = require('smartcard');
const devices = new Devices();
devices.on('card-inserted', async ({ reader, card }) => {
console.log(`Card detected in ${reader.name}`);
console.log(`ATR: ${card.atr.toString('hex')}`);
const response = await card.transmit([0xFF, 0xCA, 0x00, 0x00, 0x00]);
console.log(`UID: ${response.slice(0, -2).toString('hex')}`);
});
devices.on('error', (err) => console.error(err.message));
devices.start();
Run it:
node app.js
# Tap a card on your reader...
# Card detected in ACS ACR122U
# ATR: 3b8f8001804f0ca0000003060300030000000068
# UID: 04a23b7a
Recommended Hardware
Readers
| Reader |
Type |
Notes |
| ACR122U |
USB contactless |
Affordable, widely available. Great for getting started. |
| ACR1252U |
USB dual-interface |
Supports both contactless and contact cards. |
| SCM SCR35xx |
USB contact |
Tested with SCR35xx v2.0. Good for contact smart cards. |
| HID Omnikey 5427 |
USB contactless |
Enterprise-grade, faster reads. |
| Identiv uTrust 3700F |
USB contactless |
Compact, reliable. |
Any PC/SC compatible reader should work. The library uses standard PC/SC APIs.
Cards
| Card Type |
Interface |
Notes |
| MIFARE Classic 1K/4K |
Contactless |
Most common NFC cards |
| MIFARE Ultralight / NTAG |
Contactless |
Stickers, wristbands, keyfobs |
| MIFARE DESFire |
Contactless |
Higher security applications |
| ISO 14443-4 |
Contactless |
Generic contactless smart cards |
| ISO 7816 |
Contact |
Standard contact smart cards (SIM, bank cards, ID cards) |
Features
- ABI Stable: Works across Node.js versions without recompilation
- Async/Promise-based: Non-blocking card operations
- Event-driven API: High-level
Devices class with EventEmitter
- TypeScript support: Full type definitions included
- Cross-platform: Windows, macOS, and Linux
More Examples
High-Level API (Event-Driven)
const { Devices } = require('smartcard');
const devices = new Devices();
devices.on('reader-attached', (reader) => {
console.log(`Reader attached: ${reader.name}`);
});
devices.on('reader-detached', (reader) => {
console.log(`Reader detached: ${reader.name}`);
});
devices.on('card-inserted', async ({ reader, card }) => {
console.log(`Card inserted in ${reader.name}`);
console.log(` ATR: ${card.atr.toString('hex')}`);
try {
const response = await card.transmit([0xFF, 0xCA, 0x00, 0x00, 0x00]);
console.log(` UID: ${response.slice(0, -2).toString('hex')}`);
} catch (err) {
console.error('Transmit error:', err.message);
}
});
devices.on('card-removed', ({ reader }) => {
console.log(`Card removed from ${reader.name}`);
});
devices.on('error', (err) => {
console.error('Error:', err.message);
});
devices.start();
process.on('SIGINT', () => {
devices.stop();
process.exit();
});
Low-Level API (Direct PC/SC)
const {
Context,
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0,
SCARD_PROTOCOL_T1,
SCARD_LEAVE_CARD
} = require('smartcard');
async function main() {
const ctx = new Context();
console.log('Context valid:', ctx.isValid);
const readers = ctx.listReaders();
console.log('Readers:', readers.map(r => r.name));
if (readers.length === 0) {
console.log('No readers found');
ctx.close();
return;
}
const reader = readers[0];
console.log(`Using reader: ${reader.name}`);
console.log(` State: ${reader.state}`);
try {
const card = await reader.connect(
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1
);
console.log(`Connected, protocol: ${card.protocol}`);
const status = card.getStatus();
console.log(` ATR: ${status.atr.toString('hex')}`);
const response = await card.transmit(Buffer.from([0xFF, 0xCA, 0x00, 0x00, 0x00]));
console.log(` Response: ${response.toString('hex')}`);
card.disconnect(SCARD_LEAVE_CARD);
} catch (err) {
console.error('Card error:', err.message);
}
ctx.close();
}
main();
Waiting for Card Changes
const { Context } = require('smartcard');
async function waitForCard() {
const ctx = new Context();
const readers = ctx.listReaders();
if (readers.length === 0) {
console.log('No readers found');
ctx.close();
return;
}
console.log('Waiting for card...');
const changes = await ctx.waitForChange(readers, 30000);
if (changes === null) {
console.log('Cancelled');
} else if (changes.length === 0) {
console.log('Timeout');
} else {
for (const change of changes) {
if (change.changed) {
console.log(`${change.name}: state changed to ${change.state}`);
if (change.atr) {
console.log(` ATR: ${change.atr.toString('hex')}`);
}
}
}
}
ctx.close();
}
waitForCard();
API Reference
Context
The low-level PC/SC context.
class Context {
constructor();
readonly isValid: boolean;
listReaders(): Reader[];
waitForChange(readers?: Reader[] | null, timeout?: number): Promise<ReaderState[] | null>;
cancel(): void;
close(): void;
}
waitForChange(readers, timeout) waits until a reader’s state differs from the state of the readers you pass: the Reader objects from listReaders(), or the states a previous call returned. It resolves with each reader’s new state; with [] if the timeout (in milliseconds) passes first, and with no timeout it waits for ever; or with null if it was cancelled before it returned. Called without readers, or with reader names, it reports the current states at once. With no reader attached, it waits for one to be plugged in, and reports a \\?PnP?\Notification entry rather than a reader. It rejects on a PC/SC error, such as a reader that has gone, and throws once the context is closed.
Each pending wait uses a PC/SC context of its own, so the context stays usable while it waits: listReaders(), connecting its readers, and further waits all work. (On Linux, pcscd serves a limited number of contexts, 200 by default, which also limits how many waits can be pending at once. At that limit cancel() can’t reach them either, because pcscd refuses the extra connection a cancel needs: they still resolve with null, but only once something changes or their timeout passes. close() frees a context of its own first, so it ends them at once.) cancel() ends every wait pending on the context, even one only just started, and returns once they have ended, normally at once. close() ends them the same way.
Reader
Represents a smart card reader.
interface Reader {
readonly name: string;
readonly state: number;
readonly atr: Buffer | null;
connect(shareMode?: number, protocol?: number): Promise<Card>;
}
Card
Represents a connected smart card.
interface Card {
readonly protocol: number;
readonly connected: boolean;
readonly atr: Buffer | null;
transmit(command: Buffer | number[], options?: { maxRecvLength?: number; autoGetResponse?: boolean }): Promise<Buffer>;
control(code: number, data?: Buffer): Promise<Buffer>;
getStatus(): { state: number; protocol: number; atr: Buffer };
disconnect(disposition?: number): void;
reconnect(shareMode?: number, protocol?: number, init?: number): Promise<number>;
}
Reset a card in place with reconnect — no physical removal needed:
const { SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0, SCARD_PROTOCOL_T1, SCARD_RESET_CARD, SCARD_UNPOWER_CARD } = require('smartcard');
await card.reconnect(SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, SCARD_RESET_CARD);
await card.reconnect(SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, SCARD_UNPOWER_CARD);
Some reader and card combinations (an SCR35xx with a T=0-only card, for one) report the card unresponsive when a reset offers T=1 as well as T=0. When that happens, cards from Devices (or wrapCard()) retry the reconnect once with the protocol the card is already using, if you offered it. Devices works around the same quirk when it first connects.
disconnect(disposition) accepts the same constants to reset or unpower the card on the way out.
Devices
High-level event-driven API.
class Devices extends EventEmitter {
start(): void;
stop(): void;
listReaders(): Reader[];
getCards(): ReadonlyMap<string, Card>; // Get all connected cards by reader name
getCard(readerName: string): Card | null; // Get card for specific reader
on(event: 'reader-attached', listener: (reader: Reader) => void): this;
on(event: 'reader-detached', listener: (reader: Reader) => void): this;
on(event: 'card-inserted', listener: (event: { reader: Reader; card: Card }) => void): this;
on(event: 'card-removed', listener: (event: { reader: Reader; card: Card | null }) => void): this;
on(event: 'error', listener: (error: Error) => void): this;
}
Service outages
If the PC/SC service stops while Devices is running (pcscd restarting, say, or the Windows Smart Card service, which stops when the last reader is unplugged), Devices keeps running and recovers by itself. It reports the outage with one error, normally a ServiceNotRunningError (see Error Handling), when it begins.
- The service is back within about a second: every card still in a reader is reported
card-removed, then card-inserted with a new Card. The old Card’s connection died with the service. If the restarted service hasn’t found its readers again yet, they are reported detached and attached instead, as below.
- It stays down longer: every reader is reported
reader-detached, with card-removed first for its card. When the service returns, the readers are attached again, with their cards.
If the service isn’t running yet when you call start() (pcscd not started, or on Windows no reader plugged in), Devices waits for it in the same way: one error, then the readers once it starts. Without an error listener, start() throws instead.
Auto GET RESPONSE (T=0 Protocol)
For T=0 protocol cards, you can automatically handle status words by passing the autoGetResponse option:
SW1=61: Sends GET RESPONSE to retrieve remaining data
SW1=6C: Retries with corrected Le value
const raw = await card.transmit([0x00, 0xA4, 0x04, 0x00, 0x0E, ...aid]);
const response = await card.transmit([0x00, 0xA4, 0x04, 0x00, 0x0E, ...aid], {
autoGetResponse: true
});
The transmitWithAutoResponse() helper function is also available for low-level API usage:
const { transmitWithAutoResponse } = require('smartcard');
const response = await transmitWithAutoResponse(card, [0x00, 0xA4, 0x04, 0x00, 0x0E, ...aid], {
autoGetResponse: true
});
Control Codes
Utilities for reader control commands (e.g., PIN verification on pinpad readers).
const {
SCARD_CTL_CODE,
CM_IOCTL_GET_FEATURE_REQUEST,
parseFeatures,
FEATURE_VERIFY_PIN_DIRECT,
FEATURE_MODIFY_PIN_DIRECT
} = require('smartcard');
const featureResponse = await card.control(CM_IOCTL_GET_FEATURE_REQUEST);
const features = parseFeatures(featureResponse);
if (features.has(FEATURE_VERIFY_PIN_DIRECT)) {
const pinVerifyCode = features.get(FEATURE_VERIFY_PIN_DIRECT);
}
const customCode = SCARD_CTL_CODE(3500);
Constants
SCARD_SHARE_EXCLUSIVE
SCARD_SHARE_SHARED
SCARD_SHARE_DIRECT
SCARD_PROTOCOL_T0
SCARD_PROTOCOL_T1
SCARD_PROTOCOL_RAW
SCARD_LEAVE_CARD
SCARD_RESET_CARD
SCARD_UNPOWER_CARD
SCARD_EJECT_CARD
SCARD_STATE_PRESENT
SCARD_STATE_EMPTY
SCARD_STATE_CHANGED
FEATURE_VERIFY_PIN_START
FEATURE_VERIFY_PIN_FINISH
FEATURE_MODIFY_PIN_START
FEATURE_MODIFY_PIN_FINISH
FEATURE_GET_KEY_PRESSED
FEATURE_VERIFY_PIN_DIRECT
FEATURE_MODIFY_PIN_DIRECT
Common APDU Commands
const GET_UID = [0xFF, 0xCA, 0x00, 0x00, 0x00];
const SELECT_AID = [0x00, 0xA4, 0x04, 0x00, , ];
const READ_BINARY = [0x00, 0xB0, , , ];
Error Handling
const { PCSCError, CardRemovedError, TimeoutError } = require('smartcard');
try {
const response = await card.transmit([0x00, 0xA4, 0x04, 0x00]);
} catch (err) {
if (err instanceof CardRemovedError) {
console.log('Card was removed');
} else if (err instanceof TimeoutError) {
console.log('Operation timed out');
} else if (err instanceof PCSCError) {
console.log(`PC/SC error: ${err.message} (code: ${err.code})`);
} else {
throw err;
}
}
PC/SC failures from the low-level Context, Reader and Card and from Devices 'error' events are all PCSCErrors, or one of the subclasses above (also NoReadersError, ServiceNotRunningError and SharingViolationError), with the PC/SC code in err.code. Once a Context is closed, its readers and cards throw a PCSCError with code 0x80100003 (SCARD_E_INVALID_HANDLE).
Troubleshooting
“No readers available”
- Ensure a PC/SC compatible reader is connected
- On Linux, ensure
pcscd service is running: sudo systemctl status pcscd
“PC/SC service not running”
- Linux:
sudo systemctl start pcscd
- Windows: Check “Smart Card” service is running
“Sharing violation”
- Another application has exclusive access to the card
- Close other smart card applications
Build errors on Linux
- Install development headers:
sudo apt-get install libpcsclite-dev
“Could not resolve: …/…/build/Release/smartcard_napi.node”
The native addon is compiled by node-gyp during npm install. If the file is missing:
- Bun: install scripts are skipped for untrusted packages — add
"trustedDependencies": ["smartcard"] to your package.json and reinstall
- Bundlers (esbuild, webpack, electrobun): native addons can’t be bundled — mark
smartcard as external so the require happens at runtime
- Rebuild manually:
npm rebuild smartcard
Docker & containers
The library talks to the PC/SC daemon. Either mount the host daemon’s socket:
# In the image (libpcsclite-dev is needed at npm install time to build the addon)
RUN apt-get install -y libpcsclite1
docker run -v /var/run/pcscd:/var/run/pcscd myapp
Or run pcscd inside the container with USB passthrough:
docker run --privileged -v /dev/bus/usb:/dev/bus/usb myapp
Correctness
The native addon’s concurrency is modelled in TLA+ and checked with the TLC model checker. The specs cover the reader monitor (its start, stop and teardown lifecycle, and whether JS is told about every reader and card) and Context.waitForChange(). CI re-runs them whenever they change.
The models describe the design, within small bounds, and only pcsc-lite’s PC/SC semantics; they are not a proof of the C++ code. They found four bugs in 3.8.0, all since fixed and kept as regression checks. See spec/README.md for the findings and for what the models leave out.
Migrating from v1.x
Version 2.0 is a complete rewrite using N-API for stability across Node.js versions.
Breaking Changes
| v1.x |
v2.x |
device-activated event |
reader-attached event |
device-deactivated event |
reader-detached event |
event.device |
reader (passed directly) |
device.on('card-inserted') |
devices.on('card-inserted') |
card.issueCommand() |
card.transmit() |
Migration Example
v1.x:
const { Devices } = require('smartcard');
const devices = new Devices();
devices.on('device-activated', event => {
const device = event.device;
device.on('card-inserted', event => {
const card = event.card;
card.issueCommand(new CommandApdu({...}));
});
});
v2.x:
const { Devices } = require('smartcard');
const devices = new Devices();
devices.on('reader-attached', reader => {
console.log('Reader:', reader.name);
});
devices.on('card-inserted', ({ reader, card }) => {
const response = await card.transmit([0x00, 0xA4, 0x04, 0x00]);
});
devices.start();
Key Improvements in v2.x/v3.x
- Works on Node.js 18+ without recompilation (v3.x requires Node.js 18+)
- Native N-API bindings (no more NAN compatibility issues)
- Simpler flat event model
- Full TypeScript definitions
- Promise-based async API
License
MIT
- Card Spy - Smartcard and NFC IDE for macOS, Windows and Linux, built on smartcard. Send APDUs from a console and trace every exchange with status words and TLV decoded, explore EMV payment applications and NFC tags, script cards in TypeScript, and work without hardware using recorded virtual cards. Website and downloads.
- emv - Interactive EMV chip card explorer built on smartcard. Features a terminal UI for discovering payment applications, reading card data, verifying PINs, and exploring EMV tag structures. Supports GET PROCESSING OPTIONS, application cryptogram generation (ARQC/TC), and Dynamic Data Authentication (DDA).
评论