1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! NFC (Near Field Communication) client implementation
//!
//! Uses PC/SC (Personal Computer/Smart Card) API for cross-platform NFC reader support:
//! - Windows: Native WinSCard.dll
//! - macOS: Native PCSC framework
//! - Linux: PCSC lite library (pcscd daemon)
//!
//! Supports ISO14443 A/B cards, MIFARE, NFC tags via APDU commands and NDEF messages.
pub mod actions;
pub mod ndef;
use crate::client::llm_budget::call_llm_for_client;
use crate::client::nfc::actions::*;
use crate::llm::ollama_client::OllamaClient;
use crate::protocol::Event;
use crate::state::app_state::AppState;
use crate::state::ClientId;
use anyhow::{anyhow, Context, Result};
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{error, info, trace, warn};
// Re-export protocol
pub use actions::NfcClientProtocol;
/// What applying one action to the PC/SC reader actually did.
///
/// `Sent` is reported only when an APDU was really handed to a card that
/// answered — those bytes crossed the contactless interface. Everything else
/// says specifically why nothing did.
/// How many LLM turns one card exchange may take before the chain is cut.
///
/// Executing an event's answer makes the cycle real: an APDU produces
/// `nfc_apdu_response`, whose answer may be another APDU — which is exactly the
/// select-then-read conversation a smartcard requires, so it must be possible, and
/// bounded rather than forbidden.
const MAX_FOLLOWUP_DEPTH: u8 = 6;
/// Largest `Le` a short-form READ BINARY can ask for. `Le` of `00` means 256, but asking for
/// 255 keeps the request unambiguous and inside every tag's `MLe`.
const MAX_SHORT_READ: usize = 255;
/// Largest data field one short-form UPDATE BINARY carries. `Lc` reaches 255, and the margin
/// keeps the whole command inside the 261-byte short-APDU envelope some readers enforce.
const MAX_SHORT_WRITE: usize = 249;
pub enum NfcApplied {
/// This many APDU bytes reached the card; the response APDU is attached so
/// the caller can log it.
Sent {
bytes_sent: usize,
response_hex: String,
},
/// The action ran but nothing reached a card; the string says why.
Executed(String),
/// The card session was ended.
Disconnected,
}
/// NFC client implementation
pub struct NfcClient;
impl NfcClient {
/// Connect to NFC reader and start LLM integration loop
pub async fn connect_with_llm_actions(
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
client_id: ClientId,
startup_params: Value,
) -> Result<SocketAddr> {
info!("Starting NFC client via PC/SC...");
// Extract reader selection from startup params
let reader_index = startup_params["reader_index"].as_u64().unwrap_or(0) as usize;
let reader_name = startup_params["reader_name"]
.as_str()
.map(|s| s.to_string());
// Create PC/SC context
let ctx = pcsc::Context::establish(pcsc::Scope::User)
.context("Failed to establish PC/SC context. Is pcscd running (Linux)?")?;
// List available readers
let readers_buf = ctx
.list_readers_owned()
.context("Failed to list PC/SC readers")?;
if readers_buf.is_empty() {
return Err(anyhow!(
"No PC/SC readers found. Please connect an NFC reader (e.g., ACR122U)"
));
}
let readers: Vec<String> = readers_buf
.iter()
.map(|r| r.to_string_lossy().to_string())
.collect();
info!("Found {} PC/SC reader(s): {:?}", readers.len(), readers);
// Select reader. Keep the `CString` form: that is what `Context::connect`
// wants, and round-tripping through `String` can lose a non-UTF-8 name.
let selected_reader: std::ffi::CString = if let Some(name) = reader_name {
readers_buf
.iter()
.find(|r| r.to_string_lossy().contains(&name))
.ok_or_else(|| anyhow!("Reader '{}' not found", name))?
.clone()
} else {
readers_buf
.get(reader_index)
.ok_or_else(|| anyhow!("Reader index {} out of range", reader_index))?
.clone()
};
let selected_reader_name = selected_reader.to_string_lossy().to_string();
info!("Using PC/SC reader: {}", selected_reader_name);
let _ = status_tx.send(format!("Using NFC reader: {}", selected_reader_name));
// Command channel for injected actions (the dashboard's [ send ]).
// Registered BEFORE the readers-listed LLM call below: a dashboard-created
// client defaults to a `*` -> manual rule, so that call can park for minutes
// waiting for a human, and the operator must be able to reach the reader while
// it waits.
let command_rx =
crate::client::command_support::register_command_channel(&app_state, client_id).await;
let cmd_task = tokio::spawn({
let ctx = ctx.clone();
let reader = selected_reader.clone();
let app_state = app_state.clone();
let llm_client = llm_client.clone();
let status_tx = status_tx.clone();
async move {
Self::command_loop(
command_rx, ctx, reader, client_id, app_state, llm_client, status_tx,
)
.await;
}
});
app_state.register_client_task(client_id, cmd_task).await;
// Watch the reader for cards arriving and leaving.
//
// nfc_card_detected and nfc_card_disconnected are both advertised in
// get_event_types(), so the model can be told a card will appear and write a
// handler for it -- and nothing raised either, so that handler waited forever. A
// card being presented is the entire trigger an NFC client exists to react to; its
// example answer is `read_ndef`, which is now implemented and reachable.
let watch_ctx = ctx.clone();
let watch_reader = selected_reader.clone();
let watch_state = app_state.clone();
let watch_llm = llm_client.clone();
let watch_tx = status_tx.clone();
let watch_task = tokio::spawn(async move {
let mut present = false;
loop {
if watch_state.get_client(client_id).await.is_none() {
return;
}
// PC/SC is a blocking C API, so the probe runs on the blocking pool.
//
// `status2_owned` rather than `get_attribute(AtrString)`: it returns the ATR
// *and* the negotiated transmission protocol in one call, and `protocol` is
// declared on nfc_card_detected. It used to be declared and never emitted.
let probe_ctx = watch_ctx.clone();
let probe_reader = watch_reader.clone();
let probe = tokio::task::spawn_blocking(move || -> Option<(String, String)> {
let card = probe_ctx
.connect(&probe_reader, pcsc::ShareMode::Shared, pcsc::Protocols::ANY)
.ok()?;
let status = card.status2_owned().ok()?;
let protocol = match status.protocol2() {
Some(pcsc::Protocol::T0) => "T0",
Some(pcsc::Protocol::T1) => "T1",
Some(pcsc::Protocol::RAW) => "RAW",
None => "undefined",
};
Some((hex::encode_upper(status.atr()), protocol.to_string()))
})
.await
.unwrap_or(None);
match (present, probe) {
(false, Some((atr, protocol))) => {
present = true;
info!(
"NFC client {} card detected (ATR {}, protocol {})",
client_id, atr, protocol
);
Self::raise_card_event(
&NFC_CARD_DETECTED_EVENT,
serde_json::json!({ "atr": atr, "protocol": protocol }),
&watch_ctx,
&watch_reader,
0,
client_id,
&watch_state,
&watch_llm,
&watch_tx,
)
.await;
}
(true, None) => {
present = false;
info!("NFC client {} card removed", client_id);
Self::raise_card_event(
&NFC_CARD_DISCONNECTED_EVENT,
serde_json::json!({}),
&watch_ctx,
&watch_reader,
0,
client_id,
&watch_state,
&watch_llm,
&watch_tx,
)
.await;
}
_ => {}
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
});
app_state.register_client_task(client_id, watch_task).await;
// Send initial event to LLM: readers listed
{
let event = Event::new(
&NFC_READERS_LISTED_EVENT,
json!({ "readers": readers.clone() }),
);
// Get default instruction from startup params or use default
let instruction = startup_params["instruction"]
.as_str()
.unwrap_or("Monitor NFC reader and respond to card events");
// Create protocol instance for action definitions
let protocol = Arc::new(NfcClientProtocol);
// A failing readers-listed call must not kill the client: the command
// channel is already registered and an operator can drive the reader by
// hand, which is exactly the case a `*` -> manual rule sets up.
match call_llm_for_client(
&llm_client,
&app_state,
client_id.to_string(),
instruction,
"", // No memory yet
Some(&event),
protocol.as_ref(),
&status_tx,
)
.await
{
Ok(result) => {
for action in result.actions {
let applied = Self::apply_nfc_action(
&ctx,
&selected_reader,
action.clone(),
0,
client_id,
&app_state,
&llm_client,
&status_tx,
)
.await;
if matches!(applied, Ok(NfcApplied::Disconnected)) {
break;
}
if let Err(e) = applied {
error!("NFC client {} action error: {}", client_id, e);
}
}
}
Err(e) => {
error!("LLM error for NFC client {}: {}", client_id, e);
}
}
}
// Return dummy socket address (NFC doesn't use network sockets)
Ok(SocketAddr::from(([127, 0, 0, 1], 0)))
}
/// Drain injected commands until the channel closes (the client was removed,
/// which drops the handle) or an injected `disconnect_card` ends the session.
///
/// The generic `command_support::handle_stream_client_command` cannot serve this
/// client: it owns no socket, and every NFC verb yields a
/// `ClientActionResult::Custom` that only PC/SC can carry out. So the action goes
/// through [`Self::apply_nfc_action`] — the same function the readers-listed LLM
/// path uses — and the outcome is recorded and replied the way the generic arm
/// does it.
async fn command_loop(
mut command_rx: tokio::sync::mpsc::Receiver<crate::state::client_handles::ClientCommand>,
ctx: pcsc::Context,
reader: std::ffi::CString,
client_id: ClientId,
app_state: Arc<AppState>,
llm_client: OllamaClient,
status_tx: mpsc::UnboundedSender<String>,
) {
use crate::llm::actions::protocol_trait::Protocol;
use crate::state::client_handles::ClientSendOutcome;
use crate::state::AccessLogOwner;
let protocol = NfcClientProtocol;
while let Some(command) = command_rx.recv().await {
let action = command.action.clone();
let mut extra_log: Vec<serde_json::Value> = Vec::new();
let outcome: anyhow::Result<ClientSendOutcome> = match Self::apply_nfc_action(
&ctx,
&reader,
action.clone(),
0,
client_id,
&app_state,
&llm_client,
&status_tx,
)
.await
{
Ok(NfcApplied::Sent {
bytes_sent,
response_hex,
}) => {
extra_log.push(json!({ "response_hex": response_hex }));
Ok(ClientSendOutcome::Sent { bytes_sent })
}
Ok(NfcApplied::Executed(detail)) => Ok(ClientSendOutcome::Executed { detail }),
Ok(NfcApplied::Disconnected) => Ok(ClientSendOutcome::Disconnected),
Err(e) => Ok(ClientSendOutcome::Rejected {
error: e.to_string(),
}),
};
let mut responses = vec![match &outcome {
Ok(outcome) => serde_json::to_value(outcome).unwrap_or(serde_json::Value::Null),
Err(e) => json!({ "error": e.to_string() }),
}];
responses.append(&mut extra_log);
app_state
.record_access_log(
AccessLogOwner::Client(client_id.as_u32()),
protocol.protocol_name(),
None,
"injected_action",
action,
responses,
)
.await;
let disconnect = matches!(outcome, Ok(ClientSendOutcome::Disconnected));
let _ = status_tx.send("__UPDATE_UI__".to_string());
crate::client::command_support::reply(command, outcome);
if disconnect {
break;
}
}
// Every exit path lands here: drop the command handle so the dashboard stops
// offering [ send ] on a client whose loop is gone.
app_state.remove_client_handle(client_id).await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
}
/// Carry one action out against the reader. Shared by the readers-listed LLM path
/// and injected commands so the PC/SC calls exist exactly once.
///
/// `Err` means the protocol rejected the action (unknown verb / bad params); a
/// PC/SC failure is `Ok(Executed(..))` with the reason, because the action did run.
/// Raise one card-presence event at the model.
///
/// Executes nothing it answers with: the command loop owns the card path, and a
/// presence-driven action chain would re-fire every time a card is tapped.
#[allow(clippy::too_many_arguments)]
async fn raise_card_event(
event_type: &'static std::sync::LazyLock<crate::protocol::EventType>,
data: serde_json::Value,
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
depth: u8,
client_id: ClientId,
app_state: &Arc<AppState>,
llm_client: &OllamaClient,
status_tx: &mpsc::UnboundedSender<String>,
) {
let Some(instruction) = app_state.get_instruction_for_client(client_id).await else {
return;
};
let memory = app_state
.get_memory_for_client(client_id)
.await
.unwrap_or_default();
let event = Event::new(event_type, data);
match call_llm_for_client(
llm_client,
app_state,
client_id.to_string(),
&instruction,
&memory,
Some(&event),
&NfcClientProtocol,
status_tx,
)
.await
{
Ok(result) => {
if let Some(mem) = result.memory_updates {
app_state.set_memory_for_client(client_id, mem).await;
}
Self::run_followups(
result.actions,
ctx,
reader,
depth,
client_id,
app_state,
llm_client,
status_tx,
)
.await;
}
Err(e) => {
error!("NFC client {} LLM error on card event: {}", client_id, e);
}
}
}
/// NDEF file identifier, defaulting to E104 -- the value nearly every Type 4 tag uses
/// and the one the Capability Container normally points at.
fn ndef_file_id(data: &serde_json::Value) -> [u8; 2] {
data.get("file_id")
.and_then(|v| v.as_str())
.and_then(|s| hex::decode(s.trim()).ok())
.filter(|b| b.len() == 2)
.map(|b| [b[0], b[1]])
.unwrap_or([0xE1, 0x04])
}
/// Transmit one APDU on a freshly-connected card. Blocking PC/SC, off the runtime.
async fn transmit_apdu(
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
apdu: Vec<u8>,
) -> Result<Vec<u8>> {
let ctx = ctx.clone();
let reader = reader.to_owned();
tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
let card = ctx
.connect(&reader, pcsc::ShareMode::Shared, pcsc::Protocols::ANY)
.context("PC/SC connect failed (is a card on the reader?)")?;
let mut rx = vec![0u8; pcsc::MAX_BUFFER_SIZE];
let response = card
.transmit(&apdu, &mut rx)
.context("PC/SC transmit failed")?;
Ok(response.to_vec())
})
.await
.context("PC/SC blocking task panicked")?
}
/// True when an APDU response ends in the success status word 0x9000.
fn apdu_ok(response: &[u8]) -> bool {
response.len() >= 2 && response[response.len() - 2..] == [0x90, 0x00]
}
/// Read the NDEF message from an NFC Forum Type 4 tag.
///
/// The sequence is fixed by NFC Forum Type 4 Tag Operation: SELECT the NDEF
/// application by AID D2760000850101, SELECT the NDEF file by `file_id`, then READ
/// BINARY -- first the two-byte NLEN, then that many bytes. It is expressed here as
/// ordinary APDUs so it rides the same PC/SC transmit path `send_apdu` uses.
///
/// **It does not read the Capability Container**, though this comment used to say it
/// took the file ID from there. `file_id` is a parameter defaulting to E104, which is
/// what nearly every tag's CC points at; the CC's `MLe`/`MLc` read and write limits are
/// ignored too, so a tag that answers fewer bytes than asked is the case below.
///
/// Untested against real hardware: this machine has no PC/SC reader. The byte
/// sequences are taken from the specification rather than observed, which is what
/// `Experimental` is for -- see `src/client/nfc/CLAUDE.md`.
async fn read_ndef(
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
file_id: [u8; 2],
) -> Result<Vec<u8>> {
// SELECT the NDEF application (by name).
let select_app = vec![
0x00, 0xA4, 0x04, 0x00, 0x07, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01, 0x00,
];
let r = Self::transmit_apdu(ctx, reader, select_app).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!(
"SELECT NDEF application refused (SW {})",
hex::encode_upper(&r)
);
}
// SELECT the NDEF file (by identifier).
let select_file = vec![0x00, 0xA4, 0x00, 0x0C, 0x02, file_id[0], file_id[1]];
let r = Self::transmit_apdu(ctx, reader, select_file).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!("SELECT NDEF file refused (SW {})", hex::encode_upper(&r));
}
// READ BINARY the 2-byte NLEN header, then the message itself.
let r = Self::transmit_apdu(ctx, reader, vec![0x00, 0xB0, 0x00, 0x00, 0x02]).await?;
if !Self::apdu_ok(&r) || r.len() < 4 {
anyhow::bail!("READ BINARY of NLEN failed (SW {})", hex::encode_upper(&r));
}
let nlen = u16::from_be_bytes([r[0], r[1]]) as usize;
if nlen == 0 {
return Ok(Vec::new());
}
let mut message = Vec::with_capacity(nlen);
let mut offset = 2usize;
while message.len() < nlen {
// `Le` is a maximum, not a promise: a tag may answer fewer bytes than asked,
// and its CC's MLe may be well under 255. So the offset advances by what came
// *back*, not by what was requested - advancing by the request skipped every
// byte the tag withheld, and a tag answering zero data bytes made this loop
// run forever, hammering the card.
let want = std::cmp::min(MAX_SHORT_READ, nlen - message.len());
let offset_bytes = Self::read_binary_offset(offset)?;
let apdu = vec![
0x00,
0xB0,
offset_bytes[0],
offset_bytes[1],
// Bounded by MAX_SHORT_READ (255) immediately above.
want as u8,
];
let r = Self::transmit_apdu(ctx, reader, apdu).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!("READ BINARY failed (SW {})", hex::encode_upper(&r));
}
let got = &r[..r.len() - 2];
if got.is_empty() {
anyhow::bail!(
"READ BINARY returned 9000 with no data at offset {offset} while {} of {} \
byte(s) are still outstanding; the tag is not making progress",
nlen - message.len(),
nlen
);
}
message.extend_from_slice(got);
offset += got.len();
}
message.truncate(nlen);
Ok(message)
}
/// P1 P2 of a READ/UPDATE BINARY, refusing an offset the two bytes cannot hold.
///
/// `(offset >> 8) as u8` wraps silently past 65535, and a wrapped offset is not a failed
/// command: it is a *successful* read or write of the wrong part of the file.
fn read_binary_offset(offset: usize) -> Result<[u8; 2]> {
let offset = u16::try_from(offset).map_err(|_| {
anyhow!(
"offset {offset} does not fit the two P1 P2 bytes of a short-form \
READ/UPDATE BINARY (max {})",
u16::MAX
)
})?;
Ok(offset.to_be_bytes())
}
/// Write an NDEF message to an NFC Forum Type 4 tag.
///
/// NLEN is zeroed first and written last, which the specification requires: a reader
/// that interrupts the write mid-way then sees an empty message rather than a
/// truncated one it would parse as valid.
///
/// Untested against real hardware, as for [`Self::read_ndef`].
async fn write_ndef(
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
file_id: [u8; 2],
message: &[u8],
) -> Result<()> {
// Checked before anything is written, and before the `as u16` that publishes NLEN
// below. A 70 000-byte message would otherwise write NLEN = 4464 over wrapped
// offsets: a tag left holding a body that describes itself wrongly, which no
// reader can recover from and nothing on this side would have reported.
if message.len() > ndef::MAX_MESSAGE_LEN {
anyhow::bail!(
"NDEF message is {} bytes; a Type 4 tag's two-byte NLEN describes at most {}",
message.len(),
ndef::MAX_MESSAGE_LEN
);
}
let select_app = vec![
0x00, 0xA4, 0x04, 0x00, 0x07, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01, 0x00,
];
let r = Self::transmit_apdu(ctx, reader, select_app).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!(
"SELECT NDEF application refused (SW {})",
hex::encode_upper(&r)
);
}
let select_file = vec![0x00, 0xA4, 0x00, 0x0C, 0x02, file_id[0], file_id[1]];
let r = Self::transmit_apdu(ctx, reader, select_file).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!("SELECT NDEF file refused (SW {})", hex::encode_upper(&r));
}
// NLEN = 0 while the body is in flight.
let r = Self::transmit_apdu(ctx, reader, vec![0x00, 0xD6, 0x00, 0x00, 0x02, 0x00, 0x00])
.await?;
if !Self::apdu_ok(&r) {
anyhow::bail!(
"UPDATE BINARY of NLEN failed (SW {})",
hex::encode_upper(&r)
);
}
let mut written = 0usize;
while written < message.len() {
let chunk = std::cmp::min(MAX_SHORT_WRITE, message.len() - written);
let offset = 2 + written;
let offset_bytes = Self::read_binary_offset(offset)?;
let mut apdu = vec![
0x00,
0xD6,
offset_bytes[0],
offset_bytes[1],
// Bounded by MAX_SHORT_WRITE immediately above.
chunk as u8,
];
apdu.extend_from_slice(&message[written..written + chunk]);
let r = Self::transmit_apdu(ctx, reader, apdu).await?;
if !Self::apdu_ok(&r) {
anyhow::bail!("UPDATE BINARY failed (SW {})", hex::encode_upper(&r));
}
written += chunk;
}
// Publish the real length last. Range-checked at the top of this function, so the
// cast is the safe one it looks like.
let nlen = (message.len() as u16).to_be_bytes();
let r = Self::transmit_apdu(
ctx,
reader,
vec![0x00, 0xD6, 0x00, 0x00, 0x02, nlen[0], nlen[1]],
)
.await?;
if !Self::apdu_ok(&r) {
anyhow::bail!(
"UPDATE BINARY of final NLEN failed (SW {})",
hex::encode_upper(&r)
);
}
Ok(())
}
/// Carry out what the model answered an NFC event with, bounded by [`MAX_FOLLOWUP_DEPTH`].
///
/// The three notify paths used to be `if let Err(..)` with no success arm, so every answer
/// was dropped. `nfc_apdu_response` is the one that mattered most: a smartcard exchange is
/// inherently a conversation (SELECT, then READ BINARY against what SELECT returned), and
/// the model was told what the card said and then never asked again.
#[allow(clippy::too_many_arguments)]
async fn run_followups(
actions: Vec<serde_json::Value>,
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
depth: u8,
client_id: ClientId,
app_state: &Arc<AppState>,
llm_client: &OllamaClient,
status_tx: &mpsc::UnboundedSender<String>,
) {
if actions.is_empty() {
return;
}
if depth >= MAX_FOLLOWUP_DEPTH {
warn!(
"NFC client {} stopped a follow-up chain at depth {}: {} action(s) not executed",
client_id,
depth,
actions.len()
);
let _ = status_tx.send(format!(
"[CLIENT] ⚠ nfc client {} hit the follow-up depth limit ({}); {} action(s) were \
not executed",
client_id,
MAX_FOLLOWUP_DEPTH,
actions.len()
));
return;
}
for action in actions {
match Self::apply_nfc_action(
ctx,
reader,
action,
depth + 1,
client_id,
app_state,
llm_client,
status_tx,
)
.await
{
Ok(NfcApplied::Disconnected) => return,
Ok(_) => trace!("NFC client {} follow-up action completed", client_id),
Err(e) => {
error!("NFC client {} follow-up action failed: {:#}", client_id, e);
let _ = status_tx.send(format!(
"[CLIENT] nfc client {client_id} follow-up failed: {e}"
));
}
}
}
}
/// Returns an explicitly boxed future rather than being an `async fn`: the chain
/// `apply_nfc_action` -> `notify_apdu_response` -> `run_followups` -> `apply_nfc_action`
/// is a cycle of `async fn`s whose opaque return types cannot be inferred (E0391).
#[allow(clippy::too_many_arguments)]
fn apply_nfc_action<'a>(
ctx: &'a pcsc::Context,
reader: &'a std::ffi::CStr,
action: Value,
depth: u8,
client_id: ClientId,
app_state: &'a Arc<AppState>,
llm_client: &'a OllamaClient,
status_tx: &'a mpsc::UnboundedSender<String>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<NfcApplied>> + Send + 'a>> {
Box::pin(async move {
use crate::llm::actions::client_trait::{Client, ClientActionResult};
match NfcClientProtocol.execute_action(action)? {
ClientActionResult::Custom { name, data } if name == "send_apdu" => {
let apdu_hex = data
.get("apdu_hex")
.and_then(|v| v.as_str())
.context("Missing apdu_hex in action data")?
.to_string();
let apdu = hex::decode(apdu_hex.trim())
.context("apdu_hex is not valid hexadecimal")?;
let sent = apdu.len();
// PC/SC is a blocking C API: connect to whatever card is on the
// reader, transmit, and drop the card handle, all on a blocking
// thread. The handle is not kept between commands, so a card that
// was removed and re-presented still works.
let card_ctx = ctx.clone();
let card_reader = reader.to_owned();
let transmit = tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
let card = card_ctx
.connect(&card_reader, pcsc::ShareMode::Shared, pcsc::Protocols::ANY)
.context("PC/SC connect failed (is a card on the reader?)")?;
let mut rx = vec![0u8; pcsc::MAX_BUFFER_SIZE];
let response = card
.transmit(&apdu, &mut rx)
.context("PC/SC transmit failed")?;
Ok(response.to_vec())
})
.await
.context("PC/SC blocking task panicked")?;
match transmit {
Ok(response) => {
let response_hex = hex::encode_upper(&response);
info!(
"NFC client {} APDU {} bytes -> response {}",
client_id, sent, response_hex
);
let _ = status_tx.send(format!(
"[CLIENT] NFC client {} APDU response: {}",
client_id, response_hex
));
// `nfc_apdu_response` was declared and never emitted; an
// injected APDU is the first thing that actually raises it.
Self::notify_apdu_response(
&response, &ctx, &reader, depth, client_id, app_state, llm_client,
status_tx,
)
.await;
Ok(NfcApplied::Sent {
bytes_sent: sent,
response_hex,
})
}
Err(e) => {
warn!("NFC client {} APDU failed: {:#}", client_id, e);
Ok(NfcApplied::Executed(format!(
"send_apdu did not reach a card: {e:#}"
)))
}
}
}
ClientActionResult::Custom { name, data } if name == "read_ndef" => {
let file_id = Self::ndef_file_id(&data);
match Self::read_ndef(ctx, reader, file_id).await {
Ok(message) => {
let hex_msg = hex::encode_upper(&message);
info!(
"NFC client {} read {} byte NDEF message",
client_id,
message.len()
);
// NFC_NDEF_READ_EVENT was declared and never emitted; nothing
// could read an NDEF message at all until now.
Self::notify_ndef_read(
&message, &ctx, &reader, depth, client_id, app_state, llm_client,
status_tx,
)
.await;
Ok(NfcApplied::Executed(format!(
"read_ndef: {} bytes ({})",
message.len(),
if hex_msg.is_empty() {
"empty"
} else {
&hex_msg
}
)))
}
Err(e) => Ok(NfcApplied::Executed(format!("read_ndef failed: {e:#}"))),
}
}
ClientActionResult::Custom { name, data } if name == "write_ndef" => {
let file_id = Self::ndef_file_id(&data);
// `execute_action` encoded the model's typed records into NDEF bytes and
// put them here. Before that existed this arm read `message_hex` or
// `message`, which the action declared nowhere and `execute_action`
// never produced - so every write_ndef ended in "write_ndef needs
// message_hex or message" and the verb could not write anything at all.
let record_count = data
.get("records")
.and_then(|v| v.as_array())
.map(|r| r.len())
.unwrap_or(0);
let bytes =
match data.get("message_hex").and_then(|v| v.as_str()) {
Some(h) => match hex::decode(h.trim()) {
Ok(b) => b,
Err(e) => {
return Ok(NfcApplied::Executed(format!(
"write_ndef: encoded message is not valid hexadecimal: {e}"
)))
}
},
None => return Ok(NfcApplied::Executed(
"write_ndef: no encoded message; 'records' must be a non-empty \
array of typed NDEF records"
.to_string(),
)),
};
match Self::write_ndef(ctx, reader, file_id, &bytes).await {
Ok(()) => Ok(NfcApplied::Sent {
bytes_sent: bytes.len(),
response_hex: format!(
"write_ndef ok ({record_count} record(s), {} NDEF byte(s))",
bytes.len()
),
}),
Err(e) => Ok(NfcApplied::Executed(format!("write_ndef failed: {e:#}"))),
}
}
ClientActionResult::Custom { name, .. } => Ok(NfcApplied::Executed(format!(
"'{name}' is declared but not implemented by the NFC client; \
send_apdu / send_apdu_raw / read_ndef / write_ndef reach the card \
(see src/client/nfc/CLAUDE.md)"
))),
ClientActionResult::Disconnect => {
info!("NFC client {} disconnecting card session", client_id);
app_state
.update_client_status(client_id, crate::state::ClientStatus::Disconnected)
.await;
// Drop the command handle here rather than only in the command loop:
// the LLM can disconnect too, and a handle left behind would offer
// [ send ] into a client that is gone.
app_state.remove_client_handle(client_id).await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
Ok(NfcApplied::Disconnected)
}
ClientActionResult::WaitForMore => {
Ok(NfcApplied::Executed("wait_for_more".to_string()))
}
other => Ok(NfcApplied::Executed(format!(
"unhandled action result {other:?}"
))),
}
})
}
/// Raise `nfc_ndef_read` so the model can act on the message that was read.
///
/// The event was declared and never emitted, because nothing could read an NDEF
/// message at all.
#[allow(clippy::too_many_arguments)]
async fn notify_ndef_read(
message: &[u8],
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
depth: u8,
client_id: ClientId,
app_state: &Arc<AppState>,
llm_client: &OllamaClient,
status_tx: &mpsc::UnboundedSender<String>,
) {
let Some(instruction) = app_state.get_instruction_for_client(client_id).await else {
return;
};
// `records` is what the event declares and what the model is told to expect; it was
// declared and never emitted, because nothing decoded NDEF. `ndef::decode_message`
// walks the records iteratively and never descends into a nested payload, so a
// hostile tag cannot stack-overflow the process here.
let records = ndef::decode_message(message).unwrap_or_default();
let event = Event::new(
&NFC_NDEF_READ_EVENT,
json!({
"records": records,
"length": message.len(),
// The hex stays authoritative: `records` is a best-effort decode of it.
"message_hex": hex::encode_upper(message),
"message_text": String::from_utf8_lossy(message).to_string(),
}),
);
let memory = app_state
.get_memory_for_client(client_id)
.await
.unwrap_or_default();
match call_llm_for_client(
llm_client,
app_state,
client_id.to_string(),
&instruction,
&memory,
Some(&event),
&NfcClientProtocol,
status_tx,
)
.await
{
Ok(result) => {
if let Some(mem) = result.memory_updates {
app_state.set_memory_for_client(client_id, mem).await;
}
Self::run_followups(
result.actions,
ctx,
reader,
depth,
client_id,
app_state,
llm_client,
status_tx,
)
.await;
}
Err(e) => {
error!("NFC client {} LLM error on nfc_ndef_read: {}", client_id, e);
}
}
}
/// Raise `nfc_apdu_response` so the model can act on what the card answered.
#[allow(clippy::too_many_arguments)]
async fn notify_apdu_response(
response: &[u8],
ctx: &pcsc::Context,
reader: &std::ffi::CStr,
depth: u8,
client_id: ClientId,
app_state: &Arc<AppState>,
llm_client: &OllamaClient,
status_tx: &mpsc::UnboundedSender<String>,
) {
let Some(instruction) = app_state.get_instruction_for_client(client_id).await else {
return;
};
let (data, sw) = if response.len() >= 2 {
response.split_at(response.len() - 2)
} else {
(response, &[][..])
};
let event = Event::new(
&NFC_APDU_RESPONSE_EVENT,
json!({
"response_hex": hex::encode_upper(response),
"sw1": sw.first().map(|b| format!("{b:02X}")).unwrap_or_default(),
"sw2": sw.get(1).map(|b| format!("{b:02X}")).unwrap_or_default(),
"data_hex": hex::encode_upper(data),
}),
);
let memory = app_state
.get_memory_for_client(client_id)
.await
.unwrap_or_default();
match call_llm_for_client(
llm_client,
app_state,
client_id.to_string(),
&instruction,
&memory,
Some(&event),
&NfcClientProtocol,
status_tx,
)
.await
{
Ok(result) => {
if let Some(mem) = result.memory_updates {
app_state.set_memory_for_client(client_id, mem).await;
}
Self::run_followups(
result.actions,
ctx,
reader,
depth,
client_id,
app_state,
llm_client,
status_tx,
)
.await;
}
Err(e) => {
error!("LLM error on nfc_apdu_response for {}: {}", client_id, e);
}
}
}
}