|
| 1 | +/** |
| 2 | + * Trait Validation Utility |
| 3 | + * |
| 4 | + * Validates that SIWE message trait requirements match backend expectations. |
| 5 | + * This prevents users from modifying trait requirements on the frontend. |
| 6 | + */ |
| 7 | + |
| 8 | +export interface TraitRequirement { |
| 9 | + [traitName: string]: string; // e.g., { 'verified': 'true', 'followers': 'gte:1000' } |
| 10 | +} |
| 11 | + |
| 12 | +export interface ValidationResult { |
| 13 | + valid: boolean; |
| 14 | + error?: string; |
| 15 | + provider?: string; |
| 16 | + foundTraits?: TraitRequirement; |
| 17 | + expectedTraits?: TraitRequirement; |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Parse trait URNs from SIWE message resources |
| 22 | + * Format: urn:verify:provider:{provider}:{trait_name}:{operation}:{value} |
| 23 | + * |
| 24 | + * @param message - The SIWE message string |
| 25 | + * @returns Object with provider and traits, or null if no provider found |
| 26 | + */ |
| 27 | +function parseTraitsFromMessage(message: string): { provider: string; traits: TraitRequirement } | null { |
| 28 | + // Extract resources section from SIWE message |
| 29 | + const resourcesMatch = message.match(/Resources:\s*\n((?:- .+\n)+)/); |
| 30 | + if (!resourcesMatch) { |
| 31 | + return null; |
| 32 | + } |
| 33 | + |
| 34 | + const resources = resourcesMatch[1] |
| 35 | + .split('\n') |
| 36 | + .map(line => line.replace(/^- /, '').trim()) |
| 37 | + .filter(line => line.length > 0); |
| 38 | + |
| 39 | + // Find provider URN |
| 40 | + const providerUrn = resources.find(r => r.match(/^urn:verify:provider:[^:]+$/)); |
| 41 | + if (!providerUrn) { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + const providerMatch = providerUrn.match(/^urn:verify:provider:([^:]+)$/); |
| 46 | + if (!providerMatch) { |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + const provider = providerMatch[1]; |
| 51 | + const traits: TraitRequirement = {}; |
| 52 | + |
| 53 | + // Parse trait URNs for this provider |
| 54 | + const traitPattern = new RegExp(`^urn:verify:provider:${provider}:([^:]+):([^:]+):(.+)$`); |
| 55 | + |
| 56 | + resources.forEach(resource => { |
| 57 | + const traitMatch = resource.match(traitPattern); |
| 58 | + if (traitMatch) { |
| 59 | + const [, traitName, operation, value] = traitMatch; |
| 60 | + |
| 61 | + // Reconstruct the trait value with operation prefix |
| 62 | + // (except for 'eq' which is the default and can be omitted) |
| 63 | + if (operation === 'eq') { |
| 64 | + traits[traitName] = value; |
| 65 | + } else { |
| 66 | + traits[traitName] = `${operation}:${value}`; |
| 67 | + } |
| 68 | + } |
| 69 | + }); |
| 70 | + |
| 71 | + return { provider, traits }; |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Normalize trait requirement for comparison |
| 76 | + * Handles the 'eq' operation being implicit |
| 77 | + * |
| 78 | + * @param value - The trait value (e.g., 'true', 'gte:1000') |
| 79 | + * @returns Normalized value with explicit operation |
| 80 | + */ |
| 81 | +function normalizeTraitValue(value: string): string { |
| 82 | + // If value doesn't have an operation prefix, it's implicitly 'eq' |
| 83 | + if (!value.match(/^(eq|gt|gte|lt|lte|in):/)) { |
| 84 | + return `eq:${value}`; |
| 85 | + } |
| 86 | + return value; |
| 87 | +} |
| 88 | + |
| 89 | +/** |
| 90 | + * Validate that message traits match expected requirements |
| 91 | + * |
| 92 | + * @param message - The SIWE message string |
| 93 | + * @param expectedProvider - Expected provider name (e.g., 'x', 'coinbase') |
| 94 | + * @param expectedTraits - Expected trait requirements |
| 95 | + * @returns ValidationResult with validation status and details |
| 96 | + */ |
| 97 | +export function validateTraits( |
| 98 | + message: string, |
| 99 | + expectedProvider: string, |
| 100 | + expectedTraits: TraitRequirement |
| 101 | +): ValidationResult { |
| 102 | + // Parse traits from message |
| 103 | + const parsed = parseTraitsFromMessage(message); |
| 104 | + |
| 105 | + if (!parsed) { |
| 106 | + return { |
| 107 | + valid: false, |
| 108 | + error: `No provider found in SIWE message`, |
| 109 | + expectedTraits |
| 110 | + }; |
| 111 | + } |
| 112 | + |
| 113 | + const { provider, traits: foundTraits } = parsed; |
| 114 | + |
| 115 | + // Check provider matches |
| 116 | + if (provider !== expectedProvider) { |
| 117 | + return { |
| 118 | + valid: false, |
| 119 | + error: `Provider mismatch: expected '${expectedProvider}', found '${provider}'`, |
| 120 | + provider, |
| 121 | + foundTraits, |
| 122 | + expectedTraits |
| 123 | + }; |
| 124 | + } |
| 125 | + |
| 126 | + // Normalize all trait values for comparison |
| 127 | + const normalizedExpected: Record<string, string> = {}; |
| 128 | + Object.entries(expectedTraits).forEach(([key, value]) => { |
| 129 | + normalizedExpected[key] = normalizeTraitValue(value); |
| 130 | + }); |
| 131 | + |
| 132 | + const normalizedFound: Record<string, string> = {}; |
| 133 | + Object.entries(foundTraits).forEach(([key, value]) => { |
| 134 | + normalizedFound[key] = normalizeTraitValue(value); |
| 135 | + }); |
| 136 | + |
| 137 | + // Check all expected traits are present with correct values |
| 138 | + const missingTraits: string[] = []; |
| 139 | + const mismatchedTraits: Array<{ trait: string; expected: string; found: string }> = []; |
| 140 | + |
| 141 | + Object.entries(normalizedExpected).forEach(([traitName, expectedValue]) => { |
| 142 | + if (!(traitName in normalizedFound)) { |
| 143 | + missingTraits.push(traitName); |
| 144 | + } else if (normalizedFound[traitName] !== expectedValue) { |
| 145 | + mismatchedTraits.push({ |
| 146 | + trait: traitName, |
| 147 | + expected: expectedValue, |
| 148 | + found: normalizedFound[traitName] |
| 149 | + }); |
| 150 | + } |
| 151 | + }); |
| 152 | + |
| 153 | + // Check for unexpected traits (traits in message but not in expected) |
| 154 | + const unexpectedTraits = Object.keys(normalizedFound).filter( |
| 155 | + key => !(key in normalizedExpected) |
| 156 | + ); |
| 157 | + |
| 158 | + // Build error message if validation fails |
| 159 | + if (missingTraits.length > 0 || mismatchedTraits.length > 0 || unexpectedTraits.length > 0) { |
| 160 | + const errors: string[] = []; |
| 161 | + |
| 162 | + if (missingTraits.length > 0) { |
| 163 | + errors.push(`Missing required traits: ${missingTraits.join(', ')}`); |
| 164 | + } |
| 165 | + |
| 166 | + if (mismatchedTraits.length > 0) { |
| 167 | + const details = mismatchedTraits |
| 168 | + .map(({ trait, expected, found }) => `${trait} (expected: ${expected}, found: ${found})`) |
| 169 | + .join('; '); |
| 170 | + errors.push(`Trait value mismatch: ${details}`); |
| 171 | + } |
| 172 | + |
| 173 | + if (unexpectedTraits.length > 0) { |
| 174 | + errors.push(`Unexpected traits: ${unexpectedTraits.join(', ')}`); |
| 175 | + } |
| 176 | + |
| 177 | + return { |
| 178 | + valid: false, |
| 179 | + error: errors.join('. '), |
| 180 | + provider, |
| 181 | + foundTraits, |
| 182 | + expectedTraits |
| 183 | + }; |
| 184 | + } |
| 185 | + |
| 186 | + // All checks passed |
| 187 | + return { |
| 188 | + valid: true, |
| 189 | + provider, |
| 190 | + foundTraits, |
| 191 | + expectedTraits |
| 192 | + }; |
| 193 | +} |
| 194 | + |
0 commit comments