@ripwords/myinvois-client 0.2.40 → 0.2.41

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.
Files changed (46) hide show
  1. package/dist/{apiQueue-CrR6pgYn.js → apiQueue-CCrZMnMu.js} +11 -10
  2. package/dist/{apiQueue-Dj0xtcGe.cjs → apiQueue-Djd7WlnV.cjs} +12 -11
  3. package/dist/apiQueue-Djd7WlnV.cjs.map +1 -0
  4. package/dist/index.cjs +2 -2
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.js +2 -2
  7. package/dist/index10.cjs +4 -195
  8. package/dist/index11.cjs +22 -0
  9. package/dist/index12.cjs +2 -24
  10. package/dist/index13.cjs +3 -0
  11. package/dist/index14.cjs +330 -0
  12. package/dist/{index29.cjs.map → index14.cjs.map} +1 -1
  13. package/dist/index15.cjs +189 -25
  14. package/dist/index15.cjs.map +1 -1
  15. package/dist/index16.cjs +53 -16
  16. package/dist/index16.cjs.map +1 -1
  17. package/dist/index17.cjs +532 -0
  18. package/dist/index17.cjs.map +1 -0
  19. package/dist/index18.cjs +187 -25
  20. package/dist/index18.cjs.map +1 -1
  21. package/dist/index19.cjs +0 -24
  22. package/dist/index20.cjs +25 -0
  23. package/dist/{index12.cjs.map → index20.cjs.map} +1 -1
  24. package/dist/index23.cjs +28 -3
  25. package/dist/index23.cjs.map +1 -0
  26. package/dist/index24.cjs +21 -9
  27. package/dist/index24.cjs.map +1 -1
  28. package/dist/index25.cjs +0 -5
  29. package/dist/index26.cjs +33 -21
  30. package/dist/index26.cjs.map +1 -0
  31. package/dist/index27.cjs +23 -2
  32. package/dist/{index19.cjs.map → index27.cjs.map} +1 -1
  33. package/dist/index28.cjs +0 -3
  34. package/dist/index29.cjs +0 -330
  35. package/dist/index30.cjs +0 -193
  36. package/dist/index68.cts.map +1 -1
  37. package/dist/index8.cjs +3 -61
  38. package/dist/index9.cjs +9 -528
  39. package/dist/index9.cjs.map +1 -1
  40. package/dist/utils/apiQueue.d.ts +3 -1
  41. package/dist/utils/apiQueue.js +1 -1
  42. package/package.json +1 -1
  43. package/dist/apiQueue-Dj0xtcGe.cjs.map +0 -1
  44. package/dist/index10.cjs.map +0 -1
  45. package/dist/index30.cjs.map +0 -1
  46. package/dist/index8.cjs.map +0 -1
