@@ -0,0 +1,153 @@
/**
* @crosscode/auth-client — signing in through the church's Accounts, the product side
* (docs/ACCOUNTS-1.0-PLAN.md §3– 6). The Church Website, the Church App and Cross Events 3.0 all use
* it, so every product returns people to the page they came from in the same safe way:
*
* const auth = await accountsClient({ accountsUrl, productUrl, clientId: installId, linkSecret });
* // "Sign in" (or a page that needs it):
* const { url, cookie } = await auth.startSignIn(req.originalUrl); // set `cookie` HttpOnly, then redirect to `url`
* // GET /api/auth/callback:
* const { claims, returnTo } = await auth.finishSignIn(fullCallbackUrl, cookie); // start your own session, redirect to returnTo
* // POST /api/auth/backchannel-logout:
* const { sub, sid } = await auth.verifyLogoutToken(form.logout_token); // end that person's sessions
* // POST /api/accounts/v1/events:
* const call = auth.verifyAccountsCall(rawBody, headers); // user.updated / user.deleted / user.export
*
* The client secret is derived from the product's link with Accounts (Connect), so a product only
* keeps its link secret. Roles are never in the claims: each product keeps its own, keyed by `sub`.
*/
import crypto from 'node:crypto' ;
import * as oidc from 'openid-client' ;
import {
accountsCallSchema , ACR_MFA , decodeState , encodeState , identityClaimsSchema , OIDC_CLIENT_PATHS , OIDC_PROVIDER_PATHS , OIDC_SCOPES ,
safeReturnPath , type AccountsCall , type IdentityClaims ,
} from '@crosscode/contracts' ;
import { LINK_HEADERS , oidcClientSecret , verify } from '@crosscode/contracts/signing' ;
export type AccountsClientOptions = {
/** The church's Accounts address, e.g. https://accounts.hopefamily.co.za */
accountsUrl : string ;
/** This product's address as the Hub lists it, e.g. https://www.hopefamily.co.za */
productUrl : string ;
/** This product's Hub install id (its client_id at Accounts). */
clientId : string ;
/** The secret of this product's link with Accounts. */
linkSecret : string ;
/** Local testing only: allow http. */
allowInsecure? : boolean ;
} ;
/** What goes in the short-lived HttpOnly cookie between starting and finishing a sign-in. */
type Pending = { nonce : string ; verifier : string ; state : string } ;
export class SignInError extends Error {
constructor ( message : string , public code : string ) {
super ( message ) ;
}
}
export async function accountsClient ( o : AccountsClientOptions ) {
const base = o . productUrl . replace ( /\/+$/ , '' ) ;
const issuer = new URL ( ` ${ o . accountsUrl . replace ( /\/+$/ , '' ) } ${ OIDC_PROVIDER_PATHS . issuer } ` ) ;
const config = await oidc . discovery ( issuer , o . clientId , oidcClientSecret ( o . linkSecret ) , undefined , o . allowInsecure ? { execute : [ oidc . allowInsecureRequests ] } : undefined ) ;
const redirectUri = ` ${ base } ${ OIDC_CLIENT_PATHS . callback } ` ;
return {
config ,
/** Starts a sign-in that comes back to `returnTo` (the page the person was on). `requireTwoFactor` for staff roles. */
async startSignIn ( returnTo : string , opts : { requireTwoFactor? : boolean ; loginHint? : string } = { } ) {
const nonce = oidc . randomNonce ( ) ;
const verifier = oidc . randomPKCECodeVerifier ( ) ;
const state = encodeState ( { nonce : crypto.randomBytes ( 16 ) . toString ( 'base64url' ) , returnTo : safeReturnPath ( returnTo ) } ) ;
const url = oidc . buildAuthorizationUrl ( config , {
redirect_uri : redirectUri ,
scope : OIDC_SCOPES.join ( ' ' ) ,
state ,
nonce ,
code_challenge : await oidc . calculatePKCECodeChallenge ( verifier ) ,
code_challenge_method : 'S256' ,
. . . ( opts . requireTwoFactor ? { acr_values : ACR_MFA } : { } ) ,
. . . ( opts . loginHint ? { login_hint : opts.loginHint } : { } ) ,
} ) ;
const pending : Pending = { nonce , verifier , state } ;
return { url : url.toString ( ) , cookie : Buffer.from ( JSON . stringify ( pending ) ) . toString ( 'base64url' ) } ;
} ,
/** Finishes a sign-in at the callback. Returns the person and the safe page to send them to. */
async finishSignIn ( callbackUrl : string | URL , cookie : string | undefined ) : Promise < { claims : IdentityClaims ; returnTo : string ; idToken : string } > {
let pending : Pending ;
try {
pending = JSON . parse ( Buffer . from ( String ( cookie ? ? '' ) , 'base64url' ) . toString ( 'utf8' ) ) as Pending ;
} catch {
throw new SignInError ( 'The sign-in expired. Please try again.' , 'NO_PENDING' ) ;
}
if ( ! pending ? . verifier || ! pending . state ) throw new SignInError ( 'The sign-in expired. Please try again.' , 'NO_PENDING' ) ;
const tokens = await oidc . authorizationCodeGrant ( config , new URL ( callbackUrl ) , {
pkceCodeVerifier : pending.verifier , expectedState : pending.state , expectedNonce : pending.nonce , idTokenExpected : true ,
} ) ;
const parsed = identityClaimsSchema . safeParse ( tokens . claims ( ) ) ;
if ( ! parsed . success ) throw new SignInError ( 'Accounts answered with claims this product doesn\'t understand.' , 'BAD_CLAIMS' ) ;
return { claims : parsed.data , returnTo : safeReturnPath ( decodeState ( pending . state ) ? . returnTo ) , idToken : tokens.id_token ! } ;
} ,
/** Where "Sign out" sends the browser: signed out of all the church's products, then back here. */
signOutUrl ( idToken? : string ) {
return oidc . buildEndSessionUrl ( config , {
post_logout_redirect_uri : ` ${ base } ${ OIDC_CLIENT_PATHS . postLogout } ` ,
. . . ( idToken ? { id_token_hint : idToken } : { } ) ,
} ) . toString ( ) ;
} ,
/** Checks a back-channel logout token (OIDC Back-Channel Logout 1.0) and says whose sessions to end. */
async verifyLogoutToken ( token : string ) : Promise < { sub : string ; sid : string | null } > {
const [ h , p , s ] = String ( token ) . split ( '.' ) ;
if ( ! h || ! p || ! s ) throw new SignInError ( 'Not a logout token.' , 'BAD_TOKEN' ) ;
let header : { kid? : string ; alg? : string } ;
let payload : Record < string , unknown > ;
try {
header = JSON . parse ( Buffer . from ( h , 'base64url' ) . toString ( ) ) as typeof header ;
payload = JSON . parse ( Buffer . from ( p , 'base64url' ) . toString ( ) ) as typeof payload ;
} catch {
throw new SignInError ( 'Not a logout token.' , 'BAD_TOKEN' ) ;
}
const meta = config . serverMetadata ( ) ;
const jwks = ( await fetch ( meta . jwks_uri ! ) . then ( ( r ) = > r . json ( ) ) ) as { keys : ( crypto . JsonWebKey & { kid? : string } ) [ ] } ;
const jwk = jwks . keys . find ( ( k ) = > k . kid === header . kid ) ;
if ( ! jwk || header . alg !== 'ES256' ) throw new SignInError ( 'Unknown signing key.' , 'BAD_TOKEN' ) ;
const signed = crypto . verify ( 'sha256' , Buffer . from ( ` ${ h } . ${ p } ` ) , { key : crypto.createPublicKey ( { key : jwk , format : 'jwk' } ) , dsaEncoding : 'ieee-p1363' } , Buffer . from ( s , 'base64url' ) ) ;
const now = Math . floor ( Date . now ( ) / 1000 ) ;
const events = payload . events as Record < string , unknown > | undefined ;
const valid = signed
&& payload . iss === meta . issuer
&& payload . aud === o . clientId
&& ! ! events ? . [ 'http://schemas.openid.net/event/backchannel-logout' ]
&& ! ( 'nonce' in payload )
&& Number ( payload . iat ) <= now + 60
&& ( payload . exp === undefined || Number ( payload . exp ) >= now ) ;
if ( ! valid ) throw new SignInError ( 'That logout token isn\'t valid.' , 'BAD_TOKEN' ) ;
return { sub : String ( payload . sub ) , sid : payload.sid ? String ( payload . sid ) : null } ;
} ,
/** Checks and reads a back-channel call from Accounts (signed with the link secret). */
verifyAccountsCall ( rawBody : string | Uint8Array , headers : Record < string , string | string [ ] | undefined > ) : AccountsCall {
const get = ( n : string ) = > {
const v = headers [ n ] ? ? headers [ n . toLowerCase ( ) ] ;
return Array . isArray ( v ) ? v [ 0 ] : v ;
} ;
const check = verify ( { secret : o.linkSecret , timestamp : get ( LINK_HEADERS . timestamp ) , signature : get ( LINK_HEADERS . signature ) , rawBody } ) ;
if ( ! check . ok ) throw new SignInError ( 'That call isn\'t signed by Accounts.' , check . code ) ;
let body : unknown ;
try {
body = JSON . parse ( typeof rawBody === 'string' ? rawBody : Buffer.from ( rawBody ) . toString ( 'utf8' ) ) ;
} catch {
throw new SignInError ( 'Not JSON.' , 'INVALID_REQUEST' ) ;
}
const parsed = accountsCallSchema . safeParse ( body ) ;
if ( ! parsed . success ) throw new SignInError ( 'Not a crosscode.identity/1 call.' , 'INVALID_REQUEST' ) ;
return parsed . data ;
} ,
} ;
}
export type AccountsClient = Awaited < ReturnType < typeof accountsClient > > ;