1use std::fmt;
8
9use base64::Engine;
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::enums::ChecksumAlgorithm;
13use crate::error::TeiError;
14use crate::ids::TeaUuid;
15
16const SCHEME: &str = "tei://";
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub struct Tei {
21 original: String,
22 domain: String,
23 tei_type: String,
24 identifier: String,
25}
26
27impl Tei {
28 pub fn parse(input: &str) -> Result<Self, TeiError> {
37 if input.is_empty() {
38 return Err(TeiError::Empty);
39 }
40 if input
41 .get(..8)
42 .is_some_and(|prefix| prefix.eq_ignore_ascii_case("urn:tei:"))
43 {
44 return Err(TeiError::LegacyUrn);
45 }
46 let rest = input.strip_prefix(SCHEME).ok_or(TeiError::Scheme)?;
47 if rest.contains(['?', '#', ' ']) {
48 return Err(TeiError::Structure);
49 }
50 let mut parts = rest.split('/');
51 let domain = parts.next().ok_or(TeiError::Structure)?;
52 let tei_type = parts.next().ok_or(TeiError::Structure)?;
53 let identifier = parts.next().ok_or(TeiError::Structure)?;
54 if parts.next().is_some()
55 || domain.is_empty()
56 || tei_type.is_empty()
57 || identifier.is_empty()
58 {
59 return Err(TeiError::Structure);
60 }
61 validate_domain(domain)?;
62 validate_type(tei_type)?;
63 validate_identifier_segment(identifier)?;
64 Ok(Self {
65 original: input.to_owned(),
66 domain: domain.to_owned(),
67 tei_type: tei_type.to_owned(),
68 identifier: identifier.to_owned(),
69 })
70 }
71
72 #[must_use]
74 pub fn as_str(&self) -> &str {
75 &self.original
76 }
77
78 #[must_use]
80 pub fn domain(&self) -> &str {
81 &self.domain
82 }
83
84 #[must_use]
86 pub fn tei_type(&self) -> &str {
87 &self.tei_type
88 }
89
90 #[must_use]
92 pub fn identifier(&self) -> &str {
93 &self.identifier
94 }
95
96 #[must_use]
98 pub fn well_known_url(&self) -> String {
99 format!("https://{}/.well-known/tea", self.domain)
100 }
101
102 #[must_use]
119 pub fn purl(&self) -> Option<Result<crate::purl::Purl, crate::purl::PurlError>> {
120 if self.tei_type != "purl" {
121 return None;
122 }
123 let decoded = if self.identifier.contains('=') {
124 None
125 } else {
126 base64::engine::general_purpose::URL_SAFE_NO_PAD
127 .decode(&self.identifier)
128 .ok()
129 .and_then(|bytes| String::from_utf8(bytes).ok())
130 };
131 Some(match decoded {
132 Some(text) => crate::purl::Purl::parse(&text),
133 None => Err(crate::purl::PurlError::TeiIdentifier),
134 })
135 }
136
137 pub fn validate_registry(&self) -> Result<(), TeiError> {
146 match self.tei_type.as_str() {
147 "purl" => validate_purl(&self.identifier),
148 "hash" => validate_hash(&self.identifier),
149 "uuid" => validate_uuid_id(&self.identifier),
150 "eanupc" => validate_eanupc(&self.identifier),
151 "gtin" => validate_gtin(&self.identifier),
152 "asin" => validate_asin(&self.identifier),
153 "udi" => validate_udi(&self.identifier),
154 _ => Ok(()),
155 }
156 }
157
158 #[must_use]
164 pub fn publication_issues(&self) -> Vec<String> {
165 let mut issues = Vec::new();
166 if self.domain.chars().any(|c| c.is_ascii_uppercase()) {
167 issues.push("domain name is not lowercase ASCII".into());
168 }
169 if self.identifier.contains('%') && !uppercase_percent_hex(&self.identifier) {
170 issues.push("percent-escapes are not uppercase hexadecimal".into());
171 }
172 issues
173 }
174}
175
176impl fmt::Display for Tei {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.write_str(&self.original)
179 }
180}
181
182impl Serialize for Tei {
183 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
184 serializer.serialize_str(&self.original)
185 }
186}
187
188impl<'de> Deserialize<'de> for Tei {
189 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
190 let value = String::deserialize(deserializer)?;
191 Self::parse(&value).map_err(serde::de::Error::custom)
192 }
193}
194
195fn validate_domain(domain: &str) -> Result<(), TeiError> {
196 if domain.len() > 253
197 || domain.starts_with('.')
198 || domain.ends_with('.')
199 || domain.contains(':')
200 || domain.contains('@')
201 {
202 return Err(TeiError::Domain);
203 }
204 let labels: Vec<&str> = domain.split('.').collect();
205 if labels.iter().any(|label| !valid_dns_label(label)) {
206 return Err(TeiError::Domain);
207 }
208 Ok(())
209}
210
211fn valid_dns_label(label: &str) -> bool {
212 let bytes = label.as_bytes();
213 if bytes.is_empty() || bytes.len() > 63 {
214 return false;
215 }
216 if bytes[0] == b'-' || bytes[bytes.len() - 1] == b'-' {
217 return false;
218 }
219 bytes
220 .iter()
221 .all(|b| b.is_ascii_alphanumeric() || *b == b'-')
222}
223
224fn validate_type(tei_type: &str) -> Result<(), TeiError> {
225 let mut chars = tei_type.chars();
226 let Some(first) = chars.next() else {
227 return Err(TeiError::Type);
228 };
229 if !first.is_ascii_lowercase() {
230 return Err(TeiError::Type);
231 }
232 if chars.any(|c| !c.is_ascii_lowercase() && !c.is_ascii_digit()) {
233 return Err(TeiError::Type);
234 }
235 Ok(())
236}
237
238fn validate_identifier_segment(identifier: &str) -> Result<(), TeiError> {
239 let bytes = identifier.as_bytes();
240 let mut index = 0;
241 while index < bytes.len() {
242 if bytes[index] == b'/' {
243 return Err(TeiError::Identifier);
244 }
245 if bytes[index] == b'%' {
246 if index + 2 >= bytes.len() {
247 return Err(TeiError::PercentEncoding);
248 }
249 let (high, low) = (bytes[index + 1], bytes[index + 2]);
252 if !high.is_ascii_hexdigit() || !low.is_ascii_hexdigit() {
253 return Err(TeiError::PercentEncoding);
254 }
255 if high == b'2' && low.eq_ignore_ascii_case(&b'f') {
256 return Err(TeiError::Identifier);
257 }
258 index += 3;
259 continue;
260 }
261 if bytes[index].is_ascii_control() || bytes[index] == b' ' {
262 return Err(TeiError::Identifier);
263 }
264 index += 1;
265 }
266 Ok(())
267}
268
269fn uppercase_percent_hex(identifier: &str) -> bool {
270 let bytes = identifier.as_bytes();
271 let mut index = 0;
272 while index < bytes.len() {
273 if bytes[index] == b'%' && index + 2 < bytes.len() {
274 if bytes[index + 1..index + 3]
275 .iter()
276 .any(u8::is_ascii_lowercase)
277 {
278 return false;
279 }
280 index += 3;
281 } else {
282 index += 1;
283 }
284 }
285 true
286}
287
288fn validate_purl(identifier: &str) -> Result<(), TeiError> {
289 if identifier.contains('=')
290 || !identifier
291 .bytes()
292 .all(|b| matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_'))
293 {
294 return Err(registry("purl", "must be unpadded Base64URL"));
295 }
296 let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
297 .decode(identifier)
298 .map_err(|_| registry("purl", "is not valid Base64URL"))?;
299 let text =
300 std::str::from_utf8(&decoded).map_err(|_| registry("purl", "does not decode to UTF-8"))?;
301 if !text.starts_with("pkg:") || text.is_empty() {
302 return Err(registry("purl", "does not decode to a Package URL"));
303 }
304 Ok(())
305}
306
307fn validate_hash(identifier: &str) -> Result<(), TeiError> {
308 let Some((alg, hex_value)) = identifier.split_once(':') else {
309 return Err(registry("hash", "must be `<hashtype>:<hex>`"));
310 };
311 let algorithm = ChecksumAlgorithm::from_wire(alg);
312 let Some(len) = algorithm.digest_len() else {
313 return Err(registry(
314 "hash",
315 "hashtype must be a checksum-type value such as SHA-256",
316 ));
317 };
318 if hex_value.len() != len * 2
319 || !hex_value.bytes().all(|b| b.is_ascii_hexdigit())
320 || hex_value.bytes().any(|b| b.is_ascii_uppercase())
321 {
322 return Err(registry(
323 "hash",
324 "digest must be lowercase hexadecimal of the algorithm length",
325 ));
326 }
327 Ok(())
328}
329
330fn validate_uuid_id(identifier: &str) -> Result<(), TeiError> {
331 TeaUuid::parse(identifier)
332 .map(|_| ())
333 .map_err(|_| registry("uuid", "must be the lowercase hyphenated RFC 9562 form"))
334}
335
336fn validate_eanupc(identifier: &str) -> Result<(), TeiError> {
337 if !matches!(identifier.len(), 8 | 12 | 13) {
338 return Err(registry(
339 "eanupc",
340 "must be 8, 12, or 13 digits with its check digit",
341 ));
342 }
343 gs1(identifier, "eanupc")
344}
345
346fn validate_gtin(identifier: &str) -> Result<(), TeiError> {
347 if !matches!(identifier.len(), 8 | 12 | 13 | 14) {
348 return Err(registry(
349 "gtin",
350 "must be a GTIN-8, GTIN-12, GTIN-13, or GTIN-14",
351 ));
352 }
353 gs1(identifier, "gtin")
354}
355
356fn validate_asin(identifier: &str) -> Result<(), TeiError> {
357 if identifier.len() != 10
358 || !identifier
359 .bytes()
360 .all(|b| matches!(b, b'A'..=b'Z' | b'0'..=b'9'))
361 {
362 return Err(registry("asin", "must be 10 uppercase letters or digits"));
363 }
364 Ok(())
365}
366
367fn validate_udi(identifier: &str) -> Result<(), TeiError> {
368 if identifier.is_empty() {
369 return Err(registry("udi", "device identifier must not be empty"));
370 }
371 if identifier.starts_with("(01)") || identifier.starts_with('+') {
372 return Err(registry(
373 "udi",
374 "must not include an application identifier or data identifier prefix",
375 ));
376 }
377 Ok(())
378}
379
380fn gs1(identifier: &str, tei_type: &str) -> Result<(), TeiError> {
381 if !identifier.bytes().all(|b| b.is_ascii_digit()) {
382 return Err(registry(tei_type, "must be digits"));
383 }
384 let digits: Vec<u32> = identifier.bytes().map(|b| u32::from(b - b'0')).collect();
385 let check = digits[digits.len() - 1];
386 let mut sum = 0u32;
387 for (index, digit) in digits[..digits.len() - 1].iter().rev().enumerate() {
388 let weight = if index % 2 == 0 { 3 } else { 1 };
389 sum += digit * weight;
390 }
391 let calculated = (10 - (sum % 10)) % 10;
392 if calculated != check {
393 return Err(registry(tei_type, "check digit is not valid"));
394 }
395 Ok(())
396}
397
398fn registry(tei_type: &str, reason: &str) -> TeiError {
399 TeiError::Registry {
400 tei_type: tei_type.to_owned(),
401 reason: reason.to_owned(),
402 }
403}
404
405#[must_use]
407pub fn encode_query_component(value: &str) -> String {
408 let mut out = String::with_capacity(value.len());
409 for byte in value.bytes() {
410 match byte {
411 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
412 out.push(char::from(byte));
413 }
414 _ => out.push_str(&format!("%{byte:02X}")),
415 }
416 }
417 out
418}
419
420#[cfg(test)]
421mod tests {
422 #[test]
423 fn non_ascii_after_percent_is_an_error_not_a_panic() {
424 for text in [
425 "tei://example.com/uuid/%a\u{e9}",
426 "tei://example.com/purl/x%a\u{e9}",
427 "tei://example.com/purl/%\u{e9}a",
428 "tei://example.com/hash/%4\u{1f600}",
429 "tei://example.com/x/%\u{e9}",
430 ] {
431 assert!(Tei::parse(text).is_err(), "{text}");
432 }
433 let tei = Tei::parse("tei://example.com/x/%41\u{e9}").unwrap();
435 assert!(tei.publication_issues().is_empty());
436 let lower = Tei::parse("tei://example.com/x/%4a\u{e9}").unwrap();
437 assert_eq!(lower.publication_issues().len(), 1);
438 }
439
440 use super::*;
441
442 const UUID_TEI: &str = "tei://example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1";
443 const PURL_TEI: &str =
444 "tei://example.com/purl/cGtnOm1hdmVuL2NvbW1vbnMtaW8vY29tbW9ucy1pb0AyLjIyLjA";
445 const HASH_TEI: &str = "tei://example.com/hash/SHA-256:fd44efd601f651c8865acf0dfeacb0df19a2b50ec69ead0262096fd2f67197b9";
446
447 #[test]
448 fn parses_registry_examples() {
449 for tei in [
450 UUID_TEI,
451 PURL_TEI,
452 HASH_TEI,
453 "tei://example.com/eanupc/1234567890128",
454 "tei://example.com/gtin/0234567890129",
455 "tei://example.com/asin/B07FZ8S74R",
456 "tei://example.com/udi/00123456789012",
457 ] {
458 let parsed = Tei::parse(tei).unwrap();
459 parsed.validate_registry().unwrap();
460 assert_eq!(parsed.as_str(), tei);
461 assert_eq!(parsed.to_string(), tei);
462 }
463 }
464
465 #[test]
466 fn does_not_treat_case_variants_as_equal() {
467 let lower = Tei::parse(UUID_TEI).unwrap();
468 let upper_domain =
469 Tei::parse("tei://Example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").unwrap();
470 assert_ne!(lower, upper_domain);
471 assert!(!upper_domain.publication_issues().is_empty());
472 assert!(Tei::parse("TEI://example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err());
473 assert!(Tei::parse("tei://example.com/UUID/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err());
474 }
475
476 #[test]
477 fn rejects_slash_and_port() {
478 assert!(Tei::parse("tei://example.com/uuid/a/b").is_err());
479 assert!(Tei::parse("tei://example.com/uuid/a%2Fb").is_err());
480 assert!(Tei::parse("tei://example.com/uuid/a%2fb").is_err());
481 assert!(
482 Tei::parse("tei://example.com:443/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err()
483 );
484 }
485
486 #[test]
487 fn unknown_type_parses_without_registry_rules() {
488 let tei = Tei::parse("tei://example.com/sku/ABC-1").unwrap();
489 assert!(tei.validate_registry().is_ok());
490 }
491
492 #[test]
493 fn padded_purl_is_rejected() {
494 let tei =
495 Tei::parse("tei://example.com/purl/cGtnOnB5cGkvY3ljbG9uZWR4LXB5dGhvbi1saWI=").unwrap();
496 assert!(tei.validate_registry().is_err());
497 }
498
499 #[test]
500 fn query_encoding_matches_openapi_example_shape() {
501 let encoded = encode_query_component(
502 "tei://products.example.com/uuid/47f51950-b0e2-11f1-adc2-1a52914d44b2",
503 );
504 assert_eq!(
505 encoded,
506 "tei%3A%2F%2Fproducts.example.com%2Fuuid%2F47f51950-b0e2-11f1-adc2-1a52914d44b2"
507 );
508 }
509}