smartcard 3.7.2 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -297,6 +297,22 @@ interface Card {
297
297
  }
298
298
  ```
299
299
 
300
+ Reset a card in place with `reconnect` — no physical removal needed:
301
+
302
+ ```javascript
303
+ const { SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0, SCARD_PROTOCOL_T1, SCARD_RESET_CARD, SCARD_UNPOWER_CARD } = require('smartcard');
304
+
305
+ // Warm reset
306
+ await card.reconnect(SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, SCARD_RESET_CARD);
307
+
308
+ // Cold reset (power off, then power back on)
309
+ await card.reconnect(SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, SCARD_UNPOWER_CARD);
310
+ ```
311
+
312
+ 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.
313
+
314
+ `disconnect(disposition)` accepts the same constants to reset or unpower the card on the way out.
315
+
300
316
  ### Devices
301
317
 
302
318
  High-level event-driven API.
@@ -440,6 +456,8 @@ try {
440
456
  }
441
457
  ```
442
458
 
459
+ PC/SC failures from the low-level `Context`, `Reader` and `Card` and from `Devices` `'error'` events are all `PCSCError`s, 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`).
460
+
443
461
  ## Troubleshooting
444
462
 
445
463
  ### "No readers available"
@@ -457,6 +475,30 @@ try {
457
475
  ### Build errors on Linux
458
476
  - Install development headers: `sudo apt-get install libpcsclite-dev`
459
477
 
478
+ ### "Could not resolve: ../../build/Release/smartcard_napi.node"
479
+ The native addon is compiled by `node-gyp` during `npm install`. If the file is missing:
480
+ - **Bun**: install scripts are skipped for untrusted packages — add `"trustedDependencies": ["smartcard"]` to your package.json and reinstall
481
+ - **Bundlers** (esbuild, webpack, electrobun): native addons can't be bundled — mark `smartcard` as external so the require happens at runtime
482
+ - Rebuild manually: `npm rebuild smartcard`
483
+
484
+ ### Docker & containers
485
+ The library talks to the PC/SC daemon. Either mount the host daemon's socket:
486
+
487
+ ```dockerfile
488
+ # In the image (libpcsclite-dev is needed at npm install time to build the addon)
489
+ RUN apt-get install -y libpcsclite1
490
+ ```
491
+
492
+ ```bash
493
+ docker run -v /var/run/pcscd:/var/run/pcscd myapp
494
+ ```
495
+
496
+ Or run `pcscd` inside the container with USB passthrough:
497
+
498
+ ```bash
499
+ docker run --privileged -v /dev/bus/usb:/dev/bus/usb myapp
500
+ ```
501
+
460
502
  ## Migrating from v1.x
461
503
 
462
504
  Version 2.0 is a complete rewrite using N-API for stability across Node.js versions.
@@ -516,5 +558,5 @@ MIT
516
558
 
517
559
  ## Related Projects
518
560
 
519
- - [nfc-pcsc](https://www.npmjs.com/package/nfc-pcsc) - NFC library built on smartcard
561
+ - [Card Spy](https://github.com/tomkp/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](https://tomkp.github.io/card-spy/).
520
562
  - [emv](https://github.com/tomkp/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).
package/binding.gyp CHANGED
@@ -1,4 +1,7 @@
1
1
  {
2
+ "variables": {
3
+ "smartcard_build_tests%": "false"
4
+ },
2
5
  "targets": [{
3
6
  "target_name": "smartcard_napi",
4
7
  "cflags!": ["-fno-exceptions"],
@@ -16,14 +19,19 @@
16
19
  ],
17
20
  "defines": [
18
21
  "NAPI_VERSION=8",
19
- "NAPI_CPP_EXCEPTIONS"
22
+ "NAPI_CPP_EXCEPTIONS",
23
+ # A callback that runs while Node tears its environment down (a
24
+ # worker exiting) can't throw into JS; without this,
25
+ # node-addon-api rethrows that into Node: std::terminate
26
+ "NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS"
20
27
  ],
21
28
  "conditions": [
22
29
  ["OS=='win'", {
23
30
  "libraries": ["-lwinscard"],
24
31
  "msvs_settings": {
25
32
  "VCCLCompilerTool": {
26
- "ExceptionHandling": 1
33
+ "ExceptionHandling": 1,
34
+ "AdditionalOptions": ["/std:c++17"]
27
35
  }
28
36
  }
29
37
  }],
@@ -32,14 +40,53 @@
32
40
  "xcode_settings": {
33
41
  "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
34
42
  "CLANG_CXX_LIBRARY": "libc++",
43
+ "CLANG_CXX_LANGUAGE_STANDARD": "c++17",
35
44
  "MACOSX_DEPLOYMENT_TARGET": "10.15"
36
45
  }
37
46
  }],
38
47
  ["OS=='linux'", {
39
48
  "libraries": ["-lpcsclite"],
40
49
  "include_dirs": ["/usr/include/PCSC"],
41
- "cflags_cc": ["-fexceptions"]
50
+ "cflags_cc": ["-std=c++17", "-fexceptions"]
42
51
  }]
43
52
  ]
44
- }]
53
+ }],
54
+ "conditions": [
55
+ ["smartcard_build_tests=='true'", {
56
+ "targets": [{
57
+ "target_name": "smartcard_tests",
58
+ "type": "executable",
59
+ "sources": [
60
+ "src/test/test_main.cpp",
61
+ "src/test/reader_state_utils_test.cpp"
62
+ ],
63
+ "include_dirs": [
64
+ "src"
65
+ ],
66
+ "cflags!": ["-fno-exceptions"],
67
+ "cflags_cc!": ["-fno-exceptions"],
68
+ "conditions": [
69
+ ["OS=='win'", {
70
+ "msvs_settings": {
71
+ "VCCLCompilerTool": {
72
+ "ExceptionHandling": 1,
73
+ "AdditionalOptions": ["/std:c++17"]
74
+ }
75
+ }
76
+ }],
77
+ ["OS=='mac'", {
78
+ "xcode_settings": {
79
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
80
+ "CLANG_CXX_LIBRARY": "libc++",
81
+ "CLANG_CXX_LANGUAGE_STANDARD": "c++17",
82
+ "MACOSX_DEPLOYMENT_TARGET": "10.15"
83
+ }
84
+ }],
85
+ ["OS=='linux'", {
86
+ "cflags_cc": ["-std=c++17", "-fexceptions"]
87
+ }]
88
+ ]
89
+ }]
90
+ }]
91
+ ]
45
92
  }
@@ -1 +1 @@
1
- {"version":3,"file":"card-wrapper.d.ts","sourceRoot":"","sources":["../../lib/card-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAGjE;;GAEG;AACH,qBAAa,WAAY,YAAW,IAAI;IACpC,OAAO,CAAC,WAAW,CAAO;gBAEd,UAAU,EAAE,IAAI;IAI5B,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAEK,QAAQ,CACV,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,eAAe,GAC1B,OAAO,CAAC,MAAM,CAAC;IASlB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhE,SAAS,IAAI,UAAU;IAIvB,UAAU,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI;IAIhC,SAAS,CACX,SAAS,CAAC,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,MAAM,EACjB,cAAc,CAAC,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC;CAGrB;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,UAAU,EAAE,IAAI,GAAG,IAAI,CAE/C"}
1
+ {"version":3,"file":"card-wrapper.d.ts","sourceRoot":"","sources":["../../lib/card-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAWjE;;GAEG;AACH,qBAAa,WAAY,YAAW,IAAI;IACpC,OAAO,CAAC,WAAW,CAAO;gBAEd,UAAU,EAAE,IAAI;IAI5B,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAEK,QAAQ,CACV,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,eAAe,GAC1B,OAAO,CAAC,MAAM,CAAC;IASlB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhE,SAAS,IAAI,UAAU;IAIvB,UAAU,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI;IAIhC,SAAS,CACX,SAAS,CAAC,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,MAAM,EACjB,cAAc,CAAC,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC;CAwCrB;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,UAAU,EAAE,IAAI,GAAG,IAAI,CAE/C"}
@@ -9,6 +9,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.CardWrapper = void 0;
10
10
  exports.wrapCard = wrapCard;
11
11
  const t0_handler_1 = require("./t0-handler");
12
+ const errors_1 = require("./errors");
13
+ /**
14
+ * What the native layer offers when reconnect() is given no protocol.
15
+ * T=0 and T=1 are 1 and 2 in pcsc-lite, macOS and WinSCard alike (only RAW
16
+ * differs between them).
17
+ */
18
+ const DEFAULT_PROTOCOLS = 0x1 | 0x2;
12
19
  /**
13
20
  * Wraps a native Card to add autoGetResponse support to transmit()
14
21
  */
@@ -44,7 +51,36 @@ class CardWrapper {
44
51
  return this._nativeCard.disconnect(disposition);
45
52
  }
46
53
  async reconnect(shareMode, protocol, initialization) {
47
- return this._nativeCard.reconnect(shareMode, protocol, initialization);
54
+ const active = this._nativeCard.protocol;
55
+ try {
56
+ return await this._nativeCard.reconnect(shareMode, protocol, initialization);
57
+ }
58
+ catch (err) {
59
+ // Some reader and card combinations (issue #34: an SCR35xx with a
60
+ // T=0-only card) report the card unresponsive when a reset offers
61
+ // T=1 as well. Retry once with the protocol the card is already
62
+ // using, but only if the caller offered it. The failed attempt has
63
+ // usually reset the card already, so this resets it a second time.
64
+ const requested = protocol ?? DEFAULT_PROTOCOLS;
65
+ const offered = (requested & active) === active;
66
+ if (!active ||
67
+ !offered ||
68
+ requested === active ||
69
+ !(0, errors_1.isUnresponsiveCardError)(err)) {
70
+ throw err;
71
+ }
72
+ try {
73
+ return await this._nativeCard.reconnect(shareMode, active, initialization);
74
+ }
75
+ catch (retryErr) {
76
+ // Report the failure of the call that was made; keep the
77
+ // fallback's failure as its cause
78
+ if (err instanceof Error && err.cause === undefined) {
79
+ err.cause = retryErr;
80
+ }
81
+ throw err;
82
+ }
83
+ }
48
84
  }
49
85
  }
50
86
  exports.CardWrapper = CardWrapper;
@@ -1 +1 @@
1
- {"version":3,"file":"card-wrapper.js","sourceRoot":"","sources":["../../lib/card-wrapper.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AA+DH,4BAEC;AA9DD,6CAAwD;AAExD;;GAEG;AACH,MAAa,WAAW;IACZ,WAAW,CAAO;IAE1B,YAAY,UAAgB;QACxB,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;IAClC,CAAC;IAED,IAAI,QAAQ;QACR,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;IACrC,CAAC;IAED,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,CACjB,CAAC;QACN,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,kEAAkE;YAClE,kEAAkE;YAClE,gEAAgE;YAChE,mEAAmE;YACnE,mEAAmE;YACnE,MAAM,SAAS,GAAG,QAAQ,IAAI,iBAAiB,CAAC;YAChD,MAAM,OAAO,GAAG,CAAC,SAAS,GAAG,MAAM,CAAC,KAAK,MAAM,CAAC;YAChD,IACI,CAAC,MAAM;gBACP,CAAC,OAAO;gBACR,SAAS,KAAK,MAAM;gBACpB,CAAC,IAAA,gCAAuB,EAAC,GAAY,CAAC,EACxC,CAAC;gBACC,MAAM,GAAG,CAAC;YACd,CAAC;YACD,IAAI,CAAC;gBACD,OAAO,MAAM,IAAI,CAAC,WAAW,CAAC,SAAS,CACnC,SAAS,EACT,MAAM,EACN,cAAc,CACjB,CAAC;YACN,CAAC;YAAC,OAAO,QAAQ,EAAE,CAAC;gBAChB,yDAAyD;gBACzD,kCAAkC;gBAClC,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;oBAClD,GAAG,CAAC,KAAK,GAAG,QAAQ,CAAC;gBACzB,CAAC;gBACD,MAAM,GAAG,CAAC;YACd,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAvFD,kCAuFC;AAED;;GAEG;AACH,SAAgB,QAAQ,CAAC,UAAgB;IACrC,OAAO,IAAI,WAAW,CAAC,UAAU,CAAC,CAAC;AACvC,CAAC"}
@@ -1,10 +1,5 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import type { Card, DeviceEvents, DevicesOptions, Reader } from './types';
3
- /**
4
- * Check if an error indicates an unresponsive card (SCARD_W_UNRESPONSIVE_CARD).
5
- * Used to determine if we should fallback to T=0 protocol.
6
- */
7
- export declare function isUnresponsiveCardError(err: Error): boolean;
8
3
  /**
9
4
  * High-level event-driven API for PC/SC devices
10
5
  *
@@ -24,6 +19,7 @@ export declare class Devices extends EventEmitter {
24
19
  private _running;
25
20
  private _readers;
26
21
  private _eventQueue;
22
+ private _generation;
27
23
  private _Context;
28
24
  private _ReaderMonitor;
29
25
  private _SCARD_STATE_PRESENT;
@@ -63,10 +59,35 @@ export declare class Devices extends EventEmitter {
63
59
  * Queues events to prevent race conditions when multiple events arrive concurrently
64
60
  */
65
61
  private _handleEvent;
62
+ /**
63
+ * Emit an error without killing the event pump: with no 'error' listener
64
+ * EventEmitter throws, which would reject the event queue and stop all
65
+ * future event processing.
66
+ */
67
+ private _safeEmitError;
66
68
  /**
67
69
  * Process a single event (called sequentially via queue)
68
70
  */
69
71
  private _processEvent;
72
+ /**
73
+ * Replace the PC/SC context after the native monitor recovered from a
74
+ * service restart (the old handle is dead).
75
+ */
76
+ private _recreateContext;
77
+ /**
78
+ * The context for listing readers and connecting cards, created here
79
+ * if replacing it after a service outage failed: one failure must not
80
+ * leave Devices without a context until it is restarted. None while
81
+ * not running, so a handler that outlives its session can't open one.
82
+ */
83
+ private _ensureContext;
84
+ /**
85
+ * Whether an event of this generation still belongs to the running
86
+ * session. A listener can stop (and restart) Devices while a handler
87
+ * is part-way through, so handlers check again after every emit and
88
+ * await.
89
+ */
90
+ private _isCurrent;
70
91
  /**
71
92
  * Handle reader attached
72
93
  */
@@ -1 +1 @@
1
- {"version":3,"file":"devices.d.ts","sourceRoot":"","sources":["../../lib/devices.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,KAAK,EACR,IAAI,EAGJ,YAAY,EACZ,cAAc,EAGd,MAAM,EAGT,MAAM,SAAS,CAAC;AAUjB;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,KAAK,GAAG,OAAO,CAK3D;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,OAAQ,SAAQ,YAAY;IACrC,OAAO,CAAC,QAAQ,CAA8B;IAC9C,OAAO,CAAC,QAAQ,CAAwB;IACxC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,C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ports.Devices = void 0;
4
- exports.isUnresponsiveCardError = isUnresponsiveCardError;
5
4
  const events_1 = require("events");
6
5
  const card_wrapper_1 = require("./card-wrapper");
6
+ const errors_1 = require("./errors");
7
7
  const addon = require('../../build/Release/smartcard_napi.node');
8
- /**
9
- * Check if an error indicates an unresponsive card (SCARD_W_UNRESPONSIVE_CARD).
10
- * Used to determine if we should fallback to T=0 protocol.
11
- */
12
- function isUnresponsiveCardError(err) {
13
- if (!err || typeof err.message !== 'string') {
14
- return false;
15
- }
16
- return err.message.toLowerCase().includes('unresponsive');
17
- }
18
8
  /**
19
9
  * High-level event-driven API for PC/SC devices
20
10
  *
@@ -34,6 +24,7 @@ class Devices extends events_1.EventEmitter {
34
24
  _running = false;
35
25
  _readers = new Map();
36
26
  _eventQueue = Promise.resolve();
27
+ _generation = 0;
37
28
  // Dependencies (can be injected for testing)
38
29
  _Context;
39
30
  _ReaderMonitor;
@@ -68,16 +59,54 @@ class Devices extends events_1.EventEmitter {
68
59
  try {
69
60
  // Create context for card connections
70
61
  this._context = new this._Context();
62
+ // A rejected queue from a previous session must not block this one
63
+ this._eventQueue = Promise.resolve();
71
64
  // Create native monitor
72
65
  this._monitor = new this._ReaderMonitor();
73
- this._running = true;
74
- // Start native monitoring with callback
66
+ // Start native monitoring with callback. Events carry this
67
+ // session's generation: a stopped monitor can still deliver
68
+ // events it had queued, and after a same-tick stop()/start()
69
+ // they would otherwise land in the new session.
70
+ const generation = this._generation;
75
71
  this._monitor.start((event) => {
76
- this._handleEvent(event);
72
+ if (generation === this._generation) {
73
+ this._handleEvent(event, generation);
74
+ }
77
75
  });
76
+ // Set only after everything succeeded, so a partial failure
77
+ // leaves start() retryable. Events queue as microtasks, so none
78
+ // is processed before this line runs.
79
+ this._running = true;
78
80
  }
79
81
  catch (err) {
80
- this.emit('error', err);
82
+ // Roll back whatever was created so a later start() can succeed
83
+ if (this._monitor) {
84
+ try {
85
+ this._monitor.stop();
86
+ }
87
+ catch {
88
+ // Monitor never started
89
+ }
90
+ this._monitor = null;
91
+ }
92
+ if (this._context) {
93
+ try {
94
+ this._context.close();
95
+ }
96
+ catch {
97
+ // Ignore close errors
98
+ }
99
+ this._context = null;
100
+ }
101
+ const error = (0, errors_1.toPCSCError)(err);
102
+ if (this.listenerCount('error') > 0) {
103
+ this.emit('error', error);
104
+ }
105
+ else {
106
+ // No listener: fail loudly to the caller instead of
107
+ // silently doing nothing - but only after the rollback above
108
+ throw error;
109
+ }
81
110
  }
82
111
  }
83
112
  /**
@@ -85,6 +114,9 @@ class Devices extends events_1.EventEmitter {
85
114
  */
86
115
  stop() {
87
116
  this._running = false;
117
+ // Invalidate in-flight handlers parked on an await: a handler that
118
+ // resumes after this stop (or a later restart) must not touch state
119
+ this._generation++;
88
120
  if (this._monitor) {
89
121
  try {
90
122
  this._monitor.stop();
@@ -120,11 +152,8 @@ class Devices extends events_1.EventEmitter {
120
152
  * List currently known readers
121
153
  */
122
154
  listReaders() {
123
- if (!this._context || !this._context.isValid) {
124
- return [];
125
- }
126
155
  try {
127
- return this._context.listReaders();
156
+ return this._ensureContext()?.listReaders() ?? [];
128
157
  }
129
158
  catch {
130
159
  return [];
@@ -156,41 +185,110 @@ class Devices extends events_1.EventEmitter {
156
185
  * Handle events from native monitor
157
186
  * Queues events to prevent race conditions when multiple events arrive concurrently
158
187
  */
159
- _handleEvent(event) {
160
- // Chain this event onto the queue to serialize processing
161
- this._eventQueue = this._eventQueue.then(() => this._processEvent(event));
188
+ _handleEvent(event, generation) {
189
+ // Chain this event onto the queue to serialize processing. The catch
190
+ // keeps the chain alive: a rejected link would otherwise silently
191
+ // stop all future event processing.
192
+ this._eventQueue = this._eventQueue
193
+ .then(() => this._processEvent(event, generation))
194
+ .catch((err) => this._safeEmitError(err));
195
+ }
196
+ /**
197
+ * Emit an error without killing the event pump: with no 'error' listener
198
+ * EventEmitter throws, which would reject the event queue and stop all
199
+ * future event processing.
200
+ */
201
+ _safeEmitError(err) {
202
+ if (this.listenerCount('error') > 0) {
203
+ this.emit('error', (0, errors_1.toPCSCError)(err));
204
+ }
162
205
  }
163
206
  /**
164
207
  * Process a single event (called sequentially via queue)
165
208
  */
166
- async _processEvent(event) {
167
- if (!this._running) {
209
+ async _processEvent(event, generation) {
210
+ // Dropped once monitoring stopped, even if it has started again:
211
+ // the event belongs to the earlier session
212
+ if (!this._isCurrent(generation)) {
168
213
  return;
169
214
  }
170
- const { type, reader: readerName, state, atr } = event;
215
+ const { type, reader: readerName, state, atr, code } = event;
171
216
  switch (type) {
172
217
  case 'reader-attached':
173
- await this._handleReaderAttached(readerName, state, atr);
218
+ await this._handleReaderAttached(readerName, state, atr, generation);
174
219
  break;
175
220
  case 'reader-detached':
176
221
  this._handleReaderDetached(readerName);
177
222
  break;
178
223
  case 'card-inserted':
179
- await this._handleCardInserted(readerName, state, atr);
224
+ await this._handleCardInserted(readerName, state, atr, generation);
180
225
  break;
181
226
  case 'card-removed':
182
227
  this._handleCardRemoved(readerName);
183
228
  break;
229
+ case 'monitor-recovered':
230
+ // The native monitor re-established its PC/SC context after a
231
+ // service restart; ours died with the same restart - replace it.
232
+ this._recreateContext();
233
+ break;
184
234
  case 'error':
185
235
  // readerName contains error message for error events
186
- this.emit('error', new Error(readerName));
236
+ this._safeEmitError(code !== undefined
237
+ ? (0, errors_1.createPCSCError)(readerName, code)
238
+ : new Error(readerName));
187
239
  break;
188
240
  }
189
241
  }
242
+ /**
243
+ * Replace the PC/SC context after the native monitor recovered from a
244
+ * service restart (the old handle is dead).
245
+ */
246
+ _recreateContext() {
247
+ if (this._context) {
248
+ try {
249
+ this._context.close();
250
+ }
251
+ catch {
252
+ // Dead context - nothing left to release
253
+ }
254
+ }
255
+ this._context = null;
256
+ try {
257
+ this._ensureContext();
258
+ }
259
+ catch (err) {
260
+ // _ensureContext() tries again when a context is next needed
261
+ this._safeEmitError(err);
262
+ }
263
+ }
264
+ /**
265
+ * The context for listing readers and connecting cards, created here
266
+ * if replacing it after a service outage failed: one failure must not
267
+ * leave Devices without a context until it is restarted. None while
268
+ * not running, so a handler that outlives its session can't open one.
269
+ */
270
+ _ensureContext() {
271
+ if (!this._running) {
272
+ return null;
273
+ }
274
+ if (!this._context) {
275
+ this._context = new this._Context();
276
+ }
277
+ return this._context;
278
+ }
279
+ /**
280
+ * Whether an event of this generation still belongs to the running
281
+ * session. A listener can stop (and restart) Devices while a handler
282
+ * is part-way through, so handlers check again after every emit and
283
+ * await.
284
+ */
285
+ _isCurrent(generation) {
286
+ return this._running && this._generation === generation;
287
+ }
190
288
  /**
191
289
  * Handle reader attached
192
290
  */
193
- async _handleReaderAttached(readerName, state, atr) {
291
+ async _handleReaderAttached(readerName, state, atr, generation) {
194
292
  // Initialize reader state
195
293
  this._readers.set(readerName, {
196
294
  hasCard: false,
@@ -205,7 +303,7 @@ class Devices extends events_1.EventEmitter {
205
303
  this.emit('reader-attached', reader);
206
304
  // Check if card is already present
207
305
  if ((state & this._SCARD_STATE_PRESENT) !== 0) {
208
- await this._handleCardInserted(readerName, state, atr);
306
+ await this._handleCardInserted(readerName, state, atr, generation);
209
307
  }
210
308
  }
211
309
  /**
@@ -224,7 +322,11 @@ class Devices extends events_1.EventEmitter {
224
322
  /**
225
323
  * Handle card inserted
226
324
  */
227
- async _handleCardInserted(readerName, eventState, atr) {
325
+ async _handleCardInserted(readerName, eventState, atr, generation) {
326
+ // A 'reader-attached' listener may have stopped Devices
327
+ if (!this._isCurrent(generation)) {
328
+ return;
329
+ }
228
330
  let state = this._readers.get(readerName);
229
331
  if (!state) {
230
332
  state = { hasCard: false, card: null };
@@ -233,37 +335,67 @@ class Devices extends events_1.EventEmitter {
233
335
  state.hasCard = true;
234
336
  // Try to connect to the card
235
337
  try {
236
- const readers = this._context.listReaders();
237
- const reader = readers.find((r) => r.name === readerName);
238
- if (reader) {
239
- let nativeCard;
338
+ // The reader list can lag the monitor event during PnP churn -
339
+ // retry briefly before giving up (Issue #117)
340
+ let reader;
341
+ for (let attempt = 0; attempt < 3; attempt++) {
342
+ if (attempt > 0) {
343
+ await new Promise((resolve) => setTimeout(resolve, 50));
344
+ // Bail if monitoring stopped or restarted while we slept
345
+ if (!this._isCurrent(generation)) {
346
+ return;
347
+ }
348
+ }
349
+ const readers = this._ensureContext()?.listReaders() ?? [];
350
+ reader = readers.find((r) => r.name === readerName);
351
+ if (reader) {
352
+ break;
353
+ }
354
+ }
355
+ if (!reader) {
356
+ // Reader vanished mid-churn: leave no half-state behind - the
357
+ // queued reader-detached will finish the cleanup
358
+ state.hasCard = false;
359
+ return;
360
+ }
361
+ let nativeCard;
362
+ try {
363
+ // First try with both T=0 and T=1 protocols
364
+ nativeCard = await reader.connect(this._SCARD_SHARE_SHARED, this._SCARD_PROTOCOL_T0 | this._SCARD_PROTOCOL_T1);
365
+ }
366
+ catch (dualProtocolErr) {
367
+ // If dual protocol fails with unresponsive card error,
368
+ // fallback to T=0 only (issue #34)
369
+ if ((0, errors_1.isUnresponsiveCardError)(dualProtocolErr)) {
370
+ nativeCard = await reader.connect(this._SCARD_SHARE_SHARED, this._SCARD_PROTOCOL_T0);
371
+ }
372
+ else {
373
+ // Re-throw if it's a different error
374
+ throw dualProtocolErr;
375
+ }
376
+ }
377
+ if (!this._isCurrent(generation)) {
378
+ // stop() ran while connect was in flight - it cannot see this
379
+ // card, so release the handle here
240
380
  try {
241
- // First try with both T=0 and T=1 protocols
242
- nativeCard = await reader.connect(this._SCARD_SHARE_SHARED, this._SCARD_PROTOCOL_T0 | this._SCARD_PROTOCOL_T1);
381
+ nativeCard.disconnect();
243
382
  }
244
- catch (dualProtocolErr) {
245
- // If dual protocol fails with unresponsive card error,
246
- // fallback to T=0 only (issue #34)
247
- if (isUnresponsiveCardError(dualProtocolErr)) {
248
- nativeCard = await reader.connect(this._SCARD_SHARE_SHARED, this._SCARD_PROTOCOL_T0);
249
- }
250
- else {
251
- // Re-throw if it's a different error
252
- throw dualProtocolErr;
253
- }
383
+ catch {
384
+ // Ignore disconnect errors
254
385
  }
255
- // Wrap the native card to add autoGetResponse support
256
- const card = (0, card_wrapper_1.wrapCard)(nativeCard);
257
- state.card = card;
258
- this.emit('card-inserted', {
259
- reader: { name: readerName, state: eventState, atr: atr },
260
- card: card,
261
- });
386
+ return;
262
387
  }
388
+ // Wrap the native card to add autoGetResponse support
389
+ const card = (0, card_wrapper_1.wrapCard)(nativeCard);
390
+ state.card = card;
391
+ this.emit('card-inserted', {
392
+ reader: { name: readerName, state: eventState, atr: atr },
393
+ card: card,
394
+ });
263
395
  }
264
396
  catch (err) {
265
397
  // Emit error but don't fail
266
- this.emit('error', err);
398
+ this._safeEmitError(err);
267
399
  }
268
400
  }
269
401
  /**