credentials.test.mjs 1.5 KB

12345678910111213141516171819202122
  1. import {test} from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import {mkdtemp,realpath,rm} from 'node:fs/promises'
  4. import {join,resolve} from 'node:path'
  5. import {tmpdir} from 'node:os'
  6. import {execFile} from 'node:child_process'
  7. import {promisify} from 'node:util'
  8. import {DesktopCredentials} from './credentials.mjs'
  9. test('native Keychain encryption is scoped to a directory and authenticates ciphertext',{timeout:30000},async()=>{
  10. const home=await realpath(await mkdtemp(join(tmpdir(),'yaoyao-keychain-')))
  11. const credentials=new DesktopCredentials({home,helper:resolve('.desktop-build/keychain-helper-dev'),legacyDecrypt:async()=>{throw new Error('legacy')}})
  12. try{
  13. const value='{"token":"fixture-private-machine-token"}',encrypted=await credentials.encrypt(value)
  14. assert.equal(encrypted.includes('fixture-private-machine-token'),false)
  15. assert.equal(await credentials.decrypt(encrypted),value)
  16. const changed=Buffer.from(encrypted);changed[changed.length-1]^=1
  17. await assert.rejects(credentials.decrypt(changed))
  18. const other=new DesktopCredentials({home:home+'-other',helper:credentials.helper,legacyDecrypt:credentials.legacyDecrypt})
  19. await assert.rejects(other.decrypt(encrypted))
  20. await assert.rejects(promisify(execFile)(resolve('.desktop-build/keychain-helper'),['decrypt',credentials.account]),/只允许所属 App/)
  21. }finally{await promisify(execFile)('/usr/bin/security',['delete-generic-password','-s','cn.samien.yaoyao.runner-key.v1','-a',credentials.account]).catch(()=>{});await rm(home,{recursive:true,force:true})}
  22. })