mirror of
https://github.com/UNITRONIX/BetterDesk.git
synced 2026-11-24 01:52:12 +00:00
fix(devices): use Go address book as alias source
Route panel alias reads and writes through the Go-owned RustDesk address book so legacy SQLite, consolidated SQLite, and PostgreSQL deployments do not diverge into auth.db. Preserve the full legacy document and serialize panel/client writes. Refs #510 Reported-by: @PeterLinuxOSS Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow); muopc (@muopc)
This commit is contained in:
+5
-1
@@ -1,7 +1,11 @@
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- _(none yet)_
|
||||
- Devices address-book aliases in BetterDesk mode now read and write the Go-owned
|
||||
`address_books` data through the panel trust bridge, so legacy RustDesk clients,
|
||||
SQLite consolidated/legacy deployments and PostgreSQL use the same source of
|
||||
truth. The full legacy address-book document remains intact when one alias is
|
||||
changed.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -466,7 +466,10 @@ func (s *Server) handleClientAddressBook(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "Address book too large"})
|
||||
return
|
||||
}
|
||||
if err := s.db.SaveAddressBook(username, "legacy", dataStr); err != nil {
|
||||
s.addressBookMu.Lock()
|
||||
err = s.db.SaveAddressBook(username, "legacy", dataStr)
|
||||
s.addressBookMu.Unlock()
|
||||
if err != nil {
|
||||
log.Printf("[api] SaveAddressBook error for %s: %v", username, err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Internal error"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/unitronix/betterdesk-server/db"
|
||||
)
|
||||
|
||||
const panelAddressBookAliasMaxLength = 128
|
||||
|
||||
type panelAddressBookAliasRequest struct {
|
||||
Alias string `json:"alias"`
|
||||
}
|
||||
|
||||
// sanitizePanelAddressBookAlias keeps the panel write compatible with the
|
||||
// legacy RustDesk client, which stores aliases as ordinary peer strings.
|
||||
func sanitizePanelAddressBookAlias(value string) string {
|
||||
value = strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) && r != '\t' && r != '\n' && r != '\r' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, value)
|
||||
value = strings.TrimSpace(value)
|
||||
runes := []rune(value)
|
||||
if len(runes) > panelAddressBookAliasMaxLength {
|
||||
runes = runes[:panelAddressBookAliasMaxLength]
|
||||
}
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
// updateAddressBookPeerAlias changes only peers[].alias in a legacy address
|
||||
// book document. The map-based representation deliberately preserves all
|
||||
// unknown top-level, peer, tag and hash fields.
|
||||
func updateAddressBookPeerAlias(data, peerID, alias string) (string, bool, error) {
|
||||
book := parseAddressBookMap(data)
|
||||
id := strings.TrimSpace(peerID)
|
||||
alias = sanitizePanelAddressBookAlias(alias)
|
||||
|
||||
var target map[string]any
|
||||
for _, rawPeer := range toPeerSlice(book["peers"]) {
|
||||
if strings.TrimSpace(stringValue(rawPeer["id"])) != id {
|
||||
continue
|
||||
}
|
||||
target = rawPeer
|
||||
}
|
||||
found := target != nil
|
||||
if found {
|
||||
target["alias"] = alias
|
||||
} else if id != "" && alias != "" {
|
||||
peers := append(toPeerSlice(book["peers"]), map[string]any{
|
||||
"id": id,
|
||||
"alias": alias,
|
||||
})
|
||||
book["peers"] = peersToAny(peers)
|
||||
found = true
|
||||
}
|
||||
|
||||
encoded, err := json.Marshal(book)
|
||||
if err != nil {
|
||||
return "", found, err
|
||||
}
|
||||
return string(encoded), found, nil
|
||||
}
|
||||
|
||||
func stringValue(value any) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
valueString, _ := value.(string)
|
||||
return valueString
|
||||
}
|
||||
|
||||
// handlePanelAddressBookAlias updates the current operator's legacy
|
||||
// RustDesk address book in the Go-owned database. It intentionally does not
|
||||
// use the merged GET /api/ab document as the write source: that response may
|
||||
// include organization overlays and ACL filtering.
|
||||
func (s *Server) handlePanelAddressBookAlias(w http.ResponseWriter, r *http.Request) {
|
||||
username := getUsernameFromCtx(r)
|
||||
role := getRoleFromCtx(r)
|
||||
peerID := strings.TrimSpace(r.PathValue("id"))
|
||||
if username == "" || peerID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid address book peer"})
|
||||
return
|
||||
}
|
||||
|
||||
peer, err := s.db.GetPeer(peerID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Internal error"})
|
||||
return
|
||||
}
|
||||
if peer == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "Device not found"})
|
||||
return
|
||||
}
|
||||
|
||||
user := s.rustDeskUserForGroups(r, username, role)
|
||||
peerByID := map[string]*db.Peer{peerID: peer}
|
||||
visible := s.rustDeskVisiblePeerSet(user, role, peerByID)
|
||||
if visible != nil && !visible[peerID] {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "Device is outside your scope"})
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
|
||||
var request panelAddressBookAliasRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
s.addressBookMu.Lock()
|
||||
defer s.addressBookMu.Unlock()
|
||||
|
||||
data, err := s.db.GetAddressBook(username, "legacy")
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Internal error"})
|
||||
return
|
||||
}
|
||||
updated, _, err := updateAddressBookPeerAlias(data, peerID, request.Alias)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Internal error"})
|
||||
return
|
||||
}
|
||||
if len(updated) > 512*1024 {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "Address book too large"})
|
||||
return
|
||||
}
|
||||
if err := s.db.SaveAddressBook(username, "legacy", updated); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"address_book_alias": sanitizePanelAddressBookAlias(request.Alias),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdateAddressBookPeerAliasPreservesDocument(t *testing.T) {
|
||||
input := `{"hash":"book-hash","tag_colors":{"Ops":"#ff0000"},"tags":["Ops"],"peers":[{"id":"PEER1","hash":"peer-hash","tags":["Ops"],"unknown":{"keep":true},"alias":"old"}]}`
|
||||
|
||||
output, found, err := updateAddressBookPeerAlias(input, "PEER1", " New alias ")
|
||||
if err != nil {
|
||||
t.Fatalf("updateAddressBookPeerAlias: %v", err)
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("expected existing peer to be found")
|
||||
}
|
||||
|
||||
var book map[string]any
|
||||
if err := json.Unmarshal([]byte(output), &book); err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
if book["hash"] != "book-hash" {
|
||||
t.Fatalf("top-level hash was not preserved: %#v", book["hash"])
|
||||
}
|
||||
peers := toPeerSlice(book["peers"])
|
||||
if len(peers) != 1 {
|
||||
t.Fatalf("peer count = %d, want 1", len(peers))
|
||||
}
|
||||
if peers[0]["alias"] != "New alias" || peers[0]["hash"] != "peer-hash" {
|
||||
t.Fatalf("peer fields were not preserved/updated: %#v", peers[0])
|
||||
}
|
||||
if unknown, ok := peers[0]["unknown"].(map[string]any); !ok || unknown["keep"] != true {
|
||||
t.Fatalf("unknown peer fields were not preserved: %#v", peers[0]["unknown"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAddressBookPeerAliasAddsAndClears(t *testing.T) {
|
||||
output, found, err := updateAddressBookPeerAlias(`{"peers":[]}`, "PEER2", "Added")
|
||||
if err != nil {
|
||||
t.Fatalf("add alias: %v", err)
|
||||
}
|
||||
if !found || len(toPeerSlice(parseAddressBookMap(output)["peers"])) != 1 {
|
||||
t.Fatalf("expected a new peer alias, found=%v output=%s", found, output)
|
||||
}
|
||||
|
||||
output, found, err = updateAddressBookPeerAlias(output, "PEER2", "")
|
||||
if err != nil {
|
||||
t.Fatalf("clear alias: %v", err)
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("expected added peer to be found when clearing alias")
|
||||
}
|
||||
peers := toPeerSlice(parseAddressBookMap(output)["peers"])
|
||||
if peers[0]["alias"] != "" {
|
||||
t.Fatalf("alias = %#v, want empty", peers[0]["alias"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAddressBookPeerAliasUsesLastDuplicate(t *testing.T) {
|
||||
input := `{"peers":[{"id":"PEER3","alias":"first"},{"id":"PEER3","alias":"last"}]}`
|
||||
output, _, err := updateAddressBookPeerAlias(input, "PEER3", "updated")
|
||||
if err != nil {
|
||||
t.Fatalf("update duplicate alias: %v", err)
|
||||
}
|
||||
peers := toPeerSlice(parseAddressBookMap(output)["peers"])
|
||||
if peers[0]["alias"] != "first" || peers[1]["alias"] != "updated" {
|
||||
t.Fatalf("duplicate update changed the wrong peers: %#v", peers)
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,7 @@ type Server struct {
|
||||
panelStore db.PanelSyncStore // device groups, folders, ACL (PostgreSQL or legacy auth.db)
|
||||
panelTrustSecret []byte // HMAC key for panel-originated requests (nil = bridge off)
|
||||
panelNonces *panelNonceCache // replay window for verified panel statements
|
||||
addressBookMu sync.Mutex // serializes legacy AB read/modify/write operations
|
||||
timeSync *timesync.Service
|
||||
billing *billing.Service
|
||||
peerVault *peervault.Vault // AES-GCM for org peer credentials (#367)
|
||||
@@ -545,6 +546,8 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
// role-default definitions (strangler stage P3). Every signed-in principal
|
||||
// may read it: each role needs it to render its own navigation.
|
||||
mux.HandleFunc("GET /api/panel/catalog", s.handlePanelCatalog)
|
||||
mux.HandleFunc("PATCH /api/panel/address-book/peers/{id}/alias",
|
||||
s.requirePermission(auth.PermDeviceView, s.handlePanelAddressBookAlias))
|
||||
|
||||
// Time sync / billing (commercialization)
|
||||
mux.HandleFunc("GET /api/timesync/status", s.requirePermission(auth.PermBillingView, s.handleTimeSyncStatus))
|
||||
|
||||
@@ -14,8 +14,6 @@ const tagManagementService = require('../services/tagManagementService');
|
||||
const { requireAuth, requirePermission, requestHasPermission } = require('../middleware/auth');
|
||||
const { bodyInt, bodyString, bodyBool, plainBodyObject } = require('../lib/bodyScalars');
|
||||
|
||||
const legacyAddressBookLocks = new Map();
|
||||
|
||||
/**
|
||||
* GET /devices - Devices list page
|
||||
*/
|
||||
@@ -50,14 +48,15 @@ function mapChangeIdError(req, error) {
|
||||
|
||||
async function getLegacyAddressBookAliasMap(req) {
|
||||
const aliases = new Map();
|
||||
const userId = req.session?.user?.id || req.session?.userId;
|
||||
if (!userId || typeof db.getAddressBook !== 'function') return aliases;
|
||||
|
||||
try {
|
||||
const row = await db.getAddressBook(userId, 'legacy');
|
||||
return addressBookSync.buildLegacyAliasMap(row?.data);
|
||||
const result = await betterdeskApi.getPanelLegacyAddressBook(req);
|
||||
if (!result.success) {
|
||||
console.warn('[API:DEVICES] Failed to read Go legacy address book:', result.error);
|
||||
return aliases;
|
||||
}
|
||||
return addressBookSync.buildLegacyAliasMap(result.data?.data);
|
||||
} catch (err) {
|
||||
console.warn('[API:DEVICES] Failed to read legacy address book aliases:', err.message);
|
||||
console.warn('[API:DEVICES] Failed to read Go legacy address book aliases:', err.message);
|
||||
return aliases;
|
||||
}
|
||||
}
|
||||
@@ -69,27 +68,6 @@ async function enrichDeviceWithAddressBookAlias(req, device, aliases) {
|
||||
return device;
|
||||
}
|
||||
|
||||
async function withLegacyAddressBookLock(userId, operation) {
|
||||
const key = String(userId);
|
||||
const previous = legacyAddressBookLocks.get(key) || Promise.resolve();
|
||||
let release;
|
||||
const current = new Promise(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
const queue = previous.catch(() => {}).then(() => current);
|
||||
legacyAddressBookLocks.set(key, queue);
|
||||
|
||||
await previous.catch(() => {});
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
release();
|
||||
if (legacyAddressBookLocks.get(key) === queue) {
|
||||
legacyAddressBookLocks.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
router.get('/api/devices', requireAuth, requirePermission('device.view'), async (req, res) => {
|
||||
try {
|
||||
// Validate and sanitize sort parameters
|
||||
@@ -1038,21 +1016,15 @@ router.patch('/api/devices/:id/address-book-alias', requireAuth, requirePermissi
|
||||
}
|
||||
if (await rejectIfDeviceOutOfScope(req, res, device)) return;
|
||||
|
||||
const userId = req.session.user?.id || req.session.userId;
|
||||
if (!userId || typeof db.getAddressBook !== 'function' || typeof db.saveAddressBook !== 'function') {
|
||||
return res.status(500).json({
|
||||
const alias = addressBookSync.sanitizeAlias(rawAlias);
|
||||
const result = await betterdeskApi.updatePanelLegacyAddressBookAlias(id, alias, req);
|
||||
if (!result.success) {
|
||||
return res.status(result.status || 502).json({
|
||||
success: false,
|
||||
error: req.t('errors.server_error')
|
||||
error: result.error || req.t('errors.server_error')
|
||||
});
|
||||
}
|
||||
|
||||
const alias = addressBookSync.sanitizeAlias(rawAlias);
|
||||
await withLegacyAddressBookLock(userId, async () => {
|
||||
const row = await db.getAddressBook(userId, 'legacy');
|
||||
const data = addressBookSync.updateLegacyPeerAlias(row?.data, id, alias);
|
||||
await db.saveAddressBook(userId, data, 'legacy');
|
||||
});
|
||||
|
||||
try {
|
||||
await db.logAction(
|
||||
req.session.userId,
|
||||
|
||||
@@ -742,6 +742,55 @@ function panelCallConfig(method, path, req) {
|
||||
return Object.keys(headers).length ? { headers } : undefined;
|
||||
}
|
||||
|
||||
function panelTrustConfigOrError(method, path, req) {
|
||||
if (!panelTrust.panelTrustEnabled()) {
|
||||
return { error: 'Panel trust bridge is not configured', status: 503 };
|
||||
}
|
||||
const config = panelCallConfig(method, path, req);
|
||||
if (!config) {
|
||||
return { error: 'Panel operator identity is unavailable', status: 401 };
|
||||
}
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Read the current operator's RustDesk legacy address book from Go. */
|
||||
async function getPanelLegacyAddressBook(req) {
|
||||
const trust = panelTrustConfigOrError('GET', '/api/ab', req);
|
||||
if (trust.error) return { success: false, error: trust.error, status: trust.status };
|
||||
try {
|
||||
const { data } = await apiClient.get('/ab', trust.config);
|
||||
return wrap(data);
|
||||
} catch (e) {
|
||||
return {
|
||||
success: false,
|
||||
error: e.response?.data?.error || e.message,
|
||||
status: e.response?.status
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Update one alias in the current operator's Go-owned legacy address book. */
|
||||
async function updatePanelLegacyAddressBookAlias(peerId, alias, req) {
|
||||
const safePeerId = assertSafeApiId(peerId, 'peerId');
|
||||
const path = `/api/panel/address-book/peers/${encodeURIComponent(safePeerId)}/alias`;
|
||||
const trust = panelTrustConfigOrError('PATCH', path, req);
|
||||
if (trust.error) return { success: false, error: trust.error, status: trust.status };
|
||||
try {
|
||||
const { data } = await apiClient.patch(
|
||||
`/panel/address-book/peers/${encodeURIComponent(safePeerId)}/alias`,
|
||||
{ alias },
|
||||
trust.config
|
||||
);
|
||||
return wrap(data);
|
||||
} catch (e) {
|
||||
return {
|
||||
success: false,
|
||||
error: e.response?.data?.error || e.message,
|
||||
status: e.response?.status
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Panel section catalog, permission vocabulary and role defaults (stage P3). */
|
||||
async function getPanelCatalog(config) {
|
||||
try {
|
||||
@@ -1917,6 +1966,8 @@ module.exports = {
|
||||
acknowledgeHelpRequest,
|
||||
resolveHelpRequest,
|
||||
// Panel catalog and grouping (strangler P2/P3)
|
||||
getPanelLegacyAddressBook,
|
||||
updatePanelLegacyAddressBookAlias,
|
||||
getPanelCatalog,
|
||||
listPanelDeviceGroups,
|
||||
savePanelDeviceGroup,
|
||||
|
||||
@@ -8,7 +8,15 @@ const { createTestApp } = require('./helpers');
|
||||
jest.mock('../services/betterdeskApi', () => ({
|
||||
getPeerTelemetry: jest.fn().mockResolvedValue({ success: false }),
|
||||
getConnectionMode: jest.fn().mockResolvedValue({ success: true, data: { controllable: false } }),
|
||||
setConnectionMode: jest.fn()
|
||||
setConnectionMode: jest.fn(),
|
||||
getPanelLegacyAddressBook: jest.fn().mockResolvedValue({
|
||||
success: true,
|
||||
data: { data: '{}' }
|
||||
}),
|
||||
updatePanelLegacyAddressBookAlias: jest.fn().mockResolvedValue({
|
||||
success: true,
|
||||
data: { address_book_alias: '' }
|
||||
})
|
||||
}));
|
||||
|
||||
// Mock dependencies
|
||||
@@ -110,10 +118,13 @@ describe('Devices Routes', () => {
|
||||
{ id: '123456789', hostname: 'PC-1' },
|
||||
{ id: '987654321', hostname: 'PC-2' }
|
||||
]);
|
||||
db.getAddressBook.mockResolvedValue({
|
||||
data: JSON.stringify({
|
||||
peers: [{ id: '123456789', alias: 'Office PC' }]
|
||||
})
|
||||
betterdeskApi.getPanelLegacyAddressBook.mockResolvedValue({
|
||||
success: true,
|
||||
data: {
|
||||
data: JSON.stringify({
|
||||
peers: [{ id: '123456789', alias: 'Office PC' }]
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/devices');
|
||||
@@ -123,7 +134,7 @@ describe('Devices Routes', () => {
|
||||
expect.objectContaining({ id: '123456789', address_book_alias: 'Office PC' }),
|
||||
expect.objectContaining({ id: '987654321', address_book_alias: '' })
|
||||
]));
|
||||
expect(db.getAddressBook).toHaveBeenCalledWith(1, 'legacy');
|
||||
expect(betterdeskApi.getPanelLegacyAddressBook).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should sanitize sort parameters', async () => {
|
||||
@@ -254,8 +265,11 @@ describe('Devices Routes', () => {
|
||||
id: '123456789',
|
||||
hostname: 'PC-1'
|
||||
});
|
||||
db.getAddressBook.mockResolvedValue({
|
||||
data: JSON.stringify({ peers: [{ id: '123456789', alias: 'Office PC' }] })
|
||||
betterdeskApi.getPanelLegacyAddressBook.mockResolvedValue({
|
||||
success: true,
|
||||
data: {
|
||||
data: JSON.stringify({ peers: [{ id: '123456789', alias: 'Office PC' }] })
|
||||
}
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/devices/123456789');
|
||||
@@ -268,18 +282,9 @@ describe('Devices Routes', () => {
|
||||
describe('PATCH /api/devices/:id/address-book-alias', () => {
|
||||
it('updates one alias in the legacy address book without changing other fields', async () => {
|
||||
serverBackend.getDeviceById.mockResolvedValue({ id: '123456789', hostname: 'PC-1' });
|
||||
db.getAddressBook.mockResolvedValue({
|
||||
data: JSON.stringify({
|
||||
peers: [{
|
||||
id: '123456789',
|
||||
alias: 'Old name',
|
||||
hash: 'keep-hash',
|
||||
tags: ['Office'],
|
||||
extra: true
|
||||
}],
|
||||
tags: ['Office'],
|
||||
tag_colors: '{"Office":123}'
|
||||
})
|
||||
betterdeskApi.updatePanelLegacyAddressBookAlias.mockResolvedValue({
|
||||
success: true,
|
||||
data: { address_book_alias: 'New name' }
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
@@ -288,33 +293,21 @@ describe('Devices Routes', () => {
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.data.address_book_alias).toBe('New name');
|
||||
expect(db.saveAddressBook).toHaveBeenCalledWith(
|
||||
1,
|
||||
expect.any(String),
|
||||
'legacy'
|
||||
);
|
||||
const saved = JSON.parse(db.saveAddressBook.mock.calls[0][1]);
|
||||
expect(saved.peers[0]).toEqual(expect.objectContaining({
|
||||
id: '123456789',
|
||||
alias: 'New name',
|
||||
hash: 'keep-hash',
|
||||
tags: ['Office'],
|
||||
extra: true
|
||||
}));
|
||||
expect(saved.tag_colors).toBe('{"Office":123}');
|
||||
expect(betterdeskApi.updatePanelLegacyAddressBookAlias)
|
||||
.toHaveBeenCalledWith('123456789', 'New name', expect.any(Object));
|
||||
expect(db.saveAddressBook).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates a legacy address book peer when assigning a new alias', async () => {
|
||||
serverBackend.getDeviceById.mockResolvedValue({ id: 'NEW123', hostname: 'PC-1' });
|
||||
db.getAddressBook.mockResolvedValue({ data: '{}' });
|
||||
|
||||
const res = await request(app)
|
||||
.patch('/api/devices/NEW123/address-book-alias')
|
||||
.send({ alias: 'New device' });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const saved = JSON.parse(db.saveAddressBook.mock.calls[0][1]);
|
||||
expect(saved.peers).toEqual([{ id: 'NEW123', alias: 'New device' }]);
|
||||
expect(betterdeskApi.updatePanelLegacyAddressBookAlias)
|
||||
.toHaveBeenCalledWith('NEW123', 'New device', expect.any(Object));
|
||||
});
|
||||
|
||||
it('rejects aliases longer than the client-compatible limit', async () => {
|
||||
|
||||
Reference in New Issue
Block a user