packages/auth-client: the product side of signing in through Accounts

Start a sign-in with the return path (state, nonce, PKCE), finish it,
sign-out address, back-channel logout tokens and Accounts' signed
user.* calls. Tested against the real provider. Root lint covers
Accounts' backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 13:45:39 +02:00
co-authored by Claude Opus 5.5
parent f202a5a88e
commit a3e3921b4f
12 changed files with 318 additions and 7 deletions
+1
View File
@@ -31,6 +31,7 @@
"zod": "^4.6.7"
},
"devDependencies": {
"@crosscode/auth-client": "*",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
+1 -1
View File
@@ -7,7 +7,7 @@
* from the linked products, so neither can be typed in wrong.
*/
import { churchObjectSchema, churchSchema, CHURCH_SCHEMA, type Church } from '@crosscode/contracts';
import { z } from 'zod';
import type { z } from 'zod';
import type { Ctx } from '../context.js';
import { customerId } from '../hub/licence.js';
import { queueCall } from '../links/deliveries.js';
@@ -100,7 +100,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
pending = await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
}
const extra: Record<string, unknown> = { name: a.name, email: a.email };
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
@@ -0,0 +1,85 @@
// @crosscode/auth-client (the product side, packages/auth-client) against the real provider:
// what the Website, App and Events 3.0 will run.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { accountsClient, type AccountsClient } from '@crosscode/auth-client';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import { runDue } from '../src/links/deliveries.js';
import { signOutEverywhere } from '../src/oidc/sessions.js';
let h: Harness;
let auth: AccountsClient;
before(async () => {
h = await startHarness();
auth = await accountsClient({ accountsUrl: h.publicUrl, productUrl: h.productUrl, clientId: PRODUCT_ID, linkSecret: h.linkSecret, allowInsecure: true });
await h.makeAccount({ email: 'client@hope.test', password: 'Correct-horse-1' });
});
after(async () => { await h.close(); });
async function signInWith(returnTo: string) {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn(returnTo);
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const uid = signin.url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return auth.finishSignIn(back.url, cookie);
}
describe('@crosscode/auth-client', () => {
test('signs in and returns to the page', async () => {
const r = await signInWith('/sermons/2026/advent?part=2');
assert.equal(r.claims.email, 'client@hope.test');
assert.equal(r.returnTo, '/sermons/2026/advent?part=2');
assert.ok(r.idToken);
});
test('a foreign return address is never followed', async () => {
for (const evil of ['//evil.example/x', 'https://evil.example/', '/\\evil.example']) {
assert.equal((await signInWith(evil)).returnTo, '/', evil);
}
});
test('without the cookie from starting, finishing fails', async () => {
await assert.rejects(auth.finishSignIn(`${h.productUrl}${OIDC_CLIENT_PATHS.callback}?code=x&state=y`, undefined), /expired/);
});
test('checks Accounts\' signed calls and refuses changed ones', async () => {
const { profileChanged } = await import('../src/accounts/service.js');
const a = (await h.db.account.findUnique({ where: { email: 'client@hope.test' } }))!;
h.received.length = 0;
await profileChanged(h.ctx, a.id as string);
await runDue(h.ctx);
const call = h.received.find((r) => r.path === '/api/accounts/v1/events')!;
const read = auth.verifyAccountsCall(call.body, call.headers as Record<string, string>);
assert.equal(read.type, 'user.updated');
assert.equal(read.sub, a.id);
assert.throws(() => auth.verifyAccountsCall(call.body.replace('client@hope.test', 'attacker@evil.test'), call.headers as Record<string, string>), /isn't signed/);
});
test('checks a back-channel logout token', async () => {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn('/');
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const step = await h.api(browser, 'POST', `/api/v2/interaction/${signin.url.searchParams.get('uid')}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
const { claims } = await auth.finishSignIn(back.url, cookie);
h.received.length = 0;
await signOutEverywhere(h.ctx, h.provider, claims.sub);
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout)!;
const token = new URLSearchParams(logout.body).get('logout_token')!;
const out = await auth.verifyLogoutToken(token);
assert.equal(out.sub, claims.sub);
assert.ok(out.sid);
const [hd, p, s] = token.split('.');
const forged = `${hd}.${Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p!, 'base64url').toString()), sub: 'someone-else' })).toString('base64url')}.${s}`;
await assert.rejects(auth.verifyLogoutToken(forged), /isn't valid/);
});
test('the sign-out address ends at the product', () => {
const u = new URL(auth.signOutUrl('id-token'));
assert.equal(u.pathname, '/api/oidc/session/end');
assert.equal(u.searchParams.get('post_logout_redirect_uri'), `${h.productUrl}/`);
});
});
@@ -137,7 +137,7 @@ export async function startHarness(opts: { now?: () => Date } = {}) {
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin' || u.pathname === OIDC_CLIENT_PATHS.callback);
if (url.pathname === OIDC_CLIENT_PATHS.callback) return finishSignIn(url, started);
const uid = url.searchParams.get('uid')!;
let step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
const step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
if (step.body.stage !== 'done') return { pending: step.body, uid, started };
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return finishSignIn(back.url, started);