stratum-node-core 0.1.0-alpha.3

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
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
//! The public profile document: its fixed path, the exact matcher the gate
//! uses for the unsigned read, the document and ACL a client writes, and
//! the check `profile init` makes on an existing card.
//!
//! Every function here is pure. The gate matches the request target with
//! [`profile_owner`]; the client writes [`profile_card`] and [`profile_acl`]
//! with `text/turtle` to [`profile_card_path`] and beside it.

use crate::did::DidNostr;
use crate::pod_path::PodPath;

/// The profile document's path inside a pod, relative to the pod root:
/// `profile/card`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::PROFILE_CARD_RELATIVE;
///
/// assert_eq!(PROFILE_CARD_RELATIVE, "profile/card");
/// ```
pub const PROFILE_CARD_RELATIVE: &str = "profile/card";

/// The content type the profile document is written and served with.
///
/// # Examples
///
/// ```
/// use stratum_node_core::PROFILE_CONTENT_TYPE;
///
/// assert_eq!(PROFILE_CONTENT_TYPE, "text/turtle");
/// ```
pub const PROFILE_CONTENT_TYPE: &str = "text/turtle";

/// The largest profile document the gate serves unsigned: 64 KiB. A larger
/// one is answered 404.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{profile_card, DidNostr, PROFILE_MAX_BYTES};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// assert!(profile_card(&owner).len() < PROFILE_MAX_BYTES);
/// # Ok(())
/// # }
/// ```
pub const PROFILE_MAX_BYTES: usize = 65_536;

/// The bytes before the key in a profile path.
const PODS_PREFIX: &[u8] = b"/pods/";

/// The bytes after the key in a profile path.
const CARD_SUFFIX: &[u8] = b"/profile/card";

/// The length of a key in lowercase hex.
const KEY_HEX_LEN: usize = 64;

/// The OWL namespace, whose `sameAs` names the owner's identifier.
const OWL_NAMESPACE: &str = "http://www.w3.org/2002/07/owl#";

/// The full IRI of `owl:sameAs`.
const OWL_SAME_AS: &str = "http://www.w3.org/2002/07/owl#sameAs";

/// The scheme of every decentralised identifier, lowercase.
const DID_SCHEME: &str = "did:";

/// Returns the profile document's path for `owner`:
/// `/pods/<pk>/profile/card`.
///
/// # Panics
///
/// Does not panic: the path is built from a valid key and fixed segments,
/// so it always parses.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{profile_card_path, DidNostr};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let path = profile_card_path(&owner);
/// assert_eq!(path.as_str(), format!("/pods/{}/profile/card", owner.to_hex()));
/// assert_eq!(path.owner(), owner);
/// # Ok(())
/// # }
/// ```
pub fn profile_card_path(owner: &DidNostr) -> PodPath {
    PodPath::pod_root(owner)
        .join(PROFILE_CARD_RELATIVE)
        .expect("the profile path is a valid pod path")
}

/// Returns the owner of the profile document named by a request target,
/// or `None` when the target is anything but exactly
/// `/pods/<64 lower-case hex>/profile/card`.
///
/// The comparison is byte for byte on the target as received: nothing is
/// decoded or normalised. A query (even a bare `?`), a fragment, any `%`,
/// an empty segment, a dot segment, a trailing slash, a suffix such as
/// `.acl`, a different case, or a key that is not a valid public key all
/// fail. The pod server serves the card under several equivalent spellings,
/// so this exact match is what confines the unsigned read to one resource
/// per pod.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{profile_card_path, profile_owner, DidNostr};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let path = profile_card_path(&owner);
/// assert_eq!(profile_owner(path.as_str().as_bytes()), Some(owner));
///
/// let hex = owner.to_hex();
/// for refused in [
///     format!("/pods/{hex}/profile/card?"),
///     format!("/pods/{hex}/profile/./card"),
///     format!("/pods/{hex}/profile/%2e/card"),
///     format!("/pods/{hex}/profile/card.acl"),
///     format!("/pods/{}/profile/card", hex.to_uppercase()),
/// ] {
///     assert_eq!(profile_owner(refused.as_bytes()), None, "{refused}");
/// }
/// # Ok(())
/// # }
/// ```
pub fn profile_owner(target: &[u8]) -> Option<DidNostr> {
    let rest = target.strip_prefix(PODS_PREFIX)?;
    let key = rest.get(..KEY_HEX_LEN)?;
    if rest.get(KEY_HEX_LEN..)? != CARD_SUFFIX {
        return None;
    }
    if !key.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return None;
    }
    let key = std::str::from_utf8(key).ok()?;
    DidNostr::from_hex(key).ok()
}

