diff --git a/LOCAL_ACCESS.md b/LOCAL_ACCESS.md new file mode 100644 index 0000000..4d7c7bd --- /dev/null +++ b/LOCAL_ACCESS.md @@ -0,0 +1,71 @@ +# Dùng AccManager qua mạng nội bộ khi tên miền hết hạn + +Máy chủ hiện tại vẫn chạy tại `172.20.235.176`. Có thể truy cập tạm bằng cách ánh xạ tên `accrobot.pnkr.asia` tới IP này trong file `hosts` của từng máy Windows. Trình duyệt vẫn mở `https://accrobot.pnkr.asia`, nhưng kết nối trực tiếp tới máy chủ trong LAN, không cần DNS công cộng của tên miền. + +Ứng dụng, dữ liệu SQL Server, tài khoản và cấu hình Docker hiện tại được giữ nguyên. Máy sử dụng cần kết nối mạng nội bộ hoặc VPN có đường tới `172.20.235.176`. + +## Thiết lập trên máy Windows + +1. Mở Start, tìm **Notepad**, bấm chuột phải và chọn **Run as administrator**. +2. Trong Notepad chọn **File → Open**, đổi bộ lọc thành **All files**, rồi mở: + + ```text + C:\Windows\System32\drivers\etc\hosts + ``` + +3. Thêm dòng sau vào cuối file rồi lưu. Nếu đã có dòng đang hoạt động cho đúng tên `accrobot.pnkr.asia`, sửa IP của dòng đó thay vì thêm trùng. Ghi lại IP cũ để hoàn tác; giữ nguyên các dòng của tên khác. + + ```text + 172.20.235.176 accrobot.pnkr.asia # AccManager temporary LAN + ``` + + File phải được lưu đúng tên `hosts`, không thêm đuôi `.txt`. + +4. Mở PowerShell hoặc Command Prompt với quyền Administrator và chạy: + + ```powershell + ipconfig /flushdns + ``` + +5. Đóng rồi mở lại trình duyệt, truy cập **https://accrobot.pnkr.asia** và đăng nhập như bình thường. + +Thực hiện trên từng máy cần dùng. Nếu cần áp dụng cho nhiều máy, quản trị mạng có thể tạo bản ghi DNS nội bộ tương đương, với điều kiện các máy sử dụng DNS nội bộ đó. + +## Kiểm tra + +Sau khi sửa `hosts`, chạy trong PowerShell: + +```powershell +curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 https://accrobot.pnkr.asia/api/health +``` + +Kết quả mong đợi có `"status":"ok"`. Mở trang đăng nhập và đăng nhập bằng tài khoản hiện có để kiểm tra phiên làm việc. + +Nếu chưa truy cập được, kiểm tra máy đang ở đúng LAN/VPN, dòng `hosts` không bị chú thích bằng `#` ở đầu, file không có đuôi `.txt`, rồi xóa cache DNS và mở lại trình duyệt. Nếu máy sử dụng proxy web, cần cho địa chỉ này đi trực tiếp qua LAN. + +### Kết quả kiểm tra ngày 10/09/2026 + +- `https://accrobot.pnkr.asia/api/health` qua IP `172.20.235.176` trả HTTP 200, `status: ok`. +- Trang `/pages/login.html` qua cùng đường kết nối trả HTTP 200. +- Xác minh TLS thành công; chứng chỉ cho `accrobot.pnkr.asia` hết hạn **29/10/2026 lúc 09:56:58 (giờ Việt Nam)**. +- Chưa kiểm tra đăng nhập bằng tài khoản người dùng. Phiên hỗ trợ không có quyền ghi file `hosts`, nên ánh xạ chưa được áp dụng tự động. + +Có thể kiểm tra đường kết nối trước khi sửa `hosts` bằng lệnh sau; lệnh chỉ áp dụng ánh xạ cho riêng lần gọi này: + +```powershell +curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 --resolve accrobot.pnkr.asia:443:172.20.235.176 https://accrobot.pnkr.asia/api/health +``` + +## Vì sao vẫn mở tên web thay vì gõ IP vào trình duyệt? + +Ánh xạ `hosts` sử dụng IP nội bộ để kết nối, đồng thời giữ tên HTTPS mà reverse proxy, chứng chỉ và cookie đăng nhập đang dùng. Truy cập bằng `https://172.20.235.176` không khớp tên chứng chỉ. Truy cập `http://172.20.235.176:3000` gặp cấu hình bắt buộc HTTPS và cookie Secure của ứng dụng hiện tại. + +Không cần sửa `.env`, chuyển `NODE_ENV` sang development, build image, khởi động lại container hay chuyển cơ sở dữ liệu cho phương án này. + +## Hoàn tác sau khi gia hạn tên miền + +1. Khi tên miền đã gia hạn và DNS công cộng hoạt động lại, mở file `hosts` với quyền Administrator. +2. Xóa riêng dòng có chú thích `# AccManager temporary LAN`; nếu đã sửa dòng có sẵn, khôi phục nội dung cũ. +3. Chạy `ipconfig /flushdns`, đóng rồi mở lại trình duyệt và truy cập địa chỉ web như trước. + +Ánh xạ chỉ giải quyết việc phân giải tên miền. Chứng chỉ HTTPS vẫn cần còn hạn; hoàn tất gia hạn hoặc bố trí chứng chỉ phù hợp trước mốc hết hạn nêu trên. diff --git a/README.md b/README.md index 7a3eced..8e943e7 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager ## Tài liệu liên quan - Hướng dẫn triển khai: [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md) +- Dùng tạm trong mạng nội bộ khi tên miền hết hạn: [LOCAL_ACCESS.md](LOCAL_ACCESS.md) ## Cau hinh email xac thuc dang ky diff --git a/public/js/app.js b/public/js/app.js index b03453f..91ecffb 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -2182,10 +2182,7 @@ class AccountManager { } setupEventListeners() { - // Modal close buttons - document.querySelectorAll('[data-close-modal]').forEach(btn => { - btn.addEventListener('click', () => this.closeModals()); - }); + this.setupModalCloseListeners(); // Close with Escape key document.addEventListener('keydown', (e) => { @@ -2336,30 +2333,12 @@ class AccountManager { confirmAssetRequestDeleteBtn.dataset.boundClick = 'true'; } - document.querySelectorAll('.cancel-asset-request-delete-confirm').forEach(btn => { - if (btn.dataset.boundClick === 'true') { - return; - } - - btn.addEventListener('click', () => this.resolveAssetRequestDeleteConfirm(false)); - btn.dataset.boundClick = 'true'; - }); - const confirmBulkAssetDeleteBtn = document.getElementById('confirmBulkAssetDeleteBtn'); if (confirmBulkAssetDeleteBtn && confirmBulkAssetDeleteBtn.dataset.boundClick !== 'true') { confirmBulkAssetDeleteBtn.addEventListener('click', () => this.resolveBulkAssetDeleteConfirm(true)); confirmBulkAssetDeleteBtn.dataset.boundClick = 'true'; } - document.querySelectorAll('.cancel-bulk-asset-delete-confirm').forEach(btn => { - if (btn.dataset.boundClick === 'true') { - return; - } - - btn.addEventListener('click', () => this.resolveBulkAssetDeleteConfirm(false)); - btn.dataset.boundClick = 'true'; - }); - this.setupAssetBorrowRequestModalListeners(); const assetDepartmentForm = document.getElementById('assetDepartmentForm'); @@ -2396,14 +2375,6 @@ class AccountManager { btn.dataset.boundClick = 'true'; }); - // Close when clicking backdrop outside modal content - document.querySelectorAll('.modal-backdrop').forEach(backdrop => { - backdrop.addEventListener('click', (evt) => { - if (evt.target === backdrop) { - this.closeModals(); - } - }); - }); } updateAccountDisplay() { @@ -5250,7 +5221,7 @@ class AccountManager { ${selectedStatusMeta.label} - @@ -5273,20 +5244,12 @@ class AccountManager {
- +
`; - const modal = document.getElementById('assetBorrowDetailsModal'); - if (modal) { - modal.addEventListener('click', event => { - if (event.target === modal) { - closeAssetBorrowDetailsModal(); - } - }); - } } setupAssetBorrowPagerListeners() { @@ -10827,6 +10790,53 @@ class AccountManager { document.getElementById('appModal').classList.add('open'); } + setupModalCloseListeners() { + if (this.modalCloseListenersBound) return; + + // Modals are loaded asynchronously and some forms are recreated on each open. + // Delegate clicks so both work without inline handlers blocked by CSP. + document.addEventListener('click', event => { + const closeButton = event.target.closest?.('[data-close-modal]'); + if (closeButton) { + event.preventDefault(); + const modalId = closeButton.dataset.closeModal + || closeButton.closest('.modal-backdrop')?.id; + if (modalId) this.closeModal(modalId); + return; + } + + if (event.target.classList?.contains('modal-backdrop')) { + this.closeModal(event.target.id); + } + }); + this.modalCloseListenersBound = true; + } + + closeModal(modalId) { + // These dialogs also own temporary state, child dialogs, or pending promises. + const closeHandlers = { + consumableBorrowRequestModal: closeConsumableBorrowRequestModal, + consumableBorrowRequestsModal: closeConsumableBorrowRequestsModal, + consumableRequestRejectModal: closeConsumableRequestRejectModal, + consumableReturnModal: closeConsumableReturnModal, + bulkDeleteAssetsConfirmModal: closeBulkDeleteAssetsConfirmModal, + assetBorrowRequestModal: closeAssetBorrowRequestModal, + assetPendingRequestsModal: closeAssetPendingRequestsModal, + assetRequestDeleteConfirmModal: closeAssetRequestDeleteConfirmModal, + userModal: closeUserModal, + roleModal: closeRoleModal, + userDetailsModal: closeUserDetailsModal, + profileModal: closeProfileModal, + notificationComposerModal: () => document.getElementById('notificationComposerModal')?.remove() + }; + + if (Object.hasOwn(closeHandlers, modalId)) { + closeHandlers[modalId](); + } else { + document.getElementById(modalId)?.classList.remove('open'); + } + } + closeModals() { if (this.pendingAssetRequestDeleteConfirmResolver) { this.resolveAssetRequestDeleteConfirm(false); @@ -10834,10 +10844,9 @@ class AccountManager { if (this.pendingBulkAssetDeleteConfirmResolver) { this.resolveBulkAssetDeleteConfirm(false); } - document.querySelectorAll('.modal-backdrop').forEach(modal => { - modal.classList.remove('open'); + document.querySelectorAll('.modal-backdrop.open').forEach(modal => { + this.closeModal(modal.id); }); - document.getElementById('notificationComposerModal')?.remove(); this.pendingConsumableRequestRejectId = undefined; } @@ -10926,7 +10935,7 @@ class AccountManager {
- +
@@ -10950,14 +10959,6 @@ class AccountManager { this.setupProfilePasswordToggles(); - const modal = document.getElementById('profileModal'); - if (modal) { - modal.addEventListener('click', (e) => { - if (e.target === modal) { - closeProfileModal(); - } - }); - } } setupProfilePasswordToggles() { @@ -11336,7 +11337,7 @@ class AccountManager {
- +
@@ -11359,14 +11360,6 @@ class AccountManager { form.addEventListener('submit', (e) => this.saveRole(e)); } - const modal = document.getElementById('roleModal'); - if (modal) { - modal.addEventListener('click', function(e) { - if (e.target === this) { - closeRoleModal(); - } - }); - } } async saveRole(e) { @@ -11456,7 +11449,7 @@ class AccountManager {
- +
@@ -11494,15 +11487,6 @@ class AccountManager { }); } - // Close on backdrop click - const modal = document.getElementById('userModal'); - if (modal) { - modal.addEventListener('click', function(e) { - if (e.target === this) { - closeUserModal(); - } - }); - } } async saveUser(e, userId) { @@ -11633,7 +11617,7 @@ class AccountManager {
- +
@@ -11659,7 +11643,6 @@ class AccountManager { const createdDateEl = document.getElementById('userDetailCreatedDate'); const lastLoginEl = document.getElementById('userDetailLastLogin'); const editBtn = document.getElementById('userDetailEditBtn'); - const detailsModal = document.getElementById('userDetailsModal'); if (usernameEl) usernameEl.textContent = user?.Username || '-'; if (fullNameEl) fullNameEl.textContent = user?.FullName || '-'; @@ -11675,13 +11658,6 @@ class AccountManager { }); } - if (detailsModal) { - detailsModal.addEventListener('click', function(e) { - if (e.target === this) { - closeUserDetailsModal(); - } - }); - } } async deleteUserConfirm(userId) { diff --git a/public/modals.html b/public/modals.html index 2226ad2..8e74814 100644 --- a/public/modals.html +++ b/public/modals.html @@ -3,7 +3,7 @@
- +
@@ -39,7 +39,7 @@
- +
@@ -83,7 +83,7 @@

Are you sure you want to delete the account for -? This action cannot be undone.

- +
@@ -95,7 +95,7 @@
- +
@@ -141,7 +141,7 @@
- +
@@ -191,7 +191,7 @@

Are you sure you want to delete -? This action cannot be undone.

- +
@@ -203,7 +203,7 @@
- +
@@ -305,7 +305,7 @@
- +
@@ -385,7 +385,7 @@

Bạn có chắc muốn xóa vật tư -? Hành động này không thể hoàn tác.

- +
@@ -396,7 +396,7 @@
- +
@@ -460,7 +460,7 @@

Tồn kho chỉ được trừ sau khi Asset/Admin chấp nhận đơn.

- +
@@ -537,7 +537,7 @@

Đơn mượn vật tư của tôi

Theo dõi trạng thái các đơn đã gửi.

- @@ -575,7 +575,7 @@
- +
@@ -598,7 +598,7 @@

Khi xác nhận, số lượng này sẽ được cộng lại vào tồn kho ngay.

- +
@@ -644,7 +644,7 @@
- +
@@ -741,7 +741,7 @@
- +
@@ -801,7 +801,7 @@ - + diff --git a/test/modal-close.test.js b/test/modal-close.test.js new file mode 100644 index 0000000..1bca5d0 --- /dev/null +++ b/test/modal-close.test.js @@ -0,0 +1,240 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const appSource = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8'); + +// A small DOM fixture lets the actual event handler and cleanup methods run +// without starting authentication, network requests, or the application itself. +function createFixture() { + const elements = []; + const listeners = new Map(); + class Element { + constructor({ id = '', classes = [], dataset = {}, parent = null } = {}) { + this.id = id; + this.dataset = dataset; + this.parentElement = parent; + this.children = []; + this.value = ''; + this.isConnected = true; + const names = new Set(classes); + this.classList = { + contains: name => names.has(name), + add: (...added) => added.forEach(name => names.add(name)), + remove: (...removed) => removed.forEach(name => names.delete(name)) + }; + if (parent) parent.children.push(this); + elements.push(this); + } + matches(selector) { + if (selector === '[data-close-modal]') return 'closeModal' in this.dataset; + if (selector.startsWith('.')) { + return selector.slice(1).split('.').every(name => this.classList.contains(name)); + } + return false; + } + closest(selector) { + return this.matches(selector) ? this : this.parentElement?.closest(selector) || null; + } + getAttribute(name) { + return name === 'data-close-modal' ? this.dataset.closeModal ?? null : null; + } + remove() { + this.isConnected = false; + this.children.forEach(child => child.remove()); + } + set innerHTML(value) { + assert.equal(value, '', 'The fixture only supports clearing an existing container'); + this.children.forEach(child => child.remove()); + this.children = []; + } + get innerHTML() { + return this.children.length ? '' : ''; + } + } + const document = { + addEventListener(type, handler) { + if (!listeners.has(type)) listeners.set(type, []); + listeners.get(type).push(handler); + }, + getElementById: id => elements.find(node => node.id === id && node.isConnected) || null, + querySelectorAll: selector => elements.filter(node => node.isConnected && node.matches(selector)), + contains: node => node.isConnected + }; + const context = vm.createContext({ + document, + Element, + HTMLElement: Element, + window: { fetch: async () => { throw new Error('Unexpected network request'); } }, + console + }); + vm.runInContext(`${appSource}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context); + const add = options => new Element(options); + const modal = (id, parent) => add({ id, parent, classes: ['modal-backdrop', 'open'] }); + function dispatch(type, target, properties = {}) { + const event = { + target, + defaultPrevented: false, + preventDefault() { this.defaultPrevented = true; }, + stopPropagation() {}, + ...properties + }; + (listeners.get(type) || []).forEach(handler => handler(event)); + return event; + } + return { manager: context.manager, document, listeners, add, modal, dispatch }; +} + +test('close buttons work after asynchronous modal insertion, including clicks on the icon', async () => { + const fixture = createFixture(); + fixture.manager.setupModalCloseListeners(); + await Promise.resolve(); // modals.html is fetched after listeners are installed. + const parent = fixture.modal('accountModal'); + const other = fixture.modal('assetModal'); + const button = fixture.add({ parent, dataset: { closeModal: 'accountModal' } }); + const icon = fixture.add({ parent: button }); + + const event = fixture.dispatch('click', icon); + + assert.equal(parent.classList.contains('open'), false); + assert.equal(other.classList.contains('open'), true); + assert.equal(event.defaultPrevented, true); + + parent.classList.add('open'); + fixture.dispatch('click', button); + assert.equal(parent.classList.contains('open'), false); +}); + +test('repeated setup installs one modal close handler', () => { + const fixture = createFixture(); + fixture.manager.setupModalCloseListeners(); + fixture.manager.setupModalCloseListeners(); + const target = fixture.add({ dataset: { closeModal: 'accountModal' } }); + const closed = []; + fixture.manager.closeModal = id => closed.push(id); + + fixture.dispatch('click', target); + + assert.deepEqual(closed, ['accountModal']); + assert.equal(fixture.listeners.get('click').length, 1); +}); + +test('backdrop clicks close their dialog, while clicks inside the form leave it open', () => { + const fixture = createFixture(); + fixture.manager.setupModalCloseListeners(); + const modal = fixture.modal('assetModal'); + const other = fixture.modal('accountModal'); + const content = fixture.add({ parent: modal }); + const input = fixture.add({ parent: content }); + + fixture.dispatch('click', input); + assert.equal(modal.classList.contains('open'), true); + fixture.dispatch('click', modal); + assert.equal(modal.classList.contains('open'), false); + assert.equal(other.classList.contains('open'), true); +}); + +test('canceling destructive confirmations resolves false exactly once', async () => { + for (const [modalId, resolverField] of [ + ['assetRequestDeleteConfirmModal', 'pendingAssetRequestDeleteConfirmResolver'], + ['bulkDeleteAssetsConfirmModal', 'pendingBulkAssetDeleteConfirmResolver'] + ]) { + const fixture = createFixture(); + fixture.manager.setupModalCloseListeners(); + const modal = fixture.modal(modalId); + const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } }); + const resolutions = []; + const pending = new Promise(resolve => { + fixture.manager[resolverField] = value => { + resolutions.push(value); + resolve(value); + }; + }); + + fixture.dispatch('click', button); + fixture.dispatch('click', button); + + assert.equal(await pending, false); + assert.deepEqual(resolutions, [false]); + assert.equal(fixture.manager[resolverField], undefined); + assert.equal(modal.classList.contains('open'), false); + } +}); + +test('closing consumable rejection and return dialogs clears pending input state', () => { + const fixture = createFixture(); + const rejectModal = fixture.modal('consumableRequestRejectModal'); + const idInput = fixture.add({ id: 'consumableRequestRejectIdInput', parent: rejectModal }); + const reasonInput = fixture.add({ id: 'consumableRequestRejectReasonInput', parent: rejectModal }); + idInput.value = '42'; + reasonInput.value = 'Previous reason'; + fixture.manager.pendingConsumableRequestRejectId = 42; + fixture.manager.closeModal(rejectModal.id); + assert.equal(rejectModal.classList.contains('open'), false); + assert.equal(idInput.value, ''); + assert.equal(reasonInput.value, ''); + assert.equal(fixture.manager.pendingConsumableRequestRejectId, undefined); + + const returnModal = fixture.modal('consumableReturnModal'); + fixture.manager.pendingConsumableReturnHistoryId = 99; + fixture.manager.closeModal(returnModal.id); + assert.equal(returnModal.classList.contains('open'), false); + assert.equal(fixture.manager.pendingConsumableReturnHistoryId, undefined); +}); + +test('closing dynamic user, role, profile and detail dialogs clears their containers', () => { + for (const modalId of ['userModal', 'roleModal', 'profileModal', 'userDetailsModal']) { + const fixture = createFixture(); + fixture.manager.setupModalCloseListeners(); + const container = fixture.add({ id: `${modalId}Container` }); + const modal = fixture.modal(modalId, container); + const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } }); + + fixture.dispatch('click', button); + + assert.equal(container.innerHTML, '', modalId); + assert.equal(fixture.document.getElementById(modalId), null, modalId); + } +}); + +test('Escape closes dialogs through their cleanup handlers', () => { + const fixture = createFixture(); + for (const method of [ + 'updateAccountDisplay', 'setupAccountRowListeners', 'setupFilters', + 'setupResponsiveShell', 'closeMobileNav', 'closeNotificationPopover' + ]) fixture.manager[method] = () => {}; + fixture.manager.setupEventListeners(); + const confirmation = fixture.modal('bulkDeleteAssetsConfirmModal'); + let resolution; + fixture.manager.pendingBulkAssetDeleteConfirmResolver = value => { resolution = value; }; + const container = fixture.add({ id: 'profileModalContainer' }); + fixture.modal('profileModal', container); + const notification = fixture.modal('notificationComposerModal'); + + fixture.dispatch('keydown', null, { key: 'Escape' }); + + assert.equal(confirmation.classList.contains('open'), false); + assert.equal(resolution, false); + assert.equal(container.innerHTML, ''); + assert.equal(notification.isConnected, false); +}); + +test('closing a missing modal is harmless', () => { + const fixture = createFixture(); + assert.doesNotThrow(() => fixture.manager.closeModal('alreadyRemovedModal')); +}); + +test('static and dynamic modal close controls avoid inline scripts and form submission', () => { + for (const relativePath of ['public/modals.html', 'public/pages/index.html', 'public/js/app.js']) { + const source = fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8'); + assert.doesNotMatch(source, /\bonclick\s*=\s*["'][^"']*\bclose\w*Modal\s*\(/i, relativePath); + const closeButtons = [...source.matchAll(/]*\bdata-close-modal\s*=\s*["'][^"']+["'][^>]*>/g)]; + if (relativePath !== 'public/pages/index.html') assert.ok(closeButtons.length > 0, relativePath); + for (const [button] of closeButtons) { + assert.match(button, /\btype\s*=\s*["']button["']/, `${relativePath}: ${button}`); + assert.doesNotMatch(button, /\bonclick\s*=/, `${relativePath}: ${button}`); + } + } +}); diff --git a/test/security.test.js b/test/security.test.js index 38fa56c..7cabd7b 100644 --- a/test/security.test.js +++ b/test/security.test.js @@ -127,6 +127,7 @@ test('security headers and no-store API caching are enabled', async () => { assert.equal(response.status, 200); assert.match(response.headers.get('content-security-policy') || '', /default-src 'self'/); + assert.match(response.headers.get('content-security-policy') || '', /script-src-attr 'none'/); assert.equal(response.headers.get('x-powered-by'), null); assert.equal(response.headers.get('cache-control'), 'no-store'); });