package/dist/index14.cjs CHANGED
@@ -0,0 +1,330 @@
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ require('./formatIdValue-i67o4kyD.cjs');
3
+ const require_document = require('./document-CCza2JPL.cjs');
4
+ const crypto = require_chunk.__toESM(require("crypto"));
5
+
6
+ //#region src/utils/signature-diagnostics.ts
7
+ /**
8
+ * Analyzes certificate for MyInvois compatibility issues
9
+ */
10
+ function analyzeCertificateForDiagnostics(certificatePem) {
11
+ const issues = [];
12
+ const recommendations = [];
13
+ try {
14
+ const cert = new crypto.default.X509Certificate(certificatePem);
15
+ const certInfo = require_document.extractCertificateInfo(certificatePem);
16
+ const parseSubjectFields = (dn) => {
17
+ const fields = {};
18
+ dn.split("\n").forEach((line) => {
19
+ const trimmed = line.trim();
20
+ if (trimmed.includes("=")) {
21
+ const [key, ...valueParts] = trimmed.split("=");
22
+ if (key) fields[key.trim()] = valueParts.join("=").trim();
23
+ }
24
+ });
25
+ return fields;
26
+ };
27
+ const subjectFields = parseSubjectFields(cert.subject);
28
+ const organizationIdentifier = subjectFields["organizationIdentifier"] || subjectFields["2.5.4.97"];
29
+ const serialNumber = subjectFields["serialNumber"];
30
+ if (!organizationIdentifier) {
31
+ issues.push("DS311: Certificate missing organizationIdentifier field (TIN)");
32
+ recommendations.push("CRITICAL: Generate new certificate with organizationIdentifier matching your MyInvois TIN");
33
+ recommendations.push("Portal Error: \"Signer of invoice doesn't match the submitter of document. TIN doesn't match with the OI.\"");
34
+ } else if (organizationIdentifier.length < 10) {
35
+ issues.push("DS311: OrganizationIdentifier (TIN) appears too short - may cause submission rejection");
36
+ recommendations.push("Verify TIN format matches exactly what is registered in MyInvois");
37
+ }
38
+ if (!serialNumber) {
39
+ issues.push("DS312: Certificate missing serialNumber field (business registration)");
40
+ recommendations.push("CRITICAL: Generate new certificate with serialNumber matching your business registration");
41
+ recommendations.push("Portal Error: \"Submitter registration/identity number doesn't match with the certificate SERIALNUMBER.\"");
42
+ }
43
+ if (cert.issuer === cert.subject) {
44
+ issues.push("DS329: Self-signed certificate detected - will fail chain of trust validation");
45
+ recommendations.push("BLOCKING: Obtain certificate from MyInvois-approved CA:");
46
+ recommendations.push("• MSC Trustgate Sdn Bhd");
47
+ recommendations.push("• DigiCert Sdn Bhd");
48
+ recommendations.push("• Cybersign Asia Sdn Bhd");
49
+ recommendations.push("Portal Error: \"Certificate is not valid according to the chain of trust validation or has been issued by an untrusted certificate authority.\"");
50
+ } else {
51
+ const issuerName = cert.issuer.toLowerCase();
52
+ const approvedCAs = [
53
+ "msc trustgate",
54
+ "digicert",
55
+ "cybersign"
56
+ ];
57
+ const isFromApprovedCA = approvedCAs.some((ca) => issuerName.includes(ca));
58
+ if (!isFromApprovedCA) {
59
+ issues.push("DS329: Certificate may not be from MyInvois-approved CA");
60
+ recommendations.push("Verify certificate was issued by an approved CA for MyInvois");
61
+ }
62
+ }
63
+ const rawIssuer = cert.issuer;
64
+ const normalizedIssuer = certInfo.issuerName;
65
+ const normalizedIssuerIssues = [
66
+ {
67
+ check: normalizedIssuer.includes("\n"),
68
+ issue: "Normalized issuer still contains newlines"
69
+ },
70
+ {
71
+ check: normalizedIssuer.includes(" "),
72
+ issue: "Normalized issuer contains double spaces"
73
+ },
74
+ {
75
+ check: /=\s+/.test(normalizedIssuer),
76
+ issue: "Normalized issuer has spaces after equals"
77
+ },
78
+ {
79
+ check: /\s+=/.test(normalizedIssuer),
80
+ issue: "Normalized issuer has spaces before equals"
81
+ },
82
+ {
83
+ check: normalizedIssuer.includes("\r"),
84
+ issue: "Normalized issuer contains carriage returns"
85
+ }
86
+ ];
87
+ const hasActualFormatIssues = normalizedIssuerIssues.some(({ check, issue }) => {
88
+ if (check) {
89
+ issues.push(`DS326: ${issue} - will cause X509IssuerName mismatch`);
90
+ return true;
91
+ }
92
+ return false;
93
+ });
94
+ const hasRawIssuesButNormalizedOk = rawIssuer.includes("\n") && !normalizedIssuer.includes("\n");
95
+ if (hasActualFormatIssues) {
96
+ recommendations.push("CRITICAL: Fix issuer name normalization in signature generation");
97
+ recommendations.push("Portal Error: \"Certificate X509IssuerName doesn't match the X509IssuerName value provided in the signed properties section.\"");
98
+ recommendations.push("The normalization function is not properly formatting the issuer name");
99
+ recommendations.push("Debug: Check document.ts extractCertificateInfo() normalization logic");
100
+ } else if (hasRawIssuesButNormalizedOk) console.log("ℹ️ Note: Raw certificate issuer has newlines but normalization is handling them correctly");
101
+ const now = /* @__PURE__ */ new Date();
102
+ const validFrom = new Date(cert.validFrom);
103
+ const validTo = new Date(cert.validTo);
104
+ if (now < validFrom) {
105
+ issues.push("DS329: Certificate not yet valid (future start date)");
106
+ recommendations.push("Wait until certificate validity period begins");
107
+ }
108
+ if (now > validTo) {
109
+ issues.push("DS329: Certificate has expired");
110
+ recommendations.push("BLOCKING: Renew certificate - expired certificates are rejected");
111
+ }
112
+ try {
113
+ if (cert.keyUsage && !cert.keyUsage.includes("digital signature")) {
114
+ issues.push("DS333: Certificate lacks digitalSignature key usage");
115
+ recommendations.push("Generate new certificate with digitalSignature key usage enabled");
116
+ }
117
+ } catch {
118
+ console.log("Note: Could not check key usage extensions");
119
+ }
120
+ return {
121
+ organizationIdentifier,
122
+ serialNumber,
123
+ issuerName: certInfo.issuerName,
124
+ subjectName: certInfo.subjectName,
125
+ issues,
126
+ recommendations
127
+ };
128
+ } catch (error) {
129
+ issues.push(`Certificate parsing failed: ${error}`);
130
+ recommendations.push("Verify certificate format and validity");
131
+ return {
132
+ issuerName: "",
133
+ subjectName: "",
134
+ issues,
135
+ recommendations
136
+ };
137
+ }
138
+ }
139
+ /**
140
+ * Analyzes signature generation for potential issues
141
+ */
142
+ function analyzeSignatureForDiagnostics(invoices, certificatePem) {
143
+ const issues = [];
144
+ const recommendations = [];
145
+ try {
146
+ const documentDigest = require_document.calculateDocumentDigest(invoices);
147
+ const certificateDigest = require_document.calculateCertificateDigest(certificatePem);
148
+ const certInfo = require_document.extractCertificateInfo(certificatePem);
149
+ const signingTime = (/* @__PURE__ */ new Date()).toISOString();
150
+ const signedProperties = require_document.createSignedProperties(certificateDigest, signingTime, certInfo.issuerName, certInfo.serialNumber);
151
+ const signedPropertiesDigest = require_document.calculateSignedPropertiesDigest(signedProperties);
152
+ if (documentDigest.length === 0) {
153
+ issues.push("DS333: Document digest generation failed");
154
+ recommendations.push("CRITICAL: Verify document serialization excludes UBLExtensions/Signature");
155
+ recommendations.push("Portal Error: \"Document signature value is not a valid signature of the document digest using the public key of the certificate provided.\"");
156
+ }
157
+ if (certificateDigest.length === 0) {
158
+ issues.push("DS333: Certificate digest generation failed");
159
+ recommendations.push("CRITICAL: Verify certificate format and encoding");
160
+ recommendations.push("Certificate must be properly base64 encoded without headers/footers");
161
+ }
162
+ if (signedPropertiesDigest.length === 0) {
163
+ issues.push("DS333: Signed properties digest generation failed");
164
+ recommendations.push("CRITICAL: Verify signed properties structure and canonicalization");
165
+ recommendations.push("Check XML canonicalization (C14N) is applied correctly");
166
+ }
167
+ try {
168
+ const cert = new crypto.default.X509Certificate(certificatePem);
169
+ const publicKey = cert.publicKey;
170
+ const keyDetails = publicKey.asymmetricKeyDetails;
171
+ if (keyDetails) {
172
+ if (publicKey.asymmetricKeyType === "rsa" && keyDetails.modulusLength && keyDetails.modulusLength < 2048) {
173
+ issues.push("DS333: RSA key size too small (minimum 2048 bits required)");
174
+ recommendations.push("CRITICAL: Generate new certificate with RSA 2048+ bits");
175
+ }
176
+ const supportedKeyTypes = ["rsa", "ec"];
177
+ if (!supportedKeyTypes.includes(publicKey.asymmetricKeyType || "")) {
178
+ issues.push(`DS333: Unsupported key type: ${publicKey.asymmetricKeyType}`);
179
+ recommendations.push("CRITICAL: Use RSA or EC key types for MyInvois compatibility");
180
+ }
181
+ }
182
+ const certBuffer = Buffer.from(certificatePem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
183
+ if (certBuffer.length === 0) {
184
+ issues.push("DS333: Certificate encoding appears invalid");
185
+ recommendations.push("CRITICAL: Verify certificate is properly PEM encoded");
186
+ }
187
+ } catch (error) {
188
+ issues.push(`DS333: Certificate validation failed - ${error}`);
189
+ recommendations.push("CRITICAL: Verify certificate format and structure are valid");
190
+ }
191
+ const isValidBase64 = (str) => {
192
+ try {
193
+ return Buffer.from(str, "base64").toString("base64") === str;
194
+ } catch {
195
+ return false;
196
+ }
197
+ };
198
+ if (documentDigest && !isValidBase64(documentDigest)) {
199
+ issues.push("DS333: Document digest is not valid base64 format");
200
+ recommendations.push("Ensure digest is properly base64 encoded");
201
+ }
202
+ if (certificateDigest && !isValidBase64(certificateDigest)) {
203
+ issues.push("DS333: Certificate digest is not valid base64 format");
204
+ recommendations.push("Ensure certificate digest is properly base64 encoded");
205
+ }
206
+ if (signedPropertiesDigest && !isValidBase64(signedPropertiesDigest)) {
207
+ issues.push("DS333: Signed properties digest is not valid base64 format");
208
+ recommendations.push("Ensure signed properties digest is properly base64 encoded");
209
+ }
210
+ return {
211
+ documentDigest,
212
+ certificateDigest,
213
+ signedPropertiesDigest,
214
+ issues,
215
+ recommendations
216
+ };
217
+ } catch (error) {
218
+ issues.push(`Signature analysis failed: ${error}`);
219
+ recommendations.push("Review signature generation implementation");
220
+ return {
221
+ documentDigest: "",
222
+ certificateDigest: "",
223
+ signedPropertiesDigest: "",
224
+ issues,
225
+ recommendations
226
+ };
227
+ }
228
+ }
229
+ /**
230
+ * Comprehensive signature diagnostics
231
+ */
232
+ function diagnoseSignatureIssues(invoices, certificatePem) {
233
+ const certificateAnalysis = analyzeCertificateForDiagnostics(certificatePem);
234
+ const signatureAnalysis = analyzeSignatureForDiagnostics(invoices, certificatePem);
235
+ const certificateIssues = certificateAnalysis.issues.length;
236
+ const signatureIssues = signatureAnalysis.issues.length;
237
+ return {
238
+ certificateAnalysis,
239
+ signatureAnalysis,
240
+ summary: {
241
+ totalIssues: certificateIssues + signatureIssues,
242
+ certificateIssues,
243
+ signatureIssues
244
+ }
245
+ };
246
+ }
247
+ /**
248
+ * Prints diagnostic results in a formatted way
249
+ */
250
+ function printDiagnostics(result) {
251
+ console.log("\n🔍 MyInvois Signature Diagnostics Report");
252
+ console.log("=".repeat(60));
253
+ console.log("\n📜 CERTIFICATE ANALYSIS");
254
+ console.log("-".repeat(30));
255
+ console.log(` Issuer: ${result.certificateAnalysis.issuerName}`);
256
+ console.log(` Subject: ${result.certificateAnalysis.subjectName}`);
257
+ if (result.certificateAnalysis.organizationIdentifier) console.log(` Organization ID (TIN): ${result.certificateAnalysis.organizationIdentifier}`);
258
+ if (result.certificateAnalysis.serialNumber) console.log(` Serial Number: ${result.certificateAnalysis.serialNumber}`);
259
+ if (result.certificateAnalysis.issues.length > 0) {
260
+ console.log("\n 🚨 Certificate Issues:");
261
+ result.certificateAnalysis.issues.forEach((issue, index) => {
262
+ console.log(` ${index + 1}. ${issue}`);
263
+ });
264
+ }
265
+ if (result.certificateAnalysis.recommendations.length > 0) {
266
+ console.log("\n 💡 Certificate Recommendations:");
267
+ result.certificateAnalysis.recommendations.forEach((rec, index) => {
268
+ console.log(` ${index + 1}. ${rec}`);
269
+ });
270
+ }
271
+ console.log("\n🔐 SIGNATURE ANALYSIS");
272
+ console.log("-".repeat(30));
273
+ console.log(` Document Digest: ${result.signatureAnalysis.documentDigest.substring(0, 32)}...`);
274
+ console.log(` Certificate Digest: ${result.signatureAnalysis.certificateDigest.substring(0, 32)}...`);
275
+ console.log(` Signed Properties Digest: ${result.signatureAnalysis.signedPropertiesDigest.substring(0, 32)}...`);
276
+ if (result.signatureAnalysis.issues.length > 0) {
277
+ console.log("\n 🚨 Signature Issues:");
278
+ result.signatureAnalysis.issues.forEach((issue, index) => {
279
+ console.log(` ${index + 1}. ${issue}`);
280
+ });
281
+ }
282
+ if (result.signatureAnalysis.recommendations.length > 0) {
283
+ console.log("\n 💡 Signature Recommendations:");
284
+ result.signatureAnalysis.recommendations.forEach((rec, index) => {
285
+ console.log(` ${index + 1}. ${rec}`);
286
+ });
287
+ }
288
+ console.log("\n📊 SUMMARY");
289
+ console.log("-".repeat(30));
290
+ console.log(` Total Issues Found: ${result.summary.totalIssues}`);
291
+ console.log(` Certificate Issues: ${result.summary.certificateIssues}`);
292
+ console.log(` Signature Issues: ${result.summary.signatureIssues}`);
293
+ if (result.summary.totalIssues === 0) {
294
+ console.log("\n ✅ No issues detected in current analysis");
295
+ console.log(" 🎉 Certificate and signature implementation appear valid");
296
+ } else {
297
+ console.log("\n ⚠️ Issues detected - review recommendations above");
298
+ const hasDS311 = result.certificateAnalysis.issues.some((issue) => issue.includes("DS311"));
299
+ const hasDS312 = result.certificateAnalysis.issues.some((issue) => issue.includes("DS312"));
300
+ const hasDS326 = result.certificateAnalysis.issues.some((issue) => issue.includes("DS326"));
301
+ const hasDS329 = result.certificateAnalysis.issues.some((issue) => issue.includes("DS329"));
302
+ const hasDS333 = result.signatureAnalysis.issues.some((issue) => issue.includes("DS333"));
303
+ console.log("\n 🎯 MYINVOIS PORTAL ERROR ANALYSIS:");
304
+ if (hasDS311) console.log(" ❌ DS311 - TIN mismatch between certificate and submitter");
305
+ if (hasDS312) console.log(" ❌ DS312 - Registration number mismatch with certificate");
306
+ if (hasDS326) console.log(" ❌ DS326 - X509IssuerName format inconsistency");
307
+ if (hasDS329) console.log(" ❌ DS329 - Certificate trust chain validation failure");
308
+ if (hasDS333) console.log(" ❌ DS333 - Document signature validation failure");
309
+ if (result.summary.certificateIssues > 0) {
310
+ console.log("\n 🚨 PRIMARY ACTION REQUIRED:");
311
+ console.log(" Certificate issues must be resolved first");
312
+ console.log(" Self-generated certificates cannot pass MyInvois validation");
313
+ }
314
+ if (result.summary.signatureIssues > 0) {
315
+ console.log("\n ⚙️ SECONDARY ACTION:");
316
+ console.log(" Review and optimize signature implementation");
317
+ }
318
+ console.log("\n 📋 NEXT STEPS:");
319
+ console.log(" 1. Address BLOCKING/CRITICAL issues first");
320
+ console.log(" 2. Test with updated certificate/implementation");
321
+ console.log(" 3. Re-run diagnostics to verify fixes");
322
+ console.log(" 4. Submit test document to MyInvois portal");
323
+ }
324
+ console.log("\n" + "=".repeat(60));
325
+ }
326
+
327
+ //#endregion
328
+ exports.diagnoseSignatureIssues = diagnoseSignatureIssues;
329
+ exports.printDiagnostics = printDiagnostics;
330
+ //# sourceMappingURL=index14.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index29.cjs","names":["certificatePem: string","issues: string[]","recommendations: string[]","dn: string","fields: Record<string, string>","invoices: InvoiceV1_1[]","str: string","result: DiagnosticResult"],"sources":["../src/utils/signature-diagnostics.ts"],"sourcesContent":["import crypto from 'crypto'\nimport type { InvoiceV1_1 } from '../types'\nimport {\n extractCertificateInfo,\n calculateDocumentDigest,\n calculateSignedPropertiesDigest,\n createSignedProperties,\n calculateCertificateDigest,\n} from './document'\n\nexport interface CertificateAnalysisResult {\n organizationIdentifier?: string\n serialNumber?: string\n issuerName: string\n subjectName: string\n issues: string[]\n recommendations: string[]\n}\n\nexport interface SignatureAnalysisResult {\n documentDigest: string\n certificateDigest: string\n signedPropertiesDigest: string\n issues: string[]\n recommendations: string[]\n}\n\nexport interface DiagnosticResult {\n certificateAnalysis: CertificateAnalysisResult\n signatureAnalysis: SignatureAnalysisResult\n summary: {\n totalIssues: number\n certificateIssues: number\n signatureIssues: number\n }\n}\n\n/**\n * Analyzes certificate for MyInvois compatibility issues\n */\nfunction analyzeCertificateForDiagnostics(\n certificatePem: string,\n): CertificateAnalysisResult {\n const issues: string[] = []\n const recommendations: string[] = []\n\n try {\n const cert = new crypto.X509Certificate(certificatePem)\n const certInfo = extractCertificateInfo(certificatePem)\n\n // Parse subject fields for MyInvois analysis\n const parseSubjectFields = (dn: string) => {\n const fields: Record<string, string> = {}\n dn.split('\\n').forEach(line => {\n const trimmed = line.trim()\n if (trimmed.includes('=')) {\n const [key, ...valueParts] = trimmed.split('=')\n if (key) {\n fields[key.trim()] = valueParts.join('=').trim()\n }\n }\n })\n return fields\n }\n\n const subjectFields = parseSubjectFields(cert.subject)\n const organizationIdentifier =\n subjectFields['organizationIdentifier'] || subjectFields['2.5.4.97']\n const serialNumber = subjectFields['serialNumber']\n\n // DS311 - TIN Mismatch Analysis\n if (!organizationIdentifier) {\n issues.push(\n 'DS311: Certificate missing organizationIdentifier field (TIN)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with organizationIdentifier matching your MyInvois TIN',\n )\n recommendations.push(\n 'Portal Error: \"Signer of invoice doesn\\'t match the submitter of document. TIN doesn\\'t match with the OI.\"',\n )\n } else {\n // Additional TIN format validation\n if (organizationIdentifier.length < 10) {\n issues.push(\n 'DS311: OrganizationIdentifier (TIN) appears too short - may cause submission rejection',\n )\n recommendations.push(\n 'Verify TIN format matches exactly what is registered in MyInvois',\n )\n }\n }\n\n // DS312 - Registration Number Analysis\n if (!serialNumber) {\n issues.push(\n 'DS312: Certificate missing serialNumber field (business registration)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with serialNumber matching your business registration',\n )\n recommendations.push(\n 'Portal Error: \"Submitter registration/identity number doesn\\'t match with the certificate SERIALNUMBER.\"',\n )\n }\n\n // DS329 - Certificate Trust Analysis\n if (cert.issuer === cert.subject) {\n issues.push(\n 'DS329: Self-signed certificate detected - will fail chain of trust validation',\n )\n recommendations.push(\n 'BLOCKING: Obtain certificate from MyInvois-approved CA:',\n )\n recommendations.push('• MSC Trustgate Sdn Bhd')\n recommendations.push('• DigiCert Sdn Bhd')\n recommendations.push('• Cybersign Asia Sdn Bhd')\n recommendations.push(\n 'Portal Error: \"Certificate is not valid according to the chain of trust validation or has been issued by an untrusted certificate authority.\"',\n )\n } else {\n // Check if issuer looks like a known CA\n const issuerName = cert.issuer.toLowerCase()\n const approvedCAs = ['msc trustgate', 'digicert', 'cybersign']\n const isFromApprovedCA = approvedCAs.some(ca => issuerName.includes(ca))\n\n if (!isFromApprovedCA) {\n issues.push('DS329: Certificate may not be from MyInvois-approved CA')\n recommendations.push(\n 'Verify certificate was issued by an approved CA for MyInvois',\n )\n }\n }\n\n // DS326 - Issuer Name Format Analysis (Enhanced)\n const rawIssuer = cert.issuer\n const normalizedIssuer = certInfo.issuerName\n\n // Check for issues in the NORMALIZED issuer (these are actual problems)\n const normalizedIssuerIssues = [\n {\n check: normalizedIssuer.includes('\\n'),\n issue: 'Normalized issuer still contains newlines',\n },\n {\n check: normalizedIssuer.includes(' '),\n issue: 'Normalized issuer contains double spaces',\n },\n {\n check: /=\\s+/.test(normalizedIssuer),\n issue: 'Normalized issuer has spaces after equals',\n },\n {\n check: /\\s+=/.test(normalizedIssuer),\n issue: 'Normalized issuer has spaces before equals',\n },\n {\n check: normalizedIssuer.includes('\\r'),\n issue: 'Normalized issuer contains carriage returns',\n },\n ]\n\n // Only report actual issues in the normalized version that will cause portal errors\n const hasActualFormatIssues = normalizedIssuerIssues.some(\n ({ check, issue }) => {\n if (check) {\n issues.push(`DS326: ${issue} - will cause X509IssuerName mismatch`)\n return true\n }\n return false\n },\n )\n\n // Check if raw issuer has issues but normalized version is OK (informational)\n const hasRawIssuesButNormalizedOk =\n rawIssuer.includes('\\n') && !normalizedIssuer.includes('\\n')\n\n if (hasActualFormatIssues) {\n recommendations.push(\n 'CRITICAL: Fix issuer name normalization in signature generation',\n )\n recommendations.push(\n 'Portal Error: \"Certificate X509IssuerName doesn\\'t match the X509IssuerName value provided in the signed properties section.\"',\n )\n recommendations.push(\n 'The normalization function is not properly formatting the issuer name',\n )\n recommendations.push(\n 'Debug: Check document.ts extractCertificateInfo() normalization logic',\n )\n } else if (hasRawIssuesButNormalizedOk) {\n // This is informational - normalization is working correctly\n console.log(\n 'ℹ️ Note: Raw certificate issuer has newlines but normalization is handling them correctly',\n )\n }\n\n // Additional certificate validity checks\n const now = new Date()\n const validFrom = new Date(cert.validFrom)\n const validTo = new Date(cert.validTo)\n\n if (now < validFrom) {\n issues.push('DS329: Certificate not yet valid (future start date)')\n recommendations.push('Wait until certificate validity period begins')\n }\n\n if (now > validTo) {\n issues.push('DS329: Certificate has expired')\n recommendations.push(\n 'BLOCKING: Renew certificate - expired certificates are rejected',\n )\n }\n\n // Check certificate key usage (if available)\n try {\n if (cert.keyUsage && !cert.keyUsage.includes('digital signature')) {\n issues.push('DS333: Certificate lacks digitalSignature key usage')\n recommendations.push(\n 'Generate new certificate with digitalSignature key usage enabled',\n )\n }\n } catch {\n // Key usage might not be available in all certificates\n console.log('Note: Could not check key usage extensions')\n }\n\n return {\n organizationIdentifier,\n serialNumber,\n issuerName: certInfo.issuerName,\n subjectName: certInfo.subjectName,\n issues,\n recommendations,\n }\n } catch (error) {\n issues.push(`Certificate parsing failed: ${error}`)\n recommendations.push('Verify certificate format and validity')\n\n return {\n issuerName: '',\n subjectName: '',\n issues,\n recommendations,\n }\n }\n}\n\n/**\n * Analyzes signature generation for potential issues\n */\nfunction analyzeSignatureForDiagnostics(\n invoices: InvoiceV1_1[],\n certificatePem: string,\n): SignatureAnalysisResult {\n const issues: string[] = []\n const recommendations: string[] = []\n\n try {\n // Step 1: Document digest\n const documentDigest = calculateDocumentDigest(invoices)\n\n // Step 2: Certificate digest\n const certificateDigest = calculateCertificateDigest(certificatePem)\n\n // Step 3: Extract certificate info\n const certInfo = extractCertificateInfo(certificatePem)\n const signingTime = new Date().toISOString()\n\n // Step 4: Create signed properties\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 5: Signed properties digest\n const signedPropertiesDigest =\n calculateSignedPropertiesDigest(signedProperties)\n\n // DS333 - Document Signature Validation\n if (documentDigest.length === 0) {\n issues.push('DS333: Document digest generation failed')\n recommendations.push(\n 'CRITICAL: Verify document serialization excludes UBLExtensions/Signature',\n )\n recommendations.push(\n 'Portal Error: \"Document signature value is not a valid signature of the document digest using the public key of the certificate provided.\"',\n )\n }\n\n if (certificateDigest.length === 0) {\n issues.push('DS333: Certificate digest generation failed')\n recommendations.push('CRITICAL: Verify certificate format and encoding')\n recommendations.push(\n 'Certificate must be properly base64 encoded without headers/footers',\n )\n }\n\n if (signedPropertiesDigest.length === 0) {\n issues.push('DS333: Signed properties digest generation failed')\n recommendations.push(\n 'CRITICAL: Verify signed properties structure and canonicalization',\n )\n recommendations.push(\n 'Check XML canonicalization (C14N) is applied correctly',\n )\n }\n\n // Additional DS333 checks\n try {\n const cert = new crypto.X509Certificate(certificatePem)\n\n // Verify the certificate has the required algorithms for MyInvois\n const publicKey = cert.publicKey\n const keyDetails = publicKey.asymmetricKeyDetails\n\n if (keyDetails) {\n // Check if key size is adequate for RSA (minimum 2048 bits)\n if (\n publicKey.asymmetricKeyType === 'rsa' &&\n keyDetails.modulusLength &&\n keyDetails.modulusLength < 2048\n ) {\n issues.push(\n 'DS333: RSA key size too small (minimum 2048 bits required)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with RSA 2048+ bits',\n )\n }\n\n // Check supported key types\n const supportedKeyTypes = ['rsa', 'ec']\n if (!supportedKeyTypes.includes(publicKey.asymmetricKeyType || '')) {\n issues.push(\n `DS333: Unsupported key type: ${publicKey.asymmetricKeyType}`,\n )\n recommendations.push(\n 'CRITICAL: Use RSA or EC key types for MyInvois compatibility',\n )\n }\n }\n\n // Test certificate format validity\n const certBuffer = Buffer.from(\n certificatePem.replace(/-----[^-]+-----/g, '').replace(/\\s/g, ''),\n 'base64',\n )\n if (certBuffer.length === 0) {\n issues.push('DS333: Certificate encoding appears invalid')\n recommendations.push(\n 'CRITICAL: Verify certificate is properly PEM encoded',\n )\n }\n } catch (error) {\n issues.push(`DS333: Certificate validation failed - ${error}`)\n recommendations.push(\n 'CRITICAL: Verify certificate format and structure are valid',\n )\n }\n\n // Validate digest formats (should be base64)\n const isValidBase64 = (str: string) => {\n try {\n return Buffer.from(str, 'base64').toString('base64') === str\n } catch {\n return false\n }\n }\n\n if (documentDigest && !isValidBase64(documentDigest)) {\n issues.push('DS333: Document digest is not valid base64 format')\n recommendations.push('Ensure digest is properly base64 encoded')\n }\n\n if (certificateDigest && !isValidBase64(certificateDigest)) {\n issues.push('DS333: Certificate digest is not valid base64 format')\n recommendations.push(\n 'Ensure certificate digest is properly base64 encoded',\n )\n }\n\n if (signedPropertiesDigest && !isValidBase64(signedPropertiesDigest)) {\n issues.push('DS333: Signed properties digest is not valid base64 format')\n recommendations.push(\n 'Ensure signed properties digest is properly base64 encoded',\n )\n }\n\n return {\n documentDigest,\n certificateDigest,\n signedPropertiesDigest,\n issues,\n recommendations,\n }\n } catch (error) {\n issues.push(`Signature analysis failed: ${error}`)\n recommendations.push('Review signature generation implementation')\n\n return {\n documentDigest: '',\n certificateDigest: '',\n signedPropertiesDigest: '',\n issues,\n recommendations,\n }\n }\n}\n\n/**\n * Comprehensive signature diagnostics\n */\nexport function diagnoseSignatureIssues(\n invoices: InvoiceV1_1[],\n certificatePem: string,\n): DiagnosticResult {\n const certificateAnalysis = analyzeCertificateForDiagnostics(certificatePem)\n const signatureAnalysis = analyzeSignatureForDiagnostics(\n invoices,\n certificatePem,\n )\n\n const certificateIssues = certificateAnalysis.issues.length\n const signatureIssues = signatureAnalysis.issues.length\n\n return {\n certificateAnalysis,\n signatureAnalysis,\n summary: {\n totalIssues: certificateIssues + signatureIssues,\n certificateIssues,\n signatureIssues,\n },\n }\n}\n\n/**\n * Prints diagnostic results in a formatted way\n */\nexport function printDiagnostics(result: DiagnosticResult): void {\n console.log('\\n🔍 MyInvois Signature Diagnostics Report')\n console.log('='.repeat(60))\n\n // Certificate Analysis\n console.log('\\n📜 CERTIFICATE ANALYSIS')\n console.log('-'.repeat(30))\n\n console.log(` Issuer: ${result.certificateAnalysis.issuerName}`)\n console.log(` Subject: ${result.certificateAnalysis.subjectName}`)\n\n if (result.certificateAnalysis.organizationIdentifier) {\n console.log(\n ` Organization ID (TIN): ${result.certificateAnalysis.organizationIdentifier}`,\n )\n }\n\n if (result.certificateAnalysis.serialNumber) {\n console.log(` Serial Number: ${result.certificateAnalysis.serialNumber}`)\n }\n\n if (result.certificateAnalysis.issues.length > 0) {\n console.log('\\n 🚨 Certificate Issues:')\n result.certificateAnalysis.issues.forEach((issue, index) => {\n console.log(` ${index + 1}. ${issue}`)\n })\n }\n\n if (result.certificateAnalysis.recommendations.length > 0) {\n console.log('\\n 💡 Certificate Recommendations:')\n result.certificateAnalysis.recommendations.forEach((rec, index) => {\n console.log(` ${index + 1}. ${rec}`)\n })\n }\n\n // Signature Analysis\n console.log('\\n🔐 SIGNATURE ANALYSIS')\n console.log('-'.repeat(30))\n\n console.log(\n ` Document Digest: ${result.signatureAnalysis.documentDigest.substring(0, 32)}...`,\n )\n console.log(\n ` Certificate Digest: ${result.signatureAnalysis.certificateDigest.substring(0, 32)}...`,\n )\n console.log(\n ` Signed Properties Digest: ${result.signatureAnalysis.signedPropertiesDigest.substring(0, 32)}...`,\n )\n\n if (result.signatureAnalysis.issues.length > 0) {\n console.log('\\n 🚨 Signature Issues:')\n result.signatureAnalysis.issues.forEach((issue, index) => {\n console.log(` ${index + 1}. ${issue}`)\n })\n }\n\n if (result.signatureAnalysis.recommendations.length > 0) {\n console.log('\\n 💡 Signature Recommendations:')\n result.signatureAnalysis.recommendations.forEach((rec, index) => {\n console.log(` ${index + 1}. ${rec}`)\n })\n }\n\n // Summary\n console.log('\\n📊 SUMMARY')\n console.log('-'.repeat(30))\n console.log(` Total Issues Found: ${result.summary.totalIssues}`)\n console.log(` Certificate Issues: ${result.summary.certificateIssues}`)\n console.log(` Signature Issues: ${result.summary.signatureIssues}`)\n\n if (result.summary.totalIssues === 0) {\n console.log('\\n ✅ No issues detected in current analysis')\n console.log(' 🎉 Certificate and signature implementation appear valid')\n } else {\n console.log('\\n ⚠️ Issues detected - review recommendations above')\n\n // Check for specific portal errors\n const hasDS311 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS311'),\n )\n const hasDS312 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS312'),\n )\n const hasDS326 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS326'),\n )\n const hasDS329 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS329'),\n )\n const hasDS333 = result.signatureAnalysis.issues.some(issue =>\n issue.includes('DS333'),\n )\n\n console.log('\\n 🎯 MYINVOIS PORTAL ERROR ANALYSIS:')\n\n if (hasDS311) {\n console.log(\n ' ❌ DS311 - TIN mismatch between certificate and submitter',\n )\n }\n\n if (hasDS312) {\n console.log(\n ' ❌ DS312 - Registration number mismatch with certificate',\n )\n }\n\n if (hasDS326) {\n console.log(' ❌ DS326 - X509IssuerName format inconsistency')\n }\n\n if (hasDS329) {\n console.log(' ❌ DS329 - Certificate trust chain validation failure')\n }\n\n if (hasDS333) {\n console.log(' ❌ DS333 - Document signature validation failure')\n }\n\n if (result.summary.certificateIssues > 0) {\n console.log('\\n 🚨 PRIMARY ACTION REQUIRED:')\n console.log(' Certificate issues must be resolved first')\n console.log(\n ' Self-generated certificates cannot pass MyInvois validation',\n )\n }\n\n if (result.summary.signatureIssues > 0) {\n console.log('\\n ⚙️ SECONDARY ACTION:')\n console.log(' Review and optimize signature implementation')\n }\n\n console.log('\\n 📋 NEXT STEPS:')\n console.log(' 1. Address BLOCKING/CRITICAL issues first')\n console.log(' 2. Test with updated certificate/implementation')\n console.log(' 3. Re-run diagnostics to verify fixes')\n console.log(' 4. Submit test document to MyInvois portal')\n }\n\n console.log('\\n' + '='.repeat(60))\n}\n"],"mappings":";;;;;;;;;AAwCA,SAAS,iCACPA,gBAC2B;CAC3B,MAAMC,SAAmB,CAAE;CAC3B,MAAMC,kBAA4B,CAAE;AAEpC,KAAI;EACF,MAAM,OAAO,IAAI,eAAO,gBAAgB;EACxC,MAAM,WAAW,wCAAuB,eAAe;EAGvD,MAAM,qBAAqB,CAACC,OAAe;GACzC,MAAMC,SAAiC,CAAE;AACzC,MAAG,MAAM,KAAK,CAAC,QAAQ,UAAQ;IAC7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IAAI,oDAAoD;EACjE;AAED,UAAQ,IAAI,qBAAqB;AACjC,UAAQ,IAAI,iDAAiD;AAC7D,UAAQ,IAAI,uDAAuD;AACnE,UAAQ,IAAI,6CAA6C;AACzD,UAAQ,IAAI,kDAAkD;CAC/D;AAED,SAAQ,IAAI,OAAO,IAAI,OAAO,GAAG,CAAC;AACnC"}
1
+ {"version":3,"file":"index14.cjs","names":["certificatePem: string","issues: string[]","recommendations: string[]","dn: string","fields: Record<string, string>","invoices: InvoiceV1_1[]","str: string","result: DiagnosticResult"],"sources":["../src/utils/signature-diagnostics.ts"],"sourcesContent":["import crypto from 'crypto'\nimport type { InvoiceV1_1 } from '../types'\nimport {\n extractCertificateInfo,\n calculateDocumentDigest,\n calculateSignedPropertiesDigest,\n createSignedProperties,\n calculateCertificateDigest,\n} from './document'\n\nexport interface CertificateAnalysisResult {\n organizationIdentifier?: string\n serialNumber?: string\n issuerName: string\n subjectName: string\n issues: string[]\n recommendations: string[]\n}\n\nexport interface SignatureAnalysisResult {\n documentDigest: string\n certificateDigest: string\n signedPropertiesDigest: string\n issues: string[]\n recommendations: string[]\n}\n\nexport interface DiagnosticResult {\n certificateAnalysis: CertificateAnalysisResult\n signatureAnalysis: SignatureAnalysisResult\n summary: {\n totalIssues: number\n certificateIssues: number\n signatureIssues: number\n }\n}\n\n/**\n * Analyzes certificate for MyInvois compatibility issues\n */\nfunction analyzeCertificateForDiagnostics(\n certificatePem: string,\n): CertificateAnalysisResult {\n const issues: string[] = []\n const recommendations: string[] = []\n\n try {\n const cert = new crypto.X509Certificate(certificatePem)\n const certInfo = extractCertificateInfo(certificatePem)\n\n // Parse subject fields for MyInvois analysis\n const parseSubjectFields = (dn: string) => {\n const fields: Record<string, string> = {}\n dn.split('\\n').forEach(line => {\n const trimmed = line.trim()\n if (trimmed.includes('=')) {\n const [key, ...valueParts] = trimmed.split('=')\n if (key) {\n fields[key.trim()] = valueParts.join('=').trim()\n }\n }\n })\n return fields\n }\n\n const subjectFields = parseSubjectFields(cert.subject)\n const organizationIdentifier =\n subjectFields['organizationIdentifier'] || subjectFields['2.5.4.97']\n const serialNumber = subjectFields['serialNumber']\n\n // DS311 - TIN Mismatch Analysis\n if (!organizationIdentifier) {\n issues.push(\n 'DS311: Certificate missing organizationIdentifier field (TIN)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with organizationIdentifier matching your MyInvois TIN',\n )\n recommendations.push(\n 'Portal Error: \"Signer of invoice doesn\\'t match the submitter of document. TIN doesn\\'t match with the OI.\"',\n )\n } else {\n // Additional TIN format validation\n if (organizationIdentifier.length < 10) {\n issues.push(\n 'DS311: OrganizationIdentifier (TIN) appears too short - may cause submission rejection',\n )\n recommendations.push(\n 'Verify TIN format matches exactly what is registered in MyInvois',\n )\n }\n }\n\n // DS312 - Registration Number Analysis\n if (!serialNumber) {\n issues.push(\n 'DS312: Certificate missing serialNumber field (business registration)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with serialNumber matching your business registration',\n )\n recommendations.push(\n 'Portal Error: \"Submitter registration/identity number doesn\\'t match with the certificate SERIALNUMBER.\"',\n )\n }\n\n // DS329 - Certificate Trust Analysis\n if (cert.issuer === cert.subject) {\n issues.push(\n 'DS329: Self-signed certificate detected - will fail chain of trust validation',\n )\n recommendations.push(\n 'BLOCKING: Obtain certificate from MyInvois-approved CA:',\n )\n recommendations.push('• MSC Trustgate Sdn Bhd')\n recommendations.push('• DigiCert Sdn Bhd')\n recommendations.push('• Cybersign Asia Sdn Bhd')\n recommendations.push(\n 'Portal Error: \"Certificate is not valid according to the chain of trust validation or has been issued by an untrusted certificate authority.\"',\n )\n } else {\n // Check if issuer looks like a known CA\n const issuerName = cert.issuer.toLowerCase()\n const approvedCAs = ['msc trustgate', 'digicert', 'cybersign']\n const isFromApprovedCA = approvedCAs.some(ca => issuerName.includes(ca))\n\n if (!isFromApprovedCA) {\n issues.push('DS329: Certificate may not be from MyInvois-approved CA')\n recommendations.push(\n 'Verify certificate was issued by an approved CA for MyInvois',\n )\n }\n }\n\n // DS326 - Issuer Name Format Analysis (Enhanced)\n const rawIssuer = cert.issuer\n const normalizedIssuer = certInfo.issuerName\n\n // Check for issues in the NORMALIZED issuer (these are actual problems)\n const normalizedIssuerIssues = [\n {\n check: normalizedIssuer.includes('\\n'),\n issue: 'Normalized issuer still contains newlines',\n },\n {\n check: normalizedIssuer.includes(' '),\n issue: 'Normalized issuer contains double spaces',\n },\n {\n check: /=\\s+/.test(normalizedIssuer),\n issue: 'Normalized issuer has spaces after equals',\n },\n {\n check: /\\s+=/.test(normalizedIssuer),\n issue: 'Normalized issuer has spaces before equals',\n },\n {\n check: normalizedIssuer.includes('\\r'),\n issue: 'Normalized issuer contains carriage returns',\n },\n ]\n\n // Only report actual issues in the normalized version that will cause portal errors\n const hasActualFormatIssues = normalizedIssuerIssues.some(\n ({ check, issue }) => {\n if (check) {\n issues.push(`DS326: ${issue} - will cause X509IssuerName mismatch`)\n return true\n }\n return false\n },\n )\n\n // Check if raw issuer has issues but normalized version is OK (informational)\n const hasRawIssuesButNormalizedOk =\n rawIssuer.includes('\\n') && !normalizedIssuer.includes('\\n')\n\n if (hasActualFormatIssues) {\n recommendations.push(\n 'CRITICAL: Fix issuer name normalization in signature generation',\n )\n recommendations.push(\n 'Portal Error: \"Certificate X509IssuerName doesn\\'t match the X509IssuerName value provided in the signed properties section.\"',\n )\n recommendations.push(\n 'The normalization function is not properly formatting the issuer name',\n )\n recommendations.push(\n 'Debug: Check document.ts extractCertificateInfo() normalization logic',\n )\n } else if (hasRawIssuesButNormalizedOk) {\n // This is informational - normalization is working correctly\n console.log(\n 'ℹ️ Note: Raw certificate issuer has newlines but normalization is handling them correctly',\n )\n }\n\n // Additional certificate validity checks\n const now = new Date()\n const validFrom = new Date(cert.validFrom)\n const validTo = new Date(cert.validTo)\n\n if (now < validFrom) {\n issues.push('DS329: Certificate not yet valid (future start date)')\n recommendations.push('Wait until certificate validity period begins')\n }\n\n if (now > validTo) {\n issues.push('DS329: Certificate has expired')\n recommendations.push(\n 'BLOCKING: Renew certificate - expired certificates are rejected',\n )\n }\n\n // Check certificate key usage (if available)\n try {\n if (cert.keyUsage && !cert.keyUsage.includes('digital signature')) {\n issues.push('DS333: Certificate lacks digitalSignature key usage')\n recommendations.push(\n 'Generate new certificate with digitalSignature key usage enabled',\n )\n }\n } catch {\n // Key usage might not be available in all certificates\n console.log('Note: Could not check key usage extensions')\n }\n\n return {\n organizationIdentifier,\n serialNumber,\n issuerName: certInfo.issuerName,\n subjectName: certInfo.subjectName,\n issues,\n recommendations,\n }\n } catch (error) {\n issues.push(`Certificate parsing failed: ${error}`)\n recommendations.push('Verify certificate format and validity')\n\n return {\n issuerName: '',\n subjectName: '',\n issues,\n recommendations,\n }\n }\n}\n\n/**\n * Analyzes signature generation for potential issues\n */\nfunction analyzeSignatureForDiagnostics(\n invoices: InvoiceV1_1[],\n certificatePem: string,\n): SignatureAnalysisResult {\n const issues: string[] = []\n const recommendations: string[] = []\n\n try {\n // Step 1: Document digest\n const documentDigest = calculateDocumentDigest(invoices)\n\n // Step 2: Certificate digest\n const certificateDigest = calculateCertificateDigest(certificatePem)\n\n // Step 3: Extract certificate info\n const certInfo = extractCertificateInfo(certificatePem)\n const signingTime = new Date().toISOString()\n\n // Step 4: Create signed properties\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 5: Signed properties digest\n const signedPropertiesDigest =\n calculateSignedPropertiesDigest(signedProperties)\n\n // DS333 - Document Signature Validation\n if (documentDigest.length === 0) {\n issues.push('DS333: Document digest generation failed')\n recommendations.push(\n 'CRITICAL: Verify document serialization excludes UBLExtensions/Signature',\n )\n recommendations.push(\n 'Portal Error: \"Document signature value is not a valid signature of the document digest using the public key of the certificate provided.\"',\n )\n }\n\n if (certificateDigest.length === 0) {\n issues.push('DS333: Certificate digest generation failed')\n recommendations.push('CRITICAL: Verify certificate format and encoding')\n recommendations.push(\n 'Certificate must be properly base64 encoded without headers/footers',\n )\n }\n\n if (signedPropertiesDigest.length === 0) {\n issues.push('DS333: Signed properties digest generation failed')\n recommendations.push(\n 'CRITICAL: Verify signed properties structure and canonicalization',\n )\n recommendations.push(\n 'Check XML canonicalization (C14N) is applied correctly',\n )\n }\n\n // Additional DS333 checks\n try {\n const cert = new crypto.X509Certificate(certificatePem)\n\n // Verify the certificate has the required algorithms for MyInvois\n const publicKey = cert.publicKey\n const keyDetails = publicKey.asymmetricKeyDetails\n\n if (keyDetails) {\n // Check if key size is adequate for RSA (minimum 2048 bits)\n if (\n publicKey.asymmetricKeyType === 'rsa' &&\n keyDetails.modulusLength &&\n keyDetails.modulusLength < 2048\n ) {\n issues.push(\n 'DS333: RSA key size too small (minimum 2048 bits required)',\n )\n recommendations.push(\n 'CRITICAL: Generate new certificate with RSA 2048+ bits',\n )\n }\n\n // Check supported key types\n const supportedKeyTypes = ['rsa', 'ec']\n if (!supportedKeyTypes.includes(publicKey.asymmetricKeyType || '')) {\n issues.push(\n `DS333: Unsupported key type: ${publicKey.asymmetricKeyType}`,\n )\n recommendations.push(\n 'CRITICAL: Use RSA or EC key types for MyInvois compatibility',\n )\n }\n }\n\n // Test certificate format validity\n const certBuffer = Buffer.from(\n certificatePem.replace(/-----[^-]+-----/g, '').replace(/\\s/g, ''),\n 'base64',\n )\n if (certBuffer.length === 0) {\n issues.push('DS333: Certificate encoding appears invalid')\n recommendations.push(\n 'CRITICAL: Verify certificate is properly PEM encoded',\n )\n }\n } catch (error) {\n issues.push(`DS333: Certificate validation failed - ${error}`)\n recommendations.push(\n 'CRITICAL: Verify certificate format and structure are valid',\n )\n }\n\n // Validate digest formats (should be base64)\n const isValidBase64 = (str: string) => {\n try {\n return Buffer.from(str, 'base64').toString('base64') === str\n } catch {\n return false\n }\n }\n\n if (documentDigest && !isValidBase64(documentDigest)) {\n issues.push('DS333: Document digest is not valid base64 format')\n recommendations.push('Ensure digest is properly base64 encoded')\n }\n\n if (certificateDigest && !isValidBase64(certificateDigest)) {\n issues.push('DS333: Certificate digest is not valid base64 format')\n recommendations.push(\n 'Ensure certificate digest is properly base64 encoded',\n )\n }\n\n if (signedPropertiesDigest && !isValidBase64(signedPropertiesDigest)) {\n issues.push('DS333: Signed properties digest is not valid base64 format')\n recommendations.push(\n 'Ensure signed properties digest is properly base64 encoded',\n )\n }\n\n return {\n documentDigest,\n certificateDigest,\n signedPropertiesDigest,\n issues,\n recommendations,\n }\n } catch (error) {\n issues.push(`Signature analysis failed: ${error}`)\n recommendations.push('Review signature generation implementation')\n\n return {\n documentDigest: '',\n certificateDigest: '',\n signedPropertiesDigest: '',\n issues,\n recommendations,\n }\n }\n}\n\n/**\n * Comprehensive signature diagnostics\n */\nexport function diagnoseSignatureIssues(\n invoices: InvoiceV1_1[],\n certificatePem: string,\n): DiagnosticResult {\n const certificateAnalysis = analyzeCertificateForDiagnostics(certificatePem)\n const signatureAnalysis = analyzeSignatureForDiagnostics(\n invoices,\n certificatePem,\n )\n\n const certificateIssues = certificateAnalysis.issues.length\n const signatureIssues = signatureAnalysis.issues.length\n\n return {\n certificateAnalysis,\n signatureAnalysis,\n summary: {\n totalIssues: certificateIssues + signatureIssues,\n certificateIssues,\n signatureIssues,\n },\n }\n}\n\n/**\n * Prints diagnostic results in a formatted way\n */\nexport function printDiagnostics(result: DiagnosticResult): void {\n console.log('\\n🔍 MyInvois Signature Diagnostics Report')\n console.log('='.repeat(60))\n\n // Certificate Analysis\n console.log('\\n📜 CERTIFICATE ANALYSIS')\n console.log('-'.repeat(30))\n\n console.log(` Issuer: ${result.certificateAnalysis.issuerName}`)\n console.log(` Subject: ${result.certificateAnalysis.subjectName}`)\n\n if (result.certificateAnalysis.organizationIdentifier) {\n console.log(\n ` Organization ID (TIN): ${result.certificateAnalysis.organizationIdentifier}`,\n )\n }\n\n if (result.certificateAnalysis.serialNumber) {\n console.log(` Serial Number: ${result.certificateAnalysis.serialNumber}`)\n }\n\n if (result.certificateAnalysis.issues.length > 0) {\n console.log('\\n 🚨 Certificate Issues:')\n result.certificateAnalysis.issues.forEach((issue, index) => {\n console.log(` ${index + 1}. ${issue}`)\n })\n }\n\n if (result.certificateAnalysis.recommendations.length > 0) {\n console.log('\\n 💡 Certificate Recommendations:')\n result.certificateAnalysis.recommendations.forEach((rec, index) => {\n console.log(` ${index + 1}. ${rec}`)\n })\n }\n\n // Signature Analysis\n console.log('\\n🔐 SIGNATURE ANALYSIS')\n console.log('-'.repeat(30))\n\n console.log(\n ` Document Digest: ${result.signatureAnalysis.documentDigest.substring(0, 32)}...`,\n )\n console.log(\n ` Certificate Digest: ${result.signatureAnalysis.certificateDigest.substring(0, 32)}...`,\n )\n console.log(\n ` Signed Properties Digest: ${result.signatureAnalysis.signedPropertiesDigest.substring(0, 32)}...`,\n )\n\n if (result.signatureAnalysis.issues.length > 0) {\n console.log('\\n 🚨 Signature Issues:')\n result.signatureAnalysis.issues.forEach((issue, index) => {\n console.log(` ${index + 1}. ${issue}`)\n })\n }\n\n if (result.signatureAnalysis.recommendations.length > 0) {\n console.log('\\n 💡 Signature Recommendations:')\n result.signatureAnalysis.recommendations.forEach((rec, index) => {\n console.log(` ${index + 1}. ${rec}`)\n })\n }\n\n // Summary\n console.log('\\n📊 SUMMARY')\n console.log('-'.repeat(30))\n console.log(` Total Issues Found: ${result.summary.totalIssues}`)\n console.log(` Certificate Issues: ${result.summary.certificateIssues}`)\n console.log(` Signature Issues: ${result.summary.signatureIssues}`)\n\n if (result.summary.totalIssues === 0) {\n console.log('\\n ✅ No issues detected in current analysis')\n console.log(' 🎉 Certificate and signature implementation appear valid')\n } else {\n console.log('\\n ⚠️ Issues detected - review recommendations above')\n\n // Check for specific portal errors\n const hasDS311 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS311'),\n )\n const hasDS312 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS312'),\n )\n const hasDS326 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS326'),\n )\n const hasDS329 = result.certificateAnalysis.issues.some(issue =>\n issue.includes('DS329'),\n )\n const hasDS333 = result.signatureAnalysis.issues.some(issue =>\n issue.includes('DS333'),\n )\n\n console.log('\\n 🎯 MYINVOIS PORTAL ERROR ANALYSIS:')\n\n if (hasDS311) {\n console.log(\n ' ❌ DS311 - TIN mismatch between certificate and submitter',\n )\n }\n\n if (hasDS312) {\n console.log(\n ' ❌ DS312 - Registration number mismatch with certificate',\n )\n }\n\n if (hasDS326) {\n console.log(' ❌ DS326 - X509IssuerName format inconsistency')\n }\n\n if (hasDS329) {\n console.log(' ❌ DS329 - Certificate trust chain validation failure')\n }\n\n if (hasDS333) {\n console.log(' ❌ DS333 - Document signature validation failure')\n }\n\n if (result.summary.certificateIssues > 0) {\n console.log('\\n 🚨 PRIMARY ACTION REQUIRED:')\n console.log(' Certificate issues must be resolved first')\n console.log(\n ' Self-generated certificates cannot pass MyInvois validation',\n )\n }\n\n if (result.summary.signatureIssues > 0) {\n console.log('\\n ⚙️ SECONDARY ACTION:')\n console.log(' Review and optimize signature implementation')\n }\n\n console.log('\\n 📋 NEXT STEPS:')\n console.log(' 1. Address BLOCKING/CRITICAL issues first')\n console.log(' 2. Test with updated certificate/implementation')\n console.log(' 3. Re-run diagnostics to verify fixes')\n console.log(' 4. Submit test document to MyInvois portal')\n }\n\n console.log('\\n' + '='.repeat(60))\n}\n"],"mappings":";;;;;;;;;AAwCA,SAAS,iCACPA,gBAC2B;CAC3B,MAAMC,SAAmB,CAAE;CAC3B,MAAMC,kBAA4B,CAAE;AAEpC,KAAI;EACF,MAAM,OAAO,IAAI,eAAO,gBAAgB;EACxC,MAAM,WAAW,wCAAuB,eAAe;EAGvD,MAAM,qBAAqB,CAACC,OAAe;GACzC,MAAMC,SAAiC,CAAE;AACzC,MAAG,MAAM,KAAK,CAAC,QAAQ,UAAQ;IAC7B,MAAM,UAAU,KAAK,MAAM;AAC3B,QAAI,QAAQ,SAAS,IAAI,EAAE;KACzB,MAAM,CAAC,KAAK,GAAG,WAAW,GAAG,QAAQ,M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