DEV Community

SameX
SameX

Posted on

Security and Permission Management of Cross-device Clipboard in HarmonyOS Next

In the multi-device ecosystem of HarmonyOS Next, the cross-device clipboard has greatly improved the efficiency of users' data interaction between different devices. However, with the flow of data between devices, security and permission management have become crucial issues. Today, we will conduct an in-depth discussion on the relevant content of the cross-device clipboard in this regard.

Data Security Risks of the Clipboard (Risk of Unauthorized Data Synchronization)

While bringing convenience to users, the cross-device clipboard also introduces potential data security risks, among which the risk of unauthorized data synchronization is particularly prominent. Since the cross-device clipboard involves data transmission between multiple devices, if the security mechanism is not perfect, it is possible for data to be obtained by unauthorized devices. For example, after a user's multiple devices are logged in with the same Huawei account, under certain abnormal circumstances, malicious software may exploit vulnerabilities to obtain clipboard data, resulting in the leakage of users' sensitive information (such as passwords, ID numbers, etc.).

In addition, during the data transmission process, if the encryption measures of the transmission channel are not in place, the data may also be stolen or tampered with. Although HarmonyOS Next has adopted a variety of security protection measures in its design, developers still need to attach great importance to these potential risks when using the cross-device clipboard to ensure that the application will not cause security problems due to its own vulnerabilities during use.

Permission Management and User Authorization Mechanism (How to Correctly Apply for the ohos.permission.READ_PASTEBOARD Permission)

In order to ensure the security of clipboard data, HarmonyOS Next has established a strict permission management and user authorization mechanism. When using the cross-device clipboard, if an application wants to access the clipboard in the background of a custom control, it needs to apply for the ohos.permission.READ_PASTEBOARD permission.

Starting from API 12, there is no need to apply for the ohos.permission.DISTRIBUTED_DATASYNC permission. However, for API 11 and previous versions, this permission also needs to be declared and a pop-up window should be shown to request user authorization when the application is first launched or enters the continuation page. For the application of the ohos.permission.READ_PASTEBOARD permission, developers need to follow the standardized process.

In the application code, the permission requirements should first be clearly defined in the relevant module. For example, declare the permission in the module.json5 file:

{
    "module": {
        "abilities": [
            {
                "permissions": [
                    "ohos.permission.READ_PASTEBOARD"
                ]
            }
        ]
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, in the code logic where access to the clipboard is required, carefully perform permission checking and application operations. Take ArkTS code as an example:

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';
import { hilog, LogLevel } from '@ohos.hilog';

async function readClipboardData() {
    if (!await checkPermission('ohos.permission.READ_PASTEBOARD')) {
        // Apply for permission
        let result = await requestPermission('ohos.permission.READ_PASTEBOARD');
        if (!result) {
            hilog.log(LogLevel.ERROR, 0x0010, 'Permission request failed');
            return;
        }
    }
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    systemPasteBoard.getData((err: BusinessError, data: pasteboard.PasteData) => {
        if (err) {
            hilog.error(0x0010, `Failed to get pastedata. Code: ${err.code}, message: ${err.message}`);
            return;
        }
        // Process clipboard data
        let primaryText: string = data.getPrimaryText();
        hilog.info(0x0010, `Clipboard text: ${primaryText}`);
    });
}
Enter fullscreen mode Exit fullscreen mode

In the above code, checkPermission and requestPermission are custom functions for checking and applying for permissions (which can be implemented with reference to the official documentation in actual development). Through such a process, it is ensured that the application has obtained the user's explicit authorization before accessing the clipboard data, thus protecting the user's privacy and data security.

Best Practices: How to Use the Clipboard Efficiently while Ensuring Security (Code Examples)

In actual development, developers need to make full use of the cross-device clipboard to enhance the user experience of the application while ensuring security. The following takes a simple cross-device text synchronization application as an example to show the best practices.

Device A (Copying End)

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';
import { hilog, LogLevel } from '@ohos.hilog';

async function copyTextToClipboard() {
    let text: string = 'Text content for secure synchronization';
    let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    await systemPasteBoard.setData(pasteData).catch((err: BusinessError) => {
        hilog.error(0x0010, `Failed to set pastedata. Code: ${err.code}, message: ${err.message}`);
    });
}
Enter fullscreen mode Exit fullscreen mode

In this code, device A copies the text content to the clipboard and clearly defines the data before data transmission, avoiding the risk of casually copying sensitive data.

Device B (Pasting End)

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';
import { hilog, LogLevel } from '@ohos.hilog';

async function readClipboardAndProcess() {
    if (!await checkPermission('ohos.permission.READ_PASTEBOARD')) {
        let result = await requestPermission('ohos.permission.READ_PASTEBOARD');
        if (!result) {
            hilog.log(LogLevel.ERROR, 0x0010, 'Permission request failed');
            return;
        }
    }
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    systemPasteBoard.getData((err: BusinessError, data: pasteboard.PasteData) => {
        if (err) {
            hilog.error(0x0010, `Failed to get pastedata. Code: ${err.code}, message: ${err.message}`);
            return;
        }
        let primaryText: string = data.getPrimaryText();
        if (primaryText) {
            // Perform security processing on the obtained text, such as checking whether the text content meets expectations
            if (isValidText(primaryText)) {
                hilog.info(0x0010, `Received valid text: ${primaryText}`);
                // Perform subsequent business operations, such as displaying it on the interface
            } else {
                hilog.warn(0x0010, 'Received invalid text, may be a security risk');
            }
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

At the device B end, first perform permission checking and application to ensure that the application has the right to access the clipboard. After obtaining the clipboard data, perform a validity check on the data to avoid processing data that may pose a security risk. In this way, the efficient use of the cross-device clipboard is achieved while ensuring security.

The security and permission management of the cross-device clipboard in HarmonyOS Next are aspects that developers must pay attention to during the application development process. By understanding data security risks, correctly managing permissions, and following best practices, developers can create a secure, reliable, and efficient application experience for users.

Top comments (0)