From 0196ef9340f940547980ce5b62466f4a853401d9 Mon Sep 17 00:00:00 2001 From: Guillermo Pages Date: Tue, 30 Sep 2025 11:39:38 +0200 Subject: [PATCH] fix: polyfill --- src/oidc/OIDCStandardRoutes.ts | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/oidc/OIDCStandardRoutes.ts b/src/oidc/OIDCStandardRoutes.ts index 2a3dba5..0ffb342 100644 --- a/src/oidc/OIDCStandardRoutes.ts +++ b/src/oidc/OIDCStandardRoutes.ts @@ -2,9 +2,30 @@ import { Router, Request, Response } from 'express'; import express from 'express'; import cookieParser from 'cookie-parser'; import * as crypto from 'crypto'; -import fetch from 'node-fetch'; import { jwtVerify, createRemoteJWKSet, SignJWT } from 'jose'; +type FetchFn = (input: any, init?: any) => Promise; + +let cachedFetch: FetchFn | null = typeof (globalThis as any).fetch === 'function' + ? ((input: any, init?: any) => (globalThis as any).fetch(input, init)) + : null; +let fetchLoader: Promise | null = null; + +async function getFetch(): Promise { + if (cachedFetch) { + return cachedFetch; + } + + if (!fetchLoader) { + fetchLoader = import('node-fetch').then(({ default: nodeFetch }) => { + return ((input: any, init?: any) => nodeFetch(input, init)) as FetchFn; + }); + } + + cachedFetch = await fetchLoader; + return cachedFetch; +} + /** * Standard OIDC Authorization Code Flow Routes for RP * Implements the flow as specified in CLAUDE.md @@ -258,7 +279,8 @@ export function createOidcStandardRoutes(config: OidcStandardConfig): Router { ? 'Basic ' + Buffer.from(`${swissoidClientId}:${swissoidClientSecret}`).toString('base64') : undefined; - const tokenResponse = await fetch(swissoidTokenEndpoint, { + const fetchFn = await getFetch(); + const tokenResponse = await fetchFn(swissoidTokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', @@ -544,7 +566,8 @@ export function createOidcStandardRoutes(config: OidcStandardConfig): Router { result.textContent = 'Checking...'; try { - const response = await fetch('/auth/status', { + const fetchFn = await getFetch(); + const response = await fetchFn('/auth/status', { credentials: 'include' }); const data = await response.json();