diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5009e2b --- /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: master + 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/README.md b/README.md index 6bcc14b..7ced9fc 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. +Callback cleanup redirects use a local path without a scheme or host. The client removes the authentication response parameter while preserving the other query values and fragment. + Runtime integrations -------------------- diff --git a/src/authenticator.ts b/src/authenticator.ts index 5b4cc77..86a8c0b 100644 --- a/src/authenticator.ts +++ b/src/authenticator.ts @@ -157,8 +157,10 @@ export class Authenticator { this.tidyResponseData(returnQuery); } private tidyResponseData(returnQuery: string | null = null): void { - const uri = - returnQuery === null ? this.currentUriPath : this.currentUriPath.withQuery(returnQuery); + const parsed = new URL(String(this.currentUriPath), 'https://authwave.invalid'); + const path = '/' + parsed.pathname.replace(/\\/g, '%5C').replace(/^\/+/, ''); + const local = new Uri(path + parsed.hash).withQuery(this.currentUriPath.getQuery()); + const uri = returnQuery === null ? local : local.withQuery(returnQuery); this.redirectHandler.redirect(uri.withoutQueryValue(Authenticator.RESPONSE_QUERY_PARAMETER)); } } diff --git a/test/cleanup.test.mjs b/test/cleanup.test.mjs new file mode 100644 index 0000000..8ae4ca1 --- /dev/null +++ b/test/cleanup.test.mjs @@ -0,0 +1,157 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import express from 'express'; +import expressSession from 'express-session'; +import { + Authenticator, + SessionArrayWrapper, + SessionData, + Token, + CipherText, + RedirectSignal, +} from '../dist/index.js'; +import { createNodeHandler, MemorySessionStore } from '../dist/node.js'; +import { createExpressHandler } from '../dist/express.js'; +import { createNextHandler } from '../dist/next.js'; +const clientKey = 'deployment_' + 's'.repeat(32); +class MemorySession extends SessionArrayWrapper { + regenerate() {} +} +const cases = [ + ['//evil.example/path', '/path'], + ['//evil.example', '/'], + ['https://evil.example/path', '/path'], + ['https://user:pass@evil.example/path', '/path'], + ['https://app.example//evil.example/path', '/evil.example/path'], + ['/%2F%2Fevil.example/path', '/%2F%2Fevil.example/path'], + ['/members/a%2Fb', '/members/a%2Fb'], + ['/members/orders', '/members/orders'], +]; +for (const [input, expected] of cases) + test(`cleanup stays local: ${input}`, () => { + const auth = new Authenticator({ + clientKey, + currentUriPath: input + '?keep=%7e&flag&AUTHWAVE_RESPONSE_DATA=anything#details', + session: new MemorySession({}), + redirectHandler: { + redirect(uri, code = 303) { + assert.equal(code, 303); + assert.equal(String(uri), expected + '?keep=%7e&flag#details'); + assert.equal(new URL(String(uri), 'https://app.example').origin, 'https://app.example'); + }, + }, + }); + assert.equal(auth.isLoggedIn(), false); + }); +for (const input of ['/\\evil.example/path', 'x:/\\evil.example/path']) + test(`backslashes cannot change origin: ${input}`, () => { + assert.throws( + () => + new Authenticator({ + clientKey, + currentUriPath: input + '?AUTHWAVE_RESPONSE_DATA=anything', + session: new MemorySession({}), + }), + (error) => { + assert.ok(error instanceof RedirectSignal); + assert.equal(new URL(error.uri, 'https://app.example').origin, 'https://app.example'); + return true; + }, + ); + }); +test('authenticated cleanup preserves encoded paths and the saved query', () => { + const token = new Token('s'.repeat(32)); + const session = new MemorySession({ + [SessionData.STORE_KEY]: new SessionData(token, null, 'filter=original&flag&encoded=%7e'), + }); + const cipher = String( + new CipherText( + '{"id":"user-id","email":"person@example.com"}', + token.getSecretIv(), + 's'.repeat(32), + ), + ); + const auth = new Authenticator({ + clientKey, + currentUriPath: + 'https://user:pass@evil.example//members/a%2Fb?AUTHWAVE_RESPONSE_DATA=' + + encodeURIComponent(cipher) + + '#details', + session, + redirectHandler: { + redirect(uri) { + assert.equal(String(uri), '/members/a%2Fb?filter=original&flag&encoded=%7e#details'); + }, + }, + }); + assert.equal(auth.getAuthUser().id, 'user-id'); +}); +test('cleanup removes duplicate response parameters without rewriting other values', () => { + assert.throws( + () => + new Authenticator({ + clientKey, + currentUriPath: + '//evil.example/path?AUTHWAVE_RESPONSE_DATA=one&flag&AUTHWAVE_RESPONSE_DATA=two&next=https://evil.example', + session: new MemorySession({}), + }), + (error) => { + assert.equal(error.uri, '/path?flag&next=https://evil.example'); + return error instanceof RedirectSignal; + }, + ); +}); +for (const runtime of ['node', 'express', 'next']) + test(`${runtime}: HTTP cleanup cannot redirect to another host`, async (t) => { + let invoke; + if (runtime === 'next') { + const handler = createNextHandler( + { clientKey, store: new MemorySessionStore(), secureCookie: false }, + () => assert.fail('cleanup should redirect before the handler'), + ); + invoke = () => + handler( + new Request('http://localhost//evil.example/path?keep=1&AUTHWAVE_RESPONSE_DATA=anything'), + ); + } else { + let handler; + if (runtime === 'node') + handler = createNodeHandler( + { clientKey, store: new MemorySessionStore(), secureCookie: false }, + () => assert.fail('cleanup should redirect before the handler'), + ); + else { + const app = express(); + app.use( + expressSession({ + secret: 'test signing secret', + resave: false, + saveUninitialized: false, + }), + ); + app.use( + createExpressHandler({ clientKey }, () => + assert.fail('cleanup should redirect before the handler'), + ), + ); + handler = app; + } + const server = createServer(handler); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.after(() => new Promise((resolve) => server.close(resolve))); + invoke = () => + fetch( + `http://127.0.0.1:${server.address().port}//evil.example/path?keep=1&AUTHWAVE_RESPONSE_DATA=anything`, + { redirect: 'manual' }, + ); + } + const response = await invoke(); + assert.equal(response.status, 303); + const location = response.headers.get('location'); + assert.equal(new URL(location, 'http://localhost').hostname, 'localhost'); + assert.equal(new URL(location, 'http://localhost').pathname, '/path'); + assert.equal(new URL(location, 'http://localhost').search, '?keep=1'); + }); 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);