/// Returns the profile document for `owner`, exactly as the client writes
/// it.
///
/// It is Turtle with one subject, `<#me>`, typed `foaf:Person`, and one
/// further statement, `owl:sameAs`, naming the owner's `did:nostr`
/// identifier. `owl:sameAs` is the back-link the pod server's own
/// `did:nostr` resolver looks for. The text ends with a newline.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{card_names_owner, profile_card, DidNostr};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let card = profile_card(&owner);
/// assert!(card.contains(&format!("owl:sameAs <{owner}>")));
/// assert!(card_names_owner(card.as_bytes(), &owner));
/// # Ok(())
/// # }
/// ```
pub fn profile_card(owner: &DidNostr) -> String {
    format!(
        "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
         @prefix owl: <{OWL_NAMESPACE}> .\n\
         \n\
         <#me> a foaf:Person ;\n    owl:sameAs <{owner}> .\n"
    )
}

/// Returns the ACL for the profile document of `owner`, exactly as the
/// client writes it beside the card.
///
/// It has exactly two rules, each naming the card by its root-relative
/// IRI: the owner with read, write and control, and everyone
/// (`foaf:Agent`) with read. There is no `acl:default`. The pod server
/// applies an ACL on one resource in place of the inherited one, and
/// refuses one that would remove the writer's control, so the owner rule
/// is required. The text ends with a newline.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{profile_acl, DidNostr};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let acl = profile_acl(&owner);
/// assert_eq!(acl.matches("a acl:Authorization").count(), 2);
/// assert!(acl.contains(&format!("acl:accessTo </pods/{}/profile/card>", owner.to_hex())));
/// assert!(!acl.contains("acl:default"));
/// # Ok(())
/// # }
/// ```
pub fn profile_acl(owner: &DidNostr) -> String {
    let card = profile_card_path(owner);
    let card = card.as_str();
    format!(
        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
         @prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
         \n\
         <#owner> a acl:Authorization ;\n    \
             acl:agent <{owner}> ;\n    \
             acl:accessTo <{card}> ;\n    \
             acl:mode acl:Read, acl:Write, acl:Control .\n\
         \n\
         <#public> a acl:Authorization ;\n    \
             acl:agentClass foaf:Agent ;\n    \
             acl:accessTo <{card}> ;\n    \
             acl:mode acl:Read .\n"
    )
}

