diff --git a/backend/src/lib/__tests__/providerId.test.ts b/backend/src/lib/__tests__/providerId.test.ts new file mode 100644 index 00000000..f166e3f4 --- /dev/null +++ b/backend/src/lib/__tests__/providerId.test.ts @@ -0,0 +1,317 @@ +/** + * backend/src/lib/__tests__/providerId.test.ts + * + * Unit tests for the stable canonical provider-id resolver (issue #2256). + * Every documented behaviour — normalisation, determinism, collision + * resistance, validation, error codes and observability — is pinned here. + */ + +import { + ProviderIdErrorCode, + ProviderIdError, + DEFAULT_CANONICAL_ID_CONFIG, + validateCanonicalIdConfig, + parseProviderIdentifier, + normalizeExternalId, + fnv1a32, + canonicalizeProviderId, + resolveProviderId, + areSameProviderId, + createCanonicalIdResolver, + noopCanonicalIdMetrics, + noopCanonicalIdLogger, +} from '../providerId'; +import { + CANONICAL_ID_PATTERN, + CANONICAL_ID_VERSION, + KNOWN_PROVIDERS, + MAX_NORMALIZED_ID_LENGTH, +} from '../../../../packages/billing-types/src/index'; + +/** Assert that `fn` throws a ProviderIdError carrying the expected stable code. */ +function expectCode(fn: () => unknown, code: string): void { + try { + fn(); + throw new Error('expected function to throw'); + } catch (error) { + expect((error as { code?: string }).code).toBe(code); + } +} + +describe('error surface and constants', () => { + it('exposes stable error codes', () => { + expect(ProviderIdErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(ProviderIdErrorCode.INVALID_INPUT).toBe('INVALID_INPUT'); + expect(ProviderIdErrorCode.INVALID_FORMAT).toBe('INVALID_FORMAT'); + expect(ProviderIdErrorCode.INVALID_PROVIDER).toBe('INVALID_PROVIDER'); + expect(ProviderIdErrorCode.UNKNOWN_PROVIDER).toBe('UNKNOWN_PROVIDER'); + expect(ProviderIdErrorCode.INVALID_EXTERNAL_ID).toBe('INVALID_EXTERNAL_ID'); + expect(ProviderIdErrorCode.EXTERNAL_ID_TOO_LONG).toBe('EXTERNAL_ID_TOO_LONG'); + expect(ProviderIdErrorCode.INVALID_CANONICAL_ID).toBe('INVALID_CANONICAL_ID'); + }); + + it('builds a typed ProviderIdError with code and details', () => { + const error = new ProviderIdError(ProviderIdErrorCode.INVALID_PROVIDER, 'bad provider', { + provider: 'x!', + }); + expect(error instanceof Error).toBe(true); + expect(error instanceof ProviderIdError).toBe(true); + expect(error.name).toBe('ProviderIdError'); + expect(error.code).toBe('INVALID_PROVIDER'); + expect(error.message).toBe('bad provider'); + expect(error.details).toEqual({ provider: 'x!' }); + }); + + it('exposes the shared defaults', () => { + expect(CANONICAL_ID_VERSION).toBe('1'); + expect(MAX_NORMALIZED_ID_LENGTH).toBe(128); + expect(DEFAULT_CANONICAL_ID_CONFIG.maxNormalizedLength).toBe(128); + expect(DEFAULT_CANONICAL_ID_CONFIG.allowCustomProviders).toBe(true); + expect(DEFAULT_CANONICAL_ID_CONFIG.knownProviders).toEqual(KNOWN_PROVIDERS); + expect(CANONICAL_ID_PATTERN.test('stripe:abc-a1b2c3d4')).toBe(true); + }); + + it('computes a deterministic 32-bit FNV-1a hash', () => { + expect(fnv1a32('provider\u0000id')).toBe(fnv1a32('provider\u0000id')); + expect(fnv1a32('a')).not.toBe(fnv1a32('b')); + expect(fnv1a32('x') >= 0).toBe(true); + }); +}); + +describe('validateCanonicalIdConfig', () => { + it('fills in documented defaults', () => { + const config = validateCanonicalIdConfig({}); + expect(config.maxNormalizedLength).toBe(128); + expect(config.allowCustomProviders).toBe(true); + expect(config.knownProviders).toContain('stripe'); + }); + + it('normalises and de-duplicates provider names', () => { + const config = validateCanonicalIdConfig({ + knownProviders: ['Stripe', 'stripe', 'PAYPAL'], + }); + expect(config.knownProviders).toHaveLength(2); + expect(config.knownProviders).toContain('paypal'); + expect(config.knownProviders).toContain('stripe'); + }); + + it('rejects invalid configuration', () => { + expectCode(() => validateCanonicalIdConfig({ maxNormalizedLength: 0 }), 'INVALID_CONFIG'); + expectCode(() => validateCanonicalIdConfig({ allowCustomProviders: 'yes' }), 'INVALID_CONFIG'); + expectCode(() => validateCanonicalIdConfig({ knownProviders: [] }), 'INVALID_CONFIG'); + expectCode(() => validateCanonicalIdConfig({ providerPrefixes: 'no' }), 'INVALID_CONFIG'); + }); +}); + +describe('parseProviderIdentifier', () => { + it('parses a "provider:externalId" string', () => { + expect(parseProviderIdentifier(' Stripe : cus_AbC ')).toEqual({ + provider: 'Stripe ', + externalId: ' cus_AbC', + }); + }); + + it('parses a ProviderIdentifier object', () => { + expect(parseProviderIdentifier({ provider: 'paypal', externalId: 'PAY-1' })).toEqual({ + provider: 'paypal', + externalId: 'PAY-1', + }); + }); + + it('rejects malformed shapes', () => { + expectCode(() => parseProviderIdentifier('no-separator'), 'INVALID_FORMAT'); + expectCode(() => parseProviderIdentifier('stripe:'), 'INVALID_FORMAT'); + expectCode(() => parseProviderIdentifier({ provider: 'stripe' }), 'INVALID_INPUT'); + expectCode(() => parseProviderIdentifier(null), 'INVALID_INPUT'); + expectCode(() => parseProviderIdentifier(42), 'INVALID_INPUT'); + }); +}); + +describe('normalizeExternalId', () => { + it('trims, lower-cases and collapses separators', () => { + expect(normalizeExternalId(' AbC__12--34 ')).toBe('abc-12-34'); + expect(normalizeExternalId('A/B/C')).toBe('a-b-c'); + expect(normalizeExternalId('---lead+trail---')).toBe('lead-trail'); + }); + + it('strips provider-specific prefixes', () => { + expect(normalizeExternalId('cus_AbC123', 'stripe')).toBe('abc123'); + expect(normalizeExternalId('PAY-99', 'paypal')).toBe('99'); + expect(normalizeExternalId('cus_AbC123', 'paypal')).toBe('cus-abc123'); + }); + + it('Unicode-normalises before folding', () => { + expect(normalizeExternalId('file-01')).toBe('file-01'); + }); + + it('rejects empty and non-alphanumeric identifiers', () => { + expectCode(() => normalizeExternalId(''), 'INVALID_EXTERNAL_ID'); + expectCode(() => normalizeExternalId(' '), 'INVALID_EXTERNAL_ID'); + expectCode(() => normalizeExternalId('---___'), 'INVALID_EXTERNAL_ID'); + expectCode(() => normalizeExternalId(123), 'INVALID_EXTERNAL_ID'); + }); + + it('bounds identifier length', () => { + const tooLong = 'a'.repeat(129); + expectCode(() => normalizeExternalId(tooLong), 'EXTERNAL_ID_TOO_LONG'); + expectCode(() => normalizeExternalId('a'.repeat(600)), 'EXTERNAL_ID_TOO_LONG'); + }); +}); + +describe('canonicalizeProviderId', () => { + it('is deterministic and well-formed', () => { + const a = canonicalizeProviderId({ provider: 'stripe', externalId: 'cus_AbC-12' }); + const b = canonicalizeProviderId({ provider: 'stripe', externalId: 'cus_AbC-12' }); + expect(a).toBe(b); + expect(CANONICAL_ID_PATTERN.test(a)).toBe(true); + expect(a.slice(0, 7)).toBe('stripe:'); + expect(a.slice(-9)).toBe(`-${a.slice(-8)}`); + }); + + it('is invariant to case, separators and provider prefixes', () => { + const a = canonicalizeProviderId('stripe:cus_AbC-12'); + const b = canonicalizeProviderId({ provider: 'STRIPE', externalId: ' CUS abc 12 ' }); + expect(a).toBe(b); + }); + + it('keeps different providers and identities distinct', () => { + const stripe = canonicalizeProviderId({ provider: 'stripe', externalId: 'abc' }); + const paypal = canonicalizeProviderId({ provider: 'paypal', externalId: 'abc' }); + expect(stripe).not.toBe(paypal); + expect(stripe.slice(-8)).not.toBe(paypal.slice(-8)); + }); + + it('folds Unicode deterministically and keeps distinct ids hash-distinct', () => { + const latin = canonicalizeProviderId({ provider: 'custom', externalId: 'cafe' }); + const accented = canonicalizeProviderId({ provider: 'custom', externalId: 'café' }); + expect(latin).toBe(accented); + const other = canonicalizeProviderId({ provider: 'custom', externalId: 'cafes' }); + expect(other).not.toBe(latin); + expect(other.slice(-8)).not.toBe(latin.slice(-8)); + }); + + it('passes already-canonical strings through unchanged', () => { + const canonical = canonicalizeProviderId({ provider: 'stripe', externalId: 'abc' }); + expect(canonicalizeProviderId(canonical)).toBe(canonical); + expect(canonicalizeProviderId(canonical.toUpperCase())).toBe(canonical); + }); + + it('emits every documented failure code', () => { + expectCode(() => canonicalizeProviderId({ provider: 'a!', externalId: 'x' }), 'INVALID_PROVIDER'); + expectCode(() => canonicalizeProviderId({ provider: '', externalId: 'x' }), 'INVALID_PROVIDER'); + expectCode(() => canonicalizeProviderId({ provider: 'x', externalId: '' }), 'INVALID_EXTERNAL_ID'); + expectCode(() => canonicalizeProviderId('stripe:cus_'), 'INVALID_EXTERNAL_ID'); + expectCode(() => canonicalizeProviderId({ provider: 'stripe', externalId: 'a'.repeat(600) }), 'EXTERNAL_ID_TOO_LONG'); + expectCode( + () => canonicalizeProviderId({ provider: 'unknown', externalId: 'x' }, { allowCustomProviders: false }), + 'UNKNOWN_PROVIDER' + ); + }); + + it('accepts custom providers by default and honours the allow-list', () => { + const custom = canonicalizeProviderId({ provider: 'my_saas', externalId: 'ID-1' }); + expect(CANONICAL_ID_PATTERN.test(custom)).toBe(true); + expect(custom.slice(0, 8)).toBe('my_saas:'); + expect(canonicalizeProviderId({ provider: 'my_saas', externalId: 'ID-1' }, { + allowCustomProviders: true, + knownProviders: ['my_saas'], + })).toBe(custom); + }); +}); + +describe('resolveProviderId', () => { + it('returns the full resolution record', () => { + const result = resolveProviderId({ provider: 'Stripe', externalId: ' cus_AbC ' }); + expect(result.provider).toBe('stripe'); + expect(result.normalizedId).toBe('abc'); + expect(result.hash).toHaveLength(8); + expect(result.canonicalId).toBe(`stripe:abc-${result.hash}`); + expect(result.version).toBe('1'); + expect(result.alreadyCanonical).toBe(false); + expect(result.source).toEqual({ provider: 'stripe', externalId: ' cus_AbC ' }); + }); + + it('marks canonical inputs as already canonical', () => { + const canonical = canonicalizeProviderId({ provider: 'paypal', externalId: 'PAY-7' }); + const result = resolveProviderId(canonical); + expect(result.alreadyCanonical).toBe(true); + expect(result.canonicalId).toBe(canonical); + expect(result.hash).toHaveLength(8); + }); +}); + +describe('areSameProviderId', () => { + it('matches identifiers across representations', () => { + expect(areSameProviderId( + { provider: 'stripe', externalId: 'cus_AbC' }, + 'STRIPE:ABC' + )).toBe(true); + }); + + it('distinguishes providers and canonical ids', () => { + expect(areSameProviderId( + { provider: 'stripe', externalId: 'abc' }, + { provider: 'paypal', externalId: 'abc' } + )).toBe(false); + const a = canonicalizeProviderId({ provider: 'stripe', externalId: 'abc' }); + const b = canonicalizeProviderId({ provider: 'stripe', externalId: 'abd' }); + expect(areSameProviderId(a, b)).toBe(false); + }); +}); + +describe('createCanonicalIdResolver', () => { + it('wires metrics and logger hooks on success', () => { + const events: string[] = []; + const resolver = createCanonicalIdResolver( + {}, + { + recordCanonicalized: () => events.push('canonicalized'), + recordResolved: () => events.push('resolved'), + recordComparison: () => events.push('compared'), + recordRejected: () => events.push('rejected'), + }, + { + info: () => events.push('info'), + warn: () => events.push('warn'), + } + ); + resolver.canonicalize({ provider: 'stripe', externalId: 'cus_1' }); + resolver.resolve({ provider: 'stripe', externalId: 'cus_1' }); + resolver.areSame('stripe:cus_1', { provider: 'stripe', externalId: '1' }); + resolver.normalize('cus_ABC', 'stripe'); + expect(events).toContain('canonicalized'); + expect(events).toContain('resolved'); + expect(events).toContain('compared'); + expect(events).toContain('info'); + expect(events).not.toContain('rejected'); + expect(events).not.toContain('warn'); + }); + + it('records and rethrows rejected inputs', () => { + let rejectedCode = ''; + let warned = false; + const resolver = createCanonicalIdResolver( + {}, + { recordRejected: (_operation: string, code: string) => { rejectedCode = code; } }, + { warn: () => { warned = true; } } + ); + expect(() => resolver.canonicalize({ provider: '', externalId: 'x' })).toThrow(); + expect(rejectedCode).toBe('INVALID_PROVIDER'); + expect(warned).toBe(true); + }); + + it('applies configuration to every method', () => { + const resolver = createCanonicalIdResolver({ + allowCustomProviders: false, + knownProviders: ['stripe'], + }); + expect(resolver.canonicalize({ provider: 'stripe', externalId: 'CUS-1' })).toContain('stripe:'); + expect(() => resolver.canonicalize({ provider: 'other', externalId: '1' })).toThrow(); + expect(resolver.normalize('cus_1', 'stripe')).toBe('1'); + }); + + it('exposes safe no-op sinks', () => { + expect(() => noopCanonicalIdMetrics.recordComparison(true)).not.toThrow(); + expect(() => noopCanonicalIdLogger.info('x', {})).not.toThrow(); + }); +}); diff --git a/backend/src/lib/providerId.ts b/backend/src/lib/providerId.ts new file mode 100644 index 00000000..e12a083e --- /dev/null +++ b/backend/src/lib/providerId.ts @@ -0,0 +1,576 @@ +/** + * backend/src/lib/providerId.ts + * + * Stable, provider-agnostic canonical-id resolver (issue #2256). + * + * Payment and integration providers emit wildly different identifiers + * (`cus_AbC`, `PAY-123`, ` ch_01H ` ...). This module folds every such + * identifier into one deterministic canonical form: + * + * :- + * + * The normalized segment is ASCII-folded and bounded in length; the 8-hex + * FNV-1a suffix is computed from `provider\0normalized-id`, so every input + * that is equivalent under normalisation maps to exactly one canonical id. + * The provider is part of the hash input, keeping cross-provider ids distinct. + * + * Design rules: + * - Zero dependencies, no I/O, no clock, no ambient state. Pure data in/out. + * - Shared vocabulary lives in `@subtrackr/billing-types`; no duplicated + * constants. + * - Every rejection is a typed `ProviderIdError` carrying a stable `code`. + * - Metrics and logger hooks are optional; no-op defaults are provided. + * + * Usage: + * const resolver = createCanonicalIdResolver({}, metrics, logger); + * const id = resolver.canonicalize({ provider: 'stripe', externalId: 'cus_AbC' }); + * // -> 'stripe:abc-a1b2c3d4' + */ + +import { + CANONICAL_ID_PATTERN_SOURCE, + CANONICAL_ID_VERSION, + DEFAULT_ALLOW_CUSTOM_PROVIDERS, + KNOWN_PROVIDERS, + MAX_NORMALIZED_ID_LENGTH, + PROVIDER_ID_ERROR_CODES, + PROVIDER_PREFIXES, + type CanonicalProviderId, + type ProviderIdErrorCode as SharedErrorCode, + type ProviderKind, +} from '../../../packages/billing-types/src/index.ts'; + +// --------------------------------------------------------------------------- +// Error surface (re-export of the shared vocabulary) +// --------------------------------------------------------------------------- + +/** Stable machine-readable codes emitted by this module. */ +export const ProviderIdErrorCode = PROVIDER_ID_ERROR_CODES; + +/** Union of every stable error code emitted by this module. */ +export type ProviderIdErrorCode = SharedErrorCode; + +/** Typed error thrown for invalid config, input and unresolvable identifiers. */ +export class ProviderIdError extends Error { + readonly code: ProviderIdErrorCode; + readonly details: Readonly>; + + constructor( + code: ProviderIdErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'ProviderIdError'; + this.code = code; + this.details = details; + } +} + +// --------------------------------------------------------------------------- +// Public data types +// --------------------------------------------------------------------------- + +/** Raw identifier supplied by a provider, before normalisation. */ +export interface ProviderIdentifier { + /** Provider token, e.g. `stripe`, `paypal` or a configured custom name. */ + readonly provider: string; + /** The provider's own identifier, e.g. `cus_AbC123`. */ + readonly externalId: string; +} + +/** Accepted shapes for every resolver entry point. */ +export type ProviderIdInput = ProviderIdentifier | string; + +/** + * Fully resolved configuration. Callers normally pass a `Partial` to + * {@link createCanonicalIdResolver} or {@link resolveProviderId}; defaults are + * filled in by {@link validateCanonicalIdConfig}. + */ +export interface CanonicalIdConfig { + /** Providers accepted without enabling `allowCustomProviders`. */ + readonly knownProviders: readonly string[]; + /** Accept provider tokens outside `knownProviders` that match the token pattern. */ + readonly allowCustomProviders: boolean; + /** Prefixes stripped per provider before normalisation. */ + readonly providerPrefixes: Readonly>; + /** Maximum length of the ASCII-normalized identifier segment. */ + readonly maxNormalizedLength: number; +} + +/** Rich result returned by {@link resolveProviderId}. */ +export interface ResolvedProviderId { + /** Final canonical string, e.g. `stripe:abc-a1b2c3d4`. */ + readonly canonicalId: CanonicalProviderId; + /** Normalised (lower-case) provider token. */ + readonly provider: string; + /** Deterministic 8-hex FNV-1a suffix. */ + readonly hash: string; + /** ASCII-folded identifier segment (without provider or hash). */ + readonly normalizedId: string; + /** Wire-format version, from `@subtrackr/billing-types`. */ + readonly version: string; + /** True when the input was already a canonical id and passed through. */ + readonly alreadyCanonical: boolean; + /** The parsed source identifier that produced this result. */ + readonly source: ProviderIdentifier; +} + +/** Optional metrics sink for canonical-id operations. */ +export interface CanonicalIdMetrics { + recordCanonicalized(provider: string, hash: string): void; + recordResolved(provider: string, canonicalId: string, alreadyCanonical: boolean): void; + recordComparison(equal: boolean): void; + recordRejected(operation: string, code: ProviderIdErrorCode): void; +} + +/** Optional logging hook for user-visible resolution events and rejections. */ +export interface CanonicalIdLogger { + info(message: string, details: Record): void; + warn(message: string, details: Record): void; +} + +/** Stateful façade returned by {@link createCanonicalIdResolver}. */ +export interface CanonicalIdResolver { + /** Canonicalise an identifier, returning only the canonical string. */ + canonicalize(input: ProviderIdInput): CanonicalProviderId; + /** Canonicalise an identifier and return the full resolution record. */ + resolve(input: ProviderIdInput): ResolvedProviderId; + /** True when two identifiers (or canonical strings) denote the same id. */ + areSame(a: ProviderIdInput, b: ProviderIdInput): boolean; + /** Normalise only an external id; `provider` selects which prefixes to strip. */ + normalize(externalId: string, provider?: string): string; +} + +/** Default configuration, mirroring `@subtrackr/billing-types`. */ +export const DEFAULT_CANONICAL_ID_CONFIG: CanonicalIdConfig = Object.freeze({ + knownProviders: KNOWN_PROVIDERS, + allowCustomProviders: DEFAULT_ALLOW_CUSTOM_PROVIDERS, + providerPrefixes: PROVIDER_PREFIXES, + maxNormalizedLength: MAX_NORMALIZED_ID_LENGTH, +}); + +/** No-op metrics implementation, safe in tests and development. */ +export const noopCanonicalIdMetrics: CanonicalIdMetrics = Object.freeze({ + recordCanonicalized: () => {}, + recordResolved: () => {}, + recordComparison: () => {}, + recordRejected: () => {}, +}); + +/** No-op logger implementation. */ +export const noopCanonicalIdLogger: CanonicalIdLogger = Object.freeze({ + info: () => {}, + warn: () => {}, +}); + +// --------------------------------------------------------------------------- +// Internal helpers +// --------------------------------------------------------------------------- + +/** Provider token syntax: lower-case start, then lower-case/digit/separator. */ +const PROVIDER_TOKEN = /^[a-z][a-z0-9_-]{0,31}$/; + +/** + * Case-insensitive form used only to *recognise* canonical input. Output is + * always validated/normalised with the strict shared `CANONICAL_ID_PATTERN`. + */ +const CANONICAL_INPUT_PATTERN = new RegExp(CANONICAL_ID_PATTERN_SOURCE, 'i'); + +/** Guard the raw pre-fold string so pathological inputs cannot consume CPU. */ +function maxRawLength(config: CanonicalIdConfig): number { + return config.maxNormalizedLength * 4; +} + +/** + * 32-bit FNV-1a over UTF-16 code units. Deterministic on every JS runtime and + * dependency-free (matches the bucket hash used by `@subtrackr/flags`). + */ +export function fnv1a32(input: string): number { + let hash = 0x811c9dc5; + for (let i = 0; i < input.length; i += 1) { + hash ^= input.charCodeAt(i); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + return hash >>> 0; +} + +/** Error helper that attaches input context to the typed error. */ +function fail(code: ProviderIdErrorCode, message: string, details: Record): never { + throw new ProviderIdError(code, message, details); +} + +/** Validate a provider token against syntax, allow-list and custom setting. */ +function assertProvider(provider: unknown, config: CanonicalIdConfig): string { + if (typeof provider !== 'string' || provider.trim().length === 0) { + fail(ProviderIdErrorCode.INVALID_PROVIDER, 'provider must be a non-empty string', { provider }); + } + const token = provider.trim().toLowerCase(); + if (!PROVIDER_TOKEN.test(token)) { + fail(ProviderIdErrorCode.INVALID_PROVIDER, 'provider has an invalid format', { provider }); + } + if (config.knownProviders.includes(token)) return token; + if (config.allowCustomProviders) return token; + return fail( + ProviderIdErrorCode.UNKNOWN_PROVIDER, + `provider '${token}' is not in the configured allow-list`, + { provider: token } + ); +} + +/** + * Remove a configured prefix when it is followed by a separator or a digit, + * e.g. `cus_123`, `PAY-99` or `ch 01`. A bare prefix (`cus` alone) is kept so a + * legitimate id that happens to equal a prefix is never emptied by stripping. + */ +function stripPrefix(raw: string, prefixes: readonly string[]): string { + for (const prefix of prefixes) { + if (prefix.length === 0 || !raw.startsWith(prefix) || raw.length === prefix.length) continue; + const rest = raw.slice(prefix.length); + const first = rest[0]!; + if (/[^a-z0-9]/.test(first)) return rest.replace(/^[^a-z0-9]+/, ''); + if (/[0-9]/.test(first)) return rest; + } + return raw; +} + +/** + * Trim, NFKC-fold, lower-case and strip the provider prefix. The returned + * string is the prepared identity fed into {@link foldIdentity}; it is *not* + * yet ASCII-folded. + */ +function prepareExternalId( + externalId: unknown, + prefixes: readonly string[], + config: CanonicalIdConfig +): string { + if (typeof externalId !== 'string') { + fail(ProviderIdErrorCode.INVALID_EXTERNAL_ID, 'externalId must be a string', { externalId }); + } + const trimmed = externalId.trim(); + if (trimmed.length === 0) { + fail(ProviderIdErrorCode.INVALID_EXTERNAL_ID, 'externalId must not be empty', { externalId }); + } + if (trimmed.length > maxRawLength(config)) { + fail( + ProviderIdErrorCode.EXTERNAL_ID_TOO_LONG, + 'externalId exceeds the maximum raw length', + { length: trimmed.length, max: maxRawLength(config) } + ); + } + const folded = typeof trimmed.normalize === 'function' ? trimmed.normalize('NFKD') : trimmed; + return stripPrefix(folded.toLowerCase(), prefixes); +} + +/** ASCII-fold a prepared identity into the bounded normalized segment. */ +function foldIdentity(cleaned: string, config: CanonicalIdConfig): string { + const normalized = cleaned + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + if (normalized.length === 0) { + fail(ProviderIdErrorCode.INVALID_EXTERNAL_ID, 'externalId has no alphanumeric content', { + cleaned, + }); + } + if (normalized.length > config.maxNormalizedLength) { + fail( + ProviderIdErrorCode.EXTERNAL_ID_TOO_LONG, + 'normalized id exceeds the maximum length', + { length: normalized.length, max: config.maxNormalizedLength } + ); + } + return normalized; +} + +/** Render an 8-hex FNV-1a suffix for a provider/normalized-id pair. */ +function hashIdentity(provider: string, normalizedId: string): string { + return fnv1a32(`${provider}\u0000${normalizedId}`).toString(16).padStart(8, '0'); +} + +/** Parse a `provider:externalId` string or a {@link ProviderIdentifier} object. */ +function parseRaw(input: unknown): ProviderIdentifier { + if (typeof input === 'string') { + const trimmed = input.trim(); + const separator = trimmed.indexOf(':'); + if (separator <= 0 || separator === trimmed.length - 1) { + fail( + ProviderIdErrorCode.INVALID_FORMAT, + 'string input must be ":"', + { input } + ); + } + return { + provider: trimmed.slice(0, separator), + externalId: trimmed.slice(separator + 1), + }; + } + if (input !== null && typeof input === 'object' && !Array.isArray(input)) { + const candidate = input as Partial; + if (typeof candidate.provider !== 'string' || typeof candidate.externalId !== 'string') { + fail( + ProviderIdErrorCode.INVALID_INPUT, + 'object input must have string provider and externalId fields', + { input } + ); + } + return { provider: candidate.provider, externalId: candidate.externalId }; + } + return fail( + ProviderIdErrorCode.INVALID_INPUT, + 'input must be a ":" string or a ProviderIdentifier object', + { input } + ); +} + +/** Resolve with an already-validated config (internal hot path). */ +function resolveWithConfig(input: ProviderIdInput, config: CanonicalIdConfig): ResolvedProviderId { + const source = parseRaw(input); + + // Already-canonical strings pass through unchanged (idempotent resolver). + if (typeof input === 'string' && CANONICAL_INPUT_PATTERN.test(input.trim())) { + const canonicalId = input.trim().toLowerCase(); + const body = canonicalId.slice(canonicalId.indexOf(':') + 1); + return { + canonicalId, + provider: canonicalId.slice(0, canonicalId.indexOf(':')), + hash: body.slice(-8), + normalizedId: body.slice(0, -9), + version: CANONICAL_ID_VERSION, + alreadyCanonical: true, + source, + }; + } + + const provider = assertProvider(source.provider, config); + const cleaned = prepareExternalId(source.externalId, config.providerPrefixes[provider] ?? [], config); + const normalizedId = foldIdentity(cleaned, config); + const hash = hashIdentity(provider, normalizedId); + return { + canonicalId: `${provider}:${normalizedId}-${hash}`, + provider, + hash, + normalizedId, + version: CANONICAL_ID_VERSION, + alreadyCanonical: false, + source: { provider, externalId: source.externalId }, + }; +} + +/** Canonical string for either a raw identifier or an already-canonical string. */ +function toCanonicalId(input: ProviderIdInput, config: CanonicalIdConfig): CanonicalProviderId { + if (typeof input === 'string' && CANONICAL_INPUT_PATTERN.test(input.trim())) { + return input.trim().toLowerCase(); + } + return resolveWithConfig(input, config).canonicalId; +} + +// --------------------------------------------------------------------------- +// Configuration +// --------------------------------------------------------------------------- + +/** + * Validate and resolve a partial configuration into a complete, frozen + * `CanonicalIdConfig`. Throws `ProviderIdError(INVALID_CONFIG)` on bad values. + */ +export function validateCanonicalIdConfig( + config: Partial = {} +): CanonicalIdConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'config must be an object', { config }); + } + + const maxNormalizedLength = config.maxNormalizedLength ?? MAX_NORMALIZED_ID_LENGTH; + if ( + typeof maxNormalizedLength !== 'number' || + !Number.isInteger(maxNormalizedLength) || + maxNormalizedLength < 1 || + maxNormalizedLength > 1024 + ) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'maxNormalizedLength must be 1..1024', { + maxNormalizedLength, + }); + } + + const allowCustomProviders = config.allowCustomProviders ?? DEFAULT_ALLOW_CUSTOM_PROVIDERS; + if (typeof allowCustomProviders !== 'boolean') { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'allowCustomProviders must be a boolean', { + allowCustomProviders, + }); + } + + const knownInput = config.knownProviders ?? KNOWN_PROVIDERS; + if (!Array.isArray(knownInput) || knownInput.length === 0) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'knownProviders must be a non-empty array', { + knownProviders: knownInput, + }); + } + const knownProviders = knownInput.map((provider) => { + if (typeof provider !== 'string' || !PROVIDER_TOKEN.test(provider.trim().toLowerCase())) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'invalid provider in knownProviders', { provider }); + } + return provider.trim().toLowerCase(); + }); + + const prefixesInput = config.providerPrefixes ?? PROVIDER_PREFIXES; + if (prefixesInput === null || typeof prefixesInput !== 'object' || Array.isArray(prefixesInput)) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'providerPrefixes must be an object', { + providerPrefixes: prefixesInput, + }); + } + const providerPrefixes: Record = {}; + for (const [key, values] of Object.entries(prefixesInput)) { + if (!Array.isArray(values) || values.some((value) => typeof value !== 'string')) { + fail(ProviderIdErrorCode.INVALID_CONFIG, 'each providerPrefixes entry must be string[]', { + provider: key, + }); + } + providerPrefixes[key.trim().toLowerCase()] = Object.freeze( + values.map((value) => (value as string).trim().toLowerCase()) + ); + } + + return Object.freeze({ + knownProviders: Object.freeze(Array.from(new Set(knownProviders))), + allowCustomProviders, + providerPrefixes: Object.freeze(providerPrefixes), + maxNormalizedLength, + }); +} + +// --------------------------------------------------------------------------- +// Pure entry points +// --------------------------------------------------------------------------- + +/** Parse an identifier without normalising it. */ +export function parseProviderIdentifier(input: ProviderIdInput): ProviderIdentifier { + return parseRaw(input); +} + +/** + * Normalise an external id: trim, Unicode NFKC-fold, lower-case, strip the + * provider's configured prefixes and collapse separators to a single `-`. + * + * @param externalId Raw provider identifier. + * @param provider Optional provider used to select which prefixes to strip. + * @param config Optional resolver configuration override. + */ +export function normalizeExternalId( + externalId: string, + provider?: string, + config: Partial = {} +): string { + const cfg = validateCanonicalIdConfig(config); + const prefixes = provider ? cfg.providerPrefixes[provider.trim().toLowerCase()] ?? [] : []; + return foldIdentity(prepareExternalId(externalId, prefixes, cfg), cfg); +} + +/** + * Resolve an identifier into a full {@link ResolvedProviderId} record. + * Pure: the same input and config always produce the same output. + */ +export function resolveProviderId( + input: ProviderIdInput, + config: Partial = {} +): ResolvedProviderId { + return resolveWithConfig(input, validateCanonicalIdConfig(config)); +} + +/** + * Canonicalise an identifier into a stable string. Thin wrapper over + * {@link resolveProviderId} for callers that only need the id. + */ +export function canonicalizeProviderId( + input: ProviderIdInput, + config: Partial = {} +): CanonicalProviderId { + return resolveWithConfig(input, validateCanonicalIdConfig(config)).canonicalId; +} + +/** True when two identifiers (or canonical strings) denote the same id. */ +export function areSameProviderId( + a: ProviderIdInput, + b: ProviderIdInput, + config: Partial = {} +): boolean { + const cfg = validateCanonicalIdConfig(config); + return toCanonicalId(a, cfg) === toCanonicalId(b, cfg); +} + +// --------------------------------------------------------------------------- +// Factory with observability hooks +// --------------------------------------------------------------------------- + +/** + * Create a canonical-id resolver with optional metrics and logger hooks. + * + * Successful resolutions emit `recordCanonicalized`/`recordResolved` and an + * `info` log; rejected inputs emit `recordRejected`, a `warn` log and rethrow + * the original `ProviderIdError`. + * + * @param config Partial configuration; see {@link DEFAULT_CANONICAL_ID_CONFIG}. + * @param metrics Optional metrics sink (partial implementations allowed). + * @param logger Optional logging sink (partial implementations allowed). + */ +export function createCanonicalIdResolver( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {} +): CanonicalIdResolver { + const cfg = validateCanonicalIdConfig(config); + const m: CanonicalIdMetrics = { ...noopCanonicalIdMetrics, ...metrics }; + const l: CanonicalIdLogger = { ...noopCanonicalIdLogger, ...logger }; + + function guard(operation: string, fn: () => T): T { + try { + return fn(); + } catch (error) { + const code: ProviderIdErrorCode = + error instanceof ProviderIdError ? error.code : ProviderIdErrorCode.INVALID_INPUT; + m.recordRejected(operation, code); + l.warn('provider-id resolution rejected', { + operation, + code, + message: error instanceof Error ? error.message : String(error), + }); + throw error; + } + } + + return { + canonicalize(input: ProviderIdInput): CanonicalProviderId { + return guard('canonicalize', () => { + const result = resolveWithConfig(input, cfg); + m.recordCanonicalized(result.provider, result.hash); + return result.canonicalId; + }); + }, + + resolve(input: ProviderIdInput): ResolvedProviderId { + return guard('resolve', () => { + const result = resolveWithConfig(input, cfg); + m.recordResolved(result.provider, result.canonicalId, result.alreadyCanonical); + l.info('provider-id resolved', { + provider: result.provider, + canonicalId: result.canonicalId, + alreadyCanonical: result.alreadyCanonical, + }); + return result; + }); + }, + + areSame(a: ProviderIdInput, b: ProviderIdInput): boolean { + return guard('areSame', () => { + const equal = toCanonicalId(a, cfg) === toCanonicalId(b, cfg); + m.recordComparison(equal); + return equal; + }); + }, + + normalize(externalId: string, provider?: string): string { + return guard('normalize', () => { + const prefixes = provider ? cfg.providerPrefixes[provider.trim().toLowerCase()] ?? [] : []; + return foldIdentity(prepareExternalId(externalId, prefixes, cfg), cfg); + }); + }, + }; +} diff --git a/packages/billing-types/package.json b/packages/billing-types/package.json new file mode 100644 index 00000000..a562ed24 --- /dev/null +++ b/packages/billing-types/package.json @@ -0,0 +1,10 @@ +{ + "name": "@subtrackr/billing-types", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Shared canonical provider-id types and constants for SubTrackr billing", + "main": "./src/index.ts", + "types": "./src/index.ts", + "sideEffects": false +} diff --git a/packages/billing-types/src/__tests__/index.test.ts b/packages/billing-types/src/__tests__/index.test.ts new file mode 100644 index 00000000..30dc80a0 --- /dev/null +++ b/packages/billing-types/src/__tests__/index.test.ts @@ -0,0 +1,52 @@ +/** + * packages/billing-types/src/__tests__/index.test.ts + * + * Pins the shared canonical-id vocabulary used by the resolver. + */ + +import { + CANONICAL_ID_VERSION, + CANONICAL_ID_PATTERN, + CANONICAL_ID_PATTERN_SOURCE, + KNOWN_PROVIDERS, + MAX_NORMALIZED_ID_LENGTH, + DEFAULT_ALLOW_CUSTOM_PROVIDERS, + PROVIDER_PREFIXES, + PROVIDER_ID_ERROR_CODES, +} from '../index'; + +describe('@subtrackr/billing-types', () => { + it('publishes a stable wire-format version and limits', () => { + expect(CANONICAL_ID_VERSION).toBe('1'); + expect(MAX_NORMALIZED_ID_LENGTH).toBe(128); + expect(DEFAULT_ALLOW_CUSTOM_PROVIDERS).toBe(true); + }); + + it('exposes the built-in providers', () => { + expect(KNOWN_PROVIDERS).toHaveLength(6); + expect(KNOWN_PROVIDERS).toContain('stripe'); + expect(KNOWN_PROVIDERS).toContain('paypal'); + expect(Object.isFrozen(KNOWN_PROVIDERS)).toBe(true); + }); + + it('matches canonical ids and rejects malformed ones', () => { + expect(CANONICAL_ID_PATTERN.test('stripe:abc-a1b2c3d4')).toBe(true); + expect(CANONICAL_ID_PATTERN.test('paypal:pay-99-0f0f0f0f')).toBe(true); + expect(CANONICAL_ID_PATTERN.test('stripe:ABC-a1b2c3d4')).toBe(false); + expect(CANONICAL_ID_PATTERN.test('stripe:abc')).toBe(false); + expect(CANONICAL_ID_PATTERN.test('nocolon-a1b2c3d4')).toBe(false); + expect(CANONICAL_ID_PATTERN_SOURCE).toContain('[0-9a-f]{8}'); + }); + + it('shares provider prefix defaults', () => { + expect(PROVIDER_PREFIXES['stripe']).toContain('cus'); + expect(PROVIDER_PREFIXES['paypal']).toContain('pay'); + expect(Object.isFrozen(PROVIDER_PREFIXES)).toBe(true); + }); + + it('shares the stable error-code vocabulary', () => { + expect(PROVIDER_ID_ERROR_CODES.INVALID_INPUT).toBe('INVALID_INPUT'); + expect(PROVIDER_ID_ERROR_CODES.UNKNOWN_PROVIDER).toBe('UNKNOWN_PROVIDER'); + expect(PROVIDER_ID_ERROR_CODES.EXTERNAL_ID_TOO_LONG).toBe('EXTERNAL_ID_TOO_LONG'); + }); +}); diff --git a/packages/billing-types/src/index.ts b/packages/billing-types/src/index.ts new file mode 100644 index 00000000..cde99c03 --- /dev/null +++ b/packages/billing-types/src/index.ts @@ -0,0 +1,90 @@ +/** + * packages/billing-types/src/index.ts + * + * Shared, dependency-free type definitions and constants for canonical + * provider identifiers (issue #2256). + * + * A "canonical provider id" is a stable, provider-agnostic string of the form + * + * :- + * + * e.g. `stripe:1a2b3c4d-9f8e7d6c`. It is produced by the resolver in + * `backend/src/lib/providerId.ts`; this package owns only the vocabulary + * (providers, prefixes, limits, pattern, version) so the backend and any + * consumer agree on the wire format without importing implementation code. + */ + +/** Semantic version of the canonical-id wire format. Bump on breaking changes. */ +export const CANONICAL_ID_VERSION = '1'; + +/** + * Default maximum length of the normalized (ASCII-folded) identifier segment. + * Resolvers reject longer inputs rather than silently truncating them. + */ +export const MAX_NORMALIZED_ID_LENGTH = 128; + +/** Default for whether providers outside {@link KNOWN_PROVIDERS} are accepted. */ +export const DEFAULT_ALLOW_CUSTOM_PROVIDERS = true; + +/** + * Providers recognised out of the box. Values are already lower-case so they + * can be compared directly against a normalised provider token. + */ +export const KNOWN_PROVIDERS = Object.freeze([ + 'stripe', + 'paypal', + 'github', + 'openai', + 'anthropic', + 'slack', +] as const); + +/** Union of the built-in provider identifiers. */ +export type ProviderKind = (typeof KNOWN_PROVIDERS)[number]; + +/** + * Pattern every canonical id produced by the resolver matches. + * No `g` flag: safe to reuse with `RegExp.prototype.test`. + */ +export const CANONICAL_ID_PATTERN: RegExp = + /^[a-z][a-z0-9_-]{0,31}:[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/; + +/** Regex source for environments that cannot share a RegExp instance. */ +export const CANONICAL_ID_PATTERN_SOURCE: string = CANONICAL_ID_PATTERN.source; + +/** A string already normalised into the canonical wire format. */ +export type CanonicalProviderId = string; + +/** + * Identifier prefixes stripped by each provider before normalisation. + * Configurable on the resolver; this is the shared default. + */ +export const PROVIDER_PREFIXES: Readonly> = + Object.freeze({ + stripe: Object.freeze([ + 'cus', 'ch', 'pi', 'sub', 'inv', 're', 'po', 'evt', 'pm', 'txn', 'price', 'prod', + ]), + paypal: Object.freeze(['pay', 'ipn', 'txn', 'inv']), + github: Object.freeze(['gh', 'repo', 'org', 'evt']), + openai: Object.freeze(['chatcmpl', 'file', 'ft']), + anthropic: Object.freeze(['msg', 'msgbatch']), + // Slack object ids use single-letter prefixes (C/U/...); stripping those + // would mangle ordinary ids, so no prefix is removed for this provider. + slack: Object.freeze([]), + }); + +/** Stable error codes emitted by the canonical-id resolver. */ +export const PROVIDER_ID_ERROR_CODES = Object.freeze({ + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_INPUT: 'INVALID_INPUT', + INVALID_FORMAT: 'INVALID_FORMAT', + INVALID_PROVIDER: 'INVALID_PROVIDER', + UNKNOWN_PROVIDER: 'UNKNOWN_PROVIDER', + INVALID_EXTERNAL_ID: 'INVALID_EXTERNAL_ID', + EXTERNAL_ID_TOO_LONG: 'EXTERNAL_ID_TOO_LONG', + INVALID_CANONICAL_ID: 'INVALID_CANONICAL_ID', +} as const); + +/** Union of every stable canonical-id error code. */ +export type ProviderIdErrorCode = + (typeof PROVIDER_ID_ERROR_CODES)[keyof typeof PROVIDER_ID_ERROR_CODES];