feat(worker): user-scoped box terminal token verification
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { verifyBoxTerminalToken } from '../../src/terminal-token';
|
||||
|
||||
const mintBox = (username: string, expiresAt: number, secret: string) => {
|
||||
const payload = `${expiresAt}.box.${username}`;
|
||||
const sig = createHmac('sha256', secret).update(payload).digest('hex');
|
||||
return `${payload}.${sig}`;
|
||||
};
|
||||
|
||||
describe('verifyBoxTerminalToken', () => {
|
||||
const secret = 'test-secret';
|
||||
|
||||
test('accepts a valid, unexpired, username-matched token', () => {
|
||||
const token = mintBox('alice', Date.now() + 60_000, secret);
|
||||
expect(verifyBoxTerminalToken(token, 'alice', secret)).toBe(true);
|
||||
});
|
||||
|
||||
test('rejects an expired token', () => {
|
||||
const token = mintBox('alice', Date.now() - 1, secret);
|
||||
expect(verifyBoxTerminalToken(token, 'alice', secret)).toBe(false);
|
||||
});
|
||||
|
||||
test('rejects a token minted for another username', () => {
|
||||
const token = mintBox('alice', Date.now() + 60_000, secret);
|
||||
expect(verifyBoxTerminalToken(token, 'bob', secret)).toBe(false);
|
||||
});
|
||||
|
||||
test('rejects a token signed with a different secret', () => {
|
||||
const token = mintBox('alice', Date.now() + 60_000, 'other-secret');
|
||||
expect(verifyBoxTerminalToken(token, 'alice', secret)).toBe(false);
|
||||
});
|
||||
|
||||
test('rejects malformed input and an empty secret', () => {
|
||||
expect(verifyBoxTerminalToken('garbage', 'alice', secret)).toBe(false);
|
||||
expect(verifyBoxTerminalToken('', 'alice', secret)).toBe(false);
|
||||
expect(
|
||||
verifyBoxTerminalToken(mintBox('alice', Date.now() + 1000, ''), 'alice', ''),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('rejects a 3-part job token (cross-scheme confusion guard)', () => {
|
||||
const payload = `${Date.now() + 60_000}.alice`;
|
||||
const sig = createHmac('sha256', secret).update(payload).digest('hex');
|
||||
const jobToken = `${payload}.${sig}`;
|
||||
expect(verifyBoxTerminalToken(jobToken, 'alice', secret)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user