/// Returns `true` when an existing profile card names `owner`, for
/// `profile init`'s decision to leave it alone.
///
/// The check is conservative: it may say `false` for a card a full Turtle
/// parser would accept, in which case `profile init` reports a conflict and
/// changes nothing without `--replace`. It never says `true` for a card
/// that is not Turtle, or that does not state, about `<#me>`,
/// `owl:sameAs <did:nostr:<owner>>`.
///
/// The whole card is read against a subset of the Turtle grammar, and any
/// byte outside that subset makes the answer `false`, wherever it is. The
/// subset covers `@prefix` and `PREFIX` directives; triples whose subject
/// is an IRI, a prefixed name, a blank-node label, a blank-node property
/// list or a collection; predicate lists with `;` (a `;` with nothing after
/// it included) and object lists with `,`; and objects that are IRIs,
/// prefixed names, labels, nested lists and collections, string literals in
/// all four quotings with an optional language tag or datatype, numbers
/// and booleans. It returns `true` only when all of these hold:
///
/// - the bytes are UTF-8 and every statement is complete and ends with
///   `.` (a `PREFIX` directive has none);
/// - whitespace is only space, tab, CR and LF; a comment ends at CR or LF;
///   a short string holds no raw CR or LF, and every escape in a string is
///   one Turtle defines;
/// - no IRI and no prefixed name contains `\`, so no escape can disguise
///   one, and every prefixed name uses a prefix declared before it;
/// - there is no `@base` or `BASE` directive and no other `@` keyword, so
///   `<#me>` means this document;
/// - some triple has the subject `<#me>` and, in its own predicate list,
///   a predicate that is `owl:sameAs` (written as the full IRI, or as a
///   prefixed name whose expansion, with the prefixes declared at that
///   point, is exactly that IRI) with the object `<did:nostr:<owner hex>>`;
/// - that triple contains no blank-node or collection brackets;
/// - no IRI in the card begins with `did:` (in any case) other than the
///   owner's exact one, and no prefix declaration's IRI begins with `did:`
///   at all, the owner's included, so no other identifier can be named
///   directly or built from a prefix.
///
/// An identifier in a comment or a string literal does not count, nor does
/// one stated about another subject.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{card_names_owner, DidNostr};
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let custom = format!(
///     "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
///      @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
///      <#me> a foaf:Person ; foaf:name \"Ada\" ; owl:sameAs <{owner}> .\n"
/// );
/// assert!(card_names_owner(custom.as_bytes(), &owner));
///
/// let comment_only = format!("<#me> a <http://xmlns.com/foaf/0.1/Person> . # owl:sameAs <{owner}>\n");
/// assert!(!card_names_owner(comment_only.as_bytes(), &owner));
///
/// // A comment ends at CR, so this base directive is live.
/// let hidden_base = format!(
///     "# note\r@base <https://elsewhere.example/> .\n\
///      <#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}> .\n"
/// );
/// assert!(!card_names_owner(hidden_base.as_bytes(), &owner));
///
/// // A statement must be complete.
/// let unfinished = format!("<#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}>\n");
/// assert!(!card_names_owner(unfinished.as_bytes(), &owner));
/// # Ok(())
/// # }
/// ```
pub fn card_names_owner(card: &[u8], owner: &DidNostr) -> bool {
    let Ok(text) = std::str::from_utf8(card) else {
        return false;
    };
    let Some(tokens) = tokenize(text) else {
        return false;
    };
    let owner_iri = owner.to_string();
    // A prefixed name cannot build a DID either: the reader refuses any
    // prefix whose IRI begins with `did:`, and a relative prefix IRI
    // resolves against the card's own address, never to a `did:` IRI.
    let foreign_did = tokens
        .iter()
        .any(|token| matches!(token, Token::Iri(iri) if is_did(iri) && *iri != owner_iri));
    if foreign_did {
        return false;
    }
    let mut reader = Reader {
        tokens: &tokens,
        at: 0,
        prefixes: Vec::new(),
        owner_iri: &owner_iri,
        depth: 0,
    };
    reader.document() == Some(true)
}

/// Returns `true` when `iri` begins with `did:`, in any case.
fn is_did(iri: &str) -> bool {
    iri.get(..DID_SCHEME.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(DID_SCHEME))
}

/// Returns `true` when `word` is the directive `name` in either Turtle
/// spelling: `@name` (case-sensitive) or the SPARQL-style `NAME`
/// (case-insensitive).
fn is_directive(word: &str, name: &str) -> bool {
    word.strip_prefix('@') == Some(name) || word.eq_ignore_ascii_case(name)
}

/// The deepest nesting of blank-node lists and collections read; a deeper
/// card is refused rather than risk the stack.
const MAX_NESTING: usize = 32;

/// A reader of the Turtle subset [`card_names_owner`] accepts. Every
/// method returns `None` for input outside the subset, which the caller
/// turns into `false`.
struct Reader<'t, 'a> {
    tokens: &'t [Token<'a>],
    at: usize,
    /// Prefix bindings in declaration order; the last one for a name wins.
    prefixes: Vec<(&'a str, &'a str)>,
    owner_iri: &'t str,
    depth: usize,
}

/// What a term in subject or object position was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Term<'a> {
    /// An IRI written in angle brackets, as written.
    Iri(&'a str),
    /// Anything else: a prefixed name, a label, a literal, a number, a
    /// boolean, a blank-node list or a collection.
    Other,
}

