@ripwords/myinvois-client 0.2.35 → 0.2.37
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.
- package/dist/api/documentManagement.d.ts +2 -2
- package/dist/api/documentSubmission.d.ts +3 -3
- package/dist/api/documentSubmission.js +2 -2
- package/dist/api/documentTypeManagement.d.ts +2 -2
- package/dist/api/notificationManagement.d.ts +2 -2
- package/dist/api/platformLogin.d.ts +3 -3
- package/dist/api/platformLogin.js +1 -1
- package/dist/api/taxpayerValidation.d.ts +2 -2
- package/dist/{apiQueue-BE3-DB1A.js → apiQueue-CfneHIgD.js} +53 -19
- package/dist/{apiQueue-DDXeQJDC.cjs → apiQueue-CiZxlntc.cjs} +54 -20
- package/dist/apiQueue-CiZxlntc.cjs.map +1 -0
- package/dist/{document-DWsGewNs.cjs → document-CCza2JPL.cjs} +30 -4
- package/dist/document-CCza2JPL.cjs.map +1 -0
- package/dist/{document-DI6hw1MO.js → document-DLFdGSK1.js} +29 -3
- package/dist/{documentSubmission-YwuM4ap1.cjs → documentSubmission-M4UlirJ7.cjs} +8 -7
- package/dist/documentSubmission-M4UlirJ7.cjs.map +1 -0
- package/dist/{documentSubmission-CgW1Cm0W.js → documentSubmission-ZAgXsd3X.js} +7 -6
- package/dist/{documents-4B5YOXeb.d.cts → documents-DCZ3Ffya.d.cts} +39 -1
- package/dist/{documents-ChNlyKB2.d.ts → documents-DzZA3NHj.d.ts} +38 -0
- package/dist/index.cjs +9 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +9 -6
- package/dist/index10.cjs +195 -4
- package/dist/index10.cjs.map +1 -0
- package/dist/index11.cjs +0 -22
- package/dist/index12.cjs +24 -2
- package/dist/{index20.cjs.map → index12.cjs.map} +1 -1
- package/dist/index13.cjs +0 -3
- package/dist/index14.cjs +0 -330
- package/dist/index15.cjs +25 -189
- package/dist/index15.cjs.map +1 -1
- package/dist/index16.cjs +16 -53
- package/dist/index16.cjs.map +1 -1
- package/dist/index17.cjs +0 -532
- package/dist/index18.cjs +25 -187
- package/dist/index18.cjs.map +1 -1
- package/dist/index19.cjs +24 -0
- package/dist/{index27.cjs.map → index19.cjs.map} +1 -1
- package/dist/index20.cjs +0 -25
- package/dist/index23.cjs +3 -28
- package/dist/index24.cjs +9 -21
- package/dist/index24.cjs.map +1 -1
- package/dist/index25.cjs +5 -0
- package/dist/index26.cjs +21 -33
- package/dist/index27.cjs +2 -23
- package/dist/index28.cjs +3 -0
- package/dist/index29.cjs +330 -0
- package/dist/{index14.cjs.map → index29.cjs.map} +1 -1
- package/dist/index3.cjs +2 -2
- package/dist/index30.cjs +193 -0
- package/dist/index30.cjs.map +1 -0
- package/dist/index6.cjs +1 -1
- package/dist/index62.cts.map +1 -1
- package/dist/index65.cts.map +1 -1
- package/dist/index67.cts.map +1 -1
- package/dist/index71.cts.map +1 -1
- package/dist/index8.cjs +61 -3
- package/dist/index8.cjs.map +1 -0
- package/dist/index9.cjs +528 -9
- package/dist/index9.cjs.map +1 -1
- package/dist/{platformLogin-CqI9OLYP.js → platformLogin-B6f18bB7.js} +2 -2
- package/dist/{platformLogin-Ch6hFKoU.cjs → platformLogin-BVTUzLjd.cjs} +3 -3
- package/dist/platformLogin-BVTUzLjd.cjs.map +1 -0
- package/dist/{taxpayer-C9VMf0iv.d.ts → taxpayer-DmHW0m7o.d.ts} +1 -1
- package/dist/{taxpayer-DubRo4qZ.d.cts → taxpayer-Pm90MrPj.d.cts} +2 -2
- package/dist/types/documents.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/taxpayer.d.ts +2 -2
- package/dist/utils/apiQueue.js +1 -1
- package/dist/utils/document.d.ts +6 -2
- package/dist/utils/document.js +1 -1
- package/dist/utils/signature-diagnostics.d.ts +2 -2
- package/dist/utils/signature-diagnostics.js +1 -1
- package/dist/utils/validation.d.ts +2 -2
- package/package.json +1 -1
- package/dist/apiQueue-DDXeQJDC.cjs.map +0 -1
- package/dist/document-DWsGewNs.cjs.map +0 -1
- package/dist/documentSubmission-YwuM4ap1.cjs.map +0 -1
- package/dist/index17.cjs.map +0 -1
- package/dist/index23.cjs.map +0 -1
- package/dist/index26.cjs.map +0 -1
- package/dist/platformLogin-Ch6hFKoU.cjs.map +0 -1
package/dist/index29.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=index29.cjs.map
|
|
@@ -1 +1 @@
|
|
|
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,EAA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AI,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":"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;IAC7B,MAAM,UAAU,KAAK,MAAM;AAC3B,QAAI,QAAQ,SAAS,IAAI,EAAE;KACzB,MAAM,CAAC,KAAK,GAAG,WAAW,GAAG,QAAQ,MAAM,IAAI;AAC/C,SAAI,IACF,QAAO,IAAI,MAAM,IAAI,WA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SAAQ,IAAI,OAAO,IAAI,OAAO,GAAG,CAAC;AACnC"}
|
package/dist/index3.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
require('./formatIdValue-i67o4kyD.cjs');
|
|
2
|
-
require('./document-
|
|
3
|
-
const require_documentSubmission = require('./documentSubmission-
|
|
2
|
+
require('./document-CCza2JPL.cjs');
|
|
3
|
+
const require_documentSubmission = require('./documentSubmission-M4UlirJ7.cjs');
|
|
4
4
|
|
|
5
5
|
exports.getSubmissionStatus = require_documentSubmission.getSubmissionStatus;
|
|
6
6
|
exports.performDocumentAction = require_documentSubmission.performDocumentAction;
|
package/dist/index30.cjs
CHANGED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/utils/validation.ts
|
|
3
|
+
/**
|
|
4
|
+
* Validates TIN format based on registration type
|
|
5
|
+
*/
|
|
6
|
+
const validateTIN = (tin, registrationType) => {
|
|
7
|
+
const errors = [];
|
|
8
|
+
if (!tin) {
|
|
9
|
+
errors.push({
|
|
10
|
+
field: "tin",
|
|
11
|
+
code: "TIN_REQUIRED",
|
|
12
|
+
message: "TIN is required",
|
|
13
|
+
severity: "error"
|
|
14
|
+
});
|
|
15
|
+
return errors;
|
|
16
|
+
}
|
|
17
|
+
if (registrationType === "BRN" && !tin.startsWith("C")) errors.push({
|
|
18
|
+
field: "tin",
|
|
19
|
+
code: "TIN_FORMAT_INVALID",
|
|
20
|
+
message: "Company TIN should start with \"C\" for BRN registration",
|
|
21
|
+
severity: "warning"
|
|
22
|
+
});
|
|
23
|
+
if (registrationType === "NRIC" && !tin.startsWith("IG")) errors.push({
|
|
24
|
+
field: "tin",
|
|
25
|
+
code: "TIN_FORMAT_INVALID",
|
|
26
|
+
message: "Individual TIN should start with \"IG\" for NRIC registration",
|
|
27
|
+
severity: "warning"
|
|
28
|
+
});
|
|
29
|
+
if (tin.length > 14) errors.push({
|
|
30
|
+
field: "tin",
|
|
31
|
+
code: "TIN_LENGTH_INVALID",
|
|
32
|
+
message: "TIN cannot exceed 14 characters",
|
|
33
|
+
severity: "error"
|
|
34
|
+
});
|
|
35
|
+
return errors;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Validates contact number format (E.164 standard)
|
|
39
|
+
*/
|
|
40
|
+
const validateContactNumber = (contactNumber) => {
|
|
41
|
+
const errors = [];
|
|
42
|
+
if (!contactNumber || contactNumber === "NA") return errors;
|
|
43
|
+
const e164Regex = /^\+[1-9]\d{1,14}$/;
|
|
44
|
+
if (!e164Regex.test(contactNumber)) errors.push({
|
|
45
|
+
field: "contactNumber",
|
|
46
|
+
code: "CONTACT_FORMAT_INVALID",
|
|
47
|
+
message: "Contact number must be in E.164 format (e.g., +60123456789)",
|
|
48
|
+
severity: "error"
|
|
49
|
+
});
|
|
50
|
+
if (contactNumber.length < 8) errors.push({
|
|
51
|
+
field: "contactNumber",
|
|
52
|
+
code: "CONTACT_LENGTH_INVALID",
|
|
53
|
+
message: "Contact number must be at least 8 characters",
|
|
54
|
+
severity: "error"
|
|
55
|
+
});
|
|
56
|
+
return errors;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Validates monetary amounts
|
|
60
|
+
*/
|
|
61
|
+
const validateMonetaryAmount = (amount, fieldName, maxDigits = 18, maxDecimals = 2) => {
|
|
62
|
+
const errors = [];
|
|
63
|
+
if (amount < 0) errors.push({
|
|
64
|
+
field: fieldName,
|
|
65
|
+
code: "AMOUNT_NEGATIVE",
|
|
66
|
+
message: `${fieldName} cannot be negative`,
|
|
67
|
+
severity: "error"
|
|
68
|
+
});
|
|
69
|
+
const amountStr = amount.toString();
|
|
70
|
+
const [integerPart, decimalPart] = amountStr.split(".");
|
|
71
|
+
if (integerPart && integerPart.length > maxDigits - maxDecimals) errors.push({
|
|
72
|
+
field: fieldName,
|
|
73
|
+
code: "AMOUNT_DIGITS_EXCEEDED",
|
|
74
|
+
message: `${fieldName} exceeds maximum ${maxDigits} digits`,
|
|
75
|
+
severity: "error"
|
|
76
|
+
});
|
|
77
|
+
if (decimalPart && decimalPart.length > maxDecimals) errors.push({
|
|
78
|
+
field: fieldName,
|
|
79
|
+
code: "AMOUNT_DECIMALS_EXCEEDED",
|
|
80
|
+
message: `${fieldName} exceeds maximum ${maxDecimals} decimal places`,
|
|
81
|
+
severity: "error"
|
|
82
|
+
});
|
|
83
|
+
return errors;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Validates line item tax calculation consistency for both fixed rate and percentage taxation
|
|
87
|
+
*/
|
|
88
|
+
const validateLineItemTax = (item, index) => {
|
|
89
|
+
const errors = [];
|
|
90
|
+
const tolerance = .01;
|
|
91
|
+
const hasFixedRate = item.taxPerUnitAmount !== void 0 && item.baseUnitMeasure !== void 0;
|
|
92
|
+
const hasPercentageRate = item.taxRate !== void 0;
|
|
93
|
+
if (!hasFixedRate && !hasPercentageRate) {
|
|
94
|
+
errors.push({
|
|
95
|
+
field: `lineItem[${index}]`,
|
|
96
|
+
code: "TAX_METHOD_MISSING",
|
|
97
|
+
message: `Line item ${index + 1} must specify either taxRate (for percentage) or taxPerUnitAmount + baseUnitMeasure (for fixed rate)`,
|
|
98
|
+
severity: "error"
|
|
99
|
+
});
|
|
100
|
+
return errors;
|
|
101
|
+
}
|
|
102
|
+
if (hasFixedRate && hasPercentageRate) errors.push({
|
|
103
|
+
field: `lineItem[${index}]`,
|
|
104
|
+
code: "TAX_METHOD_CONFLICT",
|
|
105
|
+
message: `Line item ${index + 1} cannot have both percentage and fixed rate tax methods`,
|
|
106
|
+
severity: "error"
|
|
107
|
+
});
|
|
108
|
+
if (hasFixedRate) {
|
|
109
|
+
if (item.baseUnitMeasureCode === void 0) errors.push({
|
|
110
|
+
field: `lineItem[${index}].baseUnitMeasureCode`,
|
|
111
|
+
code: "UNIT_CODE_MISSING",
|
|
112
|
+
message: `Line item ${index + 1} with fixed rate tax must specify baseUnitMeasureCode`,
|
|
113
|
+
severity: "error"
|
|
114
|
+
});
|
|
115
|
+
const expectedTaxAmount = item.taxPerUnitAmount * item.baseUnitMeasure;
|
|
116
|
+
if (Math.abs(item.taxAmount - expectedTaxAmount) > tolerance) errors.push({
|
|
117
|
+
field: `lineItem[${index}].taxAmount`,
|
|
118
|
+
code: "FIXED_TAX_CALCULATION_MISMATCH",
|
|
119
|
+
message: `Line item ${index + 1} tax amount (${item.taxAmount}) doesn't match fixed rate calculation (${item.taxPerUnitAmount} × ${item.baseUnitMeasure} = ${expectedTaxAmount})`,
|
|
120
|
+
severity: "error"
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (hasPercentageRate && !hasFixedRate) {
|
|
124
|
+
const expectedTaxAmount = item.totalTaxableAmountPerLine * item.taxRate / 100;
|
|
125
|
+
if (Math.abs(item.taxAmount - expectedTaxAmount) > tolerance) errors.push({
|
|
126
|
+
field: `lineItem[${index}].taxAmount`,
|
|
127
|
+
code: "PERCENTAGE_TAX_CALCULATION_MISMATCH",
|
|
128
|
+
message: `Line item ${index + 1} tax amount (${item.taxAmount}) doesn't match percentage calculation (${item.totalTaxableAmountPerLine} × ${item.taxRate}% = ${expectedTaxAmount})`,
|
|
129
|
+
severity: "error"
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return errors;
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Validates tax calculation consistency
|
|
136
|
+
*/
|
|
137
|
+
const validateTaxCalculations = (invoice) => {
|
|
138
|
+
const errors = [];
|
|
139
|
+
invoice.invoiceLineItems.forEach((item, index) => {
|
|
140
|
+
errors.push(...validateLineItemTax(item, index));
|
|
141
|
+
});
|
|
142
|
+
const expectedTaxExclusive = invoice.invoiceLineItems.reduce((sum, item) => sum + item.totalTaxableAmountPerLine, 0);
|
|
143
|
+
const expectedTaxAmount = invoice.invoiceLineItems.reduce((sum, item) => sum + item.taxAmount, 0);
|
|
144
|
+
const tolerance = .01;
|
|
145
|
+
if (Math.abs(invoice.legalMonetaryTotal.taxExclusiveAmount - expectedTaxExclusive) > tolerance) errors.push({
|
|
146
|
+
field: "legalMonetaryTotal.taxExclusiveAmount",
|
|
147
|
+
code: "TAX_EXCLUSIVE_MISMATCH",
|
|
148
|
+
message: `Tax exclusive amount (${invoice.legalMonetaryTotal.taxExclusiveAmount}) doesn't match sum of line items (${expectedTaxExclusive})`,
|
|
149
|
+
severity: "error"
|
|
150
|
+
});
|
|
151
|
+
if (Math.abs(invoice.taxTotal.taxAmount - expectedTaxAmount) > tolerance) errors.push({
|
|
152
|
+
field: "taxTotal.taxAmount",
|
|
153
|
+
code: "TAX_AMOUNT_MISMATCH",
|
|
154
|
+
message: `Tax amount (${invoice.taxTotal.taxAmount}) doesn't match sum of line item taxes (${expectedTaxAmount})`,
|
|
155
|
+
severity: "error"
|
|
156
|
+
});
|
|
157
|
+
return errors;
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Main validation function for complete invoice
|
|
161
|
+
*/
|
|
162
|
+
const validateInvoice = (invoice) => {
|
|
163
|
+
const allErrors = [];
|
|
164
|
+
allErrors.push(...validateTIN(invoice.supplier.tin, invoice.supplier.registrationType));
|
|
165
|
+
allErrors.push(...validateTIN(invoice.buyer.tin, invoice.buyer.registrationType));
|
|
166
|
+
allErrors.push(...validateContactNumber(invoice.supplier.contactNumber));
|
|
167
|
+
allErrors.push(...validateContactNumber(invoice.buyer.contactNumber));
|
|
168
|
+
allErrors.push(...validateMonetaryAmount(invoice.legalMonetaryTotal.taxExclusiveAmount, "taxExclusiveAmount"));
|
|
169
|
+
allErrors.push(...validateMonetaryAmount(invoice.legalMonetaryTotal.payableAmount, "payableAmount"));
|
|
170
|
+
allErrors.push(...validateMonetaryAmount(invoice.taxTotal.taxAmount, "taxAmount"));
|
|
171
|
+
invoice.invoiceLineItems.forEach((item, index) => {
|
|
172
|
+
allErrors.push(...validateMonetaryAmount(item.unitPrice, `lineItem[${index}].unitPrice`));
|
|
173
|
+
allErrors.push(...validateMonetaryAmount(item.taxAmount, `lineItem[${index}].taxAmount`));
|
|
174
|
+
allErrors.push(...validateMonetaryAmount(item.totalTaxableAmountPerLine, `lineItem[${index}].totalTaxableAmountPerLine`));
|
|
175
|
+
});
|
|
176
|
+
allErrors.push(...validateTaxCalculations(invoice));
|
|
177
|
+
const errors = allErrors.filter((e) => e.severity === "error");
|
|
178
|
+
const warnings = allErrors.filter((e) => e.severity === "warning");
|
|
179
|
+
return {
|
|
180
|
+
isValid: errors.length === 0,
|
|
181
|
+
errors,
|
|
182
|
+
warnings
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
//#endregion
|
|
187
|
+
exports.validateContactNumber = validateContactNumber;
|
|
188
|
+
exports.validateInvoice = validateInvoice;
|
|
189
|
+
exports.validateLineItemTax = validateLineItemTax;
|
|
190
|
+
exports.validateMonetaryAmount = validateMonetaryAmount;
|
|
191
|
+
exports.validateTIN = validateTIN;
|
|
192
|
+
exports.validateTaxCalculations = validateTaxCalculations;
|
|
193
|
+
//# sourceMappingURL=index30.cjs.map
|