diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b0c9faa --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI +on: [push, pull_request] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ['22', '24'] + defaults: + run: + working-directory: typescript-client + steps: + - uses: actions/checkout@v6 + with: + path: typescript-client + - uses: actions/checkout@v6 + with: + repository: Authwave/php-client + ref: 72c213ddef1797cd096757e1c8c70d826abd7514 + path: php-client + - uses: actions/setup-node@v6 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: typescript-client/package-lock.json + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + extensions: sodium, curl + tools: composer + coverage: none + - name: Install PHP reference dependencies + run: composer install --no-dev --no-interaction --prefer-dist + working-directory: php-client + - run: npm ci + - run: npm run format:check + - run: npm test + - run: npm run typecheck diff --git a/PARITY.md b/PARITY.md index 6529718..895c810 100644 --- a/PARITY.md +++ b/PARITY.md @@ -1,6 +1,6 @@ # PHP reference parity -Reference: the sibling `Authwave/php-client` checkout. Every source class is represented below. Parity means equivalent client features and wire behavior, with the runtime adaptations described here; it is not a claim that PHP and JavaScript have identical type systems or every inherited PSR-7 URI operation. +Reference: `Authwave/php-client` commit `72c213ddef1797cd096757e1c8c70d826abd7514`. Every source class is represented below. Parity means equivalent client features and wire behavior, with the runtime adaptations described here; it is not a claim that PHP and JavaScript have identical type systems or every inherited PSR-7 URI operation. | PHP source | TypeScript source / export | Validation | | --- | --- | --- | @@ -46,6 +46,8 @@ The differential suite executes PHP's actual source with fixed nonces and compar ## Runtime adaptations +Tokens retain the first complete request plaintext and reject different payloads with the same nonce. Repeating an identical request remains deterministic. The binding is persisted in session serialisation. Legacy tokens without a known binding may decrypt responses but cannot encrypt another request. Login builds the request before replacing pending exchange data. + - Constructor arguments use an options object; URI-like arguments accept strings, `Uri`, and standard `URL` objects. `Uri` provides the operations needed by the client, not the full external PHP HTTP dependency API. - PHP's native `$_SESSION` has no Node equivalent. `GlobalSessionContainer` wraps an explicitly supplied per-request record. Omitting it throws; no process-global user storage is introduced. - PHP header-and-exit becomes `RedirectSignal`. Runtime adapters catch it and save before sending 303 responses. Test redirect handlers may return normally. diff --git a/README.md b/README.md index 6bcc14b..1024418 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ Register the application with your provider and configure its client return URI. Install and build this local repository with `npm ci && npm run build`. From your application, run `npm install /absolute/path/to/typescript-client`. This creates the local package dependency; no npm publication is implied. +A token can encrypt only its first complete request. Repeating the same request is allowed; a different payload raises TokenReuseException. Create a fresh token for a different action or return query, and do not copy tokens or reuse supplied IVs. Session serialisation retains the binding. Tokens restored from older sessions without a binding can still decrypt responses, but require a fresh token to start another request. + Runtime integrations -------------------- diff --git a/src/authenticator.ts b/src/authenticator.ts index 5b4cc77..af209c8 100644 --- a/src/authenticator.ts +++ b/src/authenticator.ts @@ -56,13 +56,14 @@ export class Authenticator { login(token: Token | null = null): void { if (this.isLoggedIn()) return; token ??= new Token(this.secret); + const loginUri = this.getLoginUri(token); this.sessionData = new SessionData( token, null, (this.returnUri ?? this.currentUriPath).getQuery(), ); this.session.set(SessionData.STORE_KEY, this.sessionData); - this.redirectHandler.redirect(this.getLoginUri(token)); + this.redirectHandler.redirect(loginUri); } logout(redirectTo: UriLike | null = null, token: Token | null = null): void { const isFake = this.user?.email === Authenticator.FAKE_EMAIL; diff --git a/src/errors.ts b/src/errors.ts index 2860237..a2e0253 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -12,3 +12,5 @@ export class InvalidUserDataSerializationException extends AuthwaveException {} export class ResponseCipherDecryptionException extends AuthwaveException {} export class DecryptionFailureException extends AuthwaveException {} export class EncryptionFailureException extends AuthwaveException {} + +export class TokenReuseException extends AuthwaveException {} diff --git a/src/token.ts b/src/token.ts index e7f4169..9d4db76 100644 --- a/src/token.ts +++ b/src/token.ts @@ -1,7 +1,8 @@ import { CipherText, decrypt, InitVector } from './cipher.js'; -import { InvalidUserDataSerializationException } from './errors.js'; +import { InvalidUserDataSerializationException, TokenReuseException } from './errors.js'; import { UserResponseData } from './user.js'; export class Token { + private requestPlaintext: string | null = null; constructor( private readonly secret: string, private readonly sessionIv = new InitVector(), @@ -14,7 +15,13 @@ export class Token { return this.sessionIv; } generateRequestCipher(message = ''): CipherText { - return new CipherText(`${message}&secretIv=${this.sessionIv}`, this.iv, this.secret); + const plaintext = `${message}&secretIv=${this.sessionIv}`; + if (this.requestPlaintext !== null && this.requestPlaintext !== plaintext) { + throw new TokenReuseException('Create a new token for a different request.'); + } + const cipher = new CipherText(plaintext, this.iv, this.secret); + this.requestPlaintext = plaintext; + return cipher; } decode(base64cipher: string): UserResponseData { const plain = decrypt(base64cipher, this.iv, this.secret); @@ -35,13 +42,25 @@ export class Token { } /** Server-side session serialization only; contains the client secret. */ toJSON() { - return { secret: this.secret, sessionIv: String(this.sessionIv), iv: String(this.iv) }; + return { + secret: this.secret, + sessionIv: String(this.sessionIv), + iv: String(this.iv), + requestPlaintext: this.requestPlaintext, + }; } - static fromJSON(data: ReturnType): Token { - return new Token( + static fromJSON( + data: Omit, 'requestPlaintext'> & { + requestPlaintext?: string | null; + }, + ): Token { + const token = new Token( data.secret, new InitVector().withBytes(Buffer.from(data.sessionIv, 'base64')), new InitVector().withBytes(Buffer.from(data.iv, 'base64')), ); + // Legacy records have no safe request-plaintext binding; decryption remains available. + token.requestPlaintext = Object.hasOwn(data, 'requestPlaintext') ? data.requestPlaintext! : ''; + return token; } } diff --git a/test/core.test.mjs b/test/core.test.mjs index 7236f8b..599ffc9 100644 --- a/test/core.test.mjs +++ b/test/core.test.mjs @@ -61,10 +61,13 @@ test('tokens are random, deterministic per token, supplied IV identities preserv const token = new A.Token(secret, sessionIv, iv); assert.equal(token.getIv(), iv); assert.equal(token.getSecretIv(), sessionIv); - assert.equal(String(token.generateRequestCipher()), String(token.generateRequestCipher())); + assert.equal( + String(token.generateRequestCipher('action=login')), + String(token.generateRequestCipher('action=login')), + ); assert.notEqual( - String(token.generateRequestCipher()), - String(new A.Token(secret).generateRequestCipher()), + String(token.generateRequestCipher('action=login')), + String(new A.Token(secret).generateRequestCipher('action=login')), ); assert.equal( A.decrypt(String(token.generateRequestCipher('action=login')), iv, secret), diff --git a/test/php-oracle.php b/test/php-oracle.php index 21486f0..88fa555 100644 --- a/test/php-oracle.php +++ b/test/php-oracle.php @@ -9,6 +9,10 @@ class RecordingRedirect extends RedirectHandler { public array $redirects = []; public function redirect(UriInterface $uri, int $code = 303):void { $this->redirects[] = [(string)$uri, $code]; } } +// These fixtures use in-memory state rather than a native browser session ID. +class OracleSession extends \Authwave\GlobalSessionContainer { + public function regenerate():void {} +} $cases = json_decode(stream_get_contents(STDIN), true); $out = []; foreach($cases as $index => $case) { @@ -27,7 +31,7 @@ public function redirect(UriInterface $uri, int $code = 303):void { $this->redir } $error = null; $auth = null; try { - $auth = new Authenticator('deployment_with_underscores_'.$secret, $uri, $case['host'] ?? 'login.authwave.com', redirectHandler:$redirect, onAuthenticated:($case['callback'] ?? false) ? $callback : null); + $auth = new Authenticator('deployment_with_underscores_'.$secret, $uri, $case['host'] ?? 'login.authwave.com', redirectHandler:$redirect, session:new OracleSession(), onAuthenticated:($case['callback'] ?? false) ? $callback : null); if(isset($case['returnUri'])) $auth->setReturnUri($case['returnUri']); if(($case['action'] ?? '') === 'login') $auth->login($token); if(($case['action'] ?? '') === 'logout') $auth->logout($case['redirectTo'] ?? null, $token); diff --git a/test/token-nonce.test.mjs b/test/token-nonce.test.mjs new file mode 100644 index 0000000..b210fd5 --- /dev/null +++ b/test/token-nonce.test.mjs @@ -0,0 +1,100 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + Authenticator, + Token, + TokenReuseException, + SessionArrayWrapper, + SessionData, + CipherText, + EncryptionFailureException, + LoginUri, + LogoutUri, + decrypt, +} from '../dist/index.js'; +const secret = 's'.repeat(32), + clientKey = 'deployment_' + secret; +for (const [first, second] of [ + ['action=login', 'action=logout'], + ['', 'action=login'], + ['action=login', ''], + ['action=login&returnQuery=page%3D1', 'action=login&returnQuery=page%3D2'], +]) + test(`reject changed token payload: ${first} -> ${second}`, () => { + const token = new Token(secret); + const iv = token.getIv().getBytes(); + const cipher = String(token.generateRequestCipher(first)); + assert.throws(() => token.generateRequestCipher(second), TokenReuseException); + assert.deepEqual(token.getIv().getBytes(), iv); + assert.equal(String(token.generateRequestCipher(first)), cipher); + assert.equal( + decrypt(cipher, token.getIv(), secret), + first + '&secretIv=' + token.getSecretIv(), + ); + }); +test('session serialisation preserves the request binding', () => { + const token = new Token(secret), + cipher = String(token.generateRequestCipher('action=login')); + const restored = SessionData.fromJSON( + JSON.parse(JSON.stringify(new SessionData(token))), + ).getToken(); + assert.equal(String(restored.generateRequestCipher('action=login')), cipher); + assert.throws(() => restored.generateRequestCipher('action=logout'), TokenReuseException); +}); +test('unused tokens can be restored before first encryption', () => { + const token = Token.fromJSON(JSON.parse(JSON.stringify(new Token(secret)))); + assert.ok(String(token.generateRequestCipher('action=login'))); +}); +test('legacy tokens can decrypt but cannot reuse an unknown request nonce', () => { + const token = new Token(secret), + legacy = token.toJSON(); + delete legacy.requestPlaintext; + const cipher = String( + new CipherText('{"id":"user-id","email":"person@example.com"}', token.getIv(), secret), + ); + const restored = Token.fromJSON(legacy); + assert.equal(restored.decode(cipher).getId(), 'user-id'); + assert.throws(() => restored.generateRequestCipher('action=login'), TokenReuseException); +}); +test('failed encryption does not bind the token', () => { + const token = new Token(''); + for (const message of ['action=login', 'action=logout']) + assert.throws(() => token.generateRequestCipher(message), EncryptionFailureException); +}); +test('login and logout URI builders cannot share a token', () => { + const token = new Token(secret); + const login = new LoginUri(token, '/callback', 'deployment'); + assert.equal(String(new LoginUri(token, '/callback', 'deployment')), String(login)); + assert.throws(() => new LogoutUri(token, '/callback', 'deployment'), TokenReuseException); + assert.ok(String(new LogoutUri(new Token(secret), '/callback', 'deployment'))); +}); +test('a rejected login preserves the existing exchange', () => { + const pending = new SessionData(new Token(secret)); + const state = { [SessionData.STORE_KEY]: pending, basket: ['tea'] }; + const auth = new Authenticator({ + clientKey, + currentUriPath: '/callback', + session: new SessionArrayWrapper(state), + }); + const used = new Token(secret); + used.generateRequestCipher('action=logout'); + assert.throws(() => auth.login(used), TokenReuseException); + assert.equal(state[SessionData.STORE_KEY], pending); + assert.deepEqual(state.basket, ['tea']); +}); +test('login saves the bound token for later requests', () => { + const state = {}, + session = new SessionArrayWrapper(state), + token = new Token(secret); + const auth = new Authenticator({ + clientKey, + currentUriPath: '/callback', + session, + redirectHandler: { redirect() {} }, + }); + auth.login(token); + const restored = new SessionArrayWrapper(JSON.parse(JSON.stringify(state))) + .get(SessionData.STORE_KEY) + .getToken(); + assert.throws(() => restored.generateRequestCipher('action=logout'), TokenReuseException); +});