impl<'a> Reader<'_, 'a> {
    fn peek(&self) -> Option<Token<'a>> {
        self.tokens.get(self.at).copied()
    }

    fn next(&mut self) -> Option<Token<'a>> {
        let token = self.peek()?;
        self.at += 1;
        Some(token)
    }

    fn expect(&mut self, token: Token<'_>) -> Option<()> {
        (self.next()? == token).then_some(())
    }

    /// Reads the whole document; `Some(true)` when it is in the subset and
    /// some triple names the owner.
    fn document(&mut self) -> Option<bool> {
        let mut names_owner = false;
        while let Some(token) = self.peek() {
            match token {
                Token::Word(word) if is_directive(word, "prefix") => {
                    self.at += 1;
                    let Token::Word(name) = self.next()? else {
                        return None;
                    };
                    let prefix = name.strip_suffix(':').filter(|p| is_prefix_label(p))?;
                    let Token::Iri(iri) = self.next()? else {
                        return None;
                    };
                    if word.starts_with('@') {
                        self.expect(Token::Dot)?;
                    }
                    // A prefix that is a DID, the owner's included, would
                    // build another identifier from a local name.
                    if is_did(iri) {
                        return None;
                    }
                    self.prefixes.push((prefix, iri));
                }
                Token::Word(word) if word.starts_with('@') || is_directive(word, "base") => {
                    return None;
                }
                _ => names_owner |= self.triples()?,
            }
        }
        Some(names_owner)
    }

    /// Reads one triples statement and its `.`; `Some(true)` when it names
    /// the owner.
    fn triples(&mut self) -> Option<bool> {
        let start = self.at;
        let names_owner = if self.peek()? == Token::OpenSquare {
            self.at += 1;
            // `[ ... ]` may stand alone; `[]` needs a predicate list.
            let empty = self.blank_node_list()?;
            if empty || self.peek()? != Token::Dot {
                self.predicate_objects()?;
            }
            false
        } else {
            let subject = self.subject()?;
            let named = self.predicate_objects()?;
            named && subject == Term::Iri("#me")
        };
        self.expect(Token::Dot)?;
        let bracketed = self.tokens[start..self.at].iter().any(|token| {
            matches!(
                token,
                Token::OpenSquare | Token::CloseSquare | Token::OpenParen | Token::CloseParen
            )
        });
        Some(names_owner && !bracketed)
    }

    fn subject(&mut self) -> Option<Term<'a>> {
        match self.next()? {
            Token::Iri(iri) => Some(Term::Iri(iri)),
            Token::Word(word) if self.is_name(word) || is_blank_label(word) => Some(Term::Other),
            Token::OpenParen => {
                self.collection()?;
                Some(Term::Other)
            }
            _ => None,
        }
    }

    /// Reads `verb objects (';' (verb objects)?)*`; `Some(true)` when one
    /// of its own pairs is `owl:sameAs` with the owner among the objects.
    fn predicate_objects(&mut self) -> Option<bool> {
        let mut names_owner = self.pair()?;
        while self.peek() == Some(Token::Semicolon) {
            self.at += 1;
            if matches!(self.peek(), Some(Token::Iri(_) | Token::Word(_))) {
                names_owner |= self.pair()?;
            }
        }
        Some(names_owner)
    }

    /// Reads one verb and its object list; `Some(true)` when the verb is
    /// `owl:sameAs` and the owner's IRI is among the objects.
    fn pair(&mut self) -> Option<bool> {
        let same_as = match self.next()? {
            Token::Iri(iri) => iri == OWL_SAME_AS,
            Token::Word("a") => false,
            Token::Word(word) => {
                let (namespace, local) = self.expand(word)?;
                OWL_SAME_AS.strip_prefix(namespace) == Some(local)
            }
            _ => return None,
        };
        let mut names_owner = false;
        loop {
            let object = self.object()?;
            names_owner |= same_as && matches!(object, Term::Iri(iri) if iri == self.owner_iri);
            if self.peek() != Some(Token::Comma) {
                return Some(names_owner);
            }
            self.at += 1;
        }
    }

    fn object(&mut self) -> Option<Term<'a>> {
        match self.next()? {
            Token::Iri(iri) => Some(Term::Iri(iri)),
            Token::Literal => {
                match self.peek() {
                    Some(Token::Word(word)) if word.starts_with('@') => {
                        is_language_tag(&word[1..]).then_some(())?;
                        self.at += 1;
                    }
                    Some(Token::Word("^^")) => {
                        self.at += 1;
                        let Token::Iri(_) = self.next()? else {
                            return None;
                        };
                    }
                    Some(Token::Word(word)) if word.starts_with("^^") => {
                        self.is_name(&word[2..]).then_some(())?;
                        self.at += 1;
                    }
                    _ => {}
                }
                Some(Term::Other)
            }
            Token::Word(word)
                if self.is_name(word)
                    || is_blank_label(word)
                    || is_number(word)
                    || word == "true"
                    || word == "false" =>
            {
                Some(Term::Other)
            }
            Token::OpenSquare => {
                self.blank_node_list()?;
                Some(Term::Other)
            }
            Token::OpenParen => {
                self.collection()?;
                Some(Term::Other)
            }
            _ => None,
        }
    }

    /// Reads the rest of `[ ]` or `[ predicate-objects ]` after its `[`;
    /// `Some(true)` when it was empty.
    fn blank_node_list(&mut self) -> Option<bool> {
        self.descend()?;
        let empty = self.peek()? == Token::CloseSquare;
        if !empty {
            self.predicate_objects()?;
        }
        self.expect(Token::CloseSquare)?;
        self.depth -= 1;
        Some(empty)
    }

    /// Reads the objects of a collection and its `)`, after its `(`.
    fn collection(&mut self) -> Option<()> {
        self.descend()?;
        while self.peek()? != Token::CloseParen {
            self.object()?;
        }
        self.at += 1;
        self.depth -= 1;
        Some(())
    }

    fn descend(&mut self) -> Option<()> {
        self.depth += 1;
        (self.depth <= MAX_NESTING).then_some(())
    }

    /// Returns `true` when `word` is a prefixed name whose prefix is
    /// declared.
    fn is_name(&self, word: &'a str) -> bool {
        self.expand(word).is_some()
    }

    /// Splits a prefixed name into its prefix's IRI and its local part;
    /// `None` when `word` is not a prefixed name in the subset or its
    /// prefix has not been declared.
    fn expand(&self, word: &'a str) -> Option<(&'a str, &'a str)> {
        let (prefix, local) = word.split_once(':')?;
        if !is_prefix_label(prefix) || !is_local_name(local) {
            return None;
        }
        let namespace = self
            .prefixes
            .iter()
            .rev()
            .find(|(name, _)| *name == prefix)
            .map(|(_, iri)| *iri)?;
        Some((namespace, local))
    }
}

