Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ The differential suite executes PHP's actual source with fixed nonces and compar

## Runtime adaptations

Successful authentication now regenerates the session ID before saving the identity and invalidates the old session. Unrelated data is preserved, and ordinary restoration keeps its ID. Custom session containers must provide regeneration, and custom runtime stores must support deleting the old ID.

- 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.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ Handlers receive an `Authenticator` and the request. Node handlers return a stri

See [working examples](examples) and the sibling [wiki](../typescript-client.wiki/Home.md), particularly its [Quick start guide](../typescript-client.wiki/Quick-start-guide.md). Production deployments need HTTPS and shared persistent session storage. `MemorySessionStore` is for local development. Never expose serialized session records, which contain token secrets, to the browser.

Successful authentication replaces the session ID before saving the identity and invalidates the old ID, preserving unrelated session data. Express uses express-session regeneration. Custom Node.js and Next.js SessionStore implementations must provide delete(id): Promise<void>. Custom SessionContainer implementations must provide regenerate(): void; GlobalSessionContainer accepts the regeneration callback as its second argument. This callback must replace the ID, invalidate the old session and preserve the data. Throwing stops authentication. Ordinary session restoration keeps its ID.

Running tests
-------------

Expand Down
2 changes: 2 additions & 0 deletions src/authenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export class Authenticator {
fakeLogin(userId: string, email: string | null = null, redirectTo = '/'): void {
const iv = new InitVector();
const token = new Token(this.secret, iv);
this.session.regenerate();
this.session.set(SessionData.STORE_KEY, new SessionData(token));
const data = new UserResponseData(userId, email ?? Authenticator.FAKE_EMAIL);
this.session.set(SessionData.STORE_KEY, new SessionData(token, data));
Expand Down Expand Up @@ -148,6 +149,7 @@ export class Authenticator {
throw new TypeError('Expected user id/email scalar');
};
const userData = new UserResponseData(scalar(data?.id), scalar(data?.email));
if (!this.isLoggedIn()) this.session.regenerate();
this.user = new User(userData.getId(), userData.getEmail());
const wasInvoked = this.sessionData.hasInvokedAuthenticationCallback();
const next = new SessionData(token, userData, returnQuery);
Expand Down
2 changes: 2 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 SessionRegenerationException extends AuthwaveException {}
55 changes: 47 additions & 8 deletions src/express.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { Authenticator } from './authenticator.js';
import type { AuthenticatorOptions } from './authenticator.js';
import { GlobalSessionContainer } from './session.js';
import type { AuthUser } from './user.js';
import { GlobalSessionContainer, SessionData } from './session.js';
import { RedirectSignal } from './redirect.js';
import { SessionNotStartedException } from './errors.js';
export interface ExpressRequest {
originalUrl: string;
session?: object & { save(callback: (error?: unknown) => void): void };
session?: object & {
save(callback: (error?: unknown) => void): void;
regenerate(callback: (error?: unknown) => void): void;
};
}
export interface ExpressResponse {
redirect(code: number, url: string): unknown;
Expand All @@ -16,7 +20,7 @@ export type ExpressOptions = Omit<
AuthenticatorOptions,
'session' | 'currentUriPath' | 'redirectHandler'
>;
/** Mount after express-session. Return a body; this adapter saves before sending it. */
/** Mount after express-session. Save the result only after regenerating a newly authenticated session. */
export function createExpressHandler(
options: ExpressOptions,
handler: (auth: Authenticator, req: ExpressRequest) => unknown | Promise<unknown>,
Expand All @@ -28,22 +32,57 @@ export function createExpressHandler(
): Promise<void> => {
try {
if (!req.session) throw new SessionNotStartedException('Mount express-session first');
const staged: Record<string, unknown> = {};
const original = req.session as Record<string, unknown>;
if (Object.hasOwn(original, SessionData.STORE_KEY))
staged[SessionData.STORE_KEY] = original[SessionData.STORE_KEY];
let regenerate = false;
let authenticated: AuthUser | undefined;
let body: unknown;
let failure: unknown;
let failed = false;
let redirect: RedirectSignal | undefined;
try {
const auth = new Authenticator({
...options,
currentUriPath: req.originalUrl,
session: new GlobalSessionContainer(req.session as Record<string, unknown>),
session: new GlobalSessionContainer(staged, () => {
regenerate = true;
}),
onAuthenticated: options.onAuthenticated
? (user) => {
authenticated = user;
}
: undefined,
});
body = await handler(auth, req);
} catch (error) {
if (error instanceof RedirectSignal) redirect = error;
else throw error;
else {
failed = true;
failure = error;
}
}
try {
if (regenerate) {
const preserved = { ...req.session } as Record<string, unknown>;
delete preserved[SessionData.STORE_KEY];
await new Promise<void>((resolve, reject) =>
req.session!.regenerate((error) => (error ? reject(error) : resolve())),
);
Object.assign(req.session!, preserved);
}
const target = req.session as Record<string, unknown>;
if (Object.hasOwn(staged, SessionData.STORE_KEY))
target[SessionData.STORE_KEY] = staged[SessionData.STORE_KEY];
else delete target[SessionData.STORE_KEY];
if (authenticated) options.onAuthenticated!(authenticated);
if (failed) throw failure;
} finally {
await new Promise<void>((resolve, reject) =>
req.session!.save((error) => (error ? reject(error) : resolve())),
);
if (req.session)
await new Promise<void>((resolve, reject) =>
req.session!.save((error) => (error ? reject(error) : resolve())),
);
}
res.setHeader('Cache-Control', 'no-store');
if (redirect) res.redirect(redirect.code, redirect.uri);
Expand Down
26 changes: 20 additions & 6 deletions src/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { randomBytes } from 'node:crypto';
import { GlobalSessionContainer } from './session.js';
export interface SessionStore {
delete(id: string): Promise<void>;
get(id: string): Promise<Record<string, unknown> | undefined>;
set(id: string, data: Record<string, unknown>, expiresAt: number): Promise<void>;
}
Expand All @@ -19,6 +20,9 @@ export class MemorySessionStore implements SessionStore {
}
return JSON.parse(JSON.stringify(entry.data)) as Record<string, unknown>;
}
async delete(id: string): Promise<void> {
this.sessions.delete(id);
}
async set(id: string, data: Record<string, unknown>, expiresAt: number): Promise<void> {
for (const [key, value] of this.sessions)
if (value.expiresAt <= Date.now()) this.sessions.delete(key);
Expand Down Expand Up @@ -47,12 +51,22 @@ export async function openSession(cookie: string | null | undefined, options: Se
?.slice(name.length + 1);
const stored =
candidate && /^[a-f0-9]{64}$/.test(candidate) ? await options.store.get(candidate) : undefined;
const id = stored ? candidate! : randomBytes(32).toString('hex');
const data = stored ?? {};
const setCookie = `${name}=${id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ttl}${options.secureCookie === false ? '' : '; Secure'}`;
let id = stored ? candidate! : randomBytes(32).toString('hex');
const previousIds: string[] = [];
const data: Record<string, unknown> = stored ? JSON.parse(JSON.stringify(stored)) : {};
const regenerate = () => {
const newId = randomBytes(32).toString('hex');
previousIds.push(id);
id = newId;
};
return {
session: new GlobalSessionContainer(data),
setCookie,
commit: () => options.store.set(id, data, Date.now() + ttl * 1000),
session: new GlobalSessionContainer(data, regenerate),
get setCookie() {
return `${name}=${id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ttl}${options.secureCookie === false ? '' : '; Secure'}`;
},
commit: async () => {
for (const oldId of previousIds) await options.store.delete(oldId);
await options.store.set(id, data, Date.now() + ttl * 1000);
},
};
}
17 changes: 15 additions & 2 deletions src/session.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { NotLoggedInException, SessionNotStartedException } from './errors.js';
import {
NotLoggedInException,
SessionNotStartedException,
SessionRegenerationException,
} from './errors.js';
import { Token } from './token.js';
import { BaseResponseData, UserResponseData } from './user.js';
export class SessionData {
Expand Down Expand Up @@ -52,16 +56,25 @@ export class SessionData {
}
}
export interface SessionContainer {
regenerate(): void;
get(key: string): unknown;
set(key: string, value: unknown): void;
contains(key: string): boolean;
remove(key: string): void;
}
/** Wrap an existing request-scoped session; never a process-global session. */
export class GlobalSessionContainer implements SessionContainer {
constructor(private readonly data?: Record<string, unknown>) {
constructor(
private readonly data?: Record<string, unknown>,
private readonly regenerateSession?: () => void,
) {
if (!data) throw new SessionNotStartedException();
}
regenerate(): void {
if (!this.regenerateSession)
throw new SessionRegenerationException('Supply a session regeneration callback');
this.regenerateSession();
}
get(key: string): unknown {
const value = this.data![key];
return key === SessionData.STORE_KEY && value && !(value instanceof SessionData)
Expand Down
4 changes: 2 additions & 2 deletions test/core.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const record = () => ({
});
const setup = (data = {}, uri = '/', extra = {}) => {
const redirect = record(),
session = new A.SessionArrayWrapper(data);
session = new A.SessionArrayWrapper(data, () => {});
return {
auth: new A.Authenticator({
clientKey: key,
Expand Down Expand Up @@ -204,7 +204,7 @@ test('fake login stores data, emits decryptable response, defers current user an
assert.equal(next2.redirect.destinations.length, 2);
});
test('default redirect stops execution, default login/logout tokens, URI objects and admin', () => {
const session = new A.SessionArrayWrapper({});
const session = new A.SessionArrayWrapper({}, () => {});
const auth = new A.Authenticator({
clientKey: key,
currentUriPath: new URL('https://app.example.com/path'),
Expand Down
3 changes: 2 additions & 1 deletion test/next-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const invoke = (path, cookie) =>
fetch(origin + path, { headers: cookie ? { cookie } : {}, redirect: 'manual' });
const initial = await invoke('/login');
assert.equal(initial.status, 303);
const cookie = initial.headers.get('set-cookie').split(';')[0];
let cookie = initial.headers.get('set-cookie').split(';')[0];
const query = new URL(initial.headers.get('location')).searchParams;
const plain = decrypt(
query.get('c'),
Expand All @@ -22,6 +22,7 @@ const cipher = String(
);
const callback = await invoke('/?AUTHWAVE_RESPONSE_DATA=' + encodeURIComponent(cipher), cookie);
assert.equal(callback.status, 303);
cookie = callback.headers.get('set-cookie').split(';')[0];
assert.deepEqual(await (await invoke('/', cookie)).json(), {
id: 'next-smoke',
email: 'next@example.test',
Expand Down
2 changes: 1 addition & 1 deletion test/parity.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ for (const [i, c] of cases.entries())
new InitVector().withBytes(Buffer.from('f'.repeat(24))),
);
const state = { basket: ['tea'] };
const session = new SessionArrayWrapper(state);
const session = new SessionArrayWrapper(state, () => {});
const redirects = [];
let calls = 0;
if (c.state === 'pending')
Expand Down
6 changes: 5 additions & 1 deletion test/php-oracle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
Expand Down
Loading
Loading