@ripwords/myinvois-client 0.2.28 → 0.2.29
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/documentManagement.js +1 -1
- 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-nWFcUMsi.js → document-DI6hw1MO.js} +1 -1
- package/dist/{document-CNM7-o5x.cjs → document-DWsGewNs.cjs} +2 -2
- package/dist/document-DWsGewNs.cjs.map +1 -0
- package/dist/{documentManagement-CIQPkmyb.js → documentManagement-CeNbp3qm.js} +13 -3
- package/dist/{documentManagement-DQ7JEcBq.cjs → documentManagement-CyPwiyP4.cjs} +14 -4
- package/dist/documentManagement-CyPwiyP4.cjs.map +1 -0
- package/dist/{documentSubmission-BE1En5JO.cjs → documentSubmission-D96QqHJ-.cjs} +2 -2
- package/dist/{documentSubmission-BE1En5JO.cjs.map → documentSubmission-D96QqHJ-.cjs.map} +1 -1
- package/dist/{documentSubmission-CVwFwnDd.js → documentSubmission-Dr4R4sKD.js} +1 -1
- package/dist/{documents-B4VA36Bj.d.cts → documents-BWpJ0B3C.d.cts} +2 -2
- package/dist/{documents-BIGS59JL.d.ts → documents-DRQ6_toX.d.ts} +1 -1
- package/dist/index.cjs +8 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +8 -7
- package/dist/index10.cjs +53 -187
- package/dist/index10.cjs.map +1 -1
- package/dist/index11.cjs +532 -0
- package/dist/index11.cjs.map +1 -0
- package/dist/index12.cjs +187 -16
- package/dist/index12.cjs.map +1 -1
- package/dist/index14.cjs +25 -0
- package/dist/index14.cjs.map +1 -0
- package/dist/index15.cjs +0 -29
- package/dist/index16.cjs +0 -25
- package/dist/index17.cjs +29 -0
- package/dist/{index15.cjs.map → index17.cjs.map} +1 -1
- package/dist/index18.cjs +16 -25
- package/dist/index18.cjs.map +1 -1
- package/dist/index19.cjs +0 -24
- package/dist/index2.cjs +3 -4
- package/dist/index20.cjs +34 -0
- package/dist/index20.cjs.map +1 -0
- package/dist/index21.cjs +24 -0
- package/dist/{index19.cjs.map → index21.cjs.map} +1 -1
- package/dist/index23.cjs +0 -4
- package/dist/index24.cjs +0 -13
- package/dist/index25.cjs +4 -4
- package/dist/index26.cjs +5 -20
- package/dist/index27.cjs +4 -2
- package/dist/index28.cjs +2 -2
- package/dist/index29.cjs +2 -329
- package/dist/index3.cjs +12 -6
- package/dist/index3.cjs.map +1 -0
- package/dist/index30.cjs +5 -192
- package/dist/index4.cjs +4 -4
- package/dist/index5.cjs +21 -2
- package/dist/index6.cjs +2 -2
- package/dist/index67.cts.map +1 -1
- package/dist/index7.cjs +2 -5
- package/dist/index8.cjs +324 -56
- package/dist/index8.cjs.map +1 -1
- package/dist/index9.cjs +185 -524
- package/dist/index9.cjs.map +1 -1
- package/dist/{taxpayer-iisM69iU.d.cts → taxpayer-CApK7x_O.d.cts} +2 -2
- package/dist/{taxpayer-YXsbpgpd.d.ts → taxpayer-DtyHXKwz.d.ts} +1 -1
- 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 +2 -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/document-CNM7-o5x.cjs.map +0 -1
- package/dist/documentManagement-DQ7JEcBq.cjs.map +0 -1
- package/dist/index16.cjs.map +0 -1
- package/dist/index24.cjs.map +0 -1
- package/dist/index29.cjs.map +0 -1
- package/dist/index30.cjs.map +0 -1
package/dist/index67.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index67.cts","names":[],"sources":["../src/index.d.ts"],"sourcesContent":["import { DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypesResponse, DocumentTypeVersionResponse, DocumentValidationResult, DocumentValidationStepResult, EInvoiceTypeCode, NotificationResponse, NotificationSearchParams, RegistrationType, StandardError, SubmissionResponse, SubmissionStatus, TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse, AllDocumentsV1_1 } from './types';\nexport type * from './types/index.d.ts';\nexport declare class MyInvoisClient {\n private readonly baseUrl;\n private readonly clientId;\n private readonly clientSecret;\n private readonly environment;\n private onBehalfOf?;\n private readonly signingCredentials;\n private readonly debug;\n private token;\n private tokenExpiration;\n constructor(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', certificatePem: string, privateKeyPem: string, onBehalfOf?: string, debug?: boolean);\n updateOnBehalfOf(onBehalfOf: string): Promise<void>;\n private refreshToken;\n private getToken;\n private fetch;\n /**\n * Validates a TIN against a NRIC/ARMY/PASSPORT/BRN (Business Registration Number)\n *\n * This method verifies if a given Tax Identification Number (TIN) is valid by checking it against\n * the provided identification type and value through the MyInvois platform's validation service.\n *\n * @param tin - The TIN to validate\n * @param idType - The type of ID to validate against ('NRIC', 'ARMY', 'PASSPORT', or 'BRN')\n * @param idValue - The value of the ID to validate against\n * @returns Promise resolving to true if the TIN is valid, false otherwise\n *\n * @example\n * ```typescript\n * // Validate TIN against NRIC\n * const isValid = await client.verifyTin('C12345678901234', 'NRIC', '123456789012');\n * if (isValid) {\n * console.log('TIN is valid');\n * }\n *\n * // Validate TIN against Business Registration Number\n * const isValidBusiness = await client.verifyTin('C98765432109876', 'BRN', '123456-K');\n * ```\n *\n * @remarks\n * - Returns false if validation fails due to network errors or invalid credentials\n * - Debug mode provides error logging for troubleshooting validation failures\n * - This is a non-blocking validation that won't throw exceptions on failure\n */\n verifyTin(tin: string, idType: RegistrationType, idValue: string): Promise<boolean>;\n /**\n * Searches for a Tax Identification Number (TIN) using taxpayer information.\n *\n * This method allows searching for a TIN using either a taxpayer name or a combination\n * of identification type and value. The search is flexible and supports multiple\n * identification types including NRIC, ARMY, PASSPORT, and BRN.\n *\n * @param params - Search parameters object\n * @param params.taxpayerName - Optional name of the taxpayer to search for\n * @param params.idType - Optional type of ID to search with (NRIC, ARMY, PASSPORT, BRN)\n * @param params.idValue - Optional value of the ID to search with\n * @returns Promise resolving to TIN search response or standard error\n *\n * @example\n * ```typescript\n * // Search by taxpayer name\n * const result = await client.searchTin({ taxpayerName: 'John Doe' });\n * if ('tin' in result) {\n * console.log('Found TIN:', result.tin);\n * }\n *\n * // Search by ID type and value\n * const result = await client.searchTin({\n * idType: 'NRIC',\n * idValue: '123456789012'\n * });\n * ```\n *\n * @remarks\n * - Either taxpayerName or both idType and idValue must be provided\n * - Returns StandardError object if search criteria are invalid or inconclusive\n * - Debug mode provides detailed error logging for troubleshooting\n * - Search results are not guaranteed to be unique\n */\n searchTin(params: TinSearchParams): Promise<TinSearchResponse>;\n /**\n * Retrieves taxpayer information from a QR code.\n *\n * This method decodes a QR code containing taxpayer information and returns\n * detailed taxpayer data including TIN, name, contact details, and business information.\n *\n * @param qrCodeText - The QR code text to decode\n * @returns Promise resolving to taxpayer QR code response or standard error\n *\n * @example\n * ```typescript\n * // Get taxpayer info from QR code\n * const taxpayerInfo = await client.getTaxpayerQRCode('QR_CODE_TEXT');\n * if ('tin' in taxpayerInfo) {\n * console.log('Taxpayer TIN:', taxpayerInfo.tin);\n * console.log('Business Name:', taxpayerInfo.name);\n * console.log('Address:', taxpayerInfo.addressLine1);\n * }\n * ```\n *\n * @remarks\n * - QR code must be in the correct format specified by MyInvois\n * - Returns StandardError if QR code is invalid or cannot be decoded\n * - Debug mode provides detailed error logging\n */\n getTaxpayerQRCode(qrCodeText: string): Promise<TaxpayerQRCodeResponse>;\n /**\n * Performs an action on a document such as rejection or cancellation.\n *\n * This method allows updating the status of a document to either rejected or cancelled,\n * along with providing a reason for the action. Useful for managing document workflow\n * and maintaining audit trails.\n *\n * @param documentUid - The unique identifier of the document\n * @param status - The new status to set ('rejected' or 'cancelled')\n * @param reason - The reason for the status change\n * @returns Promise resolving to document action response containing UUID, status, and any errors\n *\n * @example\n * ```typescript\n * // Reject a document with reason\n * const result = await client.performDocumentAction(\n * 'doc-123',\n * 'rejected',\n * 'Invalid tax calculation'\n * );\n *\n * // Cancel a document\n * const result = await client.performDocumentAction(\n * 'doc-456',\n * 'cancelled',\n * 'Duplicate submission'\n * );\n * ```\n *\n * @remarks\n * - Only valid for documents in appropriate states\n * - Reason is required and should be descriptive\n * - Action is irreversible once completed\n * - Returns error if document cannot be found or action is invalid\n */\n performDocumentAction(documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n }>;\n /**\n * Submits one or more e-invoice documents to the MyInvois platform for processing.\n *\n * This method digitally signs each document using the provided certificate and private key,\n * generates document hashes, encodes them for submission, and sends them to the platform.\n * The method includes comprehensive validation warnings for document size and count limits.\n *\n * @param documents - Array of InvoiceV1_1 documents to be submitted\n * @returns Promise resolving to submission response containing the submission data and HTTP status\n * @throws {Error} If PRIVATE_KEY or CERTIFICATE environment variables are missing\n * @throws {Error} If document signing, encoding, or API submission fails\n *\n * @example\n * ```typescript\n * // Submit a single invoice\n * const result = await client.submitDocument([invoiceData]);\n * console.log(result.data.submissionUid); // Track submission with this UID\n *\n * // Submit multiple invoices\n * const result = await client.submitDocument([invoice1, invoice2, invoice3]);\n * if (result.status === 202) {\n * console.log('Documents submitted successfully');\n * }\n * ```\n *\n * @remarks\n * - Requires PRIVATE_KEY and CERTIFICATE environment variables for document signing\n * - Each document is digitally signed with XML-DSIG before submission\n * - Documents are base64-encoded for transmission\n * - API limits: Max 100 documents per submission, 5MB total payload, 300KB per document\n * - Debug mode provides detailed logging of payload sizes and validation warnings\n * - Returns HTTP 202 for successful submissions that require processing\n */\n submitDocument(documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n }>;\n /**\n * Polls the MyInvois platform to get the current status of a document submission.\n *\n * This method continuously checks the submission status until it receives a final result\n * (Valid or Invalid) or reaches the maximum retry limit. It's designed to handle the\n * asynchronous nature of document processing on the MyInvois platform.\n *\n * @param submissionUid - The unique identifier of the submission to check\n * @param pollInterval - Time in milliseconds between status checks (default: 1000ms)\n * @param maxRetries - Maximum number of retry attempts (default: 10)\n * @returns Promise resolving to submission status object with document summary and any errors\n *\n * @example\n * ```typescript\n * // Check submission status with default polling\n * const result = await client.getSubmissionStatus('submission-uid-123');\n * if (result.status === 'Valid') {\n * console.log('All documents processed successfully');\n * console.log('Document summaries:', result.documentSummary);\n * }\n *\n * // Custom polling interval and retry count\n * const result = await client.getSubmissionStatus(\n * 'submission-uid-123',\n * 2000, // Poll every 2 seconds\n * 20 // Try up to 20 times\n * );\n * ```\n *\n * @remarks\n * - Automatically retries on network errors until maxRetries is reached\n * - Returns 'Invalid' status with timeout error if submission processing takes too long\n * - Debug mode provides detailed logging of polling attempts and responses\n * - Use reasonable poll intervals to avoid overwhelming the API\n */\n getSubmissionStatus(submissionUid: string, pollInterval?: number, maxRetries?: number): Promise<{\n status: SubmissionStatus;\n documentSummary?: DocumentSummary[];\n error?: {\n code: string;\n message: string | null;\n target: string;\n details: {\n code: string;\n message: string;\n target: string;\n }[];\n };\n }>;\n /**\n * Retrieves a document by its unique identifier with the raw document content.\n *\n * @param documentUid - The unique identifier of the document to retrieve\n * @returns Promise resolving to document summary with raw document content as a string\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const document = await client.getDocument('doc-uuid-123');\n * console.log(document.document); // Raw XML/JSON content\n * console.log(document.uuid); // Document UUID\n * ```\n */\n getDocument(documentUid: string): Promise<DocumentSummary & {\n document: string;\n }>;\n /**\n * Retrieves detailed information about a document including validation results.\n *\n * @param documentUid - The unique identifier of the document to get details for\n * @returns Promise resolving to document summary with detailed validation results\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const details = await client.getDocumentDetails('doc-uuid-123');\n * console.log(details.validationResults.status); // 'Valid' | 'Invalid' | 'Processing'\n * console.log(details.validationResults.validationSteps); // Array of validation step results\n * ```\n */\n getDocumentDetails(documentUid: string): Promise<DocumentSummary & {\n validationResults: {\n status: DocumentValidationResult;\n validationSteps: DocumentValidationStepResult[];\n };\n }>;\n /**\n * Searches for documents based on various filter criteria.\n *\n * @param params - Search parameters object\n * @param params.uuid - Optional specific document UUID to search for\n * @param params.submissionDateFrom - Required start date for submission date range (ISO date string)\n * @param params.submissionDateTo - Optional end date for submission date range (ISO date string)\n * @param params.pageSize - Optional number of results per page (default handled by API)\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.issueDateFrom - Optional start date for issue date range (ISO date string)\n * @param params.issueDateTo - Optional end date for issue date range (ISO date string)\n * @param params.invoiceDirection - Optional filter by invoice direction ('Sent' or 'Received')\n * @param params.status - Optional filter by document status\n * @param params.documentType - Optional filter by e-invoice type code\n * @param params.searchQuery - Optional text search across uuid, buyerTIN, supplierTIN, buyerName, supplierName, internalID, total\n * @returns Promise resolving to array of document summaries matching the search criteria\n * @throws {Error} If the search request fails\n *\n * @example\n * ```typescript\n * // Search for documents submitted in the last 30 days\n * const documents = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * submissionDateTo: '2024-01-31',\n * status: 'Valid',\n * pageSize: 10\n * });\n *\n * // Search by supplier name\n * const supplierDocs = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * searchQuery: 'ACME Corp',\n * invoiceDirection: 'Received'\n * });\n * ```\n */\n searchDocuments({ uuid, submissionDateFrom, submissionDateTo, pageSize, pageNo, issueDateFrom, issueDateTo, invoiceDirection, status, documentType, searchQuery, }: {\n uuid?: string;\n submissionDateFrom: string;\n submissionDateTo?: string;\n pageSize?: number;\n pageNo?: number;\n issueDateFrom?: string;\n issueDateTo?: string;\n invoiceDirection?: 'Sent' | 'Received';\n status?: DocumentStatus;\n documentType?: EInvoiceTypeCode;\n searchQuery?: string;\n }): Promise<DocumentSummary[]>;\n /**\n * Retrieves notifications from the MyInvois platform based on specified search criteria.\n *\n * This method allows you to search for system notifications, alerts, and messages\n * sent by the MyInvois platform regarding document processing, system updates,\n * or account-related information.\n *\n * @param params - Search parameters object for filtering notifications\n * @param params.dateFrom - Optional start date for notification date range (ISO date string)\n * @param params.dateTo - Optional end date for notification date range (ISO date string)\n * @param params.type - Optional notification type filter\n * @param params.language - Optional language preference for notifications\n * @param params.status - Optional notification status filter\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.pageSize - Optional number of results per page\n * @returns Promise resolving to notification response object or standard error\n *\n * @example\n * ```typescript\n * // Get all notifications from the last 7 days\n * const notifications = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * dateTo: '2024-01-07',\n * pageSize: 20\n * });\n *\n * // Get unread notifications only\n * const unreadNotifications = await client.getNotifications({\n * status: 0, // Assuming 0 = unread\n * language: 'en'\n * });\n *\n * // Paginated notification retrieval\n * const firstPage = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * pageNo: 0,\n * pageSize: 10\n * });\n * ```\n *\n * @remarks\n * - All parameters are optional, allowing flexible filtering\n * - Returns paginated results when pageNo and pageSize are specified\n * - Date parameters should be in ISO format (YYYY-MM-DD)\n * - May return StandardError object if the request fails\n */\n getNotifications({ dateFrom, dateTo, type, language, status, pageNo, pageSize, }: NotificationSearchParams): Promise<NotificationResponse>;\n getDocumentTypes(): Promise<DocumentTypesResponse>;\n /**\n * Retrieves detailed information about a specific document type from the MyInvois platform.\n *\n * This method fetches metadata and configuration details for a specific document type,\n * including supported versions, validation rules, and structural requirements.\n * Useful for understanding document format requirements before submission.\n *\n * @param id - The unique identifier of the document type to retrieve\n * @returns Promise resolving to document type response object or standard error\n *\n * @example\n * ```typescript\n * // Get details for e-invoice document type\n * const invoiceType = await client.getDocumentType(1);\n * if ('id' in invoiceType) {\n * console.log('Document type name:', invoiceType.name);\n * console.log('Available versions:', invoiceType.versionNumber);\n * console.log('Description:', invoiceType.description);\n * }\n *\n * // Handle potential errors\n * const documentType = await client.getDocumentType(999);\n * if ('error' in documentType) {\n * console.error('Failed to retrieve document type:', documentType.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if the document type ID doesn't exist\n * - Document type information includes validation schemas and business rules\n * - Use this method to discover supported document formats and versions\n * - Essential for understanding submission requirements for different document types\n */\n getDocumentType(id: number): Promise<DocumentTypeResponse>;\n /**\n * Generates a shareable QR code URL for a specific document.\n *\n * This method retrieves the document details using its unique identifier,\n * then constructs a URL that can be used to access or share the document\n * via the MyInvois platform. The URL format differs between sandbox and\n * production environments.\n *\n * @param documentUid - The unique identifier of the document\n * @returns Promise resolving to a string containing the QR code URL\n *\n * @example\n * ```typescript\n * const qrCodeUrl = await client.getDocumentQrCode('abc123');\n * console.log('Shareable QR code URL:', qrCodeUrl);\n * // Output (sandbox): https://preprod.myinvois.hasil.gov.my/abc123/share/longID\n * // Output (production): https://myinvois.hasil.gov.my/abc123/share/longID\n * ```\n *\n * @remarks\n * - The returned URL can be embedded in a QR code for document sharing.\n * - The method fetches the document to obtain its longID, which is required for the URL.\n * - Ensure the documentUid is valid and accessible by the current client.\n */\n getDocumentQrCode(documentUid: string): Promise<string>;\n /**\n * Retrieves detailed information about a specific version of a document type.\n *\n * This method fetches version-specific metadata, schema definitions, and validation rules\n * for a particular document type version. Essential for understanding the exact format\n * and requirements for document submission in a specific version.\n *\n * @param id - The unique identifier of the document type\n * @param versionId - The unique identifier of the specific version to retrieve\n * @returns Promise resolving to document type version response object or standard error\n *\n * @example\n * ```typescript\n * // Get specific version details for e-invoice\n * const invoiceV1_1 = await client.getDocumentTypeVersion(1, 1);\n * if ('id' in invoiceV1_1) {\n * console.log('Version number:', invoiceV1_1.versionNumber);\n * console.log('Schema:', invoiceV1_1.jsonSchema);\n * console.log('Status:', invoiceV1_1.status);\n * }\n *\n * // Compare different versions\n * const [v1_0, v1_1] = await Promise.all([\n * client.getDocumentTypeVersion(1, 0),\n * client.getDocumentTypeVersion(1, 1)\n * ]);\n *\n * // Handle version not found\n * const result = await client.getDocumentTypeVersion(1, 999);\n * if ('error' in result) {\n * console.error('Version not found:', result.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if document type ID or version ID doesn't exist\n * - Version information includes JSON schema for validation\n * - Different versions may have different validation rules and field requirements\n * - Use this to ensure your documents conform to the specific version requirements\n * - Version status indicates if the version is active, deprecated, or under development\n */\n getDocumentTypeVersion(id: number, versionId: number): Promise<DocumentTypeVersionResponse>;\n static fromP12(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', p12Input: Buffer | string, passphrase: string, onBehalfOf?: string, debug?: boolean): MyInvoisClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAW,iBAAiB;CAAC;CAAK,MAAE;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"index67.cts","names":[],"sources":["../src/index.d.ts"],"sourcesContent":["import { DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypesResponse, DocumentTypeVersionResponse, DocumentValidationResult, DocumentValidationStepResult, EInvoiceTypeCode, NotificationResponse, NotificationSearchParams, RegistrationType, StandardError, SubmissionResponse, SubmissionStatus, TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse, AllDocumentsV1_1 } from './types';\nexport type * from './types/index.d.ts';\nexport declare class MyInvoisClient {\n private readonly baseUrl;\n private readonly clientId;\n private readonly clientSecret;\n private readonly environment;\n private onBehalfOf?;\n private readonly signingCredentials;\n private readonly debug;\n private token;\n private tokenExpiration;\n constructor(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', certificatePem: string, privateKeyPem: string, onBehalfOf?: string, debug?: boolean);\n updateOnBehalfOf(onBehalfOf: string): Promise<void>;\n private refreshToken;\n private getToken;\n private fetch;\n /**\n * Validates a TIN against a NRIC/ARMY/PASSPORT/BRN (Business Registration Number)\n *\n * This method verifies if a given Tax Identification Number (TIN) is valid by checking it against\n * the provided identification type and value through the MyInvois platform's validation service.\n *\n * @param tin - The TIN to validate\n * @param idType - The type of ID to validate against ('NRIC', 'ARMY', 'PASSPORT', or 'BRN')\n * @param idValue - The value of the ID to validate against\n * @returns Promise resolving to true if the TIN is valid, false otherwise\n *\n * @example\n * ```typescript\n * // Validate TIN against NRIC\n * const isValid = await client.verifyTin('C12345678901234', 'NRIC', '123456789012');\n * if (isValid) {\n * console.log('TIN is valid');\n * }\n *\n * // Validate TIN against Business Registration Number\n * const isValidBusiness = await client.verifyTin('C98765432109876', 'BRN', '123456-K');\n * ```\n *\n * @remarks\n * - Returns false if validation fails due to network errors or invalid credentials\n * - Debug mode provides error logging for troubleshooting validation failures\n * - This is a non-blocking validation that won't throw exceptions on failure\n */\n verifyTin(tin: string, idType: RegistrationType, idValue: string): Promise<boolean>;\n /**\n * Searches for a Tax Identification Number (TIN) using taxpayer information.\n *\n * This method allows searching for a TIN using either a taxpayer name or a combination\n * of identification type and value. The search is flexible and supports multiple\n * identification types including NRIC, ARMY, PASSPORT, and BRN.\n *\n * @param params - Search parameters object\n * @param params.taxpayerName - Optional name of the taxpayer to search for\n * @param params.idType - Optional type of ID to search with (NRIC, ARMY, PASSPORT, BRN)\n * @param params.idValue - Optional value of the ID to search with\n * @returns Promise resolving to TIN search response or standard error\n *\n * @example\n * ```typescript\n * // Search by taxpayer name\n * const result = await client.searchTin({ taxpayerName: 'John Doe' });\n * if ('tin' in result) {\n * console.log('Found TIN:', result.tin);\n * }\n *\n * // Search by ID type and value\n * const result = await client.searchTin({\n * idType: 'NRIC',\n * idValue: '123456789012'\n * });\n * ```\n *\n * @remarks\n * - Either taxpayerName or both idType and idValue must be provided\n * - Returns StandardError object if search criteria are invalid or inconclusive\n * - Debug mode provides detailed error logging for troubleshooting\n * - Search results are not guaranteed to be unique\n */\n searchTin(params: TinSearchParams): Promise<TinSearchResponse>;\n /**\n * Retrieves taxpayer information from a QR code.\n *\n * This method decodes a QR code containing taxpayer information and returns\n * detailed taxpayer data including TIN, name, contact details, and business information.\n *\n * @param qrCodeText - The QR code text to decode\n * @returns Promise resolving to taxpayer QR code response or standard error\n *\n * @example\n * ```typescript\n * // Get taxpayer info from QR code\n * const taxpayerInfo = await client.getTaxpayerQRCode('QR_CODE_TEXT');\n * if ('tin' in taxpayerInfo) {\n * console.log('Taxpayer TIN:', taxpayerInfo.tin);\n * console.log('Business Name:', taxpayerInfo.name);\n * console.log('Address:', taxpayerInfo.addressLine1);\n * }\n * ```\n *\n * @remarks\n * - QR code must be in the correct format specified by MyInvois\n * - Returns StandardError if QR code is invalid or cannot be decoded\n * - Debug mode provides detailed error logging\n */\n getTaxpayerQRCode(qrCodeText: string): Promise<TaxpayerQRCodeResponse>;\n /**\n * Performs an action on a document such as rejection or cancellation.\n *\n * This method allows updating the status of a document to either rejected or cancelled,\n * along with providing a reason for the action. Useful for managing document workflow\n * and maintaining audit trails.\n *\n * @param documentUid - The unique identifier of the document\n * @param status - The new status to set ('rejected' or 'cancelled')\n * @param reason - The reason for the status change\n * @returns Promise resolving to document action response containing UUID, status, and any errors\n *\n * @example\n * ```typescript\n * // Reject a document with reason\n * const result = await client.performDocumentAction(\n * 'doc-123',\n * 'rejected',\n * 'Invalid tax calculation'\n * );\n *\n * // Cancel a document\n * const result = await client.performDocumentAction(\n * 'doc-456',\n * 'cancelled',\n * 'Duplicate submission'\n * );\n * ```\n *\n * @remarks\n * - Only valid for documents in appropriate states\n * - Reason is required and should be descriptive\n * - Action is irreversible once completed\n * - Returns error if document cannot be found or action is invalid\n */\n performDocumentAction(documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n }>;\n /**\n * Submits one or more e-invoice documents to the MyInvois platform for processing.\n *\n * This method digitally signs each document using the provided certificate and private key,\n * generates document hashes, encodes them for submission, and sends them to the platform.\n * The method includes comprehensive validation warnings for document size and count limits.\n *\n * @param documents - Array of InvoiceV1_1 documents to be submitted\n * @returns Promise resolving to submission response containing the submission data and HTTP status\n * @throws {Error} If PRIVATE_KEY or CERTIFICATE environment variables are missing\n * @throws {Error} If document signing, encoding, or API submission fails\n *\n * @example\n * ```typescript\n * // Submit a single invoice\n * const result = await client.submitDocument([invoiceData]);\n * console.log(result.data.submissionUid); // Track submission with this UID\n *\n * // Submit multiple invoices\n * const result = await client.submitDocument([invoice1, invoice2, invoice3]);\n * if (result.status === 202) {\n * console.log('Documents submitted successfully');\n * }\n * ```\n *\n * @remarks\n * - Requires PRIVATE_KEY and CERTIFICATE environment variables for document signing\n * - Each document is digitally signed with XML-DSIG before submission\n * - Documents are base64-encoded for transmission\n * - API limits: Max 100 documents per submission, 5MB total payload, 300KB per document\n * - Debug mode provides detailed logging of payload sizes and validation warnings\n * - Returns HTTP 202 for successful submissions that require processing\n */\n submitDocument(documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n }>;\n /**\n * Polls the MyInvois platform to get the current status of a document submission.\n *\n * This method continuously checks the submission status until it receives a final result\n * (Valid or Invalid) or reaches the maximum retry limit. It's designed to handle the\n * asynchronous nature of document processing on the MyInvois platform.\n *\n * @param submissionUid - The unique identifier of the submission to check\n * @param pollInterval - Time in milliseconds between status checks (default: 1000ms)\n * @param maxRetries - Maximum number of retry attempts (default: 10)\n * @returns Promise resolving to submission status object with document summary and any errors\n *\n * @example\n * ```typescript\n * // Check submission status with default polling\n * const result = await client.getSubmissionStatus('submission-uid-123');\n * if (result.status === 'Valid') {\n * console.log('All documents processed successfully');\n * console.log('Document summaries:', result.documentSummary);\n * }\n *\n * // Custom polling interval and retry count\n * const result = await client.getSubmissionStatus(\n * 'submission-uid-123',\n * 2000, // Poll every 2 seconds\n * 20 // Try up to 20 times\n * );\n * ```\n *\n * @remarks\n * - Automatically retries on network errors until maxRetries is reached\n * - Returns 'Invalid' status with timeout error if submission processing takes too long\n * - Debug mode provides detailed logging of polling attempts and responses\n * - Use reasonable poll intervals to avoid overwhelming the API\n */\n getSubmissionStatus(submissionUid: string, pollInterval?: number, maxRetries?: number): Promise<{\n status: SubmissionStatus;\n documentSummary?: DocumentSummary[];\n error?: {\n code: string;\n message: string | null;\n target: string;\n details: {\n code: string;\n message: string;\n target: string;\n }[];\n };\n }>;\n /**\n * Retrieves a document by its unique identifier with the raw document content.\n *\n * @param documentUid - The unique identifier of the document to retrieve\n * @returns Promise resolving to document summary with raw document content as a string\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const document = await client.getDocument('doc-uuid-123');\n * console.log(document.document); // Raw XML/JSON content\n * console.log(document.uuid); // Document UUID\n * ```\n */\n getDocument(documentUid: string): Promise<DocumentSummary & {\n document: string;\n }>;\n /**\n * Retrieves detailed information about a document including validation results.\n *\n * @param documentUid - The unique identifier of the document to get details for\n * @returns Promise resolving to document summary with detailed validation results\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const details = await client.getDocumentDetails('doc-uuid-123');\n * console.log(details.validationResults.status); // 'Valid' | 'Invalid' | 'Processing'\n * console.log(details.validationResults.validationSteps); // Array of validation step results\n * ```\n */\n getDocumentDetails(documentUid: string): Promise<DocumentSummary & {\n validationResults: {\n status: DocumentValidationResult;\n validationSteps: DocumentValidationStepResult[];\n };\n }>;\n /**\n * Searches for documents based on various filter criteria.\n *\n * @param params - Search parameters object\n * @param params.uuid - Optional specific document UUID to search for\n * @param params.submissionDateFrom - Required start date for submission date range (ISO date string)\n * @param params.submissionDateTo - Optional end date for submission date range (ISO date string)\n * @param params.pageSize - Optional number of results per page (default handled by API)\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.issueDateFrom - Optional start date for issue date range (ISO date string)\n * @param params.issueDateTo - Optional end date for issue date range (ISO date string)\n * @param params.invoiceDirection - Optional filter by invoice direction ('Sent' or 'Received')\n * @param params.status - Optional filter by document status\n * @param params.documentType - Optional filter by e-invoice type code\n * @param params.searchQuery - Optional text search across uuid, buyerTIN, supplierTIN, buyerName, supplierName, internalID, total\n * @returns Promise resolving to array of document summaries matching the search criteria\n * @throws {Error} If the search request fails\n *\n * @example\n * ```typescript\n * // Search for documents submitted in the last 30 days\n * const documents = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * submissionDateTo: '2024-01-31',\n * status: 'Valid',\n * pageSize: 10\n * });\n *\n * // Search by supplier name\n * const supplierDocs = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * searchQuery: 'ACME Corp',\n * invoiceDirection: 'Received'\n * });\n * ```\n */\n searchDocuments({ uuid, submissionDateFrom, submissionDateTo, pageSize, pageNo, issueDateFrom, issueDateTo, invoiceDirection, status, documentType, searchQuery, }: {\n uuid?: string;\n submissionDateFrom: string;\n submissionDateTo?: string;\n pageSize?: number;\n pageNo?: number;\n issueDateFrom?: string;\n issueDateTo?: string;\n invoiceDirection?: 'Sent' | 'Received';\n status?: DocumentStatus;\n documentType?: EInvoiceTypeCode;\n searchQuery?: string;\n }): Promise<DocumentSummary[]>;\n /**\n * Retrieves notifications from the MyInvois platform based on specified search criteria.\n *\n * This method allows you to search for system notifications, alerts, and messages\n * sent by the MyInvois platform regarding document processing, system updates,\n * or account-related information.\n *\n * @param params - Search parameters object for filtering notifications\n * @param params.dateFrom - Optional start date for notification date range (ISO date string)\n * @param params.dateTo - Optional end date for notification date range (ISO date string)\n * @param params.type - Optional notification type filter\n * @param params.language - Optional language preference for notifications\n * @param params.status - Optional notification status filter\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.pageSize - Optional number of results per page\n * @returns Promise resolving to notification response object or standard error\n *\n * @example\n * ```typescript\n * // Get all notifications from the last 7 days\n * const notifications = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * dateTo: '2024-01-07',\n * pageSize: 20\n * });\n *\n * // Get unread notifications only\n * const unreadNotifications = await client.getNotifications({\n * status: 0, // Assuming 0 = unread\n * language: 'en'\n * });\n *\n * // Paginated notification retrieval\n * const firstPage = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * pageNo: 0,\n * pageSize: 10\n * });\n * ```\n *\n * @remarks\n * - All parameters are optional, allowing flexible filtering\n * - Returns paginated results when pageNo and pageSize are specified\n * - Date parameters should be in ISO format (YYYY-MM-DD)\n * - May return StandardError object if the request fails\n */\n getNotifications({ dateFrom, dateTo, type, language, status, pageNo, pageSize, }: NotificationSearchParams): Promise<NotificationResponse>;\n getDocumentTypes(): Promise<DocumentTypesResponse>;\n /**\n * Retrieves detailed information about a specific document type from the MyInvois platform.\n *\n * This method fetches metadata and configuration details for a specific document type,\n * including supported versions, validation rules, and structural requirements.\n * Useful for understanding document format requirements before submission.\n *\n * @param id - The unique identifier of the document type to retrieve\n * @returns Promise resolving to document type response object or standard error\n *\n * @example\n * ```typescript\n * // Get details for e-invoice document type\n * const invoiceType = await client.getDocumentType(1);\n * if ('id' in invoiceType) {\n * console.log('Document type name:', invoiceType.name);\n * console.log('Available versions:', invoiceType.versionNumber);\n * console.log('Description:', invoiceType.description);\n * }\n *\n * // Handle potential errors\n * const documentType = await client.getDocumentType(999);\n * if ('error' in documentType) {\n * console.error('Failed to retrieve document type:', documentType.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if the document type ID doesn't exist\n * - Document type information includes validation schemas and business rules\n * - Use this method to discover supported document formats and versions\n * - Essential for understanding submission requirements for different document types\n */\n getDocumentType(id: number): Promise<DocumentTypeResponse>;\n /**\n * Generates a shareable QR code URL for a specific document.\n *\n * This method retrieves the document details using its unique identifier,\n * then constructs a URL that can be used to access or share the document\n * via the MyInvois platform. The URL format differs between sandbox and\n * production environments.\n *\n * @param documentUid - The unique identifier of the document\n * @returns Promise resolving to a string containing the QR code URL\n *\n * @example\n * ```typescript\n * const qrCodeUrl = await client.getDocumentQrCode('abc123');\n * console.log('Shareable QR code URL:', qrCodeUrl);\n * // Output (sandbox): https://preprod.myinvois.hasil.gov.my/abc123/share/longId\n * // Output (production): https://myinvois.hasil.gov.my/abc123/share/longId\n * ```\n *\n * @remarks\n * - The returned URL can be embedded in a QR code for document sharing.\n * - The method fetches the document to obtain its longId, which is required for the URL.\n * - Ensure the documentUid is valid and accessible by the current client.\n */\n getDocumentQrCode(documentUid: string): Promise<string>;\n /**\n * Retrieves detailed information about a specific version of a document type.\n *\n * This method fetches version-specific metadata, schema definitions, and validation rules\n * for a particular document type version. Essential for understanding the exact format\n * and requirements for document submission in a specific version.\n *\n * @param id - The unique identifier of the document type\n * @param versionId - The unique identifier of the specific version to retrieve\n * @returns Promise resolving to document type version response object or standard error\n *\n * @example\n * ```typescript\n * // Get specific version details for e-invoice\n * const invoiceV1_1 = await client.getDocumentTypeVersion(1, 1);\n * if ('id' in invoiceV1_1) {\n * console.log('Version number:', invoiceV1_1.versionNumber);\n * console.log('Schema:', invoiceV1_1.jsonSchema);\n * console.log('Status:', invoiceV1_1.status);\n * }\n *\n * // Compare different versions\n * const [v1_0, v1_1] = await Promise.all([\n * client.getDocumentTypeVersion(1, 0),\n * client.getDocumentTypeVersion(1, 1)\n * ]);\n *\n * // Handle version not found\n * const result = await client.getDocumentTypeVersion(1, 999);\n * if ('error' in result) {\n * console.error('Version not found:', result.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if document type ID or version ID doesn't exist\n * - Version information includes JSON schema for validation\n * - Different versions may have different validation rules and field requirements\n * - Use this to ensure your documents conform to the specific version requirements\n * - Version status indicates if the version is active, deprecated, or under development\n */\n getDocumentTypeVersion(id: number, versionId: number): Promise<DocumentTypeVersionResponse>;\n static fromP12(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', p12Input: Buffer | string, passphrase: string, onBehalfOf?: string, debug?: boolean): MyInvoisClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAW,iBAAiB;CAAC;CAAK,MAAE;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA"}
|
package/dist/index7.cjs
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
require('./
|
|
2
|
-
const require_taxpayerValidation = require('./taxpayerValidation-D_jGaVty.cjs');
|
|
1
|
+
const require_getBaseUrl = require('./getBaseUrl-D0G4GZmp.cjs');
|
|
3
2
|
|
|
4
|
-
exports.
|
|
5
|
-
exports.tinSearch = require_taxpayerValidation.tinSearch;
|
|
6
|
-
exports.verifyTin = require_taxpayerValidation.verifyTin;
|
|
3
|
+
exports.getBaseUrl = require_getBaseUrl.getBaseUrl;
|
package/dist/index8.cjs
CHANGED
|
@@ -1,62 +1,330 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
+
require('./formatIdValue-i67o4kyD.cjs');
|
|
3
|
+
const require_document = require('./document-DWsGewNs.cjs');
|
|
4
|
+
const crypto = require_chunk.__toESM(require("crypto"));
|
|
1
5
|
|
|
2
|
-
//#region src/
|
|
6
|
+
//#region src/utils/signature-diagnostics.ts
|
|
3
7
|
/**
|
|
4
|
-
*
|
|
5
|
-
* Provides a more readable way to reference classification codes.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* const code = ClassificationCodeEnum.ComputerSmartphoneOrTablet;
|
|
9
|
-
* console.log(code); // Output: "003"
|
|
8
|
+
* Analyzes certificate for MyInvois compatibility issues
|
|
10
9
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
+
}
|
|
59
326
|
|
|
60
327
|
//#endregion
|
|
61
|
-
exports.
|
|
328
|
+
exports.diagnoseSignatureIssues = diagnoseSignatureIssues;
|
|
329
|
+
exports.printDiagnostics = printDiagnostics;
|
|
62
330
|
//# sourceMappingURL=index8.cjs.map
|
package/dist/index8.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index8.cjs","names":[],"sources":["../src/types/classification-codes.d.ts"],"sourcesContent":["/**\n * Represents the allowed classification codes for e-Invoice items.\n * Based on the documentation: https://sdk.myinvois.hasil.gov.my/codes/classification-codes/\n */\nexport type ClassificationCode =\n | '001' // Breastfeeding equipment\n | '002' // Child care centres and kindergartens fees\n | '003' // Computer, smartphone or tablet\n | '004' // Consolidated e-Invoice\n | '005' // Construction materials (as specified under Fourth Schedule of the Lembaga Pembangunan Industri Pembinaan Malaysia Act 1994)\n | '006' // Disbursement\n | '007' // Donation\n | '008' // e-Commerce - e-Invoice to buyer / purchaser\n | '009' // e-Commerce - Self-billed e-Invoice to seller, logistics, etc.\n | '010' // Education fees\n | '011' // Goods on consignment (Consignor)\n | '012' // Goods on consignment (Consignee)\n | '013' // Gym membership\n | '014' // Insurance - Education and medical benefits\n | '015' // Insurance - Takaful or life insurance\n | '016' // Interest and financing expenses\n | '017' // Internet subscription\n | '018' // Land and building\n | '019' // Medical examination for learning disabilities and early intervention or rehabilitation treatments of learning disabilities\n | '020' // Medical examination or vaccination expenses\n | '021' // Medical expenses for serious diseases\n | '022' // Others\n | '023' // Petroleum operations (as defined in Petroleum (Income Tax) Act 1967)\n | '024' // Private retirement scheme or deferred annuity scheme\n | '025' // Motor vehicle\n | '026' // Subscription of books / journals / magazines / newspapers / other similar publications\n | '027' // Reimbursement\n | '028' // Rental of motor vehicle\n | '029' // EV charging facilities (Installation, rental, sale / purchase or subscription fees)\n | '030' // Repair and maintenance\n | '031' // Research and development\n | '032' // Foreign income\n | '033' // Self-billed - Betting and gaming\n | '034' // Self-billed - Importation of goods\n | '035' // Self-billed - Importation of services\n | '036' // Self-billed - Others\n | '037' // Self-billed - Monetary payment to agents, dealers or distributors\n | '038' // Sports equipment, rental / entry fees for sports facilities, registration in sports competition or sports training fees imposed by associations / sports clubs / companies registered with the Sports Commissioner or Companies Commission of Malaysia and carrying out sports activities as listed under the Sports Development Act 1997\n | '039' // Supporting equipment for disabled person\n | '040' // Voluntary contribution to approved provident fund\n | '041' // Dental examination or treatment\n | '042' // Fertility treatment\n | '043' // Treatment and home care nursing, daycare centres and residential care centers\n | '044' // Vouchers, gift cards, loyalty points, etc\n | '045' // Self-billed - Non-monetary payment to agents, dealers or distributors\n\n/**\n * Enum representing the allowed classification codes with descriptive names.\n * Provides a more readable way to reference classification codes.\n *\n * @example\n * const code = ClassificationCodeEnum.ComputerSmartphoneOrTablet;\n * console.log(code); // Output: \"003\"\n */\nexport enum ClassificationCodeEnum {\n BreastfeedingEquipment = '001',\n ChildCareCentresAndKindergartensFees = '002',\n ComputerSmartphoneOrTablet = '003',\n ConsolidatedEInvoice = '004',\n ConstructionMaterials = '005',\n Disbursement = '006',\n Donation = '007',\n ECommerceEInvoiceToBuyer = '008',\n ECommerceSelfBilledToSellerLogistics = '009',\n EducationFees = '010',\n GoodsOnConsignmentConsignor = '011',\n GoodsOnConsignmentConsignee = '012',\n GymMembership = '013',\n InsuranceEducationMedicalBenefits = '014',\n InsuranceTakafulLife = '015',\n InterestFinancingExpenses = '016',\n InternetSubscription = '017',\n LandAndBuilding = '018',\n MedicalExamLearningDisabilities = '019',\n MedicalExamVaccination = '020',\n MedicalExpensesSeriousDiseases = '021',\n Others = '022',\n PetroleumOperations = '023',\n PrivateRetirementSchemeDeferredAnnuity = '024',\n MotorVehicle = '025',\n SubscriptionBooksJournalsEtc = '026',\n Reimbursement = '027',\n RentalOfMotorVehicle = '028',\n EVChargingFacilities = '029',\n RepairAndMaintenance = '030',\n ResearchAndDevelopment = '031',\n ForeignIncome = '032',\n SelfBilledBettingGaming = '033',\n SelfBilledImportationGoods = '034',\n SelfBilledImportationServices = '035',\n SelfBilledOthers = '036',\n SelfBilledMonetaryPaymentToAgents = '037',\n SportsEquipmentRentalFeesEtc = '038',\n SupportingEquipmentDisabledPerson = '039',\n VoluntaryContributionProvidentFund = '040',\n DentalExamTreatment = '041',\n FertilityTreatment = '042',\n TreatmentHomeCareNursingEtc = '043',\n VouchersGiftCardsLoyaltyPoints = '044',\n SelfBilledNonMonetaryPaymentToAgents = '045',\n}\n\n/**\n * Interface representing a classification code entry.\n * Contains the code and its corresponding description.\n */\nexport interface Classification {\n code: ClassificationCode\n description: string\n}\n"],"mappings":";;;;;;;;;;AA2DA,IAAY,4EAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACD"}
|
|
1
|
+
{"version":3,"file":"index8.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;EA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