import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createPrivateKey, sign as edSign } from 'node:crypto';
import { createMessage, parseMessage, verify, isAddress, base58Encode, base58Decode, MAX_LIFETIME_MS } from '../src/index.ts';
import type { MessageParams } from '../src/index.ts';
// Deterministic throwaway test keys (fixed seeds, hold nothing).
function keyFromSeed(byte: number) {
const seed = Buffer.alloc(32, byte);
const der = Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]);
const priv = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
const x = Buffer.from(priv.export({ format: 'jwk' }).x as string, 'base64url');
return { address: base58Encode(x), sign: (m: string) => new Uint8Array(edSign(null, Buffer.from(m, 'utf8'), priv)) };
}
const alice = keyFromSeed(1), mallory = keyFromSeed(2);
const DOMAIN = 'app.kognai.ai';
const T0 = Date.parse('2026-11-02T10:00:00.000Z');
const params = (o: Partial<MessageParams> = {}): MessageParams => ({
domain: DOMAIN, address: alice.address, nonce: 'n0nce12345abcdef', issuedAt: new Date(T0).toISOString(), expirationTime: new Date(T0 + 10 * 60_000).toISOString(), ...o,
});
const run = (o: Record<string, unknown> = {}) => {
const message = 'message' in o ? (o.message as string) : createMessage(params());
return verify({ message, signature: 'signature' in o ? undefined : base58Encode(alice.sign(message)), address: alice.address, allowlist: [alice.address], now: T0 + 1000, seen: new Set(), domain: DOMAIN, ...o } as never);
};
test('A1 valid: allowlisted wallet signs a fresh message for our domain', () => {
const m = createMessage(params({ statement: 'Sign in to the Kognai citizen app.' }));
assert.equal(m, [
'app.kognai.ai wants you to sign in with your Solana account:', alice.address, '', 'Sign in to the Kognai citizen app.', '',
'URI: https://app.kognai.ai', 'Version: 1', 'Chain ID: mainnet', 'Nonce: n0nce12345abcdef', 'Issued At: 2026-11-02T10:00:00.000Z', 'Expiration Time: 2026-11-02T10:10:00.000Z',
].join('\n'));
const v = run({ message: m, signature: base58Encode(alice.sign(m)) });
assert.equal(v.ok, true); assert.equal(v.reason, 'signed in'); assert.equal(v.fields!.statement, 'Sign in to the Kognai citizen app.');
// the signature may also be raw bytes or base64; the allowlist may be a Set
assert.equal(run({ message: m, signature: alice.sign(m) }).ok, true);
assert.equal(run({ message: m, signature: Buffer.from(alice.sign(m)).toString('base64'), allowlist: new Set([alice.address]) }).ok, true);
});
test('A2 wrong domain is refused', () => {
const m = createMessage(params({ domain: 'evil.example' }));
assert.deepEqual(run({ message: m, signature: base58Encode(alice.sign(m)) }), { ok: false, reason: 'the message is for evil.example, not app.kognai.ai (wrong domain)' });
assert.equal(run({ domain: undefined }).reason, 'no expected domain was given');
assert.equal(verify(undefined as never).reason, 'no expected domain was given');
});
test('A3 expired is refused (at the expiry instant too); not yet valid is refused', () => {
assert.equal(run({ now: T0 + 10 * 60_000 }).reason, 'the message expired');
assert.equal(run({ now: T0 + 10 * 60_000 - 1 }).ok, true);
assert.equal(run({ now: T0 - 1 }).reason, 'the message is not valid yet');
assert.equal(run({ now: 'later' }).reason, 'now must be milliseconds since the epoch');
});
test('A4 replayed nonce is refused; a failed attempt does not burn the nonce', () => {
const seen = new Set<string>();
const m = createMessage(params());
assert.equal(run({ message: m, signature: base58Encode(mallory.sign(m)), seen }).ok, false);
assert.equal(run({ message: m, seen }).ok, true);
assert.equal(run({ message: m, seen }).reason, 'the nonce was already used (replay)');
assert.equal(run({ seen: undefined }).reason, 'no replay store was given');
assert.equal(run({ seen: { has: () => false } }).reason, 'no replay store was given');
});
test('A5 address not on the allowlist is refused', () => {
assert.equal(run({ allowlist: [mallory.address] }).reason, 'the address is not on the allowlist');
assert.equal(run({ allowlist: [] }).reason, 'the address is not on the allowlist');
assert.equal(run({ allowlist: undefined }).reason, 'the address is not on the allowlist');
assert.equal(run({ allowlist: 42 }).reason, 'the address is not on the allowlist');
assert.equal(run({ allowlist: [alice.address.toLowerCase()] }).reason, 'the address is not on the allowlist');
});
test('A6 malformed signature is refused, never thrown', () => {
for (const s of ['', 'not base58 0OIl', base58Encode(new Uint8Array(63).fill(7)), new Uint8Array(32), 12345, null, 'A'.repeat(86) + '=']) {
assert.equal(run({ signature: s }).reason, 'the signature is malformed', String(s));
}
// well formed but wrong: another key, or a flipped byte
const m = createMessage(params());
assert.equal(run({ message: m, signature: mallory.sign(m) }).reason, 'the signature does not match the address');
const flipped = alice.sign(m); flipped[0] ^= 1;
assert.equal(run({ message: m, signature: flipped }).reason, 'the signature does not match the address');
});
test('A7 the address given must be the one in the message', () => {
assert.equal(run({ address: mallory.address, allowlist: [mallory.address] }).reason, 'the address does not match the message');
assert.equal(run({ address: 'nope' }).reason, 'the address does not match the message');
// an allowlisted 32 byte value that is not a valid ed25519 key is refused, not thrown
const notAKey = base58Encode(new Uint8Array(32).fill(0xff));
const m = createMessage(params({ address: notAKey }));
assert.equal(run({ message: m, address: notAKey, allowlist: [notAKey], signature: alice.sign(m) }).reason, 'the signature does not match the address');
});
test('A8 tampered or foreign messages are refused', () => {
const m = createMessage(params());
const sig = base58Encode(alice.sign(m));
const r = (message: unknown) => run({ message, signature: sig }).reason;
assert.equal(r(m.replace('Nonce: n0nce12345abcdef', 'Nonce: n0nce12345abcdeg')), 'the signature does not match the address');
for (const bad of [42, '', m + '\n', m.replace('Version: 1', 'Version: 2'), m.replace('URI: ', 'Url: '), m.replace(' wants you', ' asks you'), m.replace('Chain ID: ', 'Chain: '),
m.replace('Nonce: ', 'Nonc: '), m.replace('Issued At: ', 'Issued: '), m.replace('Expiration Time: ', 'Expires: '), m.replace('Expiration Time: 2026-11-02T10:10:00.000Z', 'Expiration Time: 2026-11-02T10:10:00Z'),
m.split('\n').map((l, i) => (i === 2 ? 'x' : l)).join('\n'), m.replace('\n\nURI', '\n\nhello\nx\nURI'), m.replace('Chain ID: mainnet', 'Chain ID: Main Net')]) {
assert.equal(r(bad), 'the message is not a Sign in with Solana message', JSON.stringify(bad));
}
assert.equal(parseMessage(m)!.nonce, 'n0nce12345abcdef');
});
test('A9 createMessage validates its params', () => {
const bad = (o: Partial<MessageParams> | undefined, re: RegExp) => assert.throws(() => createMessage(o === undefined ? (undefined as never) : params(o)), re);
bad(undefined, /domain/);
bad({ domain: 'App.Kognai.ai' }, /domain/);
bad({ address: 'abc' }, /address/);
bad({ nonce: 'short' }, /nonce/);
bad({ issuedAt: 'yesterday' }, /ISO 8601/);
bad({ expirationTime: new Date(T0).toISOString() }, /after issuedAt/);
bad({ expirationTime: new Date(T0 + MAX_LIFETIME_MS + 1).toISOString() }, /after issuedAt/);
bad({ statement: 'two\nlines' }, /statement/);
bad({ statement: '' }, /statement/);
bad({ uri: 'ftp://x' }, /uri/);
bad({ chainId: 'Main Net' }, /chainId/);
const m = createMessage(params({ uri: 'https://app.kognai.ai/login', chainId: 'devnet', domain: 'localhost:8080' }));
assert.match(m, /^localhost:8080 wants you/); assert.match(m, /Chain ID: devnet/); assert.match(m, /URI: https:\/\/app.kognai.ai\/login/);
});
test('A10 base58 round trips, keeps leading zeros, rejects bad input', () => {
const b = new Uint8Array([0, 0, 1, 2, 255]);
assert.deepEqual(base58Decode(base58Encode(b)), b);
assert.equal(base58Encode(new Uint8Array([0, 0])), '11');
assert.equal(base58Decode(''), null); assert.equal(base58Decode('0'), null); assert.equal(base58Decode(5 as never), null);
assert.equal(isAddress(alice.address), true); assert.equal(isAddress('1'.repeat(44)), false); assert.equal(isAddress(null), false);
assert.equal(isAddress('11111111111111111111111111111111'), true); // the system program, 32 zero bytes
});
agentgate-source: code mirror on Cloudflare Pages. All repos