@trii/identity 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ /** Versión del conjunto de normalizadores (ChannelIdentity.normalizationVersion). */
2
+ export declare const NORMALIZATION_VERSION = 1;
3
+ /** País si el espacio no tiene phoneDefaultCountry. */
4
+ export declare const FALLBACK_COUNTRY = "AR";
5
+ export declare const EVIDENCE_AR_MOBILE_WITHOUT_9 = "ar_mobile_without_9";
6
+ export declare const EVIDENCE_BR_MOBILE_WITHOUT_9 = "br_mobile_without_9";
7
+ export declare const NS: {
8
+ readonly Email: "email";
9
+ readonly Msisdn: "msisdn";
10
+ readonly WhatsAppPhone: "wa_phone";
11
+ readonly WhatsAppBsuid: "wa_bsuid";
12
+ readonly WhatsAppLid: "wa_lid";
13
+ readonly WhatsAppGroup: "wa_group";
14
+ readonly WhatsAppCloudGroup: "wa_cloud_group";
15
+ readonly RcsPhone: "rcs_phone";
16
+ readonly FacebookPsid: "psid";
17
+ readonly InstagramIgsid: "igsid";
18
+ readonly WebChat: "webchat";
19
+ readonly OpenMessaging: "openmessaging";
20
+ readonly MercadoLibreUser: "meli_user";
21
+ readonly SmsSender: "sms_sender";
22
+ readonly Self: "self";
23
+ readonly Merged: "merged";
24
+ };
25
+ export interface NormalizedKeyAlias {
26
+ key: string;
27
+ evidence: string;
28
+ }
29
+ /** Resultado de normalizar. isValid = false → identidad invalid (D6), solo historial. */
30
+ export interface NormalizedIdentity {
31
+ isValid: boolean;
32
+ error: string | null;
33
+ identityNamespace: string;
34
+ scope: string | null;
35
+ normalizedValue: string;
36
+ displayValue: string;
37
+ /** Clave principal; vacía si isValid = false. */
38
+ key: string;
39
+ aliases: NormalizedKeyAlias[];
40
+ normalizationVersion: number;
41
+ }
42
+ /** "%" → "%25" y "|" → "%7C" en cada componente. */
43
+ export declare function escapeKeyComponent(value: string | null | undefined): string;
44
+ /** Clave canónica "namespace|scope|valor". */
45
+ export declare function buildKey(identityNamespace: string, scope: string | null | undefined, normalizedValue: string): string;
46
+ /** keyHash: SHA-256 de la clave en UTF-8, primeros 16 bytes. */
47
+ export declare function keyHash(key: string): Buffer;
48
+ /** Todas las claves (principal + alias) sin repetir. */
49
+ export declare function allKeys(n: NormalizedIdentity): string[];
50
+ /**
51
+ * Trim, sin nombre visible ni <> ni "mailto:", NFC. Valida el mailbox completo antes de armar la clave (F01 de 75).
52
+ * Minúsculas: parte local solo A–Z (NZ8); dominio por IDNA (punycode). Sin reglas de Gmail.
53
+ */
54
+ export declare function normalizeEmail(raw: string | null | undefined): NormalizedIdentity;
55
+ /**
56
+ * E.164 con libphonenumber y región = país por defecto del espacio (FALLBACK_COUNTRY si falta).
57
+ * identityNamespace: msisdn, wa_phone o rcs_phone. knownMobile habilita completar el noveno dígito de un celular
58
+ * brasileño viejo. El alias sin 9 de AR/BR se agrega siempre que el E.164 tenga el 9.
59
+ */
60
+ export declare function normalizePhone(raw: string | null | undefined, defaultCountry: string | null | undefined, identityNamespace?: string, knownMobile?: boolean): NormalizedIdentity;
61
+ /**
62
+ * Principal wa_phone si hay número; si no, provisoria por LID o BSUID (N3). Alias wa_bsuid con scope = portfolio
63
+ * (cloudApiBusinessId del canal; sin portfolio no se genera, NZ1) y wa_lid sin scope.
64
+ */
65
+ export declare function normalizeWhatsApp(waId: string | null | undefined, bsuid: string | null | undefined, lid: string | null | undefined, portfolio: string | null | undefined, defaultCountry: string | null | undefined): NormalizedIdentity;
66
+ /** Grupo de WhatsApp (Baileys): id sin @g.us, sin scope. */
67
+ export declare function normalizeWhatsAppGroup(raw: string | null | undefined): NormalizedIdentity;
68
+ /** Grupo de la Cloud API: group_id opaco con scope de canal o número de negocio. */
69
+ export declare function normalizeWhatsAppCloudGroup(groupId: string | null | undefined, channelScope: string | null | undefined): NormalizedIdentity;
70
+ /** psid, igsid, webchat, openmessaging, meli_user: trim, sin cambiar mayúsculas; sin scope requerido → inválida. */
71
+ export declare function normalizeOpaque(identityNamespace: string, raw: string | null | undefined, scope: string | null | undefined, scopeRequired: boolean): NormalizedIdentity;
72
+ /** Remitente SMS no telefónico: código corto o alfanumérico en mayúsculas sin espacios; scope = canal. */
73
+ export declare function normalizeSmsSender(raw: string | null | undefined, channelId: string | null | undefined): NormalizedIdentity;
package/dist/index.js ADDED
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NS = exports.EVIDENCE_BR_MOBILE_WITHOUT_9 = exports.EVIDENCE_AR_MOBILE_WITHOUT_9 = exports.FALLBACK_COUNTRY = exports.NORMALIZATION_VERSION = void 0;
4
+ exports.escapeKeyComponent = escapeKeyComponent;
5
+ exports.buildKey = buildKey;
6
+ exports.keyHash = keyHash;
7
+ exports.allKeys = allKeys;
8
+ exports.normalizeEmail = normalizeEmail;
9
+ exports.normalizePhone = normalizePhone;
10
+ exports.normalizeWhatsApp = normalizeWhatsApp;
11
+ exports.normalizeWhatsAppGroup = normalizeWhatsAppGroup;
12
+ exports.normalizeWhatsAppCloudGroup = normalizeWhatsAppCloudGroup;
13
+ exports.normalizeOpaque = normalizeOpaque;
14
+ exports.normalizeSmsSender = normalizeSmsSender;
15
+ /**
16
+ * @trii/identity — normalizadores de identificadores externos (plan §15.21 NZ1–NZ6, tabla N1–N10 de ChannelIdentity/33).
17
+ * Espejo de Trii.Contacts.ChannelIdentityNormalizer (trii-LibDef). Misma salida comprobada con
18
+ * trii-LibDef/tests/ChannelIdentityContracts/normalization-vectors.json.
19
+ * Funciones puras: no consultan base de datos.
20
+ */
21
+ const crypto_1 = require("crypto");
22
+ const url_1 = require("url");
23
+ const max_1 = require("libphonenumber-js/max");
24
+ /** Versión del conjunto de normalizadores (ChannelIdentity.normalizationVersion). */
25
+ exports.NORMALIZATION_VERSION = 1;
26
+ /** País si el espacio no tiene phoneDefaultCountry. */
27
+ exports.FALLBACK_COUNTRY = 'AR';
28
+ exports.EVIDENCE_AR_MOBILE_WITHOUT_9 = 'ar_mobile_without_9';
29
+ exports.EVIDENCE_BR_MOBILE_WITHOUT_9 = 'br_mobile_without_9';
30
+ /** Sufijos de JID que identifican un teléfono (WhatsApp Web / Baileys). */
31
+ const PHONE_JID_SUFFIXES = ['c.us', 's.whatsapp.net'];
32
+ exports.NS = {
33
+ Email: 'email',
34
+ Msisdn: 'msisdn',
35
+ WhatsAppPhone: 'wa_phone',
36
+ WhatsAppBsuid: 'wa_bsuid',
37
+ WhatsAppLid: 'wa_lid',
38
+ WhatsAppGroup: 'wa_group',
39
+ WhatsAppCloudGroup: 'wa_cloud_group',
40
+ RcsPhone: 'rcs_phone',
41
+ FacebookPsid: 'psid',
42
+ InstagramIgsid: 'igsid',
43
+ WebChat: 'webchat',
44
+ OpenMessaging: 'openmessaging',
45
+ MercadoLibreUser: 'meli_user',
46
+ SmsSender: 'sms_sender',
47
+ Self: 'self',
48
+ Merged: 'merged',
49
+ };
50
+ // ---------------------------------------------------------------- clave y hash (M2, M3, C03)
51
+ /** "%" → "%25" y "|" → "%7C" en cada componente. */
52
+ function escapeKeyComponent(value) {
53
+ return value ? value.replace(/%/g, '%25').replace(/\|/g, '%7C') : '';
54
+ }
55
+ /** Clave canónica "namespace|scope|valor". */
56
+ function buildKey(identityNamespace, scope, normalizedValue) {
57
+ if (!identityNamespace)
58
+ throw new Error('namespace vacío');
59
+ if (!normalizedValue)
60
+ throw new Error('valor vacío');
61
+ return [identityNamespace, scope, normalizedValue].map(escapeKeyComponent).join('|');
62
+ }
63
+ /** keyHash: SHA-256 de la clave en UTF-8, primeros 16 bytes. */
64
+ function keyHash(key) {
65
+ return (0, crypto_1.createHash)('sha256').update(key, 'utf8').digest().subarray(0, 16);
66
+ }
67
+ /** Todas las claves (principal + alias) sin repetir. */
68
+ function allKeys(n) {
69
+ const all = [];
70
+ if (n.key)
71
+ all.push(n.key);
72
+ for (const a of n.aliases)
73
+ if (!all.includes(a.key))
74
+ all.push(a.key);
75
+ return all;
76
+ }
77
+ // ---------------------------------------------------------------- helpers
78
+ function invalid(ns, error, raw) {
79
+ return { isValid: false, error, identityNamespace: ns, scope: null, normalizedValue: '', displayValue: (raw !== null && raw !== void 0 ? raw : '').trim(), key: '', aliases: [], normalizationVersion: exports.NORMALIZATION_VERSION };
80
+ }
81
+ function valid(ns, scope, value, display) {
82
+ return { isValid: true, error: null, identityNamespace: ns, scope, normalizedValue: value, displayValue: display, key: buildKey(ns, scope, value), aliases: [], normalizationVersion: exports.NORMALIZATION_VERSION };
83
+ }
84
+ function stripSuffix(v, suffix) {
85
+ return v && v.toLowerCase().endsWith(suffix) ? v.slice(0, v.length - suffix.length) : v;
86
+ }
87
+ const isWhite = (c) => /\s/.test(c);
88
+ // ---------------------------------------------------------------- Email (N7)
89
+ const ATEXT_SYMBOLS = "!#$%&'*+/=?^_`{|}~-";
90
+ function isValidLocalPart(local) {
91
+ if (local.length < 1 || local.length > 64 || local.startsWith('.') || local.endsWith('.') || local.includes('..'))
92
+ return false;
93
+ for (const c of local) {
94
+ if (c === '.')
95
+ continue;
96
+ const cp = c.codePointAt(0);
97
+ if (cp < 128) {
98
+ if (!(/[A-Za-z0-9]/.test(c) || ATEXT_SYMBOLS.includes(c)))
99
+ return false;
100
+ }
101
+ else if (/[\s\p{Cc}]/u.test(c))
102
+ return false;
103
+ }
104
+ return true;
105
+ }
106
+ function isValidUnicodeDomain(domain) {
107
+ if (!domain || domain.length > 253)
108
+ return false;
109
+ const labels = domain.split('.');
110
+ if (labels.length < 2)
111
+ return false;
112
+ return labels.every(l => l.length >= 1 && l.length <= 63 && !l.startsWith('-') && !l.endsWith('-') && /^[\p{L}\p{N}\p{Mn}\p{Mc}-]+$/u.test(l));
113
+ }
114
+ function isValidAsciiDomain(domain) {
115
+ if (!domain || domain.length > 253)
116
+ return false;
117
+ const labels = domain.split('.');
118
+ if (labels.length < 2)
119
+ return false;
120
+ if (!labels.every(l => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(l)))
121
+ return false;
122
+ return !/^[0-9]+$/.test(labels[labels.length - 1]);
123
+ }
124
+ const lowerAsciiLetters = (v) => v.replace(/[A-Z]/g, c => c.toLowerCase());
125
+ /**
126
+ * Trim, sin nombre visible ni <> ni "mailto:", NFC. Valida el mailbox completo antes de armar la clave (F01 de 75).
127
+ * Minúsculas: parte local solo A–Z (NZ8); dominio por IDNA (punycode). Sin reglas de Gmail.
128
+ */
129
+ function normalizeEmail(raw) {
130
+ const ns = exports.NS.Email;
131
+ if (!raw || !raw.trim())
132
+ return invalid(ns, 'invalid_email', raw);
133
+ let s = raw.trim();
134
+ const lt = s.lastIndexOf('<'), gt = s.lastIndexOf('>');
135
+ if (lt >= 0 && gt > lt)
136
+ s = s.slice(lt + 1, gt).trim();
137
+ if (s.toLowerCase().startsWith('mailto:'))
138
+ s = s.slice(7);
139
+ const display = s;
140
+ s = s.normalize('NFC');
141
+ const at = s.lastIndexOf('@');
142
+ if (at <= 0 || at === s.length - 1 || s.indexOf('@') !== at)
143
+ return invalid(ns, 'invalid_email', raw);
144
+ const localRaw = s.slice(0, at);
145
+ let domainRaw = s.slice(at + 1);
146
+ if (domainRaw.endsWith('.'))
147
+ domainRaw = domainRaw.slice(0, -1);
148
+ if (!isValidLocalPart(localRaw) || !isValidUnicodeDomain(domainRaw))
149
+ return invalid(ns, 'invalid_email', raw);
150
+ const domain = (0, url_1.domainToASCII)(domainRaw).toLowerCase();
151
+ if (!isValidAsciiDomain(domain))
152
+ return invalid(ns, 'invalid_email', raw);
153
+ return valid(ns, null, `${lowerAsciiLetters(localRaw)}@${domain}`, display);
154
+ }
155
+ // ---------------------------------------------------------------- Teléfonos (N4–N6, NZ5, NZ6)
156
+ /**
157
+ * E.164 con libphonenumber y región = país por defecto del espacio (FALLBACK_COUNTRY si falta).
158
+ * identityNamespace: msisdn, wa_phone o rcs_phone. knownMobile habilita completar el noveno dígito de un celular
159
+ * brasileño viejo. El alias sin 9 de AR/BR se agrega siempre que el E.164 tenga el 9.
160
+ */
161
+ function normalizePhone(raw, defaultCountry, identityNamespace = exports.NS.Msisdn, knownMobile = false) {
162
+ const ns = identityNamespace;
163
+ if (!raw || !raw.trim())
164
+ return invalid(ns, 'invalid_phone', raw);
165
+ const region = (defaultCountry && defaultCountry.trim() ? defaultCountry.trim().toUpperCase() : exports.FALLBACK_COUNTRY);
166
+ let s = raw.trim();
167
+ const atIdx = s.indexOf('@');
168
+ if (atIdx >= 0) {
169
+ // D5/F03: solo sufijos de JID telefónico; @lid, @g.us, @broadcast, @newsletter y otros no son teléfonos.
170
+ if (!PHONE_JID_SUFFIXES.includes(s.slice(atIdx + 1).toLowerCase()))
171
+ return invalid(ns, 'invalid_phone', raw);
172
+ s = s.slice(0, atIdx);
173
+ }
174
+ const digits = s.replace(/\D/g, '');
175
+ if (!digits)
176
+ return invalid(ns, 'invalid_phone', raw);
177
+ const international = s.startsWith('+') || s.startsWith('00') || ns !== exports.NS.Msisdn;
178
+ let intlDigits = s.startsWith('00') ? digits.slice(2) : digits;
179
+ if (international && intlDigits.startsWith('521') && intlDigits.length === 13)
180
+ intlDigits = '52' + intlDigits.slice(3);
181
+ const toParse = international ? '+' + intlDigits : s;
182
+ let number;
183
+ try {
184
+ number = (0, max_1.parsePhoneNumberWithError)(toParse, region);
185
+ }
186
+ catch {
187
+ return invalid(ns, 'invalid_phone', raw);
188
+ }
189
+ let e164 = number.number;
190
+ const mobileSource = knownMobile || ns !== exports.NS.Msisdn;
191
+ if (mobileSource && e164.startsWith('+55') && e164.length === 13 && '6789'.includes(e164[5])) {
192
+ const with9 = '+55' + e164.slice(3, 5) + '9' + e164.slice(5);
193
+ try {
194
+ const n9 = (0, max_1.parsePhoneNumberWithError)(with9, 'BR');
195
+ if (n9.isValid()) {
196
+ number = n9;
197
+ e164 = with9;
198
+ }
199
+ }
200
+ catch { /* se queda con el original */ }
201
+ }
202
+ if (!number.isValid())
203
+ return invalid(ns, 'invalid_phone', raw);
204
+ const aliases = [];
205
+ if (e164.startsWith('+549') && e164.length === 14)
206
+ aliases.push({ key: buildKey(ns, null, '+54' + e164.slice(4)), evidence: exports.EVIDENCE_AR_MOBILE_WITHOUT_9 });
207
+ if (e164.startsWith('+55') && e164.length === 14 && e164[5] === '9')
208
+ aliases.push({ key: buildKey(ns, null, '+55' + e164.slice(3, 5) + e164.slice(6)), evidence: exports.EVIDENCE_BR_MOBILE_WITHOUT_9 });
209
+ const result = valid(ns, null, e164, number.formatInternational());
210
+ result.aliases = aliases;
211
+ return result;
212
+ }
213
+ // ---------------------------------------------------------------- WhatsApp (N2, N3, NZ1, D5)
214
+ /**
215
+ * Principal wa_phone si hay número; si no, provisoria por LID o BSUID (N3). Alias wa_bsuid con scope = portfolio
216
+ * (cloudApiBusinessId del canal; sin portfolio no se genera, NZ1) y wa_lid sin scope.
217
+ */
218
+ function normalizeWhatsApp(waId, bsuid, lid, portfolio, defaultCountry) {
219
+ var _a;
220
+ const bs = bsuid === null || bsuid === void 0 ? void 0 : bsuid.trim();
221
+ const pf = portfolio && portfolio.trim() ? portfolio.trim() : null;
222
+ let bsuidKey = bs && pf ? buildKey(exports.NS.WhatsAppBsuid, pf, bs) : null;
223
+ let wa = (waId === null || waId === void 0 ? void 0 : waId.trim()) || null;
224
+ // F03: un JID @lid informado como número es un LID, nunca un teléfono.
225
+ if (wa && wa.toLowerCase().endsWith('@lid')) {
226
+ if (!lid || !lid.trim())
227
+ lid = wa;
228
+ wa = null;
229
+ }
230
+ const l = stripSuffix(lid === null || lid === void 0 ? void 0 : lid.trim(), '@lid');
231
+ let lidKey = l ? buildKey(exports.NS.WhatsAppLid, null, l) : null;
232
+ const phoneResult = wa ? normalizePhone(wa, defaultCountry, exports.NS.WhatsAppPhone) : null;
233
+ let result;
234
+ if (phoneResult && phoneResult.isValid) {
235
+ result = phoneResult;
236
+ }
237
+ else if (phoneResult && !lidKey && !bsuidKey) {
238
+ return phoneResult;
239
+ // R01/NZ9: teléfono inválido o ausente → provisoria por LID o BSUID; el teléfono queda como evidencia (rawValue).
240
+ }
241
+ else if (lidKey) {
242
+ result = valid(exports.NS.WhatsAppLid, null, l, l);
243
+ lidKey = null;
244
+ }
245
+ else if (bsuidKey) {
246
+ result = valid(exports.NS.WhatsAppBsuid, pf, bs, bs);
247
+ bsuidKey = null;
248
+ }
249
+ else
250
+ return invalid(exports.NS.WhatsAppPhone, 'missing_whatsapp_id', (_a = waId !== null && waId !== void 0 ? waId : bsuid) !== null && _a !== void 0 ? _a : lid);
251
+ if (bsuidKey)
252
+ result.aliases.push({ key: bsuidKey, evidence: 'same_event' });
253
+ if (lidKey)
254
+ result.aliases.push({ key: lidKey, evidence: 'same_event' });
255
+ return result;
256
+ }
257
+ /** Grupo de WhatsApp (Baileys): id sin @g.us, sin scope. */
258
+ function normalizeWhatsAppGroup(raw) {
259
+ const v = stripSuffix(raw === null || raw === void 0 ? void 0 : raw.trim(), '@g.us');
260
+ if (!v)
261
+ return invalid(exports.NS.WhatsAppGroup, 'invalid_group', raw);
262
+ return valid(exports.NS.WhatsAppGroup, null, v, v);
263
+ }
264
+ /** Grupo de la Cloud API: group_id opaco con scope de canal o número de negocio. */
265
+ function normalizeWhatsAppCloudGroup(groupId, channelScope) {
266
+ return normalizeOpaque(exports.NS.WhatsAppCloudGroup, groupId, channelScope, true);
267
+ }
268
+ // ---------------------------------------------------------------- Opacos (N8, N10) y SMS (NZ4)
269
+ /** psid, igsid, webchat, openmessaging, meli_user: trim, sin cambiar mayúsculas; sin scope requerido → inválida. */
270
+ function normalizeOpaque(identityNamespace, raw, scope, scopeRequired) {
271
+ const v = raw === null || raw === void 0 ? void 0 : raw.trim();
272
+ if (!v)
273
+ return invalid(identityNamespace, 'invalid_value', raw);
274
+ const sc = scope && scope.trim() ? scope.trim() : null;
275
+ if (scopeRequired && !sc)
276
+ return invalid(identityNamespace, 'missing_scope', raw);
277
+ return valid(identityNamespace, sc, v, v);
278
+ }
279
+ /** Remitente SMS no telefónico: código corto o alfanumérico en mayúsculas sin espacios; scope = canal. */
280
+ function normalizeSmsSender(raw, channelId) {
281
+ const ns = exports.NS.SmsSender;
282
+ if (!raw || !raw.trim())
283
+ return invalid(ns, 'invalid_value', raw);
284
+ if (!channelId || !channelId.trim())
285
+ return invalid(ns, 'missing_scope', raw);
286
+ const v = [...raw].filter(c => !isWhite(c)).join('').toUpperCase();
287
+ return valid(ns, channelId.trim(), v, raw.trim());
288
+ }
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@trii/identity",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Normalizadores de identidades de canal (claves namespace|scope|valor y keyHash) para servicios Node de Trii. Espejo de Trii.Contacts.ChannelIdentityNormalizer (trii-LibDef).",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "/dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc -p .",
12
+ "test": "node tests/normalization.test.cjs ../../../trii-LibDef"
13
+ },
14
+ "dependencies": {
15
+ "libphonenumber-js": "1.13.17"
16
+ },
17
+ "author": "Trii LLC",
18
+ "license": "ISC",
19
+ "devDependencies": {
20
+ "@types/node": "^20.19.43",
21
+ "typescript": "^5.9.3"
22
+ }
23
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.