use crate::did::DidNostr;
use crate::pod_path::PodPath;
pub const PROFILE_CARD_RELATIVE: &str = "profile/card";
pub const PROFILE_CONTENT_TYPE: &str = "text/turtle";
pub const PROFILE_MAX_BYTES: usize = 65_536;
const PODS_PREFIX: &[u8] = b"/pods/";
const CARD_SUFFIX: &[u8] = b"/profile/card";
const KEY_HEX_LEN: usize = 64;
const OWL_NAMESPACE: &str = "http://www.w3.org/2002/07/owl#";
const OWL_SAME_AS: &str = "http://www.w3.org/2002/07/owl#sameAs";
const DID_SCHEME: &str = "did:";
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")
}
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()
}
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"
)
}
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"
)
}
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();
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)
}
fn is_did(iri: &str) -> bool {
iri.get(..DID_SCHEME.len())
.is_some_and(|head| head.eq_ignore_ascii_case(DID_SCHEME))
}
fn is_directive(word: &str, name: &str) -> bool {
word.strip_prefix('@') == Some(name) || word.eq_ignore_ascii_case(name)
}
const MAX_NESTING: usize = 32;
struct Reader<'t, 'a> {
tokens: &'t [Token<'a>],
at: usize,
prefixes: Vec<(&'a str, &'a str)>,
owner_iri: &'t str,
depth: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Term<'a> {
Iri(&'a str),
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(())
}
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)?;
}
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)
}
fn triples(&mut self) -> Option<bool> {
let start = self.at;
let names_owner = if self.peek()? == Token::OpenSquare {
self.at += 1;
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,
}
}
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)
}
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,
}
}
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)
}
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(())
}
fn is_name(&self, word: &'a str) -> bool {
self.expand(word).is_some()
}
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))
}
}
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('.')
}
}
}
fn is_local_name(local: &str) -> bool {
local
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ':'))
&& !local.starts_with(['-', '.'])
&& !local.ends_with('.')
}
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('.')
}
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 {
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)
}
}
}
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()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token<'a> {
Iri(&'a str),
Literal,
Word(&'a str),
Dot,
Semicolon,
Comma,
OpenSquare,
CloseSquare,
OpenParen,
CloseParen,
}
fn is_turtle_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\r' | '\n')
}
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 {
'#' => {
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];
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..];
}
}
}
}
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"
);
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:?}");
}
}
}