/// A prefix label: empty, or an ASCII letter followed by letters, digits,
/// `_`, `-` or `.`, not ending in `.`. Narrower than Turtle's, which also
/// allows other scripts.
fn is_prefix_label(label: &str) -> bool {
    let mut chars = label.chars();
    match chars.next() {
        None => true,
        Some(first) => {
            first.is_ascii_alphabetic()
                && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
                && !label.ends_with('.')
        }
    }
}

/// The local part of a prefixed name: ASCII letters, digits, `_`, `-`,
/// `.` and `:`, not starting with `-` or `.` and not ending in `.`. No
/// escape and no `%` sequence is accepted.
fn is_local_name(local: &str) -> bool {
    local
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ':'))
        && !local.starts_with(['-', '.'])
        && !local.ends_with('.')
}

/// A blank-node label, `_:` then an ASCII letter, digit or `_`, then
/// those, `-` or `.`, not ending in `.`.
fn is_blank_label(word: &str) -> bool {
    let Some(label) = word.strip_prefix("_:") else {
        return false;
    };
    let mut chars = label.chars();
    chars
        .next()
        .is_some_and(|first| first.is_ascii_alphanumeric() || first == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
        && !label.ends_with('.')
}

/// A Turtle integer, decimal or double.
fn is_number(word: &str) -> bool {
    let unsigned = word.strip_prefix(['+', '-']).unwrap_or(word);
    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
        Some(at) => (&unsigned[..at], Some(&unsigned[at + 1..])),
        None => (unsigned, None),
    };
    let (whole, fraction) = match mantissa.split_once('.') {
        Some((whole, fraction)) => (whole, Some(fraction)),
        None => (mantissa, None),
    };
    let digits = |text: &str| text.bytes().all(|b| b.is_ascii_digit());
    if !digits(whole) || !fraction.is_none_or(digits) {
        return false;
    }
    let has_point = fraction.is_some();
    let fraction = fraction.unwrap_or("");
    match exponent {
        // An integer has digits; a decimal has digits after its point.
        None if has_point => !fraction.is_empty(),
        None => !whole.is_empty(),
        Some(exponent) => {
            let exponent = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
            (!whole.is_empty() || !fraction.is_empty()) && !exponent.is_empty() && digits(exponent)
        }
    }
}

/// A language tag after its `@`: letters, then `-` and letters or digits.
fn is_language_tag(tag: &str) -> bool {
    let mut parts = tag.split('-');
    parts
        .next()
        .is_some_and(|first| !first.is_empty() && first.bytes().all(|b| b.is_ascii_alphabetic()))
        && parts.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
}

