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.
@@ -1,20 +1,54 @@
1
1
  #include "reader_monitor.h"
2
2
  #include "pcsc_errors.h"
3
+ #include "pcsc_napi_error.h"
4
+ #include <cstdio>
3
5
  #include <cstring>
4
6
  #include <unordered_map>
5
7
  #include <memory>
8
+ #include "reader_state_utils.h"
9
+
10
+ using smartcard::CardEvent;
11
+ using smartcard::DetectCardStateChange;
12
+ using smartcard::DetectCardStateChangeAcrossOutage;
13
+
14
+ // Format a PC/SC error as "message (0xXXXXXXXX)" so the numeric code
15
+ // survives to JS even when only the message string is consumed.
16
+ static std::string FormatPCSCError(LONG code) {
17
+ char hex[16];
18
+ std::snprintf(hex, sizeof(hex), " (0x%08X)", static_cast<unsigned int>(static_cast<DWORD>(code)));
19
+ return std::string(GetPCSCErrorString(code)) + hex;
20
+ }
6
21
 
7
- Napi::FunctionReference ReaderMonitor::constructor;
22
+ // The context will never work again (Smart Card service stopped or
23
+ // restarted, dead handle), so release it and re-establish (Issue #119).
24
+ // SCARD_E_INVALID_PARAMETER is deliberately not one: it is a per-call
25
+ // argument error, and recycling a healthy context would re-seed lastState
26
+ // and latch away pending transitions.
27
+ static bool IsContextFatal(LONG result) {
28
+ DWORD code = static_cast<DWORD>(result);
29
+ if (code == SCARD_E_SERVICE_STOPPED || code == SCARD_E_NO_SERVICE ||
30
+ code == SCARD_E_INVALID_HANDLE) {
31
+ return true;
32
+ }
33
+ #ifdef _WIN32
34
+ // WinSCard may report a dead context as the Win32 error instead
35
+ if (code == ERROR_INVALID_HANDLE) {
36
+ return true;
37
+ }
38
+ #endif
39
+ return false;
40
+ }
8
41
 
9
42
  // Number of iterations between forced full state refreshes (Windows reliability fix)
10
43
  static const int STATE_REFRESH_INTERVAL = 10;
11
44
 
12
45
  // Event data passed from worker thread to JS thread
13
- struct EventData {
46
+ struct ReaderMonitor::EventData {
14
47
  std::string eventType;
15
48
  std::string readerName;
16
49
  DWORD state;
17
50
  std::vector<uint8_t> atr;
51
+ DWORD code;
18
52
  };
19
53
 
20
54
  Napi::Object ReaderMonitor::Init(Napi::Env env, Napi::Object exports) {
@@ -24,9 +58,6 @@ Napi::Object ReaderMonitor::Init(Napi::Env env, Napi::Object exports) {
24
58
  InstanceAccessor("isRunning", &ReaderMonitor::GetIsRunning, nullptr),
25
59
  });
26
60
 
27
- constructor = Napi::Persistent(func);
28
- constructor.SuppressDestruct();
29
-
30
61
  exports.Set("ReaderMonitor", func);
31
62
  return exports;
32
63
  }
@@ -35,24 +66,81 @@ ReaderMonitor::ReaderMonitor(const Napi::CallbackInfo& info)
35
66
  : Napi::ObjectWrap<ReaderMonitor>(info),
36
67
  context_(0),
37
68
  contextValid_(false),
