login-sessions.test.mjs 1.9 KB

12345678910111213141516171819202122232425262728
  1. import { test } from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'
  7. import { DesktopLoginSessions } from './login-sessions.mjs'
  8. test('native login vault encrypts only session authorization, restores by origin, and durably forgets', async () => {
  9. const home = await mkdtemp(join(tmpdir(), 'yaoyao-login-vault-')), key = randomBytes(32)
  10. const options = { home,
  11. encrypt: async value => { const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); const bytes = Buffer.concat([cipher.update(value),cipher.final()]); return Buffer.concat([iv,cipher.getAuthTag(),bytes]) },
  12. decrypt: async bytes => { const cipher = createDecipheriv('aes-256-gcm',key,bytes.subarray(0,12));cipher.setAuthTag(bytes.subarray(12,28));return Buffer.concat([cipher.update(bytes.subarray(28)),cipher.final()]).toString() },
  13. }
  14. try {
  15. let vault = new DesktopLoginSessions(options)
  16. const origin = 'https://server.example', cookie = {name:'hermes_yaoyao_session',value:'opaque-revocable-token',httpOnly:true,path:'/',sameSite:'strict'}
  17. await vault.save(origin,[cookie,{name:'csrf',value:'temporary'}])
  18. assert.ok(!(await readFile(vault.path(origin))).includes(Buffer.from(cookie.value)))
  19. assert.equal((await stat(vault.path(origin))).mode & 0o777, 0o600)
  20. vault = new DesktopLoginSessions(options)
  21. assert.deepEqual(await vault.read(origin),{origin,cookie})
  22. assert.equal(await vault.read('https://other.example'),undefined)
  23. const saving = vault.save(origin,[cookie]); const forgetting = vault.forget(origin)
  24. await Promise.all([saving,forgetting])
  25. assert.equal(await new DesktopLoginSessions(options).read(origin),undefined)
  26. } finally {await rm(home,{recursive:true,force:true})}
  27. })