@ripwords/myinvois-client 0.2.26 → 0.2.28
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 +2 -2
- 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 +2 -2
- package/dist/api/taxpayerValidation.d.ts +2 -2
- package/dist/{document-B03WWFMc.cjs → document-CNM7-o5x.cjs} +79 -30
- package/dist/document-CNM7-o5x.cjs.map +1 -0
- package/dist/{document-BAUDGfZU.js → document-nWFcUMsi.js} +78 -29
- package/dist/{documentSubmission-56VbFff3.cjs → documentSubmission-BE1En5JO.cjs} +2 -2
- package/dist/{documentSubmission-56VbFff3.cjs.map → documentSubmission-BE1En5JO.cjs.map} +1 -1
- package/dist/{documentSubmission-isM8tGm0.js → documentSubmission-CVwFwnDd.js} +1 -1
- package/dist/{documents-BWpJ0B3C.d.cts → documents-B4VA36Bj.d.cts} +2 -2
- package/dist/{documents-DRQ6_toX.d.ts → documents-BIGS59JL.d.ts} +1 -1
- package/dist/index.cjs +33 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +28 -2
- package/dist/index.js +33 -2
- package/dist/index26.cjs +1 -1
- package/dist/index29.cjs +1 -1
- package/dist/index3.cjs +2 -2
- package/dist/index67.cts.map +1 -1
- package/dist/index71.cts.map +1 -1
- package/dist/{taxpayer-DtyHXKwz.d.ts → taxpayer-YXsbpgpd.d.ts} +1 -1
- package/dist/{taxpayer-CApK7x_O.d.cts → taxpayer-iisM69iU.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/document.d.ts +7 -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 +3 -1
- package/dist/document-B03WWFMc.cjs.map +0 -1
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-
|
|
54
|
+
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-
|
|
54
|
+
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../formatIdValue-qTxJqj9o.js";
|
|
2
|
-
import "../document-
|
|
3
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-
|
|
2
|
+
import "../document-nWFcUMsi.js";
|
|
3
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-CVwFwnDd.js";
|
|
4
4
|
|
|
5
5
|
export { getSubmissionStatus, performDocumentAction, submitDocument };
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-
|
|
54
|
+
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import { NotificationResponse, NotificationSearchParams } from "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import "../utils-C4FoVKLq.js";
|
|
60
60
|
import { ClientCredentials } from "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { RegistrationType } from "../documents-
|
|
54
|
+
import { RegistrationType } from "../documents-BIGS59JL.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-
|
|
58
|
+
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-YXsbpgpd.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -257,6 +257,8 @@ const generateCleanUBLDocument = (invoices) => {
|
|
|
257
257
|
* Step 1: Transform the document for hashing or transmission
|
|
258
258
|
* Removes UBLExtensions and Signature, and minifies the JSON
|
|
259
259
|
* Returns the minified, cleaned JSON string
|
|
260
|
+
*
|
|
261
|
+
* FIXED: Use regex-based minification to match PowerShell script exactly
|
|
260
262
|
*/
|
|
261
263
|
const transformDocumentForHashing = (invoices) => {
|
|
262
264
|
const cleanDocument = generateCleanUBLDocument(invoices);
|
|
@@ -265,7 +267,12 @@ const transformDocumentForHashing = (invoices) => {
|
|
|
265
267
|
delete invoice.UBLExtensions;
|
|
266
268
|
delete invoice.Signature;
|
|
267
269
|
});
|
|
268
|
-
|
|
270
|
+
const jsonString = JSON.stringify(documentForTransform);
|
|
271
|
+
const minifiedJson = jsonString.replace(/("(?:\\.|[^"\\])*")|\s+/g, (match, quotedString) => {
|
|
272
|
+
if (quotedString) return quotedString;
|
|
273
|
+
else return "";
|
|
274
|
+
});
|
|
275
|
+
return minifiedJson;
|
|
269
276
|
};
|
|
270
277
|
/**
|
|
271
278
|
* Step 2: Calculate Document Digest
|
|
@@ -281,13 +288,22 @@ const calculateDocumentDigest = (invoices) => {
|
|
|
281
288
|
/**
|
|
282
289
|
* Step 4: Calculate Certificate Digest
|
|
283
290
|
* Enhanced to handle certificate content properly
|
|
291
|
+
* FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData
|
|
284
292
|
*/
|
|
285
293
|
const calculateCertificateDigest = (certificatePem) => {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
294
|
+
try {
|
|
295
|
+
const cert = new crypto.X509Certificate(certificatePem);
|
|
296
|
+
const rawCertificateData = cert.raw;
|
|
297
|
+
const hash = crypto.default.createHash("sha256");
|
|
298
|
+
hash.update(rawCertificateData);
|
|
299
|
+
return hash.digest("base64");
|
|
300
|
+
} catch (error) {
|
|
301
|
+
const certificateContent = certificatePem.replace(/-----BEGIN CERTIFICATE-----/g, "").replace(/-----END CERTIFICATE-----/g, "").replace(/\s+/g, "");
|
|
302
|
+
const certificateBinary = Buffer.from(certificateContent, "base64");
|
|
303
|
+
const hash = crypto.default.createHash("sha256");
|
|
304
|
+
hash.update(certificateBinary);
|
|
305
|
+
return hash.digest("base64");
|
|
306
|
+
}
|
|
291
307
|
};
|
|
292
308
|
/**
|
|
293
309
|
* Enhanced certificate info extraction with better error handling
|
|
@@ -297,18 +313,22 @@ const extractCertificateInfo = (certificatePem) => {
|
|
|
297
313
|
try {
|
|
298
314
|
const cert = new crypto.X509Certificate(certificatePem);
|
|
299
315
|
const serialNumberHex = cert.serialNumber;
|
|
300
|
-
const
|
|
301
|
-
|
|
316
|
+
const escapeXmlSpecialChars = (str) => {
|
|
317
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
318
|
+
};
|
|
319
|
+
const normalizeIssuerName = (issuer) => {
|
|
320
|
+
const parts = issuer.split(/\r?\n|,\s*/).map((part) => part.trim()).filter((part) => part.length > 0).reverse();
|
|
302
321
|
return parts.join(", ").replace(/\s*=\s*/g, "=");
|
|
303
322
|
};
|
|
304
323
|
const formatSerialNumber = (serialHex) => {
|
|
305
324
|
const decimal = BigInt("0x" + serialHex).toString();
|
|
306
325
|
return decimal;
|
|
307
326
|
};
|
|
327
|
+
const rawSubjectName = cert.subject;
|
|
308
328
|
return {
|
|
309
|
-
issuerName:
|
|
329
|
+
issuerName: escapeXmlSpecialChars(normalizeIssuerName(cert.issuer)),
|
|
310
330
|
serialNumber: formatSerialNumber(serialNumberHex),
|
|
311
|
-
subjectName:
|
|
331
|
+
subjectName: rawSubjectName
|
|
312
332
|
};
|
|
313
333
|
} catch (error) {
|
|
314
334
|
throw new Error(`Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -343,6 +363,7 @@ const createSignedProperties = (certificateDigest, signingTime, issuerName, seri
|
|
|
343
363
|
/**
|
|
344
364
|
* Step 6: Calculate SignedProperties Digest
|
|
345
365
|
* Calculates the digest over the correct structure for validator compliance.
|
|
366
|
+
* FIXED: Calculate digest from SignedProperties only (without Target wrapper)
|
|
346
367
|
*/
|
|
347
368
|
const calculateSignedPropertiesDigest = (signedProperties, useTargetWrapper = true) => {
|
|
348
369
|
let digestObj;
|
|
@@ -351,10 +372,13 @@ const calculateSignedPropertiesDigest = (signedProperties, useTargetWrapper = tr
|
|
|
351
372
|
SignedProperties: signedProperties.SignedProperties
|
|
352
373
|
};
|
|
353
374
|
else digestObj = signedProperties.SignedProperties;
|
|
354
|
-
const
|
|
355
|
-
const
|
|
375
|
+
const signedPropertiesString = JSON.stringify(digestObj);
|
|
376
|
+
const minifiedSignedProperties = signedPropertiesString.replace(/("(?:\\.|[^"\\])*")|\s+/g, (match, quotedString) => {
|
|
377
|
+
if (quotedString) return quotedString;
|
|
378
|
+
else return "";
|
|
379
|
+
});
|
|
356
380
|
const hash = crypto.default.createHash("sha256");
|
|
357
|
-
hash.update(
|
|
381
|
+
hash.update(minifiedSignedProperties, "utf8");
|
|
358
382
|
return hash.digest("base64");
|
|
359
383
|
};
|
|
360
384
|
/**
|
|
@@ -407,13 +431,12 @@ const createSignedInfoAndSign = (docDigest, propsDigest, privateKeyPem) => {
|
|
|
407
431
|
/**
|
|
408
432
|
* Signs the minified document string using the provided private key PEM
|
|
409
433
|
* Returns the signature as a base64 string
|
|
434
|
+
* FIXED: Match PowerShell script exactly - first compute hash, then sign the hash
|
|
410
435
|
*/
|
|
411
436
|
const signDocumentString = (documentString, privateKeyPem) => {
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
});
|
|
416
|
-
return signature.toString("base64");
|
|
437
|
+
const signer = crypto.default.createSign("RSA-SHA256");
|
|
438
|
+
signer.update(documentString, "utf8");
|
|
439
|
+
return signer.sign(privateKeyPem, "base64");
|
|
417
440
|
};
|
|
418
441
|
/**
|
|
419
442
|
* Complete document generation with signatures
|
|
@@ -424,22 +447,45 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
424
447
|
const docDigest = calculateDocumentDigest(invoices);
|
|
425
448
|
const documentString = transformDocumentForHashing(invoices);
|
|
426
449
|
const docSignature = signDocumentString(documentString, signingCredentials.privateKeyPem);
|
|
427
|
-
const
|
|
450
|
+
const now = /* @__PURE__ */ new Date();
|
|
451
|
+
const signingTime = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0") + "T" + String(now.getHours()).padStart(2, "0") + ":" + String(now.getMinutes()).padStart(2, "0") + ":" + String(now.getSeconds()).padStart(2, "0") + "Z";
|
|
428
452
|
const certInfo = extractCertificateInfo(signingCredentials.certificatePem);
|
|
429
453
|
const certificateDigest = calculateCertificateDigest(signingCredentials.certificatePem);
|
|
430
454
|
const signedProperties = createSignedProperties(certificateDigest, signingTime, certInfo.issuerName, certInfo.serialNumber);
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
455
|
+
const propsDigest = calculateSignedPropertiesDigest(signedProperties);
|
|
456
|
+
const signedInfo = {
|
|
457
|
+
CanonicalizationMethod: [{
|
|
458
|
+
_: "",
|
|
459
|
+
Algorithm: "http://www.w3.org/2006/12/xml-c14n11"
|
|
460
|
+
}],
|
|
461
|
+
SignatureMethod: [{
|
|
462
|
+
_: "",
|
|
463
|
+
Algorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
|
|
464
|
+
}],
|
|
465
|
+
Reference: [{
|
|
466
|
+
Id: "id-doc-signed-data",
|
|
467
|
+
Type: "",
|
|
468
|
+
URI: "",
|
|
469
|
+
DigestMethod: [{
|
|
470
|
+
_: "",
|
|
471
|
+
Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256"
|
|
472
|
+
}],
|
|
473
|
+
DigestValue: [{ _: docDigest }]
|
|
474
|
+
}, {
|
|
475
|
+
Id: "id-xades-signed-props",
|
|
476
|
+
Type: "http://uri.etsi.org/01903/v1.3.2#SignedProperties",
|
|
477
|
+
URI: "#id-xades-signed-props",
|
|
478
|
+
DigestMethod: [{
|
|
479
|
+
_: "",
|
|
480
|
+
Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256"
|
|
481
|
+
}],
|
|
482
|
+
DigestValue: [{ _: propsDigest }]
|
|
483
|
+
}]
|
|
434
484
|
};
|
|
435
|
-
const
|
|
436
|
-
const
|
|
437
|
-
const propsDigest = crypto.default.createHash("sha256").update(signedPropertiesString, "utf8").digest("base64");
|
|
438
|
-
const { signedInfo } = createSignedInfoAndSign(docDigest, propsDigest, signingCredentials.privateKeyPem);
|
|
439
|
-
const certificate = signingCredentials.certificatePem.replace(/-----BEGIN CERTIFICATE-----/g, "").replace(/-----END CERTIFICATE-----/g, "").replace(/\s+/g, "");
|
|
485
|
+
const cert = new crypto.X509Certificate(signingCredentials.certificatePem);
|
|
486
|
+
const certificate = cert.raw.toString("base64");
|
|
440
487
|
const signedInvoices = invoices.map((invoice) => {
|
|
441
488
|
const cleanInvoice = generateCleanInvoiceObject(invoice);
|
|
442
|
-
const parsedCanonicalSignedProps = JSON.parse(signedPropertiesString);
|
|
443
489
|
return {
|
|
444
490
|
...cleanInvoice,
|
|
445
491
|
UBLExtensions: [{ UBLExtension: [{
|
|
@@ -449,7 +495,10 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
449
495
|
ReferencedSignatureID: [{ _: "urn:oasis:names:specification:ubl:signature:Invoice" }],
|
|
450
496
|
Signature: [{
|
|
451
497
|
Id: "signature",
|
|
452
|
-
Object: [{ QualifyingProperties: [
|
|
498
|
+
Object: [{ QualifyingProperties: [{
|
|
499
|
+
Target: "signature",
|
|
500
|
+
SignedProperties: signedProperties.SignedProperties
|
|
501
|
+
}] }],
|
|
453
502
|
KeyInfo: [{ X509Data: [{
|
|
454
503
|
X509Certificate: [{ _: certificate }],
|
|
455
504
|
X509SubjectName: [{ _: certInfo.subjectName }],
|
|
@@ -649,4 +698,4 @@ Object.defineProperty(exports, 'transformDocumentForHashing', {
|
|
|
649
698
|
return transformDocumentForHashing;
|
|
650
699
|
}
|
|
651
700
|
});
|
|
652
|
-
//# sourceMappingURL=document-
|
|
701
|
+
//# sourceMappingURL=document-CNM7-o5x.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-CNM7-o5x.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: InvoiceSubmission","certificatePem: string","X509Certificate","str: string","issuer: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","useTargetWrapper: boolean","digestObj: unknown","docDigest: string","propsDigest: string","privateKeyPem: string","signedInfo: SignedInfoObject","documentString: string","signingCredentials: SigningCredentials","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}","lineItems: InvoiceLineItem[]"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n AllDocumentsV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n UnitTypeCode,\n InvoiceLineItem,\n} from '../types'\nimport type { ClassificationCode } from '../types'\nimport type { TaxTypeCode } from '../types'\nimport { formatIdValue } from './formatIdValue'\n\n/**\n * MyInvois v1.1 Document Generation and Signing Utilities\n * Strictly follows: https://sdk.myinvois.hasil.gov.my/documents/invoice-v1-1\n * JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/\n */\n\n/**\n * Determines if a line item uses fixed rate taxation\n */\nexport const isFixedRateTax = (item: InvoiceLineItem): boolean => {\n return (\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n )\n}\n\n/**\n * Determines if a line item uses percentage taxation\n */\nexport const isPercentageTax = (item: InvoiceLineItem): boolean => {\n return item.taxRate !== undefined && !isFixedRateTax(item)\n}\n\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport const calculateExpectedTaxAmount = (item: InvoiceLineItem): number => {\n if (isFixedRateTax(item)) {\n return item.taxPerUnitAmount! * item.baseUnitMeasure!\n } else if (isPercentageTax(item)) {\n return (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n }\n return 0\n}\n\n/**\n * Extracts the line-item array from any document variant\n */\nconst getLineItems = (doc: AllDocumentsV1_1): InvoiceLineItem[] => {\n if ('invoiceLineItems' in doc) return doc.invoiceLineItems\n if ('creditNoteLineItems' in doc) return doc.creditNoteLineItems\n if ('debitNoteLineItems' in doc) return doc.debitNoteLineItems\n if ('refundNoteLineItems' in doc) return doc.refundNoteLineItems\n if ('selfBilledCreditNoteLineItems' in doc)\n return doc.selfBilledCreditNoteLineItems\n if ('selfBilledRefundNoteLineItems' in doc)\n return doc.selfBilledRefundNoteLineItems\n // Fallback (should never happen with exhaustive types)\n return []\n}\n\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport function sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys)\n }\n\n const sortedObj: Record<string, unknown> = {}\n const keys = Object.keys(obj as Record<string, unknown>).sort()\n\n for (const key of keys) {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key])\n }\n\n return sortedObj\n}\n\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport const canonicalizeJSON = (obj: unknown): string => {\n const sortedObj = sortObjectKeys(obj)\n // Use compact JSON with no extra whitespace\n return JSON.stringify(sortedObj, null, 0)\n}\n\n/**\n * Generates a clean invoice object following MyInvois v1.1 specification exactly\n * This is the base invoice structure WITHOUT signature elements (for hash calculation)\n *\n * Key requirements from working documents:\n * - All mandatory fields must be present\n * - Many optional fields must be present even if empty\n * - Specific field ordering and structure\n * - Correct listID values (e.g., \"3166-1\" not \"ISO3166-1\")\n */\nexport const generateCleanInvoiceObject = (\n invoice: AllDocumentsV1_1,\n): InvoiceSubmission => {\n const lineItems = getLineItems(invoice)\n return {\n // === MANDATORY CORE FIELDS ===\n ID: [{ _: invoice.eInvoiceCodeOrNumber }],\n IssueDate: [{ _: invoice.eInvoiceDate }],\n IssueTime: [{ _: invoice.eInvoiceTime }],\n InvoiceTypeCode: [\n {\n _: invoice.eInvoiceTypeCode,\n listVersionID: invoice.eInvoiceVersion || '1.1',\n },\n ],\n DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],\n\n // === BILLING REFERENCE (only for credit/debit/refund notes) ===\n ...('originalEInvoiceReferenceNumber' in invoice &&\n 'originalEInvoiceInternalId' in invoice &&\n invoice.originalEInvoiceReferenceNumber\n ? {\n BillingReference: [\n {\n InvoiceDocumentReference: [\n {\n UUID: [\n {\n _: invoice.originalEInvoiceReferenceNumber,\n },\n ],\n ID: [\n {\n _: invoice.originalEInvoiceInternalId,\n },\n ],\n },\n ],\n },\n ],\n }\n : {}),\n\n // === SUPPLIER PARTY (AccountingSupplierParty) ===\n AccountingSupplierParty: [\n {\n Party: [\n {\n // Industry Classification - required field\n IndustryClassificationCode: [\n {\n _: invoice.supplier.industryClassificationCode,\n name: invoice.supplier.industryClassificationDescription,\n },\n ],\n\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.supplier.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.supplier.registrationNumber),\n schemeID: invoice.supplier.registrationType || 'NRIC',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.supplier.address.cityName }],\n CountrySubentityCode: [{ _: invoice.supplier.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.supplier.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.supplier.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.supplier.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.supplier.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === BUYER PARTY (AccountingCustomerParty) ===\n AccountingCustomerParty: [\n {\n Party: [\n {\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.buyer.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.buyer.registrationNumber),\n schemeID: invoice.buyer.registrationType || 'NRIC',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.sstRegistrationNumber || 'NA',\n schemeID: 'SST',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.buyer.address.cityName }],\n CountrySubentityCode: [{ _: invoice.buyer.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.buyer.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.buyer.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.buyer.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.buyer.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === TAX TOTAL ===\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n // Generate basic tax subtotal from invoice line items\n {\n TaxableAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxCategory: [\n {\n ID: [{ _: lineItems[0]?.taxType || '01' }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // === LEGAL MONETARY TOTAL ===\n LegalMonetaryTotal: [\n {\n LineExtensionAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxExclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxInclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxInclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableAmount: [\n {\n _: invoice.legalMonetaryTotal.payableAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // === INVOICE LINES ===\n InvoiceLine: lineItems.map((item, index) => ({\n ID: [{ _: (index + 1).toString() }],\n\n // Item Information\n Item: [\n {\n CommodityClassification: [\n {\n ItemClassificationCode: [\n {\n _: item.itemClassificationCode,\n listID: 'CLASS',\n },\n ],\n },\n ],\n Description: [{ _: item.itemDescription }],\n },\n ],\n\n ItemPriceExtension: [\n {\n Amount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n LineExtensionAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n\n // Price Information\n Price: [\n {\n PriceAmount: [\n {\n _: item.unitPrice,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // Tax Information for line\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n {\n TaxableAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n // Conditional tax fields based on taxation type\n ...(item.taxPerUnitAmount !== undefined &&\n item.baseUnitMeasure !== undefined\n ? {\n // Fixed Rate Taxation\n PerUnitAmount: [\n {\n _: item.taxPerUnitAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n BaseUnitMeasure: [\n {\n _: item.baseUnitMeasure,\n unitCode: item.baseUnitMeasureCode || 'C62',\n },\n ],\n }\n : item.taxRate !== undefined\n ? {\n // Percentage Taxation\n Percent: [{ _: item.taxRate }],\n }\n : {}),\n TaxCategory: [\n {\n ID: [{ _: item.taxType }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })),\n\n // === TAX EXCHANGE RATE (mandatory where applicable) ===\n TaxExchangeRate: invoice.currencyExchangeRate\n ? [\n {\n SourceCurrencyCode: [\n {\n _: invoice.invoiceCurrencyCode,\n },\n ],\n TargetCurrencyCode: [\n {\n _: 'MYR',\n },\n ],\n CalculationRate: [\n {\n _: invoice.currencyExchangeRate,\n },\n ],\n },\n ]\n : undefined,\n }\n}\n\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport const generateCleanUBLDocument = (\n invoices: AllDocumentsV1_1[],\n): UBLDocument => {\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: invoices.map(generateCleanInvoiceObject),\n }\n}\n\n/**\n * Step 1: Transform the document for hashing or transmission\n * Removes UBLExtensions and Signature, and minifies the JSON\n * Returns the minified, cleaned JSON string\n *\n * FIXED: Use regex-based minification to match PowerShell script exactly\n */\nexport const transformDocumentForHashing = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // Deep clone to avoid mutating input\n const documentForTransform = JSON.parse(JSON.stringify(cleanDocument))\n if (\n documentForTransform.Invoice &&\n Array.isArray(documentForTransform.Invoice)\n ) {\n documentForTransform.Invoice.forEach((invoice: InvoiceSubmission) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to JSON string first\n const jsonString = JSON.stringify(documentForTransform)\n\n // Apply the exact same regex-based minification as PowerShell script\n // This regex preserves whitespace within quoted strings but removes all other whitespace\n const minifiedJson = jsonString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n return minifiedJson\n}\n\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport const calculateDocumentDigest = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Use the transformation function to get the minified, cleaned JSON string\n const documentString = transformDocumentForHashing(invoices)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(documentString, 'utf8')\n\n // Return as Base64 (DocDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n * FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n try {\n // Create X509Certificate object to get raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(certificatePem)\n\n // Get the raw certificate data (DER-encoded, like PowerShell $cert.RawData)\n const rawCertificateData = cert.raw\n\n // Calculate SHA-256 hash of raw certificate data (like PowerShell $sha256.ComputeHash($cert.RawData))\n const hash = crypto.createHash('sha256')\n hash.update(rawCertificateData)\n\n // Return as Base64 (like PowerShell [Convert]::ToBase64String($certHash))\n return hash.digest('base64')\n } catch (error) {\n // Fallback to the previous method if X509Certificate fails\n const certificateContent = certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '') // Remove all whitespace\n\n // Convert Base64 to binary\n const certificateBinary = Buffer.from(certificateContent, 'base64')\n\n // Calculate SHA-256 hash of binary content\n const hash = crypto.createHash('sha256')\n hash.update(certificateBinary)\n\n // Return as Base64\n return hash.digest('base64')\n }\n}\n\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport const extractCertificateInfo = (\n certificatePem: string,\n): {\n issuerName: string\n serialNumber: string\n subjectName: string\n} => {\n try {\n const cert = new X509Certificate(certificatePem)\n\n // Extract serial number and convert to decimal string\n const serialNumberHex = cert.serialNumber\n\n // FIXED: Use raw issuer name like PowerShell $cert.IssuerName.Name\n // Apply XML escaping to match PowerShell [System.Security.SecurityElement]::Escape()\n const escapeXmlSpecialChars = (str: string): string => {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n\n // FIXED: Normalize issuer name to match MyInvois expectations\n // The issuer name should be in the format: \"CN=Trial LHDNM Sub CA V1, OU=Terms of use at http://www.testcertcomp.com.my, O=LHDNM, C=MY\"\n const normalizeIssuerName = (issuer: string): string => {\n // Node returns issuer DN in reverse RDN order (C, O, ... , CN).\n // The MyInvois validator expects forward order (CN first).\n // 1. Break DN into components separated by newline or commas.\n // 2. Reverse to get CN → ... → C ordering.\n // 3. Join with \", \" and ensure single '=' spacing.\n const parts = issuer\n .split(/\\r?\\n|,\\s*/)\n .map(part => part.trim())\n .filter(part => part.length > 0)\n .reverse()\n return parts.join(', ').replace(/\\s*=\\s*/g, '=')\n }\n\n // Enhanced serial number formatting\n const formatSerialNumber = (serialHex: string): string => {\n // Convert hex to decimal and ensure it's a string\n const decimal = BigInt('0x' + serialHex).toString()\n return decimal\n }\n\n // FIXED: Use raw subject name without normalization to match PowerShell $cert.SubjectName.Name\n // The subject name should be in the format shown in the specification\n const rawSubjectName = cert.subject\n\n return {\n issuerName: escapeXmlSpecialChars(normalizeIssuerName(cert.issuer)),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: rawSubjectName, // Use raw subject name like PowerShell\n }\n } catch (error: unknown) {\n throw new Error(\n `Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Step 5: Create SignedProperties with enhanced structure\n * FIXED: Simplified structure to match MyInvois expectations (DS320)\n * Following MyInvois JSON signature specification exactly\n */\nexport const createSignedProperties = (\n certificateDigest: string,\n signingTime: string,\n issuerName: string,\n serialNumber: string,\n): SignedPropertiesObject => {\n return {\n SignedProperties: [\n {\n Id: 'id-xades-signed-props',\n SignedSignatureProperties: [\n {\n SigningTime: [{ _: signingTime }],\n SigningCertificate: [\n {\n Cert: [\n {\n CertDigest: [\n {\n DigestMethod: [\n {\n _: '',\n Algorithm:\n 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: certificateDigest }],\n },\n ],\n IssuerSerial: [\n {\n X509IssuerName: [{ _: issuerName }],\n X509SerialNumber: [{ _: serialNumber }],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Step 6: Calculate SignedProperties Digest\n * Calculates the digest over the correct structure for validator compliance.\n * FIXED: Calculate digest from SignedProperties only (without Target wrapper)\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n useTargetWrapper: boolean = true, // Changed to true - validator calculates digest from embedded structure with Target wrapper\n): string => {\n let digestObj: unknown\n if (useTargetWrapper) {\n digestObj = {\n Target: 'signature',\n SignedProperties: signedProperties.SignedProperties,\n }\n } else {\n digestObj = signedProperties.SignedProperties\n }\n\n // FIXED: Don't sort object keys - use exact structure as embedded\n // The validator calculates digest from the exact embedded structure\n const signedPropertiesString = JSON.stringify(digestObj)\n\n // Apply the same regex-based minification as the document transformation\n const minifiedSignedProperties = signedPropertiesString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n const hash = crypto.createHash('sha256')\n hash.update(minifiedSignedProperties, 'utf8')\n return hash.digest('base64')\n}\n\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport const createSignedInfoAndSign = (\n docDigest: string,\n propsDigest: string,\n privateKeyPem: string,\n): { signedInfo: SignedInfoObject; signatureValue: string } => {\n // Create SignedInfo structure following specification exactly\n const signedInfo: SignedInfoObject = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // Serialize the SignedInfo exactly as it will be embedded (no reordering)\n const signedInfoRaw = JSON.stringify(signedInfo)\n\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoRaw, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n // Reuse the original object so ordering is preserved\n return { signedInfo, signatureValue }\n } catch (error) {\n throw new Error(\n `Signature generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Signs the minified document string using the provided private key PEM\n * Returns the signature as a base64 string\n * FIXED: Match PowerShell script exactly - first compute hash, then sign the hash\n */\nexport const signDocumentString = (\n documentString: string,\n privateKeyPem: string,\n): string => {\n // Create signer with RSA-SHA256 (matches PowerShell RSAPKCS1SignatureFormatter)\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(documentString, 'utf8')\n return signer.sign(privateKeyPem, 'base64')\n}\n\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport const generateCompleteDocument = (\n invoices: AllDocumentsV1_1[],\n signingCredentials: SigningCredentials,\n): CompleteInvoice => {\n try {\n // Step 1: Generate clean document (done in calculateDocumentDigest)\n // Step 2: Calculate document digest\n const docDigest = calculateDocumentDigest(invoices)\n\n // Get the minified, cleaned JSON string for signing\n const documentString = transformDocumentForHashing(invoices)\n\n // Step 3: Sign the minified document string (not the digest)\n const docSignature = signDocumentString(\n documentString,\n signingCredentials.privateKeyPem,\n )\n\n // Generate signing time in proper ISO format matching PowerShell exactly\n // PowerShell: Get-Date -Format \"yyyy-MM-ddTHH:mm:ssZ\"\n const now = new Date()\n const signingTime =\n now.getFullYear() +\n '-' +\n String(now.getMonth() + 1).padStart(2, '0') +\n '-' +\n String(now.getDate()).padStart(2, '0') +\n 'T' +\n String(now.getHours()).padStart(2, '0') +\n ':' +\n String(now.getMinutes()).padStart(2, '0') +\n ':' +\n String(now.getSeconds()).padStart(2, '0') +\n 'Z'\n\n // Extract certificate information (enhanced)\n const certInfo = extractCertificateInfo(signingCredentials.certificatePem)\n\n // Step 4: Calculate certificate digest\n const certificateDigest = calculateCertificateDigest(\n signingCredentials.certificatePem,\n )\n\n // Step 5: Create SignedProperties using extracted cert info\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 6: Calculate SignedProperties digest using the dedicated function\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Create simple SignedInfo structure (matching PowerShell approach)\n const signedInfo: SignedInfoObject = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // Extract certificate content using raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(signingCredentials.certificatePem)\n const certificate = cert.raw.toString('base64')\n\n // Step 7: Create final signed document\n const signedInvoices = invoices.map(invoice => {\n const cleanInvoice = generateCleanInvoiceObject(invoice)\n\n return {\n ...cleanInvoice,\n\n // Add UBLExtensions with complete signature structure\n UBLExtensions: [\n {\n UBLExtension: [\n {\n ExtensionURI: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n ExtensionContent: [\n {\n UBLDocumentSignatures: [\n {\n SignatureInformation: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:1',\n },\n ],\n ReferencedSignatureID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n Signature: [\n {\n Id: 'signature',\n Object: [\n {\n QualifyingProperties: [\n {\n Target: 'signature',\n SignedProperties:\n signedProperties.SignedProperties,\n },\n ],\n },\n ],\n KeyInfo: [\n {\n X509Data: [\n {\n X509Certificate: [{ _: certificate }],\n X509SubjectName: [\n { _: certInfo.subjectName },\n ],\n X509IssuerSerial: [\n {\n X509IssuerName: [\n {\n _: certInfo.issuerName,\n },\n ],\n X509SerialNumber: [\n {\n _: certInfo.serialNumber,\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n SignatureValue: [{ _: docSignature }],\n SignedInfo: [signedInfo],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // Add simple Signature reference\n Signature: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n SignatureMethod: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n },\n ],\n }\n })\n\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: signedInvoices,\n }\n } catch (error) {\n throw new Error(\n `Document generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport const createPercentageTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = (totalTaxableAmount * params.taxRate) / 100\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxRate: params.taxRate,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport const createFixedRateTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxPerUnitAmount: params.taxPerUnitAmount,\n baseUnitMeasure: params.baseUnitMeasure,\n baseUnitMeasureCode: params.baseUnitMeasureCode,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Calculates invoice totals from line items\n */\nexport const calculateInvoiceTotals = (\n lineItems: InvoiceLineItem[],\n): {\n legalMonetaryTotal: {\n taxExclusiveAmount: number\n taxInclusiveAmount: number\n payableAmount: number\n }\n taxTotal: {\n taxAmount: number\n }\n} => {\n const taxExclusiveAmount = lineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const totalTaxAmount = lineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount\n\n return {\n legalMonetaryTotal: {\n taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,\n taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,\n payableAmount: Math.round(taxInclusiveAmount * 100) / 100,\n },\n taxTotal: {\n taxAmount: Math.round(totalTaxAmount * 100) / 100,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,MAAa,iBAAiB,CAACA,SAAmC;AAChE,QACE,KAAK,+BAAkC,KAAK;AAE/C;;;;AAKD,MAAa,kBAAkB,CAACA,SAAmC;AACjE,QAAO,KAAK,uBAA0B,eAAe,KAAK;AAC3D;;;;AAKD,MAAa,6BAA6B,CAACA,SAAkC;AAC3E,KAAI,eAAe,KAAK,CACtB,QAAO,KAAK,mBAAoB,KAAK;UAC5B,gBAAgB,KAAK,CAC9B,QAAQ,KAAK,4BAA4B,KAAK,UAAY;AAE5D,QAAO;AACR;;;;AAKD,MAAM,eAAe,CAACC,QAA6C;AACjE,KAAI,sBAAsB,IAAK,QAAO,IAAI;AAC1C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,wBAAwB,IAAK,QAAO,IAAI;AAC5C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,mCAAmC,IACrC,QAAO,IAAI;AACb,KAAI,mCAAmC,IACrC,QAAO,IAAI;AAEb,QAAO,CAAE;AACV;;;;AAKD,SAAgB,eAAeC,KAAuB;AACpD,KAAI,QAAQ,eAAe,QAAQ,SACjC,QAAO;AAGT,KAAI,MAAM,QAAQ,IAAI,CACpB,QAAO,IAAI,IAAI,eAAe;CAGhC,MAAMC,YAAqC,CAAE;CAC7C,MAAM,OAAO,OAAO,KAAK,IAA+B,CAAC,MAAM;AAE/D,MAAK,MAAM,OAAO,KAChB,WAAU,OAAO,eAAgB,IAAgC,KAAK;AAGxE,QAAO;AACR;;;;;AAMD,MAAa,mBAAmB,CAACD,QAAyB;CACxD,MAAM,YAAY,eAAe,IAAI;AAErC,QAAO,KAAK,UAAU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CAC1C;AACF;;;;AAKD,MAAa,6BAA6B,CAACC,WAUpB;CACrB,MAAM,WAAW,OAAO,YAAY;CACpC,MAAM,qBACJ,OAAO,6BAA6B,OAAO,YAAY;CACzD,MAAM,YAAY,OAAO,mBAAmB,OAAO;AAEnD,QAAO;EACL,wBAAwB,OAAO;EAC/B,iBAAiB,OAAO;EACxB,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,kBAAkB,OAAO;EACzB,iBAAiB,OAAO;EACxB,qBAAqB,OAAO;EAC5B,WAAW,KAAK,MAAM,YAAY,IAAI,GAAG;EACzC,2BAA2B;EAC3B,oBAAoB,qBAAqB;CAC1C;AACF;;;;AAKD,MAAa,yBAAyB,CACpCC,cAUG;CACH,MAAM,qBAAqB,UAAU,OACnC,CAAC,KAAK,SAAS,MAAM,KAAK,2BAC1B,EACD;CACD,MAAM,iBAAiB,UAAU,OAC/B,CAAC,KAAK,SAAS,MAAM,KAAK,WAC1B,EACD;CACD,MAAM,qBAAqB,qBAAqB;AAEhD,QAAO;EACL,oBAAoB;GAClB,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,eAAe,KAAK,MAAM,qBAAqB,IAAI,GAAG;EACvD;EACD,UAAU,EACR,WAAW,KAAK,MAAM,iBAAiB,IAAI,GAAG,IAC/C;CACF;AACF"}
|
|
@@ -256,6 +256,8 @@ const generateCleanUBLDocument = (invoices) => {
|
|
|
256
256
|
* Step 1: Transform the document for hashing or transmission
|
|
257
257
|
* Removes UBLExtensions and Signature, and minifies the JSON
|
|
258
258
|
* Returns the minified, cleaned JSON string
|
|
259
|
+
*
|
|
260
|
+
* FIXED: Use regex-based minification to match PowerShell script exactly
|
|
259
261
|
*/
|
|
260
262
|
const transformDocumentForHashing = (invoices) => {
|
|
261
263
|
const cleanDocument = generateCleanUBLDocument(invoices);
|
|
@@ -264,7 +266,12 @@ const transformDocumentForHashing = (invoices) => {
|
|
|
264
266
|
delete invoice.UBLExtensions;
|
|
265
267
|
delete invoice.Signature;
|
|
266
268
|
});
|
|
267
|
-
|
|
269
|
+
const jsonString = JSON.stringify(documentForTransform);
|
|
270
|
+
const minifiedJson = jsonString.replace(/("(?:\\.|[^"\\])*")|\s+/g, (match, quotedString) => {
|
|
271
|
+
if (quotedString) return quotedString;
|
|
272
|
+
else return "";
|
|
273
|
+
});
|
|
274
|
+
return minifiedJson;
|
|
268
275
|
};
|
|
269
276
|
/**
|
|
270
277
|
* Step 2: Calculate Document Digest
|
|
@@ -280,13 +287,22 @@ const calculateDocumentDigest = (invoices) => {
|
|
|
280
287
|
/**
|
|
281
288
|
* Step 4: Calculate Certificate Digest
|
|
282
289
|
* Enhanced to handle certificate content properly
|
|
290
|
+
* FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData
|
|
283
291
|
*/
|
|
284
292
|
const calculateCertificateDigest = (certificatePem) => {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
293
|
+
try {
|
|
294
|
+
const cert = new X509Certificate(certificatePem);
|
|
295
|
+
const rawCertificateData = cert.raw;
|
|
296
|
+
const hash = crypto.createHash("sha256");
|
|
297
|
+
hash.update(rawCertificateData);
|
|
298
|
+
return hash.digest("base64");
|
|
299
|
+
} catch (error) {
|
|
300
|
+
const certificateContent = certificatePem.replace(/-----BEGIN CERTIFICATE-----/g, "").replace(/-----END CERTIFICATE-----/g, "").replace(/\s+/g, "");
|
|
301
|
+
const certificateBinary = Buffer.from(certificateContent, "base64");
|
|
302
|
+
const hash = crypto.createHash("sha256");
|
|
303
|
+
hash.update(certificateBinary);
|
|
304
|
+
return hash.digest("base64");
|
|
305
|
+
}
|
|
290
306
|
};
|
|
291
307
|
/**
|
|
292
308
|
* Enhanced certificate info extraction with better error handling
|
|
@@ -296,18 +312,22 @@ const extractCertificateInfo = (certificatePem) => {
|
|
|
296
312
|
try {
|
|
297
313
|
const cert = new X509Certificate(certificatePem);
|
|
298
314
|
const serialNumberHex = cert.serialNumber;
|
|
299
|
-
const
|
|
300
|
-
|
|
315
|
+
const escapeXmlSpecialChars = (str) => {
|
|
316
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
317
|
+
};
|
|
318
|
+
const normalizeIssuerName = (issuer) => {
|
|
319
|
+
const parts = issuer.split(/\r?\n|,\s*/).map((part) => part.trim()).filter((part) => part.length > 0).reverse();
|
|
301
320
|
return parts.join(", ").replace(/\s*=\s*/g, "=");
|
|
302
321
|
};
|
|
303
322
|
const formatSerialNumber = (serialHex) => {
|
|
304
323
|
const decimal = BigInt("0x" + serialHex).toString();
|
|
305
324
|
return decimal;
|
|
306
325
|
};
|
|
326
|
+
const rawSubjectName = cert.subject;
|
|
307
327
|
return {
|
|
308
|
-
issuerName:
|
|
328
|
+
issuerName: escapeXmlSpecialChars(normalizeIssuerName(cert.issuer)),
|
|
309
329
|
serialNumber: formatSerialNumber(serialNumberHex),
|
|
310
|
-
subjectName:
|
|
330
|
+
subjectName: rawSubjectName
|
|
311
331
|
};
|
|
312
332
|
} catch (error) {
|
|
313
333
|
throw new Error(`Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -342,6 +362,7 @@ const createSignedProperties = (certificateDigest, signingTime, issuerName, seri
|
|
|
342
362
|
/**
|
|
343
363
|
* Step 6: Calculate SignedProperties Digest
|
|
344
364
|
* Calculates the digest over the correct structure for validator compliance.
|
|
365
|
+
* FIXED: Calculate digest from SignedProperties only (without Target wrapper)
|
|
345
366
|
*/
|
|
346
367
|
const calculateSignedPropertiesDigest = (signedProperties, useTargetWrapper = true) => {
|
|
347
368
|
let digestObj;
|
|
@@ -350,10 +371,13 @@ const calculateSignedPropertiesDigest = (signedProperties, useTargetWrapper = tr
|
|
|
350
371
|
SignedProperties: signedProperties.SignedProperties
|
|
351
372
|
};
|
|
352
373
|
else digestObj = signedProperties.SignedProperties;
|
|
353
|
-
const
|
|
354
|
-
const
|
|
374
|
+
const signedPropertiesString = JSON.stringify(digestObj);
|
|
375
|
+
const minifiedSignedProperties = signedPropertiesString.replace(/("(?:\\.|[^"\\])*")|\s+/g, (match, quotedString) => {
|
|
376
|
+
if (quotedString) return quotedString;
|
|
377
|
+
else return "";
|
|
378
|
+
});
|
|
355
379
|
const hash = crypto.createHash("sha256");
|
|
356
|
-
hash.update(
|
|
380
|
+
hash.update(minifiedSignedProperties, "utf8");
|
|
357
381
|
return hash.digest("base64");
|
|
358
382
|
};
|
|
359
383
|
/**
|
|
@@ -406,13 +430,12 @@ const createSignedInfoAndSign = (docDigest, propsDigest, privateKeyPem) => {
|
|
|
406
430
|
/**
|
|
407
431
|
* Signs the minified document string using the provided private key PEM
|
|
408
432
|
* Returns the signature as a base64 string
|
|
433
|
+
* FIXED: Match PowerShell script exactly - first compute hash, then sign the hash
|
|
409
434
|
*/
|
|
410
435
|
const signDocumentString = (documentString, privateKeyPem) => {
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
});
|
|
415
|
-
return signature.toString("base64");
|
|
436
|
+
const signer = crypto.createSign("RSA-SHA256");
|
|
437
|
+
signer.update(documentString, "utf8");
|
|
438
|
+
return signer.sign(privateKeyPem, "base64");
|
|
416
439
|
};
|
|
417
440
|
/**
|
|
418
441
|
* Complete document generation with signatures
|
|
@@ -423,22 +446,45 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
423
446
|
const docDigest = calculateDocumentDigest(invoices);
|
|
424
447
|
const documentString = transformDocumentForHashing(invoices);
|
|
425
448
|
const docSignature = signDocumentString(documentString, signingCredentials.privateKeyPem);
|
|
426
|
-
const
|
|
449
|
+
const now = /* @__PURE__ */ new Date();
|
|
450
|
+
const signingTime = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0") + "T" + String(now.getHours()).padStart(2, "0") + ":" + String(now.getMinutes()).padStart(2, "0") + ":" + String(now.getSeconds()).padStart(2, "0") + "Z";
|
|
427
451
|
const certInfo = extractCertificateInfo(signingCredentials.certificatePem);
|
|
428
452
|
const certificateDigest = calculateCertificateDigest(signingCredentials.certificatePem);
|
|
429
453
|
const signedProperties = createSignedProperties(certificateDigest, signingTime, certInfo.issuerName, certInfo.serialNumber);
|
|
430
|
-
const
|
|
431
|
-
|
|
432
|
-
|
|
454
|
+
const propsDigest = calculateSignedPropertiesDigest(signedProperties);
|
|
455
|
+
const signedInfo = {
|
|
456
|
+
CanonicalizationMethod: [{
|
|
457
|
+
_: "",
|
|
458
|
+
Algorithm: "http://www.w3.org/2006/12/xml-c14n11"
|
|
459
|
+
}],
|
|
460
|
+
SignatureMethod: [{
|
|
461
|
+
_: "",
|
|
462
|
+
Algorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
|
|
463
|
+
}],
|
|
464
|
+
Reference: [{
|
|
465
|
+
Id: "id-doc-signed-data",
|
|
466
|
+
Type: "",
|
|
467
|
+
URI: "",
|
|
468
|
+
DigestMethod: [{
|
|
469
|
+
_: "",
|
|
470
|
+
Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256"
|
|
471
|
+
}],
|
|
472
|
+
DigestValue: [{ _: docDigest }]
|
|
473
|
+
}, {
|
|
474
|
+
Id: "id-xades-signed-props",
|
|
475
|
+
Type: "http://uri.etsi.org/01903/v1.3.2#SignedProperties",
|
|
476
|
+
URI: "#id-xades-signed-props",
|
|
477
|
+
DigestMethod: [{
|
|
478
|
+
_: "",
|
|
479
|
+
Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256"
|
|
480
|
+
}],
|
|
481
|
+
DigestValue: [{ _: propsDigest }]
|
|
482
|
+
}]
|
|
433
483
|
};
|
|
434
|
-
const
|
|
435
|
-
const
|
|
436
|
-
const propsDigest = crypto.createHash("sha256").update(signedPropertiesString, "utf8").digest("base64");
|
|
437
|
-
const { signedInfo } = createSignedInfoAndSign(docDigest, propsDigest, signingCredentials.privateKeyPem);
|
|
438
|
-
const certificate = signingCredentials.certificatePem.replace(/-----BEGIN CERTIFICATE-----/g, "").replace(/-----END CERTIFICATE-----/g, "").replace(/\s+/g, "");
|
|
484
|
+
const cert = new X509Certificate(signingCredentials.certificatePem);
|
|
485
|
+
const certificate = cert.raw.toString("base64");
|
|
439
486
|
const signedInvoices = invoices.map((invoice) => {
|
|
440
487
|
const cleanInvoice = generateCleanInvoiceObject(invoice);
|
|
441
|
-
const parsedCanonicalSignedProps = JSON.parse(signedPropertiesString);
|
|
442
488
|
return {
|
|
443
489
|
...cleanInvoice,
|
|
444
490
|
UBLExtensions: [{ UBLExtension: [{
|
|
@@ -448,7 +494,10 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
448
494
|
ReferencedSignatureID: [{ _: "urn:oasis:names:specification:ubl:signature:Invoice" }],
|
|
449
495
|
Signature: [{
|
|
450
496
|
Id: "signature",
|
|
451
|
-
Object: [{ QualifyingProperties: [
|
|
497
|
+
Object: [{ QualifyingProperties: [{
|
|
498
|
+
Target: "signature",
|
|
499
|
+
SignedProperties: signedProperties.SignedProperties
|
|
500
|
+
}] }],
|
|
452
501
|
KeyInfo: [{ X509Data: [{
|
|
453
502
|
X509Certificate: [{ _: certificate }],
|
|
454
503
|
X509SubjectName: [{ _: certInfo.subjectName }],
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_document = require('./document-
|
|
1
|
+
const require_document = require('./document-CNM7-o5x.cjs');
|
|
2
2
|
|
|
3
3
|
//#region src/api/documentSubmission.ts
|
|
4
4
|
async function submitDocument(context, documents) {
|
|
@@ -147,4 +147,4 @@ Object.defineProperty(exports, 'submitDocument', {
|
|
|
147
147
|
return submitDocument;
|
|
148
148
|
}
|
|
149
149
|
});
|
|
150
|
-
//# sourceMappingURL=documentSubmission-
|
|
150
|
+
//# sourceMappingURL=documentSubmission-BE1En5JO.cjs.map
|