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 pub fn validate_registry(&self) -> Result<(), TeiError> {
111 match self.tei_type.as_str() {
112 "purl" => validate_purl(&self.identifier),
113 "hash" => validate_hash(&self.identifier),
114 "uuid" => validate_uuid_id(&self.identifier),
115 "eanupc" => validate_eanupc(&self.identifier),
116 "gtin" => validate_gtin(&self.identifier),
117 "asin" => validate_asin(&self.identifier),
118 "udi" => validate_udi(&self.identifier),
119 _ => Ok(()),
120 }
121 }
122
123 #[must_use]
129 pub fn publication_issues(&self) -> Vec<String> {
130 let mut issues = Vec::new();
131 if self.domain.chars().any(|c| c.is_ascii_uppercase()) {
132 issues.push("domain name is not lowercase ASCII".into());
133 }
134 if self.identifier.contains('%') && !uppercase_percent_hex(&self.identifier) {
135 issues.push("percent-escapes are not uppercase hexadecimal".into());
136 }
137 issues
138 }
139}
140
141impl fmt::Display for Tei {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str(&self.original)
144 }
145}
146
147impl Serialize for Tei {
148 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
149 serializer.serialize_str(&self.original)
150 }
151}
152
153impl<'de> Deserialize<'de> for Tei {
154 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
155 let value = String::deserialize(deserializer)?;
156 Self::parse(&value).map_err(serde::de::Error::custom)
157 }
158}
159
160fn validate_domain(domain: &str) -> Result<(), TeiError> {
161 if domain.len() > 253
162 || domain.starts_with('.')
163 || domain.ends_with('.')
164 || domain.contains(':')
165 || domain.contains('@')
166 {
167 return Err(TeiError::Domain);
168 }
169 let labels: Vec<&str> = domain.split('.').collect();
170 if labels.iter().any(|label| !valid_dns_label(label)) {
171 return Err(TeiError::Domain);
172 }
173 Ok(())
174}
175
176fn valid_dns_label(label: &str) -> bool {
177 let bytes = label.as_bytes();
178 if bytes.is_empty() || bytes.len() > 63 {
179 return false;
180 }
181 if bytes[0] == b'-' || bytes[bytes.len() - 1] == b'-' {
182 return false;
183 }
184 bytes
185 .iter()
186 .all(|b| b.is_ascii_alphanumeric() || *b == b'-')
187}
188
189fn validate_type(tei_type: &str) -> Result<(), TeiError> {
190 let mut chars = tei_type.chars();
191 let Some(first) = chars.next() else {
192 return Err(TeiError::Type);
193 };
194 if !first.is_ascii_lowercase() {
195 return Err(TeiError::Type);
196 }
197 if chars.any(|c| !c.is_ascii_lowercase() && !c.is_ascii_digit()) {
198 return Err(TeiError::Type);
199 }
200 Ok(())
201}
202
203fn validate_identifier_segment(identifier: &str) -> Result<(), TeiError> {
204 let bytes = identifier.as_bytes();
205 let mut index = 0;
206 while index < bytes.len() {
207 if bytes[index] == b'/' {
208 return Err(TeiError::Identifier);
209 }
210 if bytes[index] == b'%' {
211 if index + 2 >= bytes.len() {
212 return Err(TeiError::PercentEncoding);
213 }
214 let (high, low) = (bytes[index + 1], bytes[index + 2]);
217 if !high.is_ascii_hexdigit() || !low.is_ascii_hexdigit() {
218 return Err(TeiError::PercentEncoding);
219 }
220 if high == b'2' && low.eq_ignore_ascii_case(&b'f') {
221 return Err(TeiError::Identifier);
222 }
223 index += 3;
224 continue;
225 }
226 if bytes[index].is_ascii_control() || bytes[index] == b' ' {
227 return Err(TeiError::Identifier);
228 }
229 index += 1;
230 }
231 Ok(())
232}
233
234fn uppercase_percent_hex(identifier: &str) -> bool {
235 let bytes = identifier.as_bytes();
236 let mut index = 0;
237 while index < bytes.len() {
238 if bytes[index] == b'%' && index + 2 < bytes.len() {
239 if bytes[index + 1..index + 3]
240 .iter()
241 .any(u8::is_ascii_lowercase)
242 {
243 return false;
244 }
245 index += 3;
246 } else {
247 index += 1;
248 }
249 }
250 true
251}
252
253fn validate_purl(identifier: &str) -> Result<(), TeiError> {
254 if identifier.contains('=')
255 || !identifier
256 .bytes()
257 .all(|b| matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_'))
258 {
259 return Err(registry("purl", "must be unpadded Base64URL"));
260 }
261 let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
262 .decode(identifier)
263 .map_err(|_| registry("purl", "is not valid Base64URL"))?;
264 let text =
265 std::str::from_utf8(&decoded).map_err(|_| registry("purl", "does not decode to UTF-8"))?;
266 if !text.starts_with("pkg:") || text.is_empty() {
267 return Err(registry("purl", "does not decode to a Package URL"));
268 }
269 Ok(())
270}
271
272fn validate_hash(identifier: &str) -> Result<(), TeiError> {
273 let Some((alg, hex_value)) = identifier.split_once(':') else {
274 return Err(registry("hash", "must be `<hashtype>:<hex>`"));
275 };
276 let algorithm = ChecksumAlgorithm::from_wire(alg);
277 let Some(len) = algorithm.digest_len() else {
278 return Err(registry(
279 "hash",
280 "hashtype must be a checksum-type value such as SHA-256",
281 ));
282 };
283 if hex_value.len() != len * 2
284 || !hex_value.bytes().all(|b| b.is_ascii_hexdigit())
285 || hex_value.bytes().any(|b| b.is_ascii_uppercase())
286 {
287 return Err(registry(
288 "hash",
289 "digest must be lowercase hexadecimal of the algorithm length",
290 ));
291 }
292 Ok(())
293}
294
295fn validate_uuid_id(identifier: &str) -> Result<(), TeiError> {
296 TeaUuid::parse(identifier)
297 .map(|_| ())
298 .map_err(|_| registry("uuid", "must be the lowercase hyphenated RFC 9562 form"))
299}
300
301fn validate_eanupc(identifier: &str) -> Result<(), TeiError> {
302 if !matches!(identifier.len(), 8 | 12 | 13) {
303 return Err(registry(
304 "eanupc",
305 "must be 8, 12, or 13 digits with its check digit",
306 ));
307 }
308 gs1(identifier, "eanupc")
309}
310
311fn validate_gtin(identifier: &str) -> Result<(), TeiError> {
312 if !matches!(identifier.len(), 8 | 12 | 13 | 14) {
313 return Err(registry(
314 "gtin",
315 "must be a GTIN-8, GTIN-12, GTIN-13, or GTIN-14",
316 ));
317 }
318 gs1(identifier, "gtin")
319}
320
321fn validate_asin(identifier: &str) -> Result<(), TeiError> {
322 if identifier.len() != 10
323 || !identifier
324 .bytes()
325 .all(|b| matches!(b, b'A'..=b'Z' | b'0'..=b'9'))
326 {
327 return Err(registry("asin", "must be 10 uppercase letters or digits"));
328 }
329 Ok(())
330}
331
332fn validate_udi(identifier: &str) -> Result<(), TeiError> {
333 if identifier.is_empty() {
334 return Err(registry("udi", "device identifier must not be empty"));
335 }
336 if identifier.starts_with("(01)") || identifier.starts_with('+') {
337 return Err(registry(
338 "udi",
339 "must not include an application identifier or data identifier prefix",
340 ));
341 }
342 Ok(())
343}
344
345fn gs1(identifier: &str, tei_type: &str) -> Result<(), TeiError> {
346 if !identifier.bytes().all(|b| b.is_ascii_digit()) {
347 return Err(registry(tei_type, "must be digits"));
348 }
349 let digits: Vec<u32> = identifier.bytes().map(|b| u32::from(b - b'0')).collect();
350 let check = digits[digits.len() - 1];
351 let mut sum = 0u32;
352 for (index, digit) in digits[..digits.len() - 1].iter().rev().enumerate() {
353 let weight = if index % 2 == 0 { 3 } else { 1 };
354 sum += digit * weight;
355 }
356 let calculated = (10 - (sum % 10)) % 10;
357 if calculated != check {
358 return Err(registry(tei_type, "check digit is not valid"));
359 }
360 Ok(())
361}
362
363fn registry(tei_type: &str, reason: &str) -> TeiError {
364 TeiError::Registry {
365 tei_type: tei_type.to_owned(),
366 reason: reason.to_owned(),
367 }
368}
369
370#[must_use]
372pub fn encode_query_component(value: &str) -> String {
373 let mut out = String::with_capacity(value.len());
374 for byte in value.bytes() {
375 match byte {
376 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
377 out.push(char::from(byte));
378 }
379 _ => out.push_str(&format!("%{byte:02X}")),
380 }
381 }
382 out
383}
384
385#[cfg(test)]
386mod tests {
387 #[test]
388 fn non_ascii_after_percent_is_an_error_not_a_panic() {
389 for text in [
390 "tei://example.com/uuid/%a\u{e9}",
391 "tei://example.com/purl/x%a\u{e9}",
392 "tei://example.com/purl/%\u{e9}a",
393 "tei://example.com/hash/%4\u{1f600}",
394 "tei://example.com/x/%\u{e9}",
395 ] {
396 assert!(Tei::parse(text).is_err(), "{text}");
397 }
398 let tei = Tei::parse("tei://example.com/x/%41\u{e9}").unwrap();
400 assert!(tei.publication_issues().is_empty());
401 let lower = Tei::parse("tei://example.com/x/%4a\u{e9}").unwrap();
402 assert_eq!(lower.publication_issues().len(), 1);
403 }
404
405 use super::*;
406
407 const UUID_TEI: &str = "tei://example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1";
408 const PURL_TEI: &str =
409 "tei://example.com/purl/cGtnOm1hdmVuL2NvbW1vbnMtaW8vY29tbW9ucy1pb0AyLjIyLjA";
410 const HASH_TEI: &str = "tei://example.com/hash/SHA-256:fd44efd601f651c8865acf0dfeacb0df19a2b50ec69ead0262096fd2f67197b9";
411
412 #[test]
413 fn parses_registry_examples() {
414 for tei in [
415 UUID_TEI,
416 PURL_TEI,
417 HASH_TEI,
418 "tei://example.com/eanupc/1234567890128",
419 "tei://example.com/gtin/0234567890129",
420 "tei://example.com/asin/B07FZ8S74R",
421 "tei://example.com/udi/00123456789012",
422 ] {
423 let parsed = Tei::parse(tei).unwrap();
424 parsed.validate_registry().unwrap();
425 assert_eq!(parsed.as_str(), tei);
426 assert_eq!(parsed.to_string(), tei);
427 }
428 }
429
430 #[test]
431 fn does_not_treat_case_variants_as_equal() {
432 let lower = Tei::parse(UUID_TEI).unwrap();
433 let upper_domain =
434 Tei::parse("tei://Example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").unwrap();
435 assert_ne!(lower, upper_domain);
436 assert!(!upper_domain.publication_issues().is_empty());
437 assert!(Tei::parse("TEI://example.com/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err());
438 assert!(Tei::parse("tei://example.com/UUID/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err());
439 }
440
441 #[test]
442 fn rejects_slash_and_port() {
443 assert!(Tei::parse("tei://example.com/uuid/a/b").is_err());
444 assert!(Tei::parse("tei://example.com/uuid/a%2Fb").is_err());
445 assert!(Tei::parse("tei://example.com/uuid/a%2fb").is_err());
446 assert!(
447 Tei::parse("tei://example.com:443/uuid/d4d9f54a-abcf-11ee-ac79-1a52914d44b1").is_err()
448 );
449 }
450
451 #[test]
452 fn unknown_type_parses_without_registry_rules() {
453 let tei = Tei::parse("tei://example.com/sku/ABC-1").unwrap();
454 assert!(tei.validate_registry().is_ok());
455 }
456
457 #[test]
458 fn padded_purl_is_rejected() {
459 let tei =
460 Tei::parse("tei://example.com/purl/cGtnOnB5cGkvY3ljbG9uZWR4LXB5dGhvbi1saWI=").unwrap();
461 assert!(tei.validate_registry().is_err());
462 }
463
464 #[test]
465 fn query_encoding_matches_openapi_example_shape() {
466 let encoded = encode_query_component(
467 "tei://products.example.com/uuid/47f51950-b0e2-11f1-adc2-1a52914d44b2",
468 );
469 assert_eq!(
470 encoded,
471 "tei%3A%2F%2Fproducts.example.com%2Fuuid%2F47f51950-b0e2-11f1-adc2-1a52914d44b2"
472 );
473 }
474}