38
- running_(false) {
69
+ running_(false),
70
+ tsfnActive_(false),
71
+ cleanupHookAdded_(false),
72
+ outagePending_(false) {
39
73
  }
40
74
 
41
75
  ReaderMonitor::~ReaderMonitor() {
42
- // Ensure monitoring is stopped
76
+ Shutdown();
77
+ }
78
+
79
+ // Stop the monitor thread and release the tsfn and the PC/SC context.
80
+ // stop(), the destructor (GC, or Node finalizing objects at environment
81
+ // teardown) and the environment cleanup hook all end up here.
82
+ void ReaderMonitor::Shutdown() {
83
+ if (cleanupHookAdded_) {
84
+ napi_remove_env_cleanup_hook(Env(), OnEnvCleanup, this);
85
+ cleanupHookAdded_ = false;
86
+ }
87
+
43
88
  if (running_) {
44
89
  running_ = false;
45
- if (contextValid_) {
46
- SCardCancel(context_);
90
+
91
+ // Wake the monitor thread if it is pausing between retries
92
+ {
93
+ std::lock_guard<std::mutex> lock(pauseMutex_);
47
94
  }
95
+ pauseCv_.notify_all();
96
+
97
+ // Cancel any blocking SCardGetStatusChange call. mutex_ guards
98
+ // context_/contextValid_ against the recovery path swapping them
99
+ // on the monitor thread.
100
+ {
101
+ std::lock_guard<std::mutex> lock(mutex_);
102
+ if (contextValid_) {
103
+ SCardCancel(context_);
104
+ }
105
+ }
106
+
48
107
  if (monitorThread_.joinable()) {
49
108
  monitorThread_.join();
50
109
  }
51
110
  }
52
111
 
112
+ // A monitor destroyed without stop() would otherwise leak the tsfn,
113
+ // keeping the event loop referenced and letting its finalizer run
114
+ // after this object is gone
115
+ if (tsfnActive_) {
116
+ tsfn_.Release();
117
+ tsfnActive_ = false;
118
+ }
119
+
53
120
  if (contextValid_) {
54
121
  SCardReleaseContext(context_);
122
+ contextValid_ = false;
123
+ context_ = 0;
55
124
  }
125
+
126
+ readerStates_.clear();
127
+ outagePending_ = false;
128
+ }
129
+
130
+ // Node is tearing the environment down (a worker exiting or terminated)
131
+ // with the monitor still running. The tsfn's own cleanup hook would close
132
+ // it first and finalize this object only afterwards, so the destructor's
133
+ // Release() would reach a tsfn Node has finished with: on Node 24.15+ it
134
+ // locks the tsfn's mutex again (SIGABRT, or a hang on Linux); on Node
135
+ // 20/22 it touches a tsfn being deleted, and the monitor thread may still
136
+ // push to it (spec/README.md, finding 4). Node runs cleanup hooks newest
137
+ // first, and start() adds this one after the tsfn has added its own, so
138
+ // it stops the monitor while the tsfn is still alive.
139
+ void ReaderMonitor::OnEnvCleanup(void* arg) {
140
+ auto* self = static_cast<ReaderMonitor*>(arg);
141
+ // Node drops the hook itself once it has run
142
+ self->cleanupHookAdded_ = false;
143
+ self->Shutdown();
56
144
  }
57
145
 
58
146
  Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
@@ -74,27 +162,41 @@ Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
74
162
  // Establish PC/SC context
75
163
  LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context_);
76
164
  if (result != SCARD_S_SUCCESS) {
77
- Napi::Error::New(env, GetPCSCErrorString(result)).ThrowAsJavaScriptException();
165
+ NewPCSCError(env, result).ThrowAsJavaScriptException();
78
166
  return env.Undefined();
79
167
  }
80
168
  contextValid_ = true;
81
169
 
170
+ // Per-session liveness flag. The tsfn finalizer runs asynchronously on a
171
+ // later event-loop tick, so after a same-tick stop()/start() a stale
172
+ // finalizer from the previous session must only be able to kill its own
173
+ // session - clearing running_ directly here would silently stop the new
174
+ // monitor thread and leave its std::thread joinable but never joined.
175
+ auto sessionActive = std::make_shared<std::atomic<bool>>(true);
176
+
82
177
  // Create thread-safe function
83
- tsfn_ = Napi::ThreadSafeFunction::New(
178
+ tsfn_ = EventTsfn::New(
84
179
  env,
85
180
  callback,
86
181
  "ReaderMonitor",
87
- 0, // Unlimited queue size
88
- 1, // 1 initial thread
89
- [this](Napi::Env) {
90
- // Invoke destructor callback - called when tsfn is released
91
- running_ = false;
182
+ 0, // Unlimited queue size
183
+ 1, // 1 initial thread
184
+ nullptr, // No context
185
+ [sessionActive](Napi::Env, void*, std::nullptr_t*) {
186
+ // Called when Node finalizes the tsfn: once it is released
187
+ // (stop()) and its queue has drained, or at environment teardown
188
+ sessionActive->store(false);
92
189
  }
93
190
  );
191
+ tsfnActive_ = true;
192
+
193
+ // Added after the tsfn, so that at environment teardown it runs first
194
+ cleanupHookAdded_ =
195
+ napi_add_env_cleanup_hook(env, OnEnvCleanup, this) == napi_ok;
94
196
 
95
197
  // Start monitoring
96
198
  running_ = true;
97
- monitorThread_ = std::thread(&ReaderMonitor::MonitorLoop, this);
199
+ monitorThread_ = std::thread(&ReaderMonitor::MonitorLoop, this, sessionActive);
98
200
 
99
201
  return env.Undefined();
100
202
  }
@@ -106,29 +208,7 @@ Napi::Value ReaderMonitor::Stop(const Napi::CallbackInfo& info) {
106
208
  return env.Undefined();
107
209
  }
108
210
 
109
- running_ = false;
110
-
111
- // Cancel any blocking SCardGetStatusChange call
112
- if (contextValid_) {
113
- SCardCancel(context_);
114
- }
115
-
116
- // Wait for thread to finish
117
- if (monitorThread_.joinable()) {
118
- monitorThread_.join();
119
- }
120
-
121
- // Release thread-safe function
122
- tsfn_.Release();
123
-
124
- // Release context
125
- if (contextValid_) {
126
- SCardReleaseContext(context_);
127
- contextValid_ = false;
128
- context_ = 0;
129
- }
130
-
131
- readerStates_.clear();
211
+ Shutdown();
132
212
 
133
213
  return env.Undefined();
134
214
  }
@@ -137,7 +217,60 @@ Napi::Value ReaderMonitor::GetIsRunning(const Napi::CallbackInfo& info) {
137
217
  return Napi::Boolean::New(info.Env(), running_.load());
138
218
  }
139
219
 
140
- void ReaderMonitor::MonitorLoop() {
220
+ // Emit what a detected card event means to JS. state is the reader's
221
+ // state now; a Replaced card is reported as the old card leaving, then the
222
+ // new one arriving, and the leaving event gets that state as an empty
223
+ // reader so its flags match the event.
224
+ void ReaderMonitor::EmitCardEvent(CardEvent event, const std::string& readerName,
225
+ DWORD state, const std::vector<uint8_t>& atr) {
226
+ if (event == CardEvent::Removed) {
227
+ EmitEvent("card-removed", readerName, state, {});
228
+ } else if (event == CardEvent::Replaced) {
229
+ EmitEvent("card-removed", readerName,
230
+ (state & ~SCARD_STATE_PRESENT) | SCARD_STATE_EMPTY, {});
231
+ }
232
+ if (event == CardEvent::Inserted || event == CardEvent::Replaced) {
233
+ EmitEvent("card-inserted", readerName, state, atr);
234
+ }
235
+ }
236
+
237
+ // Commit point for card state transitions seen by the main wait.
238
+ // ResyncReaderList (PnP, timeouts, periodic refresh, recovery) detects
239
+ // events from its fresh reads with the same DetectCardStateChange and
240
+ // EmitCardEvent; UpdateReaderList, which stores those reads, applies the
241
+ // same IGNORE masking.
242
+ void ReaderMonitor::ApplyCardStateChange(ReaderInfo& info, const std::string& readerName,
243
+ const SCARD_READERSTATE& readerState) {
244
+ DWORD newState = readerState.dwEventState & ~SCARD_STATE_CHANGED;
245
+ CardEvent event = DetectCardStateChange(info.lastState, newState, SCARD_STATE_PRESENT,
246
+ SMARTCARD_PCSC_COUNTS_CARD_EVENTS);
247
+
248
+ // Commit so a stale lastState can't make the next SCardGetStatusChange
249
+ // re-report the same change - but never store SCARD_STATE_IGNORE (fed
250
+ // back as dwCurrentState it excludes the reader from future waits), and
251
+ // don't absorb an unknown/empty no-event result: a reader that vanished
252
+ // during the wait is dropped by the PnP resync, one that vanished
253
+ // between waits by the SCARD_E_UNKNOWN_READER resync.
254
+ bool unusable = readerState.dwEventState == 0 ||
255
+ (newState & SCARD_STATE_UNKNOWN) != 0;
256
+ if (event != CardEvent::None || !unusable) {
257
+ info.lastState = newState & ~SCARD_STATE_IGNORE;
258
+ }
259
+
260
+ if (event == CardEvent::Inserted || event == CardEvent::Replaced) {
261
+ // cbAtr comes from the PC/SC service; clamp to the actual buffer size
262
+ DWORD atrLen = readerState.cbAtr;
263
+ if (atrLen > sizeof(readerState.rgbAtr)) {
264
+ atrLen = sizeof(readerState.rgbAtr);
265
+ }
266
+ info.atr.assign(readerState.rgbAtr, readerState.rgbAtr + atrLen);
267
+ } else if (event == CardEvent::Removed) {
268
+ info.atr.clear();
269
+ }
270
+ EmitCardEvent(event, readerName, newState, info.atr);
271
+ }
272
+
273
+ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive) {
141
274
  // Get initial reader list
142
275
  UpdateReaderList();
143
276
 
@@ -153,61 +286,48 @@ void ReaderMonitor::MonitorLoop() {
153
286
  std::vector<SCARD_READERSTATE> states;
154
287
  std::vector<std::string> readerNames;
155
288
  int iterationCount = 0;
289
+ // The last wait failed with SCARD_E_UNKNOWN_READER right after a resync
290
+ bool resyncedForUnknownReader = false;
291
+ // The PnP entry's dwCurrentState: the reader event count from the last
292
+ // wait (SMARTCARD_PCSC_PNP_COUNTS_READER_EVENTS), so that a reader
293
+ // plugged in or unplugged between two waits ends the next one at once
294
+ // rather than at the next re-list. SCARD_STATE_UNAWARE until known.
295
+ DWORD pnpCurrentState = SCARD_STATE_UNAWARE;
296
+
297
+ while (running_ && sessionActive->load()) {
298
+ // The context died in a service outage and re-establishing it
299
+ // failed: keep trying, once a second, before anything uses it.
300
+ // (Waiting on the dead handle instead relied on the error that
301
+ // returns, which differs by platform: pcsc-lite says
302
+ // SCARD_E_INVALID_HANDLE, which was in the recovery list below,
303
+ // but WinSCard may say ERROR_INVALID_HANDLE, which isn't.)
304
+ if (!contextValid_) {
305
+ LONG recovered = RecoverContext();
306
+ if (recovered != SCARD_S_SUCCESS) {
307
+ // One error event a second while the service is down
308
+ EmitEvent("error", FormatPCSCError(recovered), 0, {},
309
+ static_cast<DWORD>(recovered));
310
+ // Still down a second after it failed: no reader can be
311
+ // used, so report them all detached (once). On Windows the
312
+ // service stops when its last reader is unplugged, so this
313
+ // is also how that unplug is reported.
314
+ DetachAllReaders();
315
+ PauseBeforeRetry(sessionActive);
316
+ continue;
317
+ }
318
+ // The recovery re-listed the readers
319
+ iterationCount = 0;
320
+ resyncedForUnknownReader = false;
321
+ }
156
322
 
157
- while (running_) {
158
- // Periodic full state refresh to handle Windows PC/SC state drift (Issue #111)
159
- // This ensures we don't miss events if the state tracking gets out of sync
323
+ // Periodic full resync to handle Windows PC/SC state drift (Issue
324
+ // #111). It re-lists readers too, because under constant card
325
+ // activity the wait may not time out, and the timeout path's
326
+ // re-list (see below) catches what the waits can't see.
160
327
  if (++iterationCount >= STATE_REFRESH_INTERVAL) {
161
328
  iterationCount = 0;
162
329
  std::lock_guard<std::mutex> lock(mutex_);
163
-
164
- // Get fresh state for all readers
165
- std::vector<SCARD_READERSTATE> refreshStates;
166
- std::vector<std::string> refreshNames;
167
-
168
- for (const auto& pair : readerStates_) {
169
- refreshNames.push_back(pair.first);
170
- SCARD_READERSTATE state = {};
171
- state.szReader = refreshNames.back().c_str();
172
- state.dwCurrentState = SCARD_STATE_UNAWARE; // Force fresh state
173
- refreshStates.push_back(state);
174
- }
175
-
176
- if (!refreshStates.empty()) {
177
- LONG refreshResult = SCardGetStatusChange(context_, 0, refreshStates.data(), refreshStates.size());
178
- if (refreshResult == SCARD_S_SUCCESS) {
179
- // Check for state divergence and emit missed events
180
- for (size_t i = 0; i < refreshStates.size(); i++) {
181
- const std::string& name = refreshNames[i];
182
- auto it = readerStates_.find(name);
183
- if (it != readerStates_.end()) {
184
- DWORD oldState = it->second.lastState;
185
- DWORD newState = refreshStates[i].dwEventState & ~SCARD_STATE_CHANGED;
186
-
187
- bool wasPresent = (oldState & SCARD_STATE_PRESENT) != 0;
188
- bool isPresent = (newState & SCARD_STATE_PRESENT) != 0;
189
-
190
- if (wasPresent != isPresent) {
191
- // State diverged - emit missed event
192
- std::vector<uint8_t> atr;
193
- if (refreshStates[i].cbAtr > 0) {
194
- atr.assign(refreshStates[i].rgbAtr,
195
- refreshStates[i].rgbAtr + refreshStates[i].cbAtr);
196
- }
197
-
198
- it->second.lastState = newState;
199
- it->second.atr = atr;
200
-
201
- if (isPresent) {
202
- EmitEvent("card-inserted", name, newState, atr);
203
- } else {
204
- EmitEvent("card-removed", name, newState, {});
205
- }
206
- }
207
- }
208
- }
209
- }
210
- }
330
+ ResyncReaderList();
211
331
  }
212
332
 
213
333
  // Build states array using reader names from our map
@@ -216,6 +336,16 @@ void ReaderMonitor::MonitorLoop() {
216
336
  states.clear();
217
337
  readerNames.clear();
218
338
 
339
+ // Reserve for all tracked readers + the PnP entry so no
340
+ // push_back reallocates after szReader pointers are taken: a
341
+ // reallocation moves the strings, and short names live inline
342
+ // in the string object (SSO - 15 chars on MSVC, e.g. "ACS ACR122
343
+ // 0"), so every szReader taken earlier would dangle and
344
+ // SCardGetStatusChange would read garbage. With a single reader
345
+ // the PnP push_back below would otherwise reallocate on the first
346
+ // iteration.
347
+ readerNames.reserve(readerStates_.size() + 1);
348
+
219
349
  // Add known readers - use the map for name-based lookup
220
350
  for (const auto& pair : readerStates_) {
221
351
  SCARD_READERSTATE state = {};
@@ -229,136 +359,112 @@ void ReaderMonitor::MonitorLoop() {
229
359
  readerNames.push_back("\\\\?PnP?\\Notification");
230
360
  SCARD_READERSTATE pnpState = {};
231
361
  pnpState.szReader = readerNames.back().c_str();
232
- pnpState.dwCurrentState = SCARD_STATE_UNAWARE;
362
+ pnpState.dwCurrentState = pnpCurrentState;
233
363
  states.push_back(pnpState);
234
364
  }
235
365
 
236
366
  // Wait for changes (with 1 second timeout for periodic refresh)
237
367
  LONG result = SCardGetStatusChange(context_, 1000, states.data(), states.size());
238
368
 
239
- if (!running_) {
369
+ if (!running_ || !sessionActive->load()) {
240
370
  break;
241
371
  }
242
372
 
243
- if (result == SCARD_E_CANCELLED) {
373
+ if (result == static_cast<LONG>(SCARD_E_CANCELLED)) {
244
374
  break;
245
375
  }
246
376
 
247
- if (result == SCARD_E_TIMEOUT) {
248
- // Timeout - query fresh state to detect missed events (Issue #111)
249
- // On Windows, dwEventState after timeout may just mirror dwCurrentState
250
- // rather than reflecting actual hardware state. We must explicitly
251
- // query with SCARD_STATE_UNAWARE to get the real current state.
252
- std::lock_guard<std::mutex> lock(mutex_);
253
-
254
- if (readerStates_.empty()) {
255
- continue;
256
- }
257
-
258
- // Build fresh state query for all readers
259
- std::vector<SCARD_READERSTATE> freshStates;
260
- std::vector<std::string> freshNames;
261
-
262
- for (const auto& pair : readerStates_) {
263
- freshNames.push_back(pair.first);
264
- SCARD_READERSTATE state = {};
265
- state.szReader = freshNames.back().c_str();
266
- state.dwCurrentState = SCARD_STATE_UNAWARE;
267
- freshStates.push_back(state);
268
- }
269
-
270
- LONG freshResult = SCardGetStatusChange(context_, 0, freshStates.data(), freshStates.size());
271
- if (freshResult != SCARD_S_SUCCESS) {
272
- continue;
273
- }
377
+ // A returned wait has the count in the PnP entry (pushed last);
378
+ // a failed one may not
379
+ if (SMARTCARD_PCSC_PNP_COUNTS_READER_EVENTS &&
380
+ (result == SCARD_S_SUCCESS ||
381
+ result == static_cast<LONG>(SCARD_E_TIMEOUT))) {
382
+ pnpCurrentState = states.back().dwEventState & 0xFFFF0000;
383
+ }
274
384
 
275
- for (size_t i = 0; i < freshStates.size(); i++) {
276
- const std::string& name = freshNames[i];
277
- auto it = readerStates_.find(name);
278
- if (it != readerStates_.end()) {
279
- DWORD freshState = freshStates[i].dwEventState & ~SCARD_STATE_CHANGED;
280
- DWORD storedState = it->second.lastState;
281
-
282
- bool wasPresent = (storedState & SCARD_STATE_PRESENT) != 0;
283
- bool isPresent = (freshState & SCARD_STATE_PRESENT) != 0;
284
-
285
- if (wasPresent != isPresent) {
286
- std::vector<uint8_t> atr;
287
- if (freshStates[i].cbAtr > 0) {
288
- atr.assign(freshStates[i].rgbAtr,
289
- freshStates[i].rgbAtr + freshStates[i].cbAtr);
290
- }
291
-
292
- it->second.lastState = freshState;
293
- it->second.atr = atr;
294
-
295
- if (isPresent) {
296
- EmitEvent("card-inserted", name, freshState, atr);
297
- } else {
298
- EmitEvent("card-removed", name, freshState, {});
299
- }
300
- }
301
- }
302
- }
385
+ // A reader passed to the wait has gone: pcsc-lite checks every name
386
+ // before waiting and rejects the whole call, so every later wait
387
+ // would fail the same way and no reader's events get through
388
+ // (spec/README.md, finding 3). An unplug is routine, so re-list and
389
+ // wait again at once - no error event, no sleep. If it fails the
390
+ // same way straight after a re-list, take the error path below (one
391
+ // error a second, still re-listing) so a lasting failure can't spin.
392
+ bool unknownReader = result == static_cast<LONG>(SCARD_E_UNKNOWN_READER);
393
+ if (unknownReader && !resyncedForUnknownReader) {
394
+ resyncedForUnknownReader = true;
395
+ std::lock_guard<std::mutex> lock(mutex_);
396
+ ResyncReaderList();
397
+ continue;
398
+ }
399
+ resyncedForUnknownReader = unknownReader;
400
+
401
+ if (result == static_cast<LONG>(SCARD_E_TIMEOUT)) {
402
+ // Timeout - re-list readers and re-read every reader with
403
+ // SCARD_STATE_UNAWARE to catch missed events:
404
+ // - On Windows, dwEventState after timeout may just mirror
405
+ // dwCurrentState rather than the hardware (Issue #111).
406
+ // - Without a reader event count (see pnpCurrentState) the PnP
407
+ // entry reports only reader changes made during a call; a
408
+ // reader plugged in between two waits is otherwise never
409
+ // announced (spec/README.md, finding 2). With the count, one
410
+ // plugged in before the first wait still isn't.
411
+ // - pcsc-lite compares a reader's card event counter only if
412
+ // the one passed in is nonzero, so a card swapped between
413
+ // waits in a reader that was plugged in with it doesn't end
414
+ // the wait (Events-seeded-swap).
415
+ // That is the periodic resync's work too, so restart its count.
416
+ iterationCount = 0;
417
+ std::lock_guard<std::mutex> lock(mutex_);
418
+ ResyncReaderList();
303
419
  continue;
304
420
  }
305
421
 
306
422
  if (result != SCARD_S_SUCCESS) {
307
- // Error - emit and continue
308
- EmitEvent("error", GetPCSCErrorString(result), 0, {});
309
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
423
+ // Error - emit and continue. The numeric code rides in the
424
+ // event's code field (and the message, for message-only
425
+ // consumers); state stays 0 so it keeps its bitmask meaning.
426
+ EmitEvent("error", FormatPCSCError(result), 0, {}, static_cast<DWORD>(result));
427
+
428
+ // The context is dead: release it. The top of the loop
429
+ // re-establishes it after the pause - once a second until the
430
+ // service is back - so there is one recovery path, and it
431
+ // can't spin.
432
+ DWORD ucode = static_cast<DWORD>(result);
433
+ if (IsContextFatal(result)) {
434
+ // mutex_ also guards context_/contextValid_ against Stop()
435
+ // and the destructor reading them for SCardCancel
436
+ std::lock_guard<std::mutex> lock(mutex_);
437
+ if (contextValid_) {
438
+ SCardReleaseContext(context_);
439
+ contextValid_ = false;
440
+ }
441
+ context_ = 0;
442
+ } else if (ucode == SCARD_E_UNKNOWN_READER) {
443
+ // Still failing after the re-list above: keep re-listing,
444
+ // once a second
445
+ std::lock_guard<std::mutex> lock(mutex_);
446
+ ResyncReaderList();
447
+ }
448
+
449
+ PauseBeforeRetry(sessionActive);
310
450
  continue;
311
451
  }
312
452
 
313
453
  // Process changes - use reader name for lookup (Issue #111 fix)
314
454
  std::lock_guard<std::mutex> lock(mutex_);
315
- bool pnpTriggered = false;
316
455
 
317
456
  for (size_t i = 0; i < states.size(); i++) {
318
457
  if (!(states[i].dwEventState & SCARD_STATE_CHANGED)) {
319
458
  continue;
320
459
  }
321
460
 
322
- // PnP notification - reader list changed
461
+ // PnP notification - reader list changed. The PnP entry is
462
+ // always pushed last, and ResyncReaderList rebuilds the map, so
463
+ // stop here: any entry processed after it would apply stale
464
+ // states[] data against the rebuilt map.
323
465
  if (readerNames[i] == "\\\\?PnP?\\Notification") {
324
- pnpTriggered = true;
325
- // Get old reader names
326
- std::vector<std::string> oldNames;
327
- for (const auto& pair : readerStates_) {
328
- oldNames.push_back(pair.first);
329
- }
330
-
331
- // Update reader list (this rebuilds readerStates_ map)
332
- UpdateReaderList();
333
-
334
- // Find new readers
335
- for (const auto& pair : readerStates_) {
336
- bool found = false;
337
- for (const auto& old : oldNames) {
338
- if (old == pair.first) {
339
- found = true;
340
- break;
341
- }
342
- }
343
- if (!found) {
344
- EmitEvent("reader-attached", pair.first, pair.second.lastState, pair.second.atr);
345
- }
346
- }
347
-
348
- // Find removed readers
349
- for (const auto& old : oldNames) {
350
- if (readerStates_.find(old) == readerStates_.end()) {
351
- EmitEvent("reader-detached", old, 0, {});
352
- }
353
- }
354
- continue;
355
- }
356
-
357
- // Skip reader state processing if PnP was triggered in this iteration
358
- // The reader list has changed, so indices are no longer valid
359
- // We'll pick up any card changes on the next iteration with fresh state
360
- if (pnpTriggered) {
361
- continue;
466
+ ResyncReaderList();
467
+ break;
362
468
  }
363
469
 
364
470
  // Reader state change - look up by name, not index (Issue #111 fix)
@@ -366,45 +472,127 @@ void ReaderMonitor::MonitorLoop() {
366
472
  auto it = readerStates_.find(readerName);
367
473
 
368
474
  if (it != readerStates_.end()) {
369
- DWORD oldState = it->second.lastState;
370
- DWORD newState = states[i].dwEventState;
475
+ ApplyCardStateChange(it->second, readerName, states[i]);
476
+ }
477
+ }
478
+ }
479
+ }
371
480
 
372
- bool wasPresent = (oldState & SCARD_STATE_PRESENT) != 0;
373
- bool isPresent = (newState & SCARD_STATE_PRESENT) != 0;
481
+ // Re-establish the context after a service outage. On success tell JS
482
+ // (monitor-recovered), then report what changed during the outage.
483
+ LONG ReaderMonitor::RecoverContext() {
484
+ // Establish outside mutex_: it can take a while when the service is
485
+ // starting, and Shutdown() needs mutex_ to cancel
486
+ SCARDCONTEXT context = 0;
487
+ LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
488
+ if (result != SCARD_S_SUCCESS) {
489
+ return result;
490
+ }
491
+ std::lock_guard<std::mutex> lock(mutex_);
492
+ context_ = context;
493
+ contextValid_ = true;
494
+ // JS's own context died in the same outage. Tell it first, so it
495
+ // replaces that context before handling the card events below.
496
+ EmitEvent("monitor-recovered", "", 0, {});
497
+ // Reader states were tracked against the dead context: rebuild them.
498
+ // Every card handle died too, so each card still in its reader is
499
+ // reported as replaced, and JS connects to it again. (If the readers
500
+ // were reported detached during the outage, they are attached again.)
501
+ ResyncReaderList(true);
502
+ return SCARD_S_SUCCESS;
503
+ }
374
504
 
375
- // Get ATR
376
- std::vector<uint8_t> atr;
377
- if (states[i].cbAtr > 0) {
378
- atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
379
- }
505
+ // The service is unavailable: report every reader detached and forget
506
+ // them. Recovery's resync attaches whatever is there when it is back.
507
+ void ReaderMonitor::DetachAllReaders() {
508
+ std::lock_guard<std::mutex> lock(mutex_);
509
+ for (const auto& pair : readerStates_) {
510
+ EmitEvent("reader-detached", pair.first, 0, {});
511
+ }
512
+ readerStates_.clear();
513
+ outagePending_ = false;
514
+ }
380
515
 
381
- // Update stored state using the map
382
- it->second.lastState = newState & ~SCARD_STATE_CHANGED;
383
- it->second.atr = atr;
516
+ // The 1 s pause between retries on the error path. Shutdown() cuts it
517
+ // short, so stop(), the destructor and the teardown hook don't wait it out.
518
+ void ReaderMonitor::PauseBeforeRetry(const std::shared_ptr<std::atomic<bool>>& sessionActive) {
519
+ std::unique_lock<std::mutex> lock(pauseMutex_);
520
+ pauseCv_.wait_for(lock, std::chrono::milliseconds(1000), [&] {
521
+ return !running_ || !sessionActive->load();
522
+ });
523
+ }
384
524
 
385
- // Emit appropriate event
386
- if (!wasPresent && isPresent) {
387
- EmitEvent("card-inserted", readerName, newState, atr);
388
- } else if (wasPresent && !isPresent) {
389
- EmitEvent("card-removed", readerName, newState, {});
390
- }
391
- }
525
+ // Rebuild readerStates_ and emit the difference: reader-attached/detached
526
+ // for membership changes, card-inserted/removed for presence changes and
527
+ // swaps on surviving readers. Needed because UpdateReaderList re-seeds
528
+ // lastState from a fresh SCARD_STATE_UNAWARE query, which would otherwise
529
+ // silently latch away any transition that happened since the last wait
530
+ // (PnP churn, a vanished reader, a timeout, or a service outage the
531
+ // recovery path just healed). Caller holds mutex_. acrossOutage: the old
532
+ // states were read before a service outage (see RecoverContext).
533
+ void ReaderMonitor::ResyncReaderList(bool acrossOutage) {
534
+ std::unordered_map<std::string, DWORD> oldStates;
535
+ for (const auto& pair : readerStates_) {
536
+ oldStates[pair.first] = pair.second.lastState;
537
+ }
538
+
539
+ bool fresh = UpdateReaderList();
540
+
541
+ // Across an outage only a fresh reading shows which cards are still
542
+ // there; if this one isn't, the next resync owes the comparison
543
+ acrossOutage = acrossOutage || outagePending_;
544
+ outagePending_ = acrossOutage && !fresh;
545
+ bool replaceHeldCards = acrossOutage && fresh;
546
+
547
+ for (const auto& pair : readerStates_) {
548
+ if (oldStates.find(pair.first) == oldStates.end()) {
549
+ EmitEvent("reader-attached", pair.first, pair.second.lastState, pair.second.atr);
392
550
  }
393
551
  }
552
+
553
+ for (const auto& pair : oldStates) {
554
+ if (readerStates_.find(pair.first) == readerStates_.end()) {
555
+ EmitEvent("reader-detached", pair.first, 0, {});
556
+ }
557
+ }
558
+
559
+ for (const auto& pair : readerStates_) {
560
+ auto oldIt = oldStates.find(pair.first);
561
+ if (oldIt == oldStates.end()) {
562
+ continue; // New reader - reader-attached already emitted
563
+ }
564
+ CardEvent event = replaceHeldCards
565
+ ? DetectCardStateChangeAcrossOutage(oldIt->second, pair.second.lastState,
566
+ SCARD_STATE_PRESENT)
567
+ : DetectCardStateChange(oldIt->second, pair.second.lastState,
568
+ SCARD_STATE_PRESENT,
569
+ SMARTCARD_PCSC_COUNTS_CARD_EVENTS);
570
+ EmitCardEvent(event, pair.first, pair.second.lastState, pair.second.atr);
571
+ }
394
572
  }
395
573
 
396
- void ReaderMonitor::UpdateReaderList() {
574
+ // Returns whether readerStates_ now comes from a fresh reading (false: it
575
+ // kept what it had, because a call failed)
576
+ bool ReaderMonitor::UpdateReaderList() {
397
577
  // Get reader list size
398
578
  DWORD readersLen = 0;
399
579
  LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
400
580
 
401
- if (result == SCARD_E_NO_READERS_AVAILABLE || readersLen == 0) {
581
+ if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
402
582
  readerStates_.clear();
403
- return;
583
+ return true;
404
584
  }
405
585
 
586
+ // Any other failure (the service went away, say) says nothing about
587
+ // the readers: keep the map rather than report every reader detached.
588
+ // readersLen is left untouched on failure, so check this first.
406
589
  if (result != SCARD_S_SUCCESS) {
407
- return;
590
+ return false;
591
+ }
592
+
593
+ if (readersLen == 0) {
594
+ readerStates_.clear();
595
+ return true;
408
596
  }
409
597
 
410
598
  // Get reader names
@@ -412,7 +600,7 @@ void ReaderMonitor::UpdateReaderList() {
412
600
  result = SCardListReaders(context_, nullptr, buffer.data(), &readersLen);
413
601
 
414
602
  if (result != SCARD_S_SUCCESS) {
415
- return;
603
+ return false;
416
604
  }
417
605
 
418
606
  // Parse multi-string
@@ -430,43 +618,98 @@ void ReaderMonitor::UpdateReaderList() {
430
618
  states[i].dwCurrentState = SCARD_STATE_UNAWARE;
431
619
  }
432
620
 
433
- SCardGetStatusChange(context_, 0, states.data(), states.size());
621
+ LONG statusResult = SCardGetStatusChange(context_, 0, states.data(), states.size());
622
+ if (statusResult == static_cast<LONG>(SCARD_E_UNKNOWN_READER)) {
623
+ // A listed reader vanished before this read (pcsc-lite rejects the
624
+ // whole call). Keep the current map rather than announce readers
625
+ // with no state; the next resync lists again.
626
+ return false;
627
+ }
628
+ bool seeded = (statusResult == SCARD_S_SUCCESS);
434
629
 
435
630
  // Update reader states map (Issue #111 fix: use map keyed by name)
436
- readerStates_.clear();
631
+ std::unordered_map<std::string, ReaderInfo> newStates;
437
632
  for (size_t i = 0; i < newNames.size(); i++) {
438
633
  ReaderInfo info;
439
- info.lastState = states[i].dwEventState & ~SCARD_STATE_CHANGED;
440
- if (states[i].cbAtr > 0) {
441
- info.atr.assign(states[i].rgbAtr, states[i].rgbAtr + states[i].cbAtr);
634
+ info.lastState = SCARD_STATE_UNAWARE;
635
+ if (seeded) {
636
+ // Never store SCARD_STATE_IGNORE: fed back as dwCurrentState it
637
+ // excludes the reader from future waits (as ApplyCardStateChange)
638
+ info.lastState = states[i].dwEventState & ~(SCARD_STATE_CHANGED | SCARD_STATE_IGNORE);
639
+ DWORD atrLen = states[i].cbAtr;
640
+ if (atrLen > sizeof(states[i].rgbAtr)) {
641
+ atrLen = sizeof(states[i].rgbAtr);
642
+ }
643
+ if (atrLen > 0) {
644
+ info.atr.assign(states[i].rgbAtr, states[i].rgbAtr + atrLen);
645
+ }
646
+ } else {
647
+ // Seed query failed: keep what we already knew about this reader
648
+ // instead of zeroing it - a zeroed lastState reads as a card
649
+ // removal to ResyncReaderList and as UNAWARE to the main wait.
650
+ auto existing = readerStates_.find(newNames[i]);
651
+ if (existing != readerStates_.end()) {
652
+ info = existing->second;
653
+ }
442
654
  }
443
- readerStates_[newNames[i]] = info;
655
+ newStates[newNames[i]] = info;
444
656
  }
657
+ readerStates_ = std::move(newStates);
658
+ return seeded;
445
659
  }
446
660
 
447
661
  void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& readerName,
448
- DWORD state, const std::vector<uint8_t>& atr) {
449
- // Use shared_ptr to ensure memory is freed even if ThreadSafeFunction is released
450
- // before the callback executes (prevents memory leak)
451
- auto data = std::make_shared<EventData>(EventData{eventType, readerName, state, atr});
452
-
453
- // Call JavaScript callback on main thread
454
- // Capture shared_ptr by value to extend lifetime until callback executes
455
- tsfn_.BlockingCall(data.get(), [data](Napi::Env env, Napi::Function callback, EventData* ptr) {
456
- // Build event object
457
- Napi::Object event = Napi::Object::New(env);
458
- event.Set("type", Napi::String::New(env, ptr->eventType));
459
- event.Set("reader", Napi::String::New(env, ptr->readerName));
460
- event.Set("state", Napi::Number::New(env, ptr->state));
461
-
462
- if (!ptr->atr.empty()) {
463
- event.Set("atr", Napi::Buffer<uint8_t>::Copy(env, ptr->atr.data(), ptr->atr.size()));
662
+ DWORD state, const std::vector<uint8_t>& atr, DWORD code) {
663
+ // Owned by the tsfn's queue from here: DeliverEvent frees it.
664
+ // If the tsfn won't take it (closing), it was never queued.
665
+ auto* data = new EventData{eventType, readerName, state, atr, code};
666
+ if (tsfn_.BlockingCall(data) != napi_ok) {
667
+ delete data;
668
+ }
669
+ }
670
+
671
+ void ReaderMonitor::DeliverEvent(Napi::Env env, Napi::Function callback,
672
+ std::nullptr_t* /*context*/, EventData* data) {
673
+ std::unique_ptr<EventData> owned(data);
674
+
675
+ // Node is draining the queue because the environment is being torn
676
+ // down (a worker exiting) before the event was dispatched
677
+ if (static_cast<napi_env>(env) == nullptr || callback.IsEmpty()) {
678
+ return;
679
+ }
680
+
681
+ napi_value event;
682
+ napi_value recv;
683
+ try {
684
+ Napi::Object object = Napi::Object::New(env);
685
+ object.Set("type", Napi::String::New(env, owned->eventType));
686
+ object.Set("reader", Napi::String::New(env, owned->readerName));
687
+ object.Set("state", Napi::Number::New(env, owned->state));
688
+ if (!owned->atr.empty()) {
689
+ object.Set("atr", Napi::Buffer<uint8_t>::Copy(env, owned->atr.data(),
690
+ owned->atr.size()));
464
691
  } else {
465
- event.Set("atr", env.Null());
692
+ object.Set("atr", env.Null());
466
693
  }
694
+ if (owned->code != 0) {
695
+ object.Set("code", Napi::Number::New(env, owned->code));
696
+ }
697
+ event = object;
698
+ } catch (const Napi::Error& e) {
699
+ // A live environment gets the exception, as before; one that is
700
+ // shutting down can't take it, and the event is dropped
701
+ napi_throw(env, e.Value());
702
+ return;
703
+ }
704
+ if (napi_get_undefined(env, &recv) != napi_ok) {
705
+ return;
706
+ }
467
707
 
468
- // Call the callback
469
- callback.Call({event});
470
- // shared_ptr automatically cleaned up when lambda is destroyed
471
- });
708
+ // Through the C API, not callback.Call(): if the callback throws, its
709
+ // exception stays pending and Node reports it as uncaught (as before);
710
+ // if the call is refused because the environment is shutting down,
711
+ // the event is dropped. callback.Call() turned that refusal into a C++
712
+ // exception which node-addon-api, unable to throw it into JS, rethrew
713
+ // into Node - std::terminate, killing the whole process.
714
+ napi_call_function(env, recv, callback, 1, &event, nullptr);
472
715
  }