From fc1f2c18ae34182c3cb3a12c19a50177b0739368 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 5 Nov 2026 15:23:33 +0000 Subject: [PATCH 1/2] Regenerate session IDs before saving authenticated users --- PARITY.md | 2 + README.md | 2 + src/authenticator.ts | 2 + src/errors.ts | 2 + src/express.ts | 55 +++++++++-- src/runtime.ts | 26 ++++-- src/session.ts | 17 +++- test/core.test.mjs | 4 +- test/next-smoke.mjs | 3 +- test/parity.test.mjs | 2 +- test/php-oracle.php | 6 +- test/rotation.test.mjs | 208 +++++++++++++++++++++++++++++++++++++++++ test/runtime.test.mjs | 12 ++- 13 files changed, 319 insertions(+), 22 deletions(-) create mode 100644 test/rotation.test.mjs diff --git a/PARITY.md b/PARITY.md index 6529718..43bb7ba 100644 --- a/PARITY.md +++ b/PARITY.md @@ -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. diff --git a/README.md b/README.md index 6bcc14b..4b0d79f 100644 --- a/README.md +++ b/README.md @@ -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. 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 ------------- diff --git a/src/authenticator.ts b/src/authenticator.ts index 5b4cc77..b244a1b 100644 --- a/src/authenticator.ts +++ b/src/authenticator.ts @@ -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)); @@ -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); diff --git a/src/errors.ts b/src/errors.ts index 2860237..c1cd073 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 SessionRegenerationException extends AuthwaveException {} diff --git a/src/express.ts b/src/express.ts index cb3c5e4..ddecc8f 100644 --- a/src/express.ts +++ b/src/express.ts @@ -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; @@ -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, @@ -28,22 +32,57 @@ export function createExpressHandler( ): Promise => { try { if (!req.session) throw new SessionNotStartedException('Mount express-session first'); + const staged: Record = {}; + const original = req.session as Record; + 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), + 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; + delete preserved[SessionData.STORE_KEY]; + await new Promise((resolve, reject) => + req.session!.regenerate((error) => (error ? reject(error) : resolve())), + ); + Object.assign(req.session!, preserved); + } + const target = req.session as Record; + 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((resolve, reject) => - req.session!.save((error) => (error ? reject(error) : resolve())), - ); + if (req.session) + await new Promise((resolve, reject) => + req.session!.save((error) => (error ? reject(error) : resolve())), + ); } res.setHeader('Cache-Control', 'no-store'); if (redirect) res.redirect(redirect.code, redirect.uri); diff --git a/src/runtime.ts b/src/runtime.ts index 25aba00..b24d780 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -1,6 +1,7 @@ import { randomBytes } from 'node:crypto'; import { GlobalSessionContainer } from './session.js'; export interface SessionStore { + delete(id: string): Promise; get(id: string): Promise | undefined>; set(id: string, data: Record, expiresAt: number): Promise; } @@ -19,6 +20,9 @@ export class MemorySessionStore implements SessionStore { } return JSON.parse(JSON.stringify(entry.data)) as Record; } + async delete(id: string): Promise { + this.sessions.delete(id); + } async set(id: string, data: Record, expiresAt: number): Promise { for (const [key, value] of this.sessions) if (value.expiresAt <= Date.now()) this.sessions.delete(key); @@ -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 = 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); + }, }; } diff --git a/src/session.ts b/src/session.ts index adcc4ea..569a149 100644 --- a/src/session.ts +++ b/src/session.ts @@ -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 { @@ -52,6 +56,7 @@ export class SessionData { } } export interface SessionContainer { + regenerate(): void; get(key: string): unknown; set(key: string, value: unknown): void; contains(key: string): boolean; @@ -59,9 +64,17 @@ export interface SessionContainer { } /** Wrap an existing request-scoped session; never a process-global session. */ export class GlobalSessionContainer implements SessionContainer { - constructor(private readonly data?: Record) { + constructor( + private readonly data?: Record, + 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) diff --git a/test/core.test.mjs b/test/core.test.mjs index 7236f8b..19fc03e 100644 --- a/test/core.test.mjs +++ b/test/core.test.mjs @@ -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, @@ -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'), diff --git a/test/next-smoke.mjs b/test/next-smoke.mjs index fb04b58..516b0de 100644 --- a/test/next-smoke.mjs +++ b/test/next-smoke.mjs @@ -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'), @@ -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', diff --git a/test/parity.test.mjs b/test/parity.test.mjs index b32c9d0..a10cc97 100644 --- a/test/parity.test.mjs +++ b/test/parity.test.mjs @@ -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') 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/rotation.test.mjs b/test/rotation.test.mjs new file mode 100644 index 0000000..82e4473 --- /dev/null +++ b/test/rotation.test.mjs @@ -0,0 +1,208 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + Authenticator, + Token, + SessionData, + SessionArrayWrapper, + UserResponseData, + CipherText, + RedirectSignal, + NotLoggedInException, + SessionRegenerationException, +} from '../dist/index.js'; +import { openSession, MemorySessionStore } from '../dist/runtime.js'; +import { createExpressHandler } from '../dist/express.js'; +const secret = 's'.repeat(32), + clientKey = 'deployment_' + secret; +function pending() { + const token = new Token(secret); + const data = { [SessionData.STORE_KEY]: new SessionData(token), basket: ['tea'] }; + const cipher = String( + new CipherText('{"id":"user-id","email":"person@example.com"}', token.getSecretIv(), secret), + ); + return { data, uri: '/callback?AUTHWAVE_RESPONSE_DATA=' + encodeURIComponent(cipher) }; +} +test('core regenerates before storing identity or invoking the callback', () => { + const { data, uri } = pending(); + const events = []; + const session = new SessionArrayWrapper(data, () => { + assert.throws(() => session.get(SessionData.STORE_KEY).getData(), NotLoggedInException); + events.push('rotate'); + }); + assert.throws( + () => + new Authenticator({ + clientKey, + currentUriPath: uri, + session, + onAuthenticated: () => { + assert.deepEqual(events, ['rotate']); + events.push('callback'); + }, + }), + RedirectSignal, + ); + assert.deepEqual(events, ['rotate', 'callback']); + assert.deepEqual(data.basket, ['tea']); +}); +test('custom core containers must supply rotation, including for fake login', () => { + const { data, uri } = pending(); + const session = new SessionArrayWrapper(data); + let called = false; + assert.throws( + () => + new Authenticator({ + clientKey, + currentUriPath: uri, + session, + onAuthenticated: () => { + called = true; + }, + }), + SessionRegenerationException, + ); + assert.equal(called, false); + assert.throws(() => session.get(SessionData.STORE_KEY).getData(), NotLoggedInException); + const fresh = {}; + const auth = new Authenticator({ + clientKey, + currentUriPath: '/', + session: new SessionArrayWrapper(fresh), + }); + assert.throws(() => auth.fakeLogin('dev'), SessionRegenerationException); + assert.deepEqual(fresh, {}); +}); +test('invalid responses and ordinary restoration do not rotate', () => { + const { data } = pending(); + let rotations = 0; + const session = new SessionArrayWrapper(data, () => { + rotations++; + }); + assert.throws( + () => new Authenticator({ clientKey, currentUriPath: '/?AUTHWAVE_RESPONSE_DATA=bad', session }), + ); + assert.equal(rotations, 0); + const token = session.get(SessionData.STORE_KEY).getToken(); + session.set(SessionData.STORE_KEY, new SessionData(token, new UserResponseData('user', 'email'))); + assert.equal(new Authenticator({ clientKey, currentUriPath: '/', session }).isLoggedIn(), true); + assert.equal(rotations, 0); +}); +test('runtime invalidates the old ID before saving identity and keeps other values', async () => { + const store = new MemorySessionStore(); + const { data, uri } = pending(); + const oldId = 'a'.repeat(64); + await store.set(oldId, data, Date.now() + 60000); + const events = []; + const set = store.set.bind(store), + del = store.delete.bind(store); + store.delete = async (id) => { + events.push('delete'); + await del(id); + }; + store.set = async (id, value, expires) => { + events.push('save'); + assert.equal(await store.get(oldId), undefined); + await set(id, value, expires); + }; + const context = await openSession('authwave.sid=' + oldId, { store }); + assert.throws( + () => new Authenticator({ clientKey, currentUriPath: uri, session: context.session }), + RedirectSignal, + ); + assert.equal((await store.get(oldId))[SessionData.STORE_KEY].data, null); + await context.commit(); + assert.deepEqual(events, ['delete', 'save']); + const cookie = context.setCookie.split(';')[0]; + assert.notEqual(cookie, 'authwave.sid=' + oldId); + const restored = await openSession(cookie, { store }); + assert.equal( + new Authenticator({ clientKey, currentUriPath: '/', session: restored.session }).getAuthUser() + .id, + 'user-id', + ); + assert.deepEqual(restored.session.get('basket'), ['tea']); + const replay = await openSession('authwave.sid=' + oldId, { store }); + assert.throws( + () => new Authenticator({ clientKey, currentUriPath: uri, session: replay.session }), + RedirectSignal, + ); + assert.equal(replay.session.contains(SessionData.STORE_KEY), false); +}); +test('failed invalidation prevents the runtime saving authenticated state', async () => { + const { data, uri } = pending(); + let saves = 0; + const store = { + get: async () => JSON.parse(JSON.stringify(data)), + delete: async () => { + throw new Error('delete failed'); + }, + set: async () => { + saves++; + }, + }; + const context = await openSession('authwave.sid=' + 'a'.repeat(64), { store }); + assert.throws( + () => new Authenticator({ clientKey, currentUriPath: uri, session: context.session }), + RedirectSignal, + ); + await assert.rejects(context.commit(), /delete failed/); + assert.equal(saves, 0); +}); +for (const fail of [false, true]) + test(`Express regenerates before persisting identity (failure=${fail})`, async () => { + const { data, uri } = pending(); + const events = []; + let callback = false; + let result; + const original = { + ...data, + save(done) { + events.push('save'); + done(); + }, + regenerate(done) { + events.push('rotate'); + assert.throws(() => original[SessionData.STORE_KEY].getData(), NotLoggedInException); + if (fail) { + done(new Error('rotation failed')); + return; + } + req.session = { save: original.save, regenerate: original.regenerate }; + done(); + }, + }; + const req = { originalUrl: uri, session: original }; + await createExpressHandler( + { + clientKey, + onAuthenticated: () => { + callback = true; + assert.equal(req.session[SessionData.STORE_KEY].getData().getId(), 'user-id'); + }, + }, + () => assert.fail('callback should redirect'), + )( + req, + { + setHeader() {}, + redirect() { + result = 'redirect'; + }, + send() {}, + }, + (error) => { + result = error; + }, + ); + if (fail) { + assert.match(result.message, /rotation failed/); + assert.equal(callback, false); + assert.throws(() => original[SessionData.STORE_KEY].getData(), NotLoggedInException); + } else { + assert.equal(result, 'redirect'); + assert.equal(callback, true); + assert.deepEqual(req.session.basket, ['tea']); + assert.deepEqual(events, ['rotate', 'save']); + } + }); diff --git a/test/runtime.test.mjs b/test/runtime.test.mjs index d414809..b97f974 100644 --- a/test/runtime.test.mjs +++ b/test/runtime.test.mjs @@ -82,15 +82,24 @@ for (const runtime of ['node', 'express', 'next']) } const first = await invoke('/login'); assert.equal(first.status, 303); - const cookie = first.headers.get('set-cookie').split(';')[0]; + let cookie = first.headers.get('set-cookie').split(';')[0]; assert.ok(cookie); + const oldCookie = cookie; const callback = simulateProvider(first.headers.get('location')); const completed = await invoke(callback, cookie); assert.equal(completed.status, 303); assert.equal(new URL(completed.headers.get('location'), origin).pathname, '/callback'); + cookie = completed.headers.get('set-cookie').split(';')[0]; + assert.notEqual(cookie, oldCookie); + const oldSession = await invoke('/callback', oldCookie); + assert.equal((await oldSession.json()).loggedIn, false); + const replay = await invoke(callback, oldCookie); + assert.equal(replay.status, 303); const restored = await invoke('/callback', cookie); assert.deepEqual(await restored.json(), { loggedIn: true, id: 'user-id' }); assert.equal(restored.headers.get('cache-control'), 'no-store'); + const restoredCookie = restored.headers.get('set-cookie'); + if (restoredCookie) assert.equal(restoredCookie.split(';')[0], cookie); const outsider = await invoke('/callback'); assert.equal((await outsider.json()).loggedIn, false); const logout = await invoke('/logout', cookie); @@ -137,6 +146,7 @@ test('store failures prevent redirects; Express missing session reaches next', a clientKey, store: { get: async () => undefined, + delete: async () => {}, set: async () => { throw new Error('store failed'); }, From 3d4f9ad124b41c6982c456778f73281e6715056a Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 5 Nov 2026 15:30:54 +0000 Subject: [PATCH 2/2] Run client checks and PHP parity tests on pull requests --- .github/workflows/ci.yml | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 .github/workflows/ci.yml 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