/// One token of the subset of Turtle [`card_names_owner`] reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token<'a> {
    /// The text between `<` and `>`.
    Iri(&'a str),
    /// A string literal, whatever its content.
    Literal,
    /// Any other run of characters: a prefixed name, a keyword, a number,
    /// `a`, a language tag or a datatype marker. The reader decides
    /// whether it is one it accepts.
    Word(&'a str),
    /// `.` ending a statement.
    Dot,
    /// `;` between predicates.
    Semicolon,
    /// `,` between objects.
    Comma,
    /// `[`.
    OpenSquare,
    /// `]`.
    CloseSquare,
    /// `(`.
    OpenParen,
    /// `)`.
    CloseParen,
}

/// Turtle's whitespace: space, tab, CR and LF, and nothing else (not form
/// feed, which Rust's ASCII whitespace includes).
fn is_turtle_space(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\r' | '\n')
}

/// Splits `text` into tokens; `None` when an IRI or string literal is not
/// terminated, an IRI holds a character Turtle forbids there or a `\`, or a
/// string holds an escape Turtle does not define.
fn tokenize(text: &str) -> Option<Vec<Token<'_>>> {
    let mut tokens = Vec::new();
    let mut rest = text;
    loop {
        rest = rest.trim_start_matches(is_turtle_space);
        let Some(first) = rest.chars().next() else {
            return Some(tokens);
        };
        let single = match first {
            '.' => Some(Token::Dot),
            ';' => Some(Token::Semicolon),
            ',' => Some(Token::Comma),
            '[' => Some(Token::OpenSquare),
            ']' => Some(Token::CloseSquare),
            '(' => Some(Token::OpenParen),
            ')' => Some(Token::CloseParen),
            _ => None,
        };
        if let Some(token) = single {
            tokens.push(token);
            rest = &rest[1..];
            continue;
        }
        match first {
            // A comment runs to the end of the line, which CR or LF ends.
            '#' => {
                rest = rest.find(['\r', '\n']).map_or("", |end| &rest[end..]);
            }
            '<' => {
                let end = rest.find('>')?;
                let iri = &rest[1..end];
                if iri
                    .chars()
                    .any(|c| c.is_whitespace() || c.is_control() || "<\"{}|^`\\".contains(c))
                {
                    return None;
                }
                tokens.push(Token::Iri(iri));
                rest = &rest[end + 1..];
            }
            '"' | '\'' => {
                rest = skip_literal(rest, first)?;
                tokens.push(Token::Literal);
            }
            _ => {
                let end = rest
                    .find(|c: char| is_turtle_space(c) || "<\"'#;,[]()".contains(c))
                    .unwrap_or(rest.len());
                let word = &rest[..end];
                // A statement's final `.` may touch the word before it.
                let trimmed = word.trim_end_matches('.');
                if !trimmed.is_empty() {
                    tokens.push(Token::Word(trimmed));
                }
                for _ in trimmed.len()..word.len() {
                    tokens.push(Token::Dot);
                }
                rest = &rest[end..];
            }
        }
    }
}

