// Server-side integration for a confidential client. Install openid-client v6. import * as oidc from 'openid-client' import {createHash, randomBytes} from 'node:crypto' export function newGuestKeys() { return {writerProof:randomBytes(32).toString('base64url'), claimProof:randomBytes(32).toString('base64url')} } async function post(registry, path, token, body) { const result = await fetch(new URL('/api/v3' + path, registry), { method:'POST', redirect:'error', headers:{Authorization:'Bearer ' + token, 'Content-Type':'application/json'}, body:JSON.stringify(body) }) const value = await result.json() if (!result.ok) throw Object.assign(new Error('Nexus HTTP ' + result.status + ': ' + value.error), {status:result.status, registryError:value.error}) return value } // Persist the proofs on the guest record before calling. A retry uses the same pair. export function registerGuest(registry, backendToken, name, {writerProof, claimProof}) { const hash = proof => createHash('sha256').update(proof).digest('hex') return post(registry, '/machines', backendToken, {name, writerChallenge:hash(writerProof), claimChallenge:hash(claimProof)}) } export async function startSignIn(config, {redirectUri, registry, machineId, publish = false, offline = false}) { const verifier = oidc.randomPKCECodeVerifier() const state = oidc.randomState(), nonce = oidc.randomNonce() const scope = ['openid','profile'] if (machineId) scope.push('nexus:machines:claim') if (publish) scope.push('nexus:publish') if (offline) scope.push('offline_access') const url = oidc.buildAuthorizationUrl(config, {redirect_uri:redirectUri, resource:registry, scope:scope.join(' '), state,nonce,code_challenge:await oidc.calculatePKCECodeChallenge(verifier),code_challenge_method:'S256'}) return {url, transaction:{verifier,state,nonce,machineId,registry,redirectUri, expiresAt:Date.now() + 600_000}} } // Load and consume this transaction from the initiating browser's server-side session. export async function finishSignIn(config, callbackUrl, transaction) { if (!transaction || transaction.expiresAt <= Date.now()) throw new Error('Sign-in expired.') const callback = new URL(callbackUrl) const redirect = new URL(transaction.redirectUri) if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname) throw new Error('Unexpected callback.') const tokens = await oidc.authorizationCodeGrant(config, callback, { pkceCodeVerifier:transaction.verifier,expectedState:transaction.state,expectedNonce:transaction.nonce }, {resource:transaction.registry}) return {subject:tokens.claims().sub, ...grantTokens(tokens), machineId:transaction.machineId} } function grantTokens(tokens) { return {accessToken:tokens.access_token, refreshToken:tokens.refresh_token, expiresAt:tokens.expires_in == null ? null : Date.now() + tokens.expires_in * 1000} } export async function refreshGrant(config, registry, grant) { const tokens = await oidc.refreshTokenGrant(config,grant.refreshToken,{resource:registry}) if (tokens.claims() && tokens.claims().sub !== grant.subject) throw new Error('Unexpected account on refresh.') return {...grant,...grantTokens(tokens),refreshToken:tokens.refresh_token ?? grant.refreshToken} } export function publishUpdate(registry, token, machineId) { return post(registry,'/blocks',token,{title:'Nexus Notebook update',publishAs:machineId}) } // The host loads this proof from the initiating guest's private record. // Keep the grant and pending claim until success so a failed HTTP request is retryable. export function claimGuest(registry, {accessToken,machineId}, claimProof) { return post(registry, '/machines/' + encodeURIComponent(machineId) + '/claim', accessToken, {claimProof}) }