Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use web api crypto instead of node:crypto for targeting evaluation #25

Merged
merged 14 commits into from
Aug 26, 2024

Conversation

zhiyuanliang-ms
Copy link
Contributor

@zhiyuanliang-ms zhiyuanliang-ms commented Aug 17, 2024

Why this PR?

node:crypto is not recognizable in browser environment.

image

Visible changes

The evaluate method of targeting filter becomes async because crypto.subtle.digest is async.

Add testcase for browser scenario. Use playwright to simulate browser and build the package to umd style so that user can consume the package through

<script src="https://unpkg.com/@microsoft/[email protected]/dist/umd/index.js"></script>
<script>
const fm = new FeatureManagement.FeatureManager();
</script>

@Eskibear
Copy link
Member

something like below would possibly make the code compatible with browser and nodejs:

async function sha256(message) {
    let crypto;

    // Check for browser environment
    if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
        crypto = window.crypto;
    } 
    // Check for Node.js environment
    else if (typeof global !== 'undefined' && global.crypto) {
        crypto = global.crypto;
    } 
    // Fallback to native Node.js crypto module
    else {
        crypto = require('crypto'); // maybe wrap with try-catch in case of uncovered runtimes... or you maybe want to fail the program because there's no way to calc hash then
    }

    // In the browser, use crypto.subtle.digest
    if (crypto.subtle) {
        const encoder = new TextEncoder();
        const data = encoder.encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return hashHex;
    } 
    // In Node.js, use the crypto module's hash function
    else {
        return crypto.createHash('sha256').update(message).digest('hex');
    }
}

// Example usage:
sha256('Hello, world!').then(hash => {
    console.log('SHA-256 hash:', hash);
});

package.json Outdated Show resolved Hide resolved
@zhiyuanliang-ms zhiyuanliang-ms merged commit 85db328 into main Aug 26, 2024
3 checks passed
@zhiyuanliang-ms zhiyuanliang-ms deleted the zhiyuanliang/update-targeting-filter branch August 26, 2024 05:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants