Skip to main content

stratum_node_core/
profile.rs

1//! The public profile document: its fixed path, the exact matcher the gate
2//! uses for the unsigned read, the document and ACL a client writes, and
3//! the check `profile init` makes on an existing card.
4//!
5//! Every function here is pure. The gate matches the request target with
6//! [`profile_owner`]; the client writes [`profile_card`] and [`profile_acl`]
7//! with `text/turtle` to [`profile_card_path`] and beside it.
8
9use crate::did::DidNostr;
10use crate::pod_path::PodPath;
11
12/// The profile document's path inside a pod, relative to the pod root:
13/// `profile/card`.
14///
15/// # Examples
16///
17/// ```
18/// use stratum_node_core::PROFILE_CARD_RELATIVE;
19///
20/// assert_eq!(PROFILE_CARD_RELATIVE, "profile/card");
21/// ```
22pub const PROFILE_CARD_RELATIVE: &str = "profile/card";
23
24/// The content type the profile document is written and served with.
25///
26/// # Examples
27///
28/// ```
29/// use stratum_node_core::PROFILE_CONTENT_TYPE;
30///
31/// assert_eq!(PROFILE_CONTENT_TYPE, "text/turtle");
32/// ```
33pub const PROFILE_CONTENT_TYPE: &str = "text/turtle";
34
35/// The largest profile document the gate serves unsigned: 64 KiB. A larger
36/// one is answered 404.
37///
38/// # Examples
39///
40/// ```
41/// use stratum_node_core::{profile_card, DidNostr, PROFILE_MAX_BYTES};
42///
43/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
44/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
45/// assert!(profile_card(&owner).len() < PROFILE_MAX_BYTES);
46/// # Ok(())
47/// # }
48/// ```
49pub const PROFILE_MAX_BYTES: usize = 65_536;
50
51/// The bytes before the key in a profile path.
52const PODS_PREFIX: &[u8] = b"/pods/";
53
54/// The bytes after the key in a profile path.
55const CARD_SUFFIX: &[u8] = b"/profile/card";
56
57/// The length of a key in lowercase hex.
58const KEY_HEX_LEN: usize = 64;
59
60/// The OWL namespace, whose `sameAs` names the owner's identifier.
61const OWL_NAMESPACE: &str = "http://www.w3.org/2002/07/owl#";
62
63/// The full IRI of `owl:sameAs`.
64const OWL_SAME_AS: &str = "http://www.w3.org/2002/07/owl#sameAs";
65
66/// The scheme of every decentralised identifier, lowercase.
67const DID_SCHEME: &str = "did:";
68
69/// Returns the profile document's path for `owner`:
70/// `/pods/<pk>/profile/card`.
71///
72/// # Panics
73///
74/// Does not panic: the path is built from a valid key and fixed segments,
75/// so it always parses.
76///
77/// # Examples
78///
79/// ```
80/// use stratum_node_core::{profile_card_path, DidNostr};
81///
82/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
83/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
84/// let path = profile_card_path(&owner);
85/// assert_eq!(path.as_str(), format!("/pods/{}/profile/card", owner.to_hex()));
86/// assert_eq!(path.owner(), owner);
87/// # Ok(())
88/// # }
89/// ```
90pub fn profile_card_path(owner: &DidNostr) -> PodPath {
91    PodPath::pod_root(owner)
92        .join(PROFILE_CARD_RELATIVE)
93        .expect("the profile path is a valid pod path")
94}
95
96/// Returns the owner of the profile document named by a request target,
97/// or `None` when the target is anything but exactly
98/// `/pods/<64 lower-case hex>/profile/card`.
99///
100/// The comparison is byte for byte on the target as received: nothing is
101/// decoded or normalised. A query (even a bare `?`), a fragment, any `%`,
102/// an empty segment, a dot segment, a trailing slash, a suffix such as
103/// `.acl`, a different case, or a key that is not a valid public key all
104/// fail. The pod server serves the card under several equivalent spellings,
105/// so this exact match is what confines the unsigned read to one resource
106/// per pod.
107///
108/// # Examples
109///
110/// ```
111/// use stratum_node_core::{profile_card_path, profile_owner, DidNostr};
112///
113/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
114/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
115/// let path = profile_card_path(&owner);
116/// assert_eq!(profile_owner(path.as_str().as_bytes()), Some(owner));
117///
118/// let hex = owner.to_hex();
119/// for refused in [
120///     format!("/pods/{hex}/profile/card?"),
121///     format!("/pods/{hex}/profile/./card"),
122///     format!("/pods/{hex}/profile/%2e/card"),
123///     format!("/pods/{hex}/profile/card.acl"),
124///     format!("/pods/{}/profile/card", hex.to_uppercase()),
125/// ] {
126///     assert_eq!(profile_owner(refused.as_bytes()), None, "{refused}");
127/// }
128/// # Ok(())
129/// # }
130/// ```
131pub fn profile_owner(target: &[u8]) -> Option<DidNostr> {
132    let rest = target.strip_prefix(PODS_PREFIX)?;
133    let key = rest.get(..KEY_HEX_LEN)?;
134    if rest.get(KEY_HEX_LEN..)? != CARD_SUFFIX {
135        return None;
136    }
137    if !key.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
138        return None;
139    }
140    let key = std::str::from_utf8(key).ok()?;
141    DidNostr::from_hex(key).ok()
142}
143
144/// Returns the profile document for `owner`, exactly as the client writes
145/// it.
146///
147/// It is Turtle with one subject, `<#me>`, typed `foaf:Person`, and one
148/// further statement, `owl:sameAs`, naming the owner's `did:nostr`
149/// identifier. `owl:sameAs` is the back-link the pod server's own
150/// `did:nostr` resolver looks for. The text ends with a newline.
151///
152/// # Examples
153///
154/// ```
155/// use stratum_node_core::{card_names_owner, profile_card, DidNostr};
156///
157/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
158/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
159/// let card = profile_card(&owner);
160/// assert!(card.contains(&format!("owl:sameAs <{owner}>")));
161/// assert!(card_names_owner(card.as_bytes(), &owner));
162/// # Ok(())
163/// # }
164/// ```
165pub fn profile_card(owner: &DidNostr) -> String {
166    format!(
167        "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
168         @prefix owl: <{OWL_NAMESPACE}> .\n\
169         \n\
170         <#me> a foaf:Person ;\n    owl:sameAs <{owner}> .\n"
171    )
172}
173
174/// Returns the ACL for the profile document of `owner`, exactly as the
175/// client writes it beside the card.
176///
177/// It has exactly two rules, each naming the card by its root-relative
178/// IRI: the owner with read, write and control, and everyone
179/// (`foaf:Agent`) with read. There is no `acl:default`. The pod server
180/// applies an ACL on one resource in place of the inherited one, and
181/// refuses one that would remove the writer's control, so the owner rule
182/// is required. The text ends with a newline.
183///
184/// # Examples
185///
186/// ```
187/// use stratum_node_core::{profile_acl, DidNostr};
188///
189/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
190/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
191/// let acl = profile_acl(&owner);
192/// assert_eq!(acl.matches("a acl:Authorization").count(), 2);
193/// assert!(acl.contains(&format!("acl:accessTo </pods/{}/profile/card>", owner.to_hex())));
194/// assert!(!acl.contains("acl:default"));
195/// # Ok(())
196/// # }
197/// ```
198pub fn profile_acl(owner: &DidNostr) -> String {
199    let card = profile_card_path(owner);
200    let card = card.as_str();
201    format!(
202        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
203         @prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
204         \n\
205         <#owner> a acl:Authorization ;\n    \
206             acl:agent <{owner}> ;\n    \
207             acl:accessTo <{card}> ;\n    \
208             acl:mode acl:Read, acl:Write, acl:Control .\n\
209         \n\
210         <#public> a acl:Authorization ;\n    \
211             acl:agentClass foaf:Agent ;\n    \
212             acl:accessTo <{card}> ;\n    \
213             acl:mode acl:Read .\n"
214    )
215}
216
217/// Returns `true` when an existing profile card names `owner`, for
218/// `profile init`'s decision to leave it alone.
219///
220/// The check is conservative: it may say `false` for a card a full Turtle
221/// parser would accept, in which case `profile init` reports a conflict and
222/// changes nothing without `--replace`. It never says `true` for a card
223/// that is not Turtle, or that does not state, about `<#me>`,
224/// `owl:sameAs <did:nostr:<owner>>`.
225///
226/// The whole card is read against a subset of the Turtle grammar, and any
227/// byte outside that subset makes the answer `false`, wherever it is. The
228/// subset covers `@prefix` and `PREFIX` directives; triples whose subject
229/// is an IRI, a prefixed name, a blank-node label, a blank-node property
230/// list or a collection; predicate lists with `;` (a `;` with nothing after
231/// it included) and object lists with `,`; and objects that are IRIs,
232/// prefixed names, labels, nested lists and collections, string literals in
233/// all four quotings with an optional language tag or datatype, numbers
234/// and booleans. It returns `true` only when all of these hold:
235///
236/// - the bytes are UTF-8 and every statement is complete and ends with
237///   `.` (a `PREFIX` directive has none);
238/// - whitespace is only space, tab, CR and LF; a comment ends at CR or LF;
239///   a short string holds no raw CR or LF, and every escape in a string is
240///   one Turtle defines;
241/// - no IRI and no prefixed name contains `\`, so no escape can disguise
242///   one, and every prefixed name uses a prefix declared before it;
243/// - there is no `@base` or `BASE` directive and no other `@` keyword, so
244///   `<#me>` means this document;
245/// - some triple has the subject `<#me>` and, in its own predicate list,
246///   a predicate that is `owl:sameAs` (written as the full IRI, or as a
247///   prefixed name whose expansion, with the prefixes declared at that
248///   point, is exactly that IRI) with the object `<did:nostr:<owner hex>>`;
249/// - that triple contains no blank-node or collection brackets;
250/// - no IRI in the card begins with `did:` (in any case) other than the
251///   owner's exact one, and no prefix declaration's IRI begins with `did:`
252///   at all, the owner's included, so no other identifier can be named
253///   directly or built from a prefix.
254///
255/// An identifier in a comment or a string literal does not count, nor does
256/// one stated about another subject.
257///
258/// # Examples
259///
260/// ```
261/// use stratum_node_core::{card_names_owner, DidNostr};
262///
263/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
264/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
265/// let custom = format!(
266///     "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
267///      @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
268///      <#me> a foaf:Person ; foaf:name \"Ada\" ; owl:sameAs <{owner}> .\n"
269/// );
270/// assert!(card_names_owner(custom.as_bytes(), &owner));
271///
272/// let comment_only = format!("<#me> a <http://xmlns.com/foaf/0.1/Person> . # owl:sameAs <{owner}>\n");
273/// assert!(!card_names_owner(comment_only.as_bytes(), &owner));
274///
275/// // A comment ends at CR, so this base directive is live.
276/// let hidden_base = format!(
277///     "# note\r@base <https://elsewhere.example/> .\n\
278///      <#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}> .\n"
279/// );
280/// assert!(!card_names_owner(hidden_base.as_bytes(), &owner));
281///
282/// // A statement must be complete.
283/// let unfinished = format!("<#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}>\n");
284/// assert!(!card_names_owner(unfinished.as_bytes(), &owner));
285/// # Ok(())
286/// # }
287/// ```
288pub fn card_names_owner(card: &[u8], owner: &DidNostr) -> bool {
289    let Ok(text) = std::str::from_utf8(card) else {
290        return false;
291    };
292    let Some(tokens) = tokenize(text) else {
293        return false;
294    };
295    let owner_iri = owner.to_string();
296    // A prefixed name cannot build a DID either: the reader refuses any
297    // prefix whose IRI begins with `did:`, and a relative prefix IRI
298    // resolves against the card's own address, never to a `did:` IRI.
299    let foreign_did = tokens
300        .iter()
301        .any(|token| matches!(token, Token::Iri(iri) if is_did(iri) && *iri != owner_iri));
302    if foreign_did {
303        return false;
304    }
305    let mut reader = Reader {
306        tokens: &tokens,
307        at: 0,
308        prefixes: Vec::new(),
309        owner_iri: &owner_iri,
310        depth: 0,
311    };
312    reader.document() == Some(true)
313}
314
315/// Returns `true` when `iri` begins with `did:`, in any case.
316fn is_did(iri: &str) -> bool {
317    iri.get(..DID_SCHEME.len())
318        .is_some_and(|head| head.eq_ignore_ascii_case(DID_SCHEME))
319}
320
321/// Returns `true` when `word` is the directive `name` in either Turtle
322/// spelling: `@name` (case-sensitive) or the SPARQL-style `NAME`
323/// (case-insensitive).
324fn is_directive(word: &str, name: &str) -> bool {
325    word.strip_prefix('@') == Some(name) || word.eq_ignore_ascii_case(name)
326}
327
328/// The deepest nesting of blank-node lists and collections read; a deeper
329/// card is refused rather than risk the stack.
330const MAX_NESTING: usize = 32;
331
332/// A reader of the Turtle subset [`card_names_owner`] accepts. Every
333/// method returns `None` for input outside the subset, which the caller
334/// turns into `false`.
335struct Reader<'t, 'a> {
336    tokens: &'t [Token<'a>],
337    at: usize,
338    /// Prefix bindings in declaration order; the last one for a name wins.
339    prefixes: Vec<(&'a str, &'a str)>,
340    owner_iri: &'t str,
341    depth: usize,
342}
343
344/// What a term in subject or object position was.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346enum Term<'a> {
347    /// An IRI written in angle brackets, as written.
348    Iri(&'a str),
349    /// Anything else: a prefixed name, a label, a literal, a number, a
350    /// boolean, a blank-node list or a collection.
351    Other,
352}
353
354impl<'a> Reader<'_, 'a> {
355    fn peek(&self) -> Option<Token<'a>> {
356        self.tokens.get(self.at).copied()
357    }
358
359    fn next(&mut self) -> Option<Token<'a>> {
360        let token = self.peek()?;
361        self.at += 1;
362        Some(token)
363    }
364
365    fn expect(&mut self, token: Token<'_>) -> Option<()> {
366        (self.next()? == token).then_some(())
367    }
368
369    /// Reads the whole document; `Some(true)` when it is in the subset and
370    /// some triple names the owner.
371    fn document(&mut self) -> Option<bool> {
372        let mut names_owner = false;
373        while let Some(token) = self.peek() {
374            match token {
375                Token::Word(word) if is_directive(word, "prefix") => {
376                    self.at += 1;
377                    let Token::Word(name) = self.next()? else {
378                        return None;
379                    };
380                    let prefix = name.strip_suffix(':').filter(|p| is_prefix_label(p))?;
381                    let Token::Iri(iri) = self.next()? else {
382                        return None;
383                    };
384                    if word.starts_with('@') {
385                        self.expect(Token::Dot)?;
386                    }
387                    // A prefix that is a DID, the owner's included, would
388                    // build another identifier from a local name.
389                    if is_did(iri) {
390                        return None;
391                    }
392                    self.prefixes.push((prefix, iri));
393                }
394                Token::Word(word) if word.starts_with('@') || is_directive(word, "base") => {
395                    return None;
396                }
397                _ => names_owner |= self.triples()?,
398            }
399        }
400        Some(names_owner)
401    }
402
403    /// Reads one triples statement and its `.`; `Some(true)` when it names
404    /// the owner.
405    fn triples(&mut self) -> Option<bool> {
406        let start = self.at;
407        let names_owner = if self.peek()? == Token::OpenSquare {
408            self.at += 1;
409            // `[ ... ]` may stand alone; `[]` needs a predicate list.
410            let empty = self.blank_node_list()?;
411            if empty || self.peek()? != Token::Dot {
412                self.predicate_objects()?;
413            }
414            false
415        } else {
416            let subject = self.subject()?;
417            let named = self.predicate_objects()?;
418            named && subject == Term::Iri("#me")
419        };
420        self.expect(Token::Dot)?;
421        let bracketed = self.tokens[start..self.at].iter().any(|token| {
422            matches!(
423                token,
424                Token::OpenSquare | Token::CloseSquare | Token::OpenParen | Token::CloseParen
425            )
426        });
427        Some(names_owner && !bracketed)
428    }
429
430    fn subject(&mut self) -> Option<Term<'a>> {
431        match self.next()? {
432            Token::Iri(iri) => Some(Term::Iri(iri)),
433            Token::Word(word) if self.is_name(word) || is_blank_label(word) => Some(Term::Other),
434            Token::OpenParen => {
435                self.collection()?;
436                Some(Term::Other)
437            }
438            _ => None,
439        }
440    }
441
442    /// Reads `verb objects (';' (verb objects)?)*`; `Some(true)` when one
443    /// of its own pairs is `owl:sameAs` with the owner among the objects.
444    fn predicate_objects(&mut self) -> Option<bool> {
445        let mut names_owner = self.pair()?;
446        while self.peek() == Some(Token::Semicolon) {
447            self.at += 1;
448            if matches!(self.peek(), Some(Token::Iri(_) | Token::Word(_))) {
449                names_owner |= self.pair()?;
450            }
451        }
452        Some(names_owner)
453    }
454
455    /// Reads one verb and its object list; `Some(true)` when the verb is
456    /// `owl:sameAs` and the owner's IRI is among the objects.
457    fn pair(&mut self) -> Option<bool> {
458        let same_as = match self.next()? {
459            Token::Iri(iri) => iri == OWL_SAME_AS,
460            Token::Word("a") => false,
461            Token::Word(word) => {
462                let (namespace, local) = self.expand(word)?;
463                OWL_SAME_AS.strip_prefix(namespace) == Some(local)
464            }
465            _ => return None,
466        };
467        let mut names_owner = false;
468        loop {
469            let object = self.object()?;
470            names_owner |= same_as && matches!(object, Term::Iri(iri) if iri == self.owner_iri);
471            if self.peek() != Some(Token::Comma) {
472                return Some(names_owner);
473            }
474            self.at += 1;
475        }
476    }
477
478    fn object(&mut self) -> Option<Term<'a>> {
479        match self.next()? {
480            Token::Iri(iri) => Some(Term::Iri(iri)),
481            Token::Literal => {
482                match self.peek() {
483                    Some(Token::Word(word)) if word.starts_with('@') => {
484                        is_language_tag(&word[1..]).then_some(())?;
485                        self.at += 1;
486                    }
487                    Some(Token::Word("^^")) => {
488                        self.at += 1;
489                        let Token::Iri(_) = self.next()? else {
490                            return None;
491                        };
492                    }
493                    Some(Token::Word(word)) if word.starts_with("^^") => {
494                        self.is_name(&word[2..]).then_some(())?;
495                        self.at += 1;
496                    }
497                    _ => {}
498                }
499                Some(Term::Other)
500            }
501            Token::Word(word)
502                if self.is_name(word)
503                    || is_blank_label(word)
504                    || is_number(word)
505                    || word == "true"
506                    || word == "false" =>
507            {
508                Some(Term::Other)
509            }
510            Token::OpenSquare => {
511                self.blank_node_list()?;
512                Some(Term::Other)
513            }
514            Token::OpenParen => {
515                self.collection()?;
516                Some(Term::Other)
517            }
518            _ => None,
519        }
520    }
521
522    /// Reads the rest of `[ ]` or `[ predicate-objects ]` after its `[`;
523    /// `Some(true)` when it was empty.
524    fn blank_node_list(&mut self) -> Option<bool> {
525        self.descend()?;
526        let empty = self.peek()? == Token::CloseSquare;
527        if !empty {
528            self.predicate_objects()?;
529        }
530        self.expect(Token::CloseSquare)?;
531        self.depth -= 1;
532        Some(empty)
533    }
534
535    /// Reads the objects of a collection and its `)`, after its `(`.
536    fn collection(&mut self) -> Option<()> {
537        self.descend()?;
538        while self.peek()? != Token::CloseParen {
539            self.object()?;
540        }
541        self.at += 1;
542        self.depth -= 1;
543        Some(())
544    }
545
546    fn descend(&mut self) -> Option<()> {
547        self.depth += 1;
548        (self.depth <= MAX_NESTING).then_some(())
549    }
550
551    /// Returns `true` when `word` is a prefixed name whose prefix is
552    /// declared.
553    fn is_name(&self, word: &'a str) -> bool {
554        self.expand(word).is_some()
555    }
556
557    /// Splits a prefixed name into its prefix's IRI and its local part;
558    /// `None` when `word` is not a prefixed name in the subset or its
559    /// prefix has not been declared.
560    fn expand(&self, word: &'a str) -> Option<(&'a str, &'a str)> {
561        let (prefix, local) = word.split_once(':')?;
562        if !is_prefix_label(prefix) || !is_local_name(local) {
563            return None;
564        }
565        let namespace = self
566            .prefixes
567            .iter()
568            .rev()
569            .find(|(name, _)| *name == prefix)
570            .map(|(_, iri)| *iri)?;
571        Some((namespace, local))
572    }
573}
574
575/// A prefix label: empty, or an ASCII letter followed by letters, digits,
576/// `_`, `-` or `.`, not ending in `.`. Narrower than Turtle's, which also
577/// allows other scripts.
578fn is_prefix_label(label: &str) -> bool {
579    let mut chars = label.chars();
580    match chars.next() {
581        None => true,
582        Some(first) => {
583            first.is_ascii_alphabetic()
584                && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
585                && !label.ends_with('.')
586        }
587    }
588}
589
590/// The local part of a prefixed name: ASCII letters, digits, `_`, `-`,
591/// `.` and `:`, not starting with `-` or `.` and not ending in `.`. No
592/// escape and no `%` sequence is accepted.
593fn is_local_name(local: &str) -> bool {
594    local
595        .chars()
596        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ':'))
597        && !local.starts_with(['-', '.'])
598        && !local.ends_with('.')
599}
600
601/// A blank-node label, `_:` then an ASCII letter, digit or `_`, then
602/// those, `-` or `.`, not ending in `.`.
603fn is_blank_label(word: &str) -> bool {
604    let Some(label) = word.strip_prefix("_:") else {
605        return false;
606    };
607    let mut chars = label.chars();
608    chars
609        .next()
610        .is_some_and(|first| first.is_ascii_alphanumeric() || first == '_')
611        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
612        && !label.ends_with('.')
613}
614
615/// A Turtle integer, decimal or double.
616fn is_number(word: &str) -> bool {
617    let unsigned = word.strip_prefix(['+', '-']).unwrap_or(word);
618    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
619        Some(at) => (&unsigned[..at], Some(&unsigned[at + 1..])),
620        None => (unsigned, None),
621    };
622    let (whole, fraction) = match mantissa.split_once('.') {
623        Some((whole, fraction)) => (whole, Some(fraction)),
624        None => (mantissa, None),
625    };
626    let digits = |text: &str| text.bytes().all(|b| b.is_ascii_digit());
627    if !digits(whole) || !fraction.is_none_or(digits) {
628        return false;
629    }
630    let has_point = fraction.is_some();
631    let fraction = fraction.unwrap_or("");
632    match exponent {
633        // An integer has digits; a decimal has digits after its point.
634        None if has_point => !fraction.is_empty(),
635        None => !whole.is_empty(),
636        Some(exponent) => {
637            let exponent = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
638            (!whole.is_empty() || !fraction.is_empty()) && !exponent.is_empty() && digits(exponent)
639        }
640    }
641}
642
643/// A language tag after its `@`: letters, then `-` and letters or digits.
644fn is_language_tag(tag: &str) -> bool {
645    let mut parts = tag.split('-');
646    parts
647        .next()
648        .is_some_and(|first| !first.is_empty() && first.bytes().all(|b| b.is_ascii_alphabetic()))
649        && parts.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
650}
651
652/// One token of the subset of Turtle [`card_names_owner`] reads.
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654enum Token<'a> {
655    /// The text between `<` and `>`.
656    Iri(&'a str),
657    /// A string literal, whatever its content.
658    Literal,
659    /// Any other run of characters: a prefixed name, a keyword, a number,
660    /// `a`, a language tag or a datatype marker. The reader decides
661    /// whether it is one it accepts.
662    Word(&'a str),
663    /// `.` ending a statement.
664    Dot,
665    /// `;` between predicates.
666    Semicolon,
667    /// `,` between objects.
668    Comma,
669    /// `[`.
670    OpenSquare,
671    /// `]`.
672    CloseSquare,
673    /// `(`.
674    OpenParen,
675    /// `)`.
676    CloseParen,
677}
678
679/// Turtle's whitespace: space, tab, CR and LF, and nothing else (not form
680/// feed, which Rust's ASCII whitespace includes).
681fn is_turtle_space(c: char) -> bool {
682    matches!(c, ' ' | '\t' | '\r' | '\n')
683}
684
685/// Splits `text` into tokens; `None` when an IRI or string literal is not
686/// terminated, an IRI holds a character Turtle forbids there or a `\`, or a
687/// string holds an escape Turtle does not define.
688fn tokenize(text: &str) -> Option<Vec<Token<'_>>> {
689    let mut tokens = Vec::new();
690    let mut rest = text;
691    loop {
692        rest = rest.trim_start_matches(is_turtle_space);
693        let Some(first) = rest.chars().next() else {
694            return Some(tokens);
695        };
696        let single = match first {
697            '.' => Some(Token::Dot),
698            ';' => Some(Token::Semicolon),
699            ',' => Some(Token::Comma),
700            '[' => Some(Token::OpenSquare),
701            ']' => Some(Token::CloseSquare),
702            '(' => Some(Token::OpenParen),
703            ')' => Some(Token::CloseParen),
704            _ => None,
705        };
706        if let Some(token) = single {
707            tokens.push(token);
708            rest = &rest[1..];
709            continue;
710        }
711        match first {
712            // A comment runs to the end of the line, which CR or LF ends.
713            '#' => {
714                rest = rest.find(['\r', '\n']).map_or("", |end| &rest[end..]);
715            }
716            '<' => {
717                let end = rest.find('>')?;
718                let iri = &rest[1..end];
719                if iri
720                    .chars()
721                    .any(|c| c.is_whitespace() || c.is_control() || "<\"{}|^`\\".contains(c))
722                {
723                    return None;
724                }
725                tokens.push(Token::Iri(iri));
726                rest = &rest[end + 1..];
727            }
728            '"' | '\'' => {
729                rest = skip_literal(rest, first)?;
730                tokens.push(Token::Literal);
731            }
732            _ => {
733                let end = rest
734                    .find(|c: char| is_turtle_space(c) || "<\"'#;,[]()".contains(c))
735                    .unwrap_or(rest.len());
736                let word = &rest[..end];
737                // A statement's final `.` may touch the word before it.
738                let trimmed = word.trim_end_matches('.');
739                if !trimmed.is_empty() {
740                    tokens.push(Token::Word(trimmed));
741                }
742                for _ in trimmed.len()..word.len() {
743                    tokens.push(Token::Dot);
744                }
745                rest = &rest[end..];
746            }
747        }
748    }
749}
750
751/// Skips the string literal at the start of `text`, which begins with
752/// `quote`, and returns what follows it; `None` when it is not terminated,
753/// a short string holds a raw CR or LF, or an escape is not one of
754/// `\t \b \n \r \f \" \' \\`, `\uXXXX` or `\UXXXXXXXX`.
755fn skip_literal(text: &str, quote: char) -> Option<&str> {
756    let triple: String = std::iter::repeat_n(quote, 3).collect();
757    let (body, close) = if text.starts_with(&triple) {
758        (&text[3..], triple.as_str())
759    } else {
760        (&text[1..], &text[..1])
761    };
762    let mut chars = body.char_indices();
763    while let Some((at, c)) = chars.next() {
764        if c == '\\' {
765            let (_, escape) = chars.next()?;
766            let hex_digits = match escape {
767                't' | 'b' | 'n' | 'r' | 'f' | '"' | '\'' | '\\' => 0,
768                'u' => 4,
769                'U' => 8,
770                _ => return None,
771            };
772            for _ in 0..hex_digits {
773                if !chars.next()?.1.is_ascii_hexdigit() {
774                    return None;
775                }
776            }
777            continue;
778        }
779        if close.len() == 1 && matches!(c, '\n' | '\r') {
780            return None;
781        }
782        if body[at..].starts_with(close) {
783            return Some(&body[at + close.len()..]);
784        }
785    }
786    None
787}
788
789#[cfg(test)]
790mod tests {
791    use super::{
792        card_names_owner, is_blank_label, is_language_tag, is_local_name, is_number,
793        is_prefix_label, tokenize, Token, MAX_NESTING,
794    };
795    use crate::NostrSecretKey;
796
797    #[test]
798    fn a_comment_ends_at_cr_or_lf() {
799        assert_eq!(
800            tokenize("# c\r<a> # d\n<b>"),
801            Some(vec![Token::Iri("a"), Token::Iri("b")]),
802            "both line ends"
803        );
804    }
805
806    #[test]
807    fn form_feed_is_not_whitespace() {
808        assert_eq!(
809            tokenize("<a>\x0c<b>"),
810            Some(vec![Token::Iri("a"), Token::Word("\x0c"), Token::Iri("b")]),
811            "kept as a word the reader refuses"
812        );
813    }
814
815    #[test]
816    fn only_defined_escapes_are_read() {
817        for good in [
818            r#""\t\b\n\r\f\"\'\\""#,
819            r#""\u00e9""#,
820            r#""\U0001F600""#,
821            "'''a\nb'''",
822        ] {
823            assert_eq!(tokenize(good), Some(vec![Token::Literal]), "{good:?}");
824        }
825        for bad in [
826            r#""\q""#,
827            r#""\u00g9""#,
828            "\"\\\n\"",
829            "\"a\rb\"",
830            "'a\rb'",
831            r"<a\u0062>",
832        ] {
833            assert_eq!(tokenize(bad), None, "{bad:?}");
834        }
835    }
836
837    #[test]
838    fn word_shapes() {
839        for label in ["", "owl", "f-o.a_f9"] {
840            assert!(is_prefix_label(label), "prefix {label:?}");
841        }
842        for label in ["9a", "a.", "_a", "a:b", "\u{e9}"] {
843            assert!(!is_prefix_label(label), "prefix {label:?}");
844        }
845        for local in ["", "sameAs", "a.b", "a:b", "9", "_x"] {
846            assert!(is_local_name(local), "local {local:?}");
847        }
848        for local in ["-a", ".a", "a.", r"o\#", "%41", "a/b"] {
849            assert!(!is_local_name(local), "local {local:?}");
850        }
851        for label in ["_:b0", "_:_", "_:a.b"] {
852            assert!(is_blank_label(label), "label {label:?}");
853        }
854        for label in ["_:", "_:-a", "_:a.", "b0"] {
855            assert!(!is_blank_label(label), "label {label:?}");
856        }
857        for number in ["1", "-1", "+1.5", "1.5", "1.e5", "1e-5", "1.5E+3", ".5"] {
858            assert!(is_number(number), "number {number:?}");
859        }
860        for number in ["", "-", "1.", "1e", "e5", "1.5.5", "0x1", "1e+"] {
861            assert!(!is_number(number), "number {number:?}");
862        }
863        for tag in ["en", "en-GB", "x-a1"] {
864            assert!(is_language_tag(tag), "tag {tag:?}");
865        }
866        for tag in ["", "en-", "-en", "e1", "en_GB"] {
867            assert!(!is_language_tag(tag), "tag {tag:?}");
868        }
869    }
870
871    #[test]
872    fn nesting_is_bounded() {
873        let owner = NostrSecretKey::from_hex(&"0b".repeat(32))
874            .expect("fixed key")
875            .public();
876        let naming = format!("<#me> <http://www.w3.org/2002/07/owl#sameAs> <{owner}> .\n");
877        let nested = |depth: usize| {
878            format!(
879                "<#x> <http://example.org/p> {}{} .\n{naming}",
880                "( ".repeat(depth),
881                ") ".repeat(depth)
882            )
883        };
884        assert!(
885            card_names_owner(nested(MAX_NESTING).as_bytes(), &owner),
886            "at the limit"
887        );
888        assert!(
889            !card_names_owner(nested(MAX_NESTING + 1).as_bytes(), &owner),
890            "past it"
891        );
892        // Far past it: refused, not a stack overflow.
893        assert!(
894            !card_names_owner(nested(100_000).as_bytes(), &owner),
895            "deep"
896        );
897    }
898
899    #[test]
900    fn tokenizer_reads_the_subset() {
901        let tokens = tokenize("<#me> a ex:P ; ex:n \"a;b.\" , '''x\n.''' . # c <x>\nex:z.")
902            .expect("tokenizes");
903        assert_eq!(
904            tokens,
905            [
906                Token::Iri("#me"),
907                Token::Word("a"),
908                Token::Word("ex:P"),
909                Token::Semicolon,
910                Token::Word("ex:n"),
911                Token::Literal,
912                Token::Comma,
913                Token::Literal,
914                Token::Dot,
915                Token::Word("ex:z"),
916                Token::Dot,
917            ],
918            "tokens"
919        );
920    }
921
922    #[test]
923    fn tokenizer_refuses_unterminated_input() {
924        for text in [
925            "<#me",
926            "\"open",
927            "'''open",
928            "\"line\nbreak\"",
929            "<a b>",
930            "\"esc\\",
931        ] {
932            assert_eq!(tokenize(text), None, "{text:?}");
933        }
934    }
935}