添加登录功能
This commit is contained in:
commit
a3f61a29d0
120 files changed
+3974
No files matched your search
@@ -0,0 +1,149 @@
|
||||
import { test } from 'node:test';
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { GuestError, GuestPayload, GuestSession, GuestSettings } from '../assets/login/scripts/GuestContracts';
|
||||
import { GuestHttpClient } from '../assets/login/scripts/GuestHttpClient';
|
||||
import { GuestLoginPresenter, LoginState } from '../assets/login/scripts/GuestLoginPresenter';
|
||||
import { GuestLoginService } from '../assets/login/scripts/GuestLoginService';
|
||||
import { GuestSessionStore } from '../assets/login/scripts/GuestSessionStore';
|
||||
import { HmacGuestSigner } from '../assets/login/scripts/GuestSignature';
|
||||
|
||||
// 测试只使用公开假数据,不加载本机签名配置。 / Use public fixtures only; never load the local signing configuration.
|
||||
const settings: GuestSettings = { origin: 'https://example.test', product: 'FruitFixture', deviceType: 'iphone', registerDevice: 'web', timeoutMs: 50 };
|
||||
const identity = '0123456789abcdef0123456789abcdef';
|
||||
const session: GuestSession = { guestId: identity, token: 'Bearer fixture.token', expires: 1234 };
|
||||
const payload: GuestPayload = { guest_id: identity, pkg: '测试&game', device_type: 'iphone', register_device: 'web', install_fb: false, gyroscope_not_spinning: false };
|
||||
function memory() {
|
||||
const values = new Map<string, string>();
|
||||
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
|
||||
}
|
||||
function response(value: unknown): Response { return { ok: true, json: async () => value } as Response; }
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(yes => { resolve = yes; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
const failure = (kind: string) => (error: unknown) => error instanceof GuestError && error.kind === kind;
|
||||
|
||||
test('signature matches independent HMAC with UTF-8, LF, empty uid and false fields', () => {
|
||||
const signer = new HmacGuestSigner('public-test-key', () => identity, () => 1700000000000);
|
||||
const fields = `device_type=iphone&guest_id=${identity}&gyroscope_not_spinning=false&install_fb=false&pkg=测试&game®ister_device=web`;
|
||||
const text = `POST\n/account/v2/guest/login\n1700000000\n${identity}\n\n${fields}`;
|
||||
const expected = createHmac('sha256', 'public-test-key').update(text, 'utf8').digest('hex');
|
||||
assert.deepEqual(signer.headers(payload), { 'X-Timestamp': '1700000000', 'X-Nonce': identity, 'X-Sign': expected });
|
||||
assert.throws(() => new HmacGuestSigner('', () => identity), failure('configuration'));
|
||||
assert.throws(() => new HmacGuestSigner('test', () => 'short').headers(payload), failure('configuration'));
|
||||
});
|
||||
|
||||
test('identity is stable and isolated from other products and origins', () => {
|
||||
const storage = memory();
|
||||
const first = new GuestSessionStore(storage, settings.origin, settings.product);
|
||||
assert.equal(first.identity(() => identity), identity);
|
||||
assert.equal(first.identity(() => { throw Error('must not regenerate'); }), identity);
|
||||
const another = new GuestSessionStore(storage, settings.origin, 'OtherProduct');
|
||||
assert.notEqual(first.identityKey, another.identityKey);
|
||||
assert.notEqual(first.identityKey, new GuestSessionStore(storage, 'https://other.test', settings.product).identityKey);
|
||||
first.save(session);
|
||||
assert.deepEqual(JSON.parse(storage.getItem(first.sessionKey)!), session);
|
||||
});
|
||||
|
||||
test('storage corruption and silent write failures stop authentication', () => {
|
||||
const storage = memory();
|
||||
const accounts = new GuestSessionStore(storage, settings.origin, settings.product);
|
||||
storage.setItem(accounts.identityKey, 'corrupt');
|
||||
assert.throws(() => accounts.identity(() => identity), failure('identity'));
|
||||
const unavailable = new GuestSessionStore({ getItem: () => null, setItem: () => {} }, settings.origin, settings.product);
|
||||
assert.throws(() => unavailable.identity(() => identity), failure('storage'));
|
||||
});
|
||||
|
||||
test('two-step login signs only registration and preserves the complete token', async () => {
|
||||
const storage = memory();
|
||||
const accounts = new GuestSessionStore(storage, settings.origin, settings.product);
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
let nonce = 0;
|
||||
const transport = new GuestHttpClient(settings.origin, 100, (async (url, init) => {
|
||||
calls.push({ url: String(url), init: init! });
|
||||
return response(calls.length % 2 === 1 ? { code: 0 } : { code: 0, data: session });
|
||||
}) as typeof fetch);
|
||||
const service = new GuestLoginService(settings, accounts, new HmacGuestSigner('fixture', () => identity + ++nonce), transport, () => identity);
|
||||
assert.deepEqual(await service.signIn(), session);
|
||||
assert.equal(calls[0].url, settings.origin + '/account/v2/guest/login');
|
||||
assert.equal(calls[1].url, settings.origin + '/account/login');
|
||||
assert.deepEqual(JSON.parse(String(calls[0].init.body)), { ...payload, pkg: settings.product });
|
||||
assert.deepEqual(JSON.parse(String(calls[1].init.body)), { guest_id: identity, pkg: settings.product });
|
||||
assert.ok((calls[0].init.headers as Record<string, string>)['X-Sign']);
|
||||
assert.deepEqual(calls[1].init.headers, { 'Content-Type': 'application/json' });
|
||||
assert.equal(calls[0].init.credentials, 'omit');
|
||||
await service.signIn();
|
||||
assert.notEqual((calls[0].init.headers as Record<string, string>)['X-Nonce'], (calls[2].init.headers as Record<string, string>)['X-Nonce']);
|
||||
assert.equal(JSON.parse(storage.getItem(accounts.sessionKey)!).token, session.token);
|
||||
});
|
||||
|
||||
test('concurrent calls coalesce; cancelled caller never joins', async () => {
|
||||
const waiting = deferred<Record<string, unknown>>();
|
||||
let calls = 0;
|
||||
const service = new GuestLoginService(settings, new GuestSessionStore(memory(), settings.origin, settings.product),
|
||||
new HmacGuestSigner('fixture', () => identity), { post: async () => ++calls === 1 ? waiting.promise : { data: session } }, () => identity);
|
||||
const first = service.signIn();
|
||||
assert.equal(first, service.signIn());
|
||||
const cancelled = new AbortController(); cancelled.abort();
|
||||
await assert.rejects(service.signIn(cancelled.signal), failure('cancelled'));
|
||||
waiting.resolve({ code: 0 });
|
||||
assert.deepEqual(await first, session); assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('business failures and missing token preserve the previous saved session', async () => {
|
||||
for (const value of [{ code: 17, msg: 'private message' }, { code: 0, data: {} }]) {
|
||||
const storage = memory(); const accounts = new GuestSessionStore(storage, settings.origin, settings.product); accounts.save(session);
|
||||
const service = new GuestLoginService(settings, accounts, new HmacGuestSigner('fixture', () => identity),
|
||||
new GuestHttpClient(settings.origin, 100, (async () => response(value)) as typeof fetch), () => identity);
|
||||
await assert.rejects(service.signIn(), error => error instanceof GuestError && !error.message.includes('private message'));
|
||||
assert.deepEqual(JSON.parse(storage.getItem(accounts.sessionKey)!), session);
|
||||
}
|
||||
});
|
||||
|
||||
test('timeout covers response body parsing and cancellation ignores late registration', async () => {
|
||||
const body = deferred<unknown>();
|
||||
const timeout = new GuestHttpClient(settings.origin, 5, (async () => ({ ok: true, json: () => body.promise } as Response)) as typeof fetch);
|
||||
await assert.rejects(timeout.post('/fixture', {}, {}), failure('timeout'));
|
||||
body.resolve({ code: 0 });
|
||||
const waiting = deferred<Response>(); let calls = 0;
|
||||
const storage = memory(); const accounts = new GuestSessionStore(storage, settings.origin, settings.product);
|
||||
const service = new GuestLoginService(settings, accounts, new HmacGuestSigner('fixture', () => identity),
|
||||
new GuestHttpClient(settings.origin, 100, (() => { calls++; return waiting.promise; }) as typeof fetch), () => identity);
|
||||
const abort = new AbortController(); const login = service.signIn(abort.signal); abort.abort();
|
||||
await assert.rejects(login, failure('cancelled'));
|
||||
waiting.resolve(response({ code: 0 })); await Promise.resolve();
|
||||
assert.equal(calls, 1); assert.equal(storage.getItem(accounts.sessionKey), null);
|
||||
});
|
||||
|
||||
test('invalid JSON is a response error and verification errors hide server text', async () => {
|
||||
const malformed = new GuestHttpClient(settings.origin, 100, (async () => new Response('invalid JSON')) as typeof fetch);
|
||||
await assert.rejects(malformed.post('/fixture', {}, {}), failure('response'));
|
||||
const rejected = new GuestHttpClient(settings.origin, 100, (async () => response({ code: 401, msg: 'request_sign_invalid secret details' })) as typeof fetch);
|
||||
await assert.rejects(rejected.post('/fixture', {}, {}), error => error instanceof GuestError && error.kind === 'verification' && !error.message.includes('secret details'));
|
||||
});
|
||||
|
||||
test('presenter ignores repeated clicks and keeps committed success if a listener throws', async () => {
|
||||
const waiting = deferred<GuestSession>(); const states: LoginState[] = []; let calls = 0;
|
||||
const presenter = new GuestLoginPresenter({ render: state => states.push(state) },
|
||||
() => ({ signIn: () => { calls++; return waiting.promise; } }), () => { throw Error('listener'); });
|
||||
const login = presenter.submit(); await presenter.submit();
|
||||
assert.equal(calls, 1); assert.equal(states[0].enabled, false);
|
||||
waiting.resolve(session); await login;
|
||||
assert.equal(states.at(-1)?.phase, 'authenticated');
|
||||
await presenter.submit(); assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('presenter destruction prevents late success and failure allows retry', async () => {
|
||||
const waiting = deferred<GuestSession>(); const states: LoginState[] = []; let completed = 0;
|
||||
const presenter = new GuestLoginPresenter({ render: state => states.push(state) }, () => ({ signIn: () => waiting.promise }), () => completed++);
|
||||
const login = presenter.submit(); presenter.dispose(); waiting.resolve(session); await login;
|
||||
assert.equal(completed, 0); assert.equal(states.length, 1);
|
||||
let calls = 0;
|
||||
const retry = new GuestLoginPresenter({ render: state => states.push(state) }, () => ({ signIn: async () => {
|
||||
if (++calls === 1) throw new GuestError('network', 'Try again.'); return session;
|
||||
} }), () => completed++);
|
||||
await retry.submit(); assert.equal(states.at(-1)?.enabled, true);
|
||||
await retry.submit(); assert.equal(completed, 1);
|
||||
});
|
||||
Reference in new issue
Block a user