/// Skips the string literal at the start of `text`, which begins with
/// `quote`, and returns what follows it; `None` when it is not terminated,
/// a short string holds a raw CR or LF, or an escape is not one of
/// `\t \b \n \r \f \" \' \\`, `\uXXXX` or `\UXXXXXXXX`.
fn skip_literal(text: &str, quote: char) -> Option<&str> {
    let triple: String = std::iter::repeat_n(quote, 3).collect();
    let (body, close) = if text.starts_with(&triple) {
        (&text[3..], triple.as_str())
    } else {
        (&text[1..], &text[..1])
    };
    let mut chars = body.char_indices();
    while let Some((at, c)) = chars.next() {
        if c == '\\' {
            let (_, escape) = chars.next()?;
            let hex_digits = match escape {
                't' | 'b' | 'n' | 'r' | 'f' | '"' | '\'' | '\\' => 0,
                'u' => 4,
                'U' => 8,
                _ => return None,
            };
            for _ in 0..hex_digits {
                if !chars.next()?.1.is_ascii_hexdigit() {
                    return None;
                }
            }
            continue;
        }
        if close.len() == 1 && matches!(c, '\n' | '\r') {
            return None;
        }
        if body[at..].starts_with(close) {
            return Some(&body[at + close.len()..]);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{
        card_names_owner, is_blank_label, is_language_tag, is_local_name, is_number,
        is_prefix_label, tokenize, Token, MAX_NESTING,
    };
    use crate::NostrSecretKey;

    #[test]
    fn a_comment_ends_at_cr_or_lf() {
        assert_eq!(
            tokenize("# c\r<a> # d\n<b>"),
            Some(vec![Token::Iri("a"), Token::Iri("b")]),
            "both line ends"
        );
    }

    #[test]
    fn form_feed_is_not_whitespace() {
        assert_eq!(
            tokenize("<a>\x0c<b>"),
            Some(vec![Token::Iri("a"), Token::Word("\x0c"), Token::Iri("b")]),
            "kept as a word the reader refuses"
        );
    }

    #[test]
    fn only_defined_escapes_are_read() {
        for good in [
            r#""\t\b\n\r\f\"\'\\""#,
            r#""\u00e9""#,
            r#""\U0001F600""#,
            "'''a\nb'''",
        ] {
            assert_eq!(tokenize(good), Some(vec![Token::Literal]), "{good:?}");
        }
        for bad in [
            r#""\q""#,
            r#""\u00g9""#,
            "\"\\\n\"",
            "\"a\rb\"",
            "'a\rb'",
            r"<a\u0062>",
        ] {
            assert_eq!(tokenize(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn word_shapes() {
        for label in ["", "owl", "f-o.a_f9"] {
            assert!(is_prefix_label(label), "prefix {label:?}");
        }
        for label in ["9a", "a.", "_a", "a:b", "\u{e9}"] {
            assert!(!is_prefix_label(label), "prefix {label:?}");
        }
        for local in ["", "sameAs", "a.b", "a:b", "9", "_x"] {
            assert!(is_local_name(local), "local {local:?}");
        }
        for local in ["-a", ".a", "a.", r"o\#", "%41", "a/b"] {
            assert!(!is_local_name(local), "local {local:?}");
        }
        for label in ["_:b0", "_:_", "_:a.b"] {
            assert!(is_blank_label(label), "label {label:?}");
        }
        for label in ["_:", "_:-a", "_:a.", "b0"] {
            assert!(!is_blank_label(label), "label {label:?}");
        }
        for number in ["1", "-1", "+1.5", "1.5", "1.e5", "1e-5", "1.5E+3", ".5"] {
            assert!(is_number(number), "number {number:?}");
        }
        for number in ["", "-", "1.", "1e", "e5", "1.5.5", "0x1", "1e+"] {
            assert!(!is_number(number), "number {number:?}");
        }
        for tag in ["en", "en-GB", "x-a1"] {
            assert!(is_language_tag(tag), "tag {tag:?}");
        }
        for tag in ["", "en-", "-en", "e1", "en_GB"] {
            assert!(!is_language_tag(tag), "tag {tag:?}");
        }
    }

    #[test]
    fn nesting_is_bounded() {
        let owner = NostrSecretKey::from_hex(&"0b".repeat(32))
            .expect("fixed key")
            .public();
        let naming = format!("<#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}> .\n");
        let nested = |depth: usize| {
            format!(
                "<#x> <http://example.org/p> {}{} .\n{naming}",
                "( ".repeat(depth),
                ") ".repeat(depth)
            )
        };
        assert!(
            card_names_owner(nested(MAX_NESTING).as_bytes(), &owner),
            "at the limit"
        );
        assert!(
            !card_names_owner(nested(MAX_NESTING + 1).as_bytes(), &owner),
            "past it"
        );
        // Far past it: refused, not a stack overflow.
        assert!(
            !card_names_owner(nested(100_000).as_bytes(), &owner),
            "deep"
        );
    }

    #[test]
    fn tokenizer_reads_the_subset() {
        let tokens = tokenize("<#me> a ex:P ; ex:n \"a;b.\" , '''x\n.''' . # c <x>\nex:z.")
            .expect("tokenizes");
        assert_eq!(
            tokens,
            [
                Token::Iri("#me"),
                Token::Word("a"),
                Token::Word("ex:P"),
                Token::Semicolon,
                Token::Word("ex:n"),
                Token::Literal,
                Token::Comma,
                Token::Literal,
                Token::Dot,
                Token::Word("ex:z"),
                Token::Dot,
            ],
            "tokens"
        );
    }

    #[test]
    fn tokenizer_refuses_unterminated_input() {
        for text in [
            "<#me",
            "\"open",
            "'''open",
            "\"line\nbreak\"",
            "<a b>",
            "\"esc\\",
        ] {
            assert_eq!(tokenize(text), None, "{text:?}");
        }
    }
}