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