@axa-fr/oidc-client-service-worker 7.29.7 → 7.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +64 -0
  2. package/dist/OidcServiceWorker.d.ts +2 -1
  3. package/dist/OidcServiceWorker.d.ts.map +1 -0
  4. package/dist/OidcServiceWorker.js +995 -765
  5. package/dist/OidcServiceWorker.js.map +1 -1
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/crypto.d.ts.map +1 -0
  8. package/dist/dpop.d.ts.map +1 -0
  9. package/dist/jwt.d.ts.map +1 -0
  10. package/dist/oidcConfig.d.ts.map +1 -0
  11. package/dist/protocol.d.ts +140 -2
  12. package/dist/protocol.d.ts.map +1 -0
  13. package/dist/protocol.js +50 -2
  14. package/dist/protocol.js.map +1 -1
  15. package/dist/resource.d.ts +22 -0
  16. package/dist/resource.d.ts.map +1 -0
  17. package/dist/tokenContexts.d.ts +5 -0
  18. package/dist/tokenContexts.d.ts.map +1 -0
  19. package/dist/{src/types.d.ts → types.d.ts} +26 -1
  20. package/dist/types.d.ts.map +1 -0
  21. package/dist/utils/codeVerifier.d.ts.map +1 -0
  22. package/dist/{src/utils → utils}/domains.d.ts +2 -2
  23. package/dist/utils/domains.d.ts.map +1 -0
  24. package/dist/utils/index.d.ts.map +1 -0
  25. package/dist/utils/normalizeUrl.d.ts.map +1 -0
  26. package/dist/utils/serializeHeaders.d.ts.map +1 -0
  27. package/dist/utils/shouldBypassDestination.d.ts.map +1 -0
  28. package/dist/utils/sleep.d.ts.map +1 -0
  29. package/dist/utils/strings.d.ts.map +1 -0
  30. package/dist/{src/utils → utils}/tokens.d.ts +12 -3
  31. package/dist/utils/tokens.d.ts.map +1 -0
  32. package/dist/utils/waitForValidTokens.d.ts.map +1 -0
  33. package/dist/version.d.ts +3 -0
  34. package/dist/version.d.ts.map +1 -0
  35. package/package.json +3 -2
  36. package/src/OidcServiceWorker.ts +290 -34
  37. package/src/__tests__/jwt.spec.ts +17 -0
  38. package/src/__tests__/resource.spec.ts +98 -0
  39. package/src/__tests__/workerResource.spec.ts +919 -0
  40. package/src/jwt.ts +4 -1
  41. package/src/oidcConfig.ts +2 -1
  42. package/src/protocol.ts +16 -1
  43. package/src/resource.ts +104 -0
  44. package/src/tokenContexts.ts +39 -0
  45. package/src/types.ts +27 -1
  46. package/src/utils/domains.ts +20 -2
  47. package/src/utils/tokens.ts +155 -8
  48. package/src/version.ts +1 -1
  49. package/dist/src/OidcServiceWorker.d.ts +0 -2
  50. package/dist/src/OidcServiceWorker.d.ts.map +0 -1
  51. package/dist/src/__tests__/jwt.spec.d.ts +0 -2
  52. package/dist/src/__tests__/jwt.spec.d.ts.map +0 -1
  53. package/dist/src/__tests__/oidcConfig.spec.d.ts +0 -2
  54. package/dist/src/__tests__/oidcConfig.spec.d.ts.map +0 -1
  55. package/dist/src/__tests__/protocol.spec.d.ts +0 -2
  56. package/dist/src/__tests__/protocol.spec.d.ts.map +0 -1
  57. package/dist/src/constants.d.ts.map +0 -1
  58. package/dist/src/crypto.d.ts.map +0 -1
  59. package/dist/src/dpop.d.ts.map +0 -1
  60. package/dist/src/jwt.d.ts.map +0 -1
  61. package/dist/src/oidcConfig.d.ts.map +0 -1
  62. package/dist/src/protocol.d.ts +0 -134
  63. package/dist/src/protocol.d.ts.map +0 -1
  64. package/dist/src/types.d.ts.map +0 -1
  65. package/dist/src/utils/__tests__/codeVerifier.spec.d.ts +0 -2
  66. package/dist/src/utils/__tests__/codeVerifier.spec.d.ts.map +0 -1
  67. package/dist/src/utils/__tests__/domains.spec.d.ts +0 -2
  68. package/dist/src/utils/__tests__/domains.spec.d.ts.map +0 -1
  69. package/dist/src/utils/__tests__/normalizeUrl.spec.d.ts +0 -2
  70. package/dist/src/utils/__tests__/normalizeUrl.spec.d.ts.map +0 -1
  71. package/dist/src/utils/__tests__/serializeHeaders.spec.d.ts +0 -2
  72. package/dist/src/utils/__tests__/serializeHeaders.spec.d.ts.map +0 -1
  73. package/dist/src/utils/__tests__/shouldBypassDestination.spec.d.ts +0 -2
  74. package/dist/src/utils/__tests__/shouldBypassDestination.spec.d.ts.map +0 -1
  75. package/dist/src/utils/__tests__/strings.spec.d.ts +0 -2
  76. package/dist/src/utils/__tests__/strings.spec.d.ts.map +0 -1
  77. package/dist/src/utils/__tests__/testHelper.d.ts +0 -58
  78. package/dist/src/utils/__tests__/testHelper.d.ts.map +0 -1
  79. package/dist/src/utils/__tests__/tokens.spec.d.ts +0 -2
  80. package/dist/src/utils/__tests__/tokens.spec.d.ts.map +0 -1
  81. package/dist/src/utils/__tests__/waitForValidTokens.spec.d.ts +0 -2
  82. package/dist/src/utils/__tests__/waitForValidTokens.spec.d.ts.map +0 -1
  83. package/dist/src/utils/codeVerifier.d.ts.map +0 -1
  84. package/dist/src/utils/domains.d.ts.map +0 -1
  85. package/dist/src/utils/index.d.ts.map +0 -1
  86. package/dist/src/utils/normalizeUrl.d.ts.map +0 -1
  87. package/dist/src/utils/serializeHeaders.d.ts.map +0 -1
  88. package/dist/src/utils/shouldBypassDestination.d.ts.map +0 -1
  89. package/dist/src/utils/sleep.d.ts.map +0 -1
  90. package/dist/src/utils/strings.d.ts.map +0 -1
  91. package/dist/src/utils/tokens.d.ts.map +0 -1
  92. package/dist/src/utils/waitForValidTokens.d.ts.map +0 -1
  93. package/dist/src/version.d.ts +0 -3
  94. package/dist/src/version.d.ts.map +0 -1
  95. /package/dist/{src/constants.d.ts → constants.d.ts} +0 -0
  96. /package/dist/{src/crypto.d.ts → crypto.d.ts} +0 -0
  97. /package/dist/{src/dpop.d.ts → dpop.d.ts} +0 -0
  98. /package/dist/{src/jwt.d.ts → jwt.d.ts} +0 -0
  99. /package/dist/{src/oidcConfig.d.ts → oidcConfig.d.ts} +0 -0
  100. /package/dist/{src/utils → utils}/codeVerifier.d.ts +0 -0
  101. /package/dist/{src/utils → utils}/index.d.ts +0 -0
  102. /package/dist/{src/utils → utils}/normalizeUrl.d.ts +0 -0
  103. /package/dist/{src/utils → utils}/serializeHeaders.d.ts +0 -0
  104. /package/dist/{src/utils → utils}/shouldBypassDestination.d.ts +0 -0
  105. /package/dist/{src/utils → utils}/sleep.d.ts +0 -0
  106. /package/dist/{src/utils → utils}/strings.d.ts +0 -0
  107. /package/dist/{src/utils → utils}/waitForValidTokens.d.ts +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"OidcServiceWorker.js","names":["getCurrentDatabasesTokenEndpoint"],"sources":["../src/constants.ts","../src/jwt.ts","../src/crypto.ts","../src/dpop.ts","../src/utils/normalizeUrl.ts","../src/utils/domains.ts","../src/utils/serializeHeaders.ts","../src/utils/shouldBypassDestination.ts","../src/utils/sleep.ts","../src/utils/tokens.ts","../src/utils/waitForValidTokens.ts","../src/oidcConfig.ts","../src/utils/codeVerifier.ts","../src/version.ts","../src/OidcServiceWorker.ts"],"sourcesContent":["const scriptFilename = 'OidcTrustedDomains.js';\nconst acceptAnyDomainToken = '*';\n\ntype TokenType = {\n readonly REFRESH_TOKEN: string;\n readonly ACCESS_TOKEN: string;\n readonly NONCE_TOKEN: string;\n readonly CODE_VERIFIER: string;\n};\n\nconst TOKEN: TokenType = {\n REFRESH_TOKEN: 'REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER',\n ACCESS_TOKEN: 'ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER',\n NONCE_TOKEN: 'NONCE_SECURED_BY_OIDC_SERVICE_WORKER',\n CODE_VERIFIER: 'CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER',\n};\n\ntype TokenRenewModeType = {\n readonly access_token_or_id_token_invalid: string;\n readonly access_token_invalid: string;\n readonly id_token_invalid: string;\n};\n\nconst TokenRenewMode: TokenRenewModeType = {\n access_token_or_id_token_invalid: 'access_token_or_id_token_invalid',\n access_token_invalid: 'access_token_invalid',\n id_token_invalid: 'id_token_invalid',\n};\n\nconst openidWellknownUrlEndWith = '/.well-known/openid-configuration';\n\nexport { acceptAnyDomainToken, openidWellknownUrlEndWith, scriptFilename, TOKEN, TokenRenewMode };\n","// code base on https://coolaj86.com/articles/sign-jwt-webcrypto-vanilla-js/\n\n// String (UCS-2) to Uint8Array\n//\n// because... JavaScript, Strings, and Buffers\n// @ts-ignore\nimport { DemonstratingProofOfPossessionConfiguration } from './types';\n\nfunction strToUint8(str: string) {\n return new TextEncoder().encode(str);\n}\n\n// Binary String to URL-Safe Base64\n//\n// btoa (Binary-to-Ascii) means \"binary string\" to base64\n// @ts-ignore\nfunction binToUrlBase64(bin) {\n return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+/g, '');\n}\n\n// UTF-8 to Binary String\n//\n// Because JavaScript has a strange relationship with strings\n// https://coolaj86.com/articles/base64-unicode-utf-8-javascript-and-you/\n// @ts-ignore\nfunction utf8ToBinaryString(str) {\n const escstr = encodeURIComponent(str);\n // replaces any uri escape sequence, such as %0A,\n // with binary escape, such as 0x0A\n // @ts-ignore\n return escstr.replace(/%([0-9A-F]{2})/g, function (match: string, p1) {\n return String.fromCharCode(parseInt(p1, 16));\n });\n}\n\n// Uint8Array to URL Safe Base64\n//\n// the shortest distant between two encodings... binary string\n// @ts-ignore\nexport const uint8ToUrlBase64 = (uint8: Uint8Array) => {\n let bin = '';\n // @ts-ignore\n uint8.forEach(function (code) {\n bin += String.fromCharCode(code);\n });\n return binToUrlBase64(bin);\n};\n\n// UCS-2 String to URL-Safe Base64\n//\n// btoa doesn't work on UTF-8 strings\n// @ts-ignore\nfunction strToUrlBase64(str) {\n return binToUrlBase64(utf8ToBinaryString(str));\n}\n\nexport const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration =\n {\n importKeyAlgorithm: {\n name: 'ECDSA',\n namedCurve: 'P-256',\n hash: { name: 'ES256' },\n },\n signAlgorithm: { name: 'ECDSA', hash: { name: 'SHA-256' } },\n generateKeyAlgorithm: {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n digestAlgorithm: { name: 'SHA-256' },\n jwtHeaderAlgorithm: 'ES256',\n };\n\n// @ts-ignore\nconst sign =\n (w: any) =>\n async (\n jwk: any,\n headers: any,\n claims: any,\n demonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration,\n jwtHeaderType = 'dpop+jwt',\n ) => {\n // Make a shallow copy of the key\n // (to set ext if it wasn't already set)\n jwk = Object.assign({}, jwk);\n\n // The headers should probably be empty\n headers.typ = jwtHeaderType;\n headers.alg = demonstratingProofOfPossessionConfiguration.jwtHeaderAlgorithm;\n switch (headers.alg) {\n case 'ES256': //if (!headers.kid) {\n // alternate: see thumbprint function below\n headers.jwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };\n //}\n break;\n case 'RS256':\n headers.jwk = { kty: jwk.kty, n: jwk.n, e: jwk.e, kid: headers.kid };\n break;\n default:\n throw new Error('Unknown or not implemented JWS algorithm');\n }\n\n const jws = {\n // @ts-ignore\n // JWT \"headers\" really means JWS \"protected headers\"\n protected: strToUrlBase64(JSON.stringify(headers)),\n // @ts-ignore\n // JWT \"claims\" are really a JSON-defined JWS \"payload\"\n payload: strToUrlBase64(JSON.stringify(claims)),\n };\n\n // To import as EC (ECDSA, P-256, SHA-256, ES256)\n const keyType = demonstratingProofOfPossessionConfiguration.importKeyAlgorithm;\n\n // To make re-exportable as JSON (or DER/PEM)\n const exportable = true;\n\n // Import as a private key that isn't black-listed from signing\n const privileges = ['sign'];\n\n // Actually do the import, which comes out as an abstract key type\n // @ts-ignore\n const privateKey = await w.crypto.subtle.importKey('jwk', jwk, keyType, exportable, privileges);\n // Convert UTF-8 to Uint8Array ArrayBuffer\n // @ts-ignore\n const data = strToUint8(`${jws.protected}.${jws.payload}`);\n\n // The signature and hash should match the bit-entropy of the key\n // https://tools.ietf.org/html/rfc7518#section-3\n const signatureType = demonstratingProofOfPossessionConfiguration.signAlgorithm;\n\n const signature = await w.crypto.subtle.sign(signatureType, privateKey, data);\n // returns an ArrayBuffer containing a JOSE (not X509) signature,\n // which must be converted to Uint8 to be useful\n // @ts-ignore\n jws.signature = uint8ToUrlBase64(new Uint8Array(signature));\n // JWT is just a \"compressed\", \"protected\" JWS\n // @ts-ignore\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n };\n\nexport const JWT = { sign };\n\n// @ts-ignore\nconst generate =\n (w: any) => async (generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams) => {\n const keyType = generateKeyAlgorithm;\n const exportable = true;\n const privileges = ['sign', 'verify'];\n // @ts-ignore\n const key = await w.crypto.subtle.generateKey(keyType, exportable, privileges);\n // returns an abstract and opaque WebCrypto object,\n // which in most cases you'll want to export as JSON to be able to save\n return await w.crypto.subtle.exportKey('jwk', key.privateKey);\n };\n\n// Create a Public Key from a Private Key\n//\n// chops off the private parts\n// @ts-ignore\nconst neuter = jwk => {\n const copy = Object.assign({}, jwk);\n delete copy.d;\n copy.key_ops = ['verify'];\n return copy;\n};\n\nconst EC = {\n generate,\n neuter,\n};\n// @ts-ignore\nconst thumbprint = (w: any) => async (jwk, digestAlgorithm: AlgorithmIdentifier) => {\n let sortedPub;\n // lexigraphically sorted, no spaces\n switch (jwk.kty) {\n case 'EC':\n sortedPub = '{\"crv\":\"CRV\",\"kty\":\"EC\",\"x\":\"X\",\"y\":\"Y\"}'\n .replace('CRV', jwk.crv)\n .replace('X', jwk.x)\n .replace('Y', jwk.y);\n break;\n case 'RSA':\n sortedPub = '{\"e\":\"E\",\"kty\":\"RSA\",\"n\":\"N\"}'.replace('E', jwk.e).replace('N', jwk.n);\n break;\n default:\n throw new Error('Unknown or not implemented JWK type');\n }\n // The hash should match the size of the key,\n // but we're only dealing with P-256\n const hash = await w.crypto.subtle.digest(digestAlgorithm, strToUint8(sortedPub));\n return uint8ToUrlBase64(new Uint8Array(hash));\n};\n\nexport const JWK = { thumbprint };\n\nexport const generateJwkAsync =\n (w: any) => async (generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams) => {\n // @ts-ignore\n const jwk = await EC.generate(w)(generateKeyAlgorithm);\n // console.info('Private Key:', JSON.stringify(jwk));\n // @ts-ignore\n // console.info('Public Key:', JSON.stringify(EC.neuter(jwk)));\n return jwk;\n };\n\nexport const generateJwtDemonstratingProofOfPossessionAsync =\n (w: any) =>\n (demonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration) =>\n async (jwk: any, method = 'POST', url: string, extrasClaims = {}) => {\n const claims = {\n // https://www.rfc-editor.org/rfc/rfc9449.html#name-concept\n jti: btoa(w.crypto.randomUUID()),\n htm: method,\n htu: url,\n iat: Math.round(Date.now() / 1000),\n ...extrasClaims,\n };\n // @ts-ignore\n const kid = await JWK.thumbprint(w)(\n jwk,\n demonstratingProofOfPossessionConfiguration.digestAlgorithm,\n );\n // @ts-ignore\n const jwt = await JWT.sign(w)(\n jwk,\n { kid: kid },\n claims,\n demonstratingProofOfPossessionConfiguration,\n );\n // console.info('JWT:', jwt);\n return jwt;\n };\n","import { uint8ToUrlBase64 } from './jwt';\n\nexport function textEncodeLite(str: string) {\n const buf = new ArrayBuffer(str.length);\n const bufView = new Uint8Array(buf);\n\n for (let i = 0; i < str.length; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return bufView;\n}\n\nexport function base64urlOfHashOfASCIIEncodingAsync(code: string): Promise<string> {\n return new Promise((resolve, reject) => {\n crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(\n buffer => {\n return resolve(uint8ToUrlBase64(new Uint8Array(buffer)));\n },\n error => reject(error),\n );\n });\n}\n","import { defaultDemonstratingProofOfPossessionConfiguration } from './jwt';\nimport { Domain, DomainDetails } from './types.js';\n\nconst isDpop = (trustedDomain: Domain[] | DomainDetails): boolean => {\n if (Array.isArray(trustedDomain)) {\n return false;\n }\n return trustedDomain.demonstratingProofOfPossession ?? false;\n};\n\nexport const getDpopConfiguration = (trustedDomain: Domain[] | DomainDetails) => {\n if (!isDpop(trustedDomain)) {\n return null;\n }\n\n if (Array.isArray(trustedDomain)) {\n return null;\n }\n\n return (\n trustedDomain.demonstratingProofOfPossessionConfiguration ??\n defaultDemonstratingProofOfPossessionConfiguration\n );\n};\n\nexport const getDpopOnlyWhenDpopHeaderPresent = (trustedDomain: Domain[] | DomainDetails) => {\n if (!isDpop(trustedDomain)) {\n return null;\n }\n\n if (Array.isArray(trustedDomain)) {\n return null;\n }\n\n return trustedDomain.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent ?? true;\n};\n","export function normalizeUrl(url: string) {\n try {\n return new URL(url).toString();\n } catch (error) {\n console.error(`Failed to normalize url: ${url}`, error);\n return url;\n }\n}\n","import { acceptAnyDomainToken, openidWellknownUrlEndWith, scriptFilename } from '../constants';\nimport { Database, Domain, DomainDetails, OidcConfig, TrustedDomains } from '../types';\nimport { normalizeUrl } from './normalizeUrl';\n\nexport function checkDomain(domains: Domain[], endpoint: string) {\n if (!endpoint) {\n return;\n }\n\n const domain = domains.find(domain => {\n let testable: RegExp;\n\n if (typeof domain === 'string') {\n testable = new RegExp(`^${domain}`);\n } else {\n testable = domain;\n }\n\n return testable.test?.(endpoint);\n });\n if (!domain) {\n throw new Error(\n 'Domain ' + endpoint + ' is not trusted, please add domain in ' + scriptFilename,\n );\n }\n}\n\nexport const getDomains = (\n trustedDomain: Domain[] | DomainDetails,\n type: 'oidc' | 'accessToken',\n) => {\n if (Array.isArray(trustedDomain)) {\n return trustedDomain;\n }\n\n return trustedDomain[`${type}Domains`] ?? trustedDomain.domains ?? [];\n};\n\nexport const getCurrentDatabaseDomain = (\n database: Database,\n url: string,\n trustedDomains: TrustedDomains,\n) => {\n if (url.endsWith(openidWellknownUrlEndWith)) {\n return null;\n }\n const datatases = [];\n for (const [key, currentDatabase] of Object.entries<OidcConfig>(database)) {\n const oidcServerConfiguration = currentDatabase.oidcServerConfiguration;\n\n if (!oidcServerConfiguration) {\n continue;\n }\n\n if (\n oidcServerConfiguration.tokenEndpoint &&\n url === normalizeUrl(oidcServerConfiguration.tokenEndpoint)\n ) {\n continue;\n }\n if (\n oidcServerConfiguration.revocationEndpoint &&\n url === normalizeUrl(oidcServerConfiguration.revocationEndpoint)\n ) {\n continue;\n }\n const trustedDomain = trustedDomains == null ? [] : trustedDomains[key.split('#')[0]];\n\n const domains = getDomains(trustedDomain, 'accessToken');\n const domainsToSendTokens = oidcServerConfiguration.userInfoEndpoint\n ? [normalizeUrl(oidcServerConfiguration.userInfoEndpoint), ...domains]\n : [...domains];\n\n let hasToSendToken = false;\n if (domainsToSendTokens.find(f => f === acceptAnyDomainToken)) {\n hasToSendToken = true;\n } else {\n for (let i = 0; i < domainsToSendTokens.length; i++) {\n let domain = domainsToSendTokens[i];\n\n if (typeof domain === 'string') {\n domain = new RegExp(`^${domain}`);\n }\n\n if (domain.test?.(url)) {\n hasToSendToken = true;\n break;\n }\n }\n }\n\n if (hasToSendToken) {\n if (currentDatabase.tokens) {\n datatases.push(currentDatabase);\n }\n }\n }\n return datatases;\n};\n","function serializeHeaders(headers: Headers): Record<string, string> {\n const headersObj: Record<string, string> = {};\n for (const key of headers.keys()) {\n const value = headers.get(key);\n if (value !== null) {\n headersObj[key] = value;\n }\n }\n return headersObj;\n}\nexport { serializeHeaders };\n","const bypassedDestinations = ['image', 'font', 'media', 'document', 'iframe', 'script'];\n\n/**\n * Determines whether a fetch event should be bypassed (not intercepted by the service worker).\n * Navigation requests (mode === 'navigate') are never bypassed, even when their destination\n * is in the bypassed list, so that access tokens can be injected into new-tab navigations.\n */\nexport const shouldBypassDestination = (destination: string, mode: string): boolean => {\n return bypassedDestinations.includes(destination) && mode !== 'navigate';\n};\n","const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\nexport { sleep };\n","/* eslint-disable simple-import-sort/exports */\nimport { TOKEN, TokenRenewMode } from '../constants';\nimport {\n AccessTokenPayload,\n IdTokenPayload,\n OidcConfig,\n OidcConfiguration,\n OidcServerConfiguration,\n Tokens,\n} from '../types';\n\nexport const parseJwt = (payload: string) => {\n return JSON.parse(b64DecodeUnicode(payload.replaceAll(/-/g, '+').replaceAll(/_/g, '/')));\n};\nfunction b64DecodeUnicode(str: string) {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n}\n\nfunction computeTimeLeft(refreshTimeBeforeTokensExpirationInSecond: number, expiresAt: number) {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n return Math.round(expiresAt - refreshTimeBeforeTokensExpirationInSecond - currentTimeUnixSecond);\n}\n\nfunction isTokensValid(tokens: Tokens | null) {\n if (!tokens) {\n return false;\n }\n return computeTimeLeft(0, tokens.expiresAt) > 0;\n}\n\nconst extractTokenPayload = (token?: string) => {\n try {\n if (!token) {\n return null;\n }\n const parts = token.split('.');\n return parts.length === 3 ? parseJwt(parts[1]) : null;\n } catch (e) {\n console.warn(e);\n }\n return null;\n};\n\n// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation (excluding rules #1, #4, #5, #7, #8, #12, and #13 which did not apply).\n// https://github.com/openid/AppAuth-JS/issues/65\nconst isTokensOidcValid = (\n tokens: Tokens,\n nonce: string | null,\n oidcServerConfiguration: OidcServerConfiguration,\n): { isValid: boolean; reason: string } => {\n if (tokens.idTokenPayload) {\n const idTokenPayload = tokens.idTokenPayload;\n // 2: The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) MUST exactly match the value of the iss (issuer) Claim.\n if (idTokenPayload && oidcServerConfiguration.issuer !== idTokenPayload.iss) {\n return {\n isValid: false,\n reason: `Issuer does not match (oidcServerConfiguration issuer) ${oidcServerConfiguration.issuer} !== (idTokenPayload issuer) ${idTokenPayload.iss}`,\n };\n }\n // 3: The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience. The aud (audience) Claim MAY contain an array with more than one element. The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n\n // 6: If the ID Token is received via direct communication between the Client and the Token Endpoint (which it is in this flow), the TLS server validation MAY be used to validate the issuer in place of checking the token signature. The Client MUST validate the signature of all other ID Tokens according to JWS [JWS] using the algorithm specified in the JWT alg Header Parameter. The Client MUST use the keys provided by the Issuer.\n\n // 9: The current time MUST be before the time represented by the exp Claim.\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n if (idTokenPayload && idTokenPayload.exp && idTokenPayload.exp < currentTimeUnixSecond) {\n return {\n isValid: false,\n reason: `Token expired at (idTokenPayload exp) ${idTokenPayload.exp} < (currentTimeUnixSecond) ${currentTimeUnixSecond}`,\n };\n }\n // 10: The iat Claim can be used to reject tokens that were issued too far away from the current time, limiting the amount of time that nonces need to be stored to prevent attacks. The acceptable range is Client specific.\n const timeInSevenDays = 60 * 60 * 24 * 7;\n if (\n idTokenPayload &&\n idTokenPayload.iat &&\n idTokenPayload.iat + timeInSevenDays < currentTimeUnixSecond\n ) {\n return {\n isValid: false,\n reason: `Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${idTokenPayload.iat + timeInSevenDays} < (currentTimeUnixSecond) ${currentTimeUnixSecond}`,\n };\n }\n // 11: If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked to verify that it is the same value as the one that was sent in the Authentication Request. The Client SHOULD check the nonce value for replay attacks. The precise method for detecting replay attacks is Client specific.\n if (idTokenPayload && nonce && idTokenPayload.nonce && idTokenPayload.nonce !== nonce) {\n return {\n isValid: false,\n reason: `Nonce does not match (nonce) ${nonce} !== (idTokenPayload nonce) ${idTokenPayload.nonce}`,\n };\n }\n }\n return { isValid: true, reason: '' };\n};\n\nfunction extractedIssueAt(\n tokens: Tokens,\n accessTokenPayload: AccessTokenPayload | null,\n _idTokenPayload: IdTokenPayload,\n) {\n if (!tokens.issued_at) {\n if (accessTokenPayload && accessTokenPayload.iat) {\n return accessTokenPayload.iat;\n } else if (_idTokenPayload && _idTokenPayload.iat) {\n return _idTokenPayload.iat;\n } else {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n return currentTimeUnixSecond;\n }\n } else if (typeof tokens.issued_at == 'string') {\n return parseInt(tokens.issued_at, 10);\n }\n return tokens.issued_at;\n}\n\nfunction _hideTokens(\n tokens: Tokens,\n currentDatabaseElement: OidcConfig,\n configurationName: string,\n) {\n if (!tokens.issued_at) {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n tokens.issued_at = currentTimeUnixSecond;\n } else if (typeof tokens.issued_at == 'string') {\n tokens.issued_at = parseInt(tokens.issued_at, 10);\n }\n\n const accessTokenPayload = extractTokenPayload(tokens.access_token);\n const secureTokens = {\n ...tokens,\n accessTokenPayload,\n };\n if (currentDatabaseElement.hideAccessToken) {\n secureTokens.access_token = `${TOKEN.ACCESS_TOKEN}_${configurationName}`;\n }\n tokens.accessTokenPayload = accessTokenPayload;\n\n // When id_token is not rotated we reuse old id_token\n const oldTokens = currentDatabaseElement.tokens;\n let id_token: string | null;\n if (oldTokens != null && 'id_token' in oldTokens && !('id_token' in tokens)) {\n id_token = oldTokens.id_token;\n } else {\n id_token = tokens.id_token;\n }\n tokens.id_token = id_token;\n\n let _idTokenPayload = null;\n if (id_token) {\n _idTokenPayload = extractTokenPayload(id_token);\n tokens.idTokenPayload = _idTokenPayload != null ? { ..._idTokenPayload } : null;\n if (_idTokenPayload && _idTokenPayload.nonce && currentDatabaseElement.nonce != null) {\n const keyNonce = `${TOKEN.NONCE_TOKEN}_${currentDatabaseElement.configurationName}`;\n _idTokenPayload.nonce = keyNonce;\n }\n secureTokens.idTokenPayload = _idTokenPayload;\n }\n if (tokens.refresh_token) {\n secureTokens.refresh_token = `${TOKEN.REFRESH_TOKEN}_${configurationName}`;\n }\n\n tokens.issued_at = extractedIssueAt(tokens, accessTokenPayload, _idTokenPayload);\n\n const expireIn =\n typeof tokens.expires_in == 'string' ? parseInt(tokens.expires_in, 10) : tokens.expires_in;\n\n const idTokenExpiresAt =\n _idTokenPayload && _idTokenPayload.exp ? _idTokenPayload.exp : Number.MAX_VALUE;\n const accessTokenExpiresAt =\n accessTokenPayload && accessTokenPayload.exp\n ? accessTokenPayload.exp\n : tokens.issued_at + expireIn;\n\n let expiresAt: number;\n const tokenRenewMode = (currentDatabaseElement.oidcConfiguration as OidcConfiguration)\n .token_renew_mode;\n if (tokenRenewMode === TokenRenewMode.access_token_invalid) {\n expiresAt = accessTokenExpiresAt;\n } else if (tokenRenewMode === TokenRenewMode.id_token_invalid) {\n expiresAt = idTokenExpiresAt;\n } else {\n expiresAt = idTokenExpiresAt < accessTokenExpiresAt ? idTokenExpiresAt : accessTokenExpiresAt;\n }\n secureTokens.expiresAt = expiresAt;\n\n tokens.expiresAt = expiresAt;\n const nonce = currentDatabaseElement.nonce ? currentDatabaseElement.nonce.nonce : null;\n const { isValid, reason } = isTokensOidcValid(\n tokens,\n nonce as string,\n currentDatabaseElement.oidcServerConfiguration as OidcServerConfiguration,\n ); // TODO: Type assertion, could be null.\n if (!isValid) {\n throw Error(`Tokens are not OpenID valid, reason: ${reason}`);\n }\n\n // When refresh_token is not rotated we reuse old refresh_token\n if (oldTokens != null && 'refresh_token' in oldTokens && !('refresh_token' in tokens)) {\n const refreshToken = oldTokens.refresh_token;\n\n currentDatabaseElement.tokens = {\n ...tokens,\n refresh_token: refreshToken,\n };\n } else {\n currentDatabaseElement.tokens = tokens;\n }\n\n currentDatabaseElement.status = 'LOGGED_IN';\n return secureTokens;\n}\n\nconst demonstratingProofOfPossessionNonceResponseHeader = 'DPoP-Nonce';\nfunction hideTokens(currentDatabaseElement: OidcConfig) {\n const configurationName = currentDatabaseElement.configurationName;\n return (response: Response) => {\n if (response.status !== 200) {\n return response;\n }\n const newHeaders = new Headers(response.headers);\n if (response.headers.has(demonstratingProofOfPossessionNonceResponseHeader)) {\n currentDatabaseElement.demonstratingProofOfPossessionNonce = response.headers.get(\n demonstratingProofOfPossessionNonceResponseHeader,\n );\n newHeaders.delete(demonstratingProofOfPossessionNonceResponseHeader);\n }\n\n return response.json().then<Response>((tokens: Tokens) => {\n const secureTokens = _hideTokens(tokens, currentDatabaseElement, configurationName);\n const body = JSON.stringify(secureTokens);\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: newHeaders,\n });\n });\n };\n}\n\nexport {\n b64DecodeUnicode,\n computeTimeLeft,\n isTokensValid,\n extractTokenPayload,\n isTokensOidcValid,\n hideTokens,\n _hideTokens,\n};\n","import { OidcConfig } from '../types';\nimport { sleep } from './sleep';\nimport { isTokensValid } from './tokens';\n\nexport const TOKEN_RENEWAL_TIMEOUT_MS = 5000;\nexport const TOKEN_RENEWAL_POLL_INTERVAL_MS = 200;\n\n/**\n * Polls until the tokens in the given config are valid, or until a timeout elapses.\n *\n * @returns `null` when tokens become valid; a synthetic 401 `Response` on timeout or\n * when the tokens are cleared while waiting (e.g. due to a parallel logout).\n */\nexport async function waitForValidTokens(\n config: OidcConfig,\n maxWaitMs = TOKEN_RENEWAL_TIMEOUT_MS,\n pollIntervalMs = TOKEN_RENEWAL_POLL_INTERVAL_MS,\n): Promise<Response | null> {\n const startTime = Date.now();\n while (config.tokens && !isTokensValid(config.tokens)) {\n if (Date.now() - startTime >= maxWaitMs) {\n return new Response(null, {\n status: 401,\n statusText: 'Token expired - service worker renewal timeout',\n });\n }\n await sleep(pollIntervalMs);\n }\n\n if (!config.tokens?.access_token) {\n return new Response(null, {\n status: 401,\n statusText: 'Missing access token',\n });\n }\n\n return null;\n}\n","import { acceptAnyDomainToken } from './constants';\nimport { Database, Domain, OidcConfig, OidcServerConfiguration, TrustedDomains } from './types';\nimport { getDomains, normalizeUrl } from './utils';\n\nconst getOidcServerUrls = (oidcServerConfiguration: OidcServerConfiguration): string[] => {\n return [\n oidcServerConfiguration.issuer,\n oidcServerConfiguration.authorizationEndpoint,\n oidcServerConfiguration.tokenEndpoint,\n oidcServerConfiguration.revocationEndpoint,\n oidcServerConfiguration.userInfoEndpoint,\n ]\n .filter(Boolean)\n .map(normalizeUrl);\n};\n\nconst isOidcServerRequest = (database: Database, normalizedUrl: string): boolean => {\n return Object.values(database).some(config => {\n const { oidcServerConfiguration } = config || {};\n if (!oidcServerConfiguration) {\n return false;\n }\n\n return getOidcServerUrls(oidcServerConfiguration).some(oidcUrl =>\n normalizedUrl.startsWith(oidcUrl),\n );\n });\n};\n\nconst isDomainMatchingUrl = (domain: Domain, normalizedUrl: string): boolean => {\n if (typeof domain === 'string') {\n domain = new RegExp(`^${domain}`);\n }\n\n return domain.test?.(normalizedUrl) ?? false;\n};\n\nconst isAccessTokenDomainRequest = (\n database: Database,\n normalizedUrl: string,\n trustedDomains: TrustedDomains,\n): boolean => {\n return Object.entries(database).some(([key, currentDatabase]) => {\n if (!currentDatabase.oidcServerConfiguration) {\n return false;\n }\n\n const trustedDomain = trustedDomains?.[key.split('#')[0]] ?? [];\n const domains = getDomains(trustedDomain, 'accessToken');\n\n if (domains.some(domain => domain === acceptAnyDomainToken)) {\n return true;\n }\n\n return domains.some(domain => isDomainMatchingUrl(domain, normalizedUrl));\n });\n};\n\nconst shouldBypassNonOidcRequest = (\n database: Database,\n normalizedUrl: string,\n trustedDomains: TrustedDomains,\n): boolean => {\n const configurations = Object.values(database);\n\n if (configurations.length === 0) {\n return false;\n }\n\n if (!configurations.every(config => config.bypassAllNonOidcRequests)) {\n return false;\n }\n\n if (!configurations.every(config => config.oidcServerConfiguration != null)) {\n return false;\n }\n\n return (\n !isOidcServerRequest(database, normalizedUrl) &&\n !isAccessTokenDomainRequest(database, normalizedUrl, trustedDomains)\n );\n};\n\nconst getMatchingOidcConfigurations = (database: Database, url: string): OidcConfig[] => {\n const normalizedUrl = normalizeUrl(url);\n return Object.values(database).filter(config => {\n const { oidcServerConfiguration } = config || {};\n const { tokenEndpoint, revocationEndpoint } = oidcServerConfiguration || {};\n\n return (\n (tokenEndpoint && normalizedUrl.startsWith(normalizeUrl(tokenEndpoint))) ||\n (revocationEndpoint && normalizedUrl.startsWith(normalizeUrl(revocationEndpoint)))\n );\n });\n};\n\nexport {\n getMatchingOidcConfigurations as getCurrentDatabasesTokenEndpoint,\n isAccessTokenDomainRequest,\n isOidcServerRequest,\n shouldBypassNonOidcRequest,\n};\n","export function replaceCodeVerifier(codeVerifier: string, newCodeVerifier: string): string {\n const regex = /[?&]code_verifier=([^&]+)/i;\n return codeVerifier.replace(regex, `&code_verifier=${newCodeVerifier}`);\n}\n\nexport const extractConfigurationNameFromCodeVerifier = (body: string): string => {\n const regex = /[?&]code_verifier=CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER_([^&]+)/;\n const match = body.match(regex);\n\n return match ? decodeURIComponent(match[1]) : '';\n};\n","export default '7.29.7';\n","import { acceptAnyDomainToken, scriptFilename, TOKEN } from './constants';\nimport { base64urlOfHashOfASCIIEncodingAsync } from './crypto';\nimport { getDpopConfiguration, getDpopOnlyWhenDpopHeaderPresent } from './dpop';\nimport { generateJwkAsync, generateJwtDemonstratingProofOfPossessionAsync } from './jwt';\nimport { getCurrentDatabasesTokenEndpoint, shouldBypassNonOidcRequest } from './oidcConfig';\nimport { Database, MessageEventData, OidcConfig, TrustedDomains } from './types';\nimport {\n checkDomain,\n getCurrentDatabaseDomain,\n getDomains,\n hideTokens,\n normalizeUrl,\n serializeHeaders,\n shouldBypassDestination,\n sleep,\n waitForValidTokens,\n} from './utils';\nimport {\n extractConfigurationNameFromCodeVerifier,\n replaceCodeVerifier,\n} from './utils/codeVerifier';\nimport version from './version';\n\n// @ts-ignore\nif (typeof trustedTypes !== 'undefined' && typeof trustedTypes.createPolicy === 'function') {\n // @ts-ignore\n trustedTypes.createPolicy('default', {\n createScriptURL: function (url: string) {\n if (url === scriptFilename) {\n return url;\n } else {\n throw new Error('Untrusted script URL blocked: ' + url);\n }\n },\n });\n}\n\nconst _self = self as ServiceWorkerGlobalScope & typeof globalThis;\n\n// `trustedDomains` is declared in the externally loaded script (OidcTrustedDomains.js)\ndeclare let trustedDomains: TrustedDomains;\n\n_self.importScripts(scriptFilename);\n\nconst id = Math.round(new Date().getTime() / 1000).toString();\nconsole.log('init service worker with id', id);\nconst keepAliveJsonFilename = 'OidcKeepAliveServiceWorker.json';\nconst database: Database = {};\n\n/**\n * Keeps the service worker alive by responding with a cached response after a sleep.\n */\nconst keepAliveAsync = async (event: FetchEvent) => {\n const originalRequest = event.request;\n const isFromVanilla = originalRequest.headers.has('oidc-vanilla');\n const init = { status: 200, statusText: 'oidc-service-worker' };\n const response = new Response('{}', init);\n\n if (!isFromVanilla) {\n const originalRequestUrl = new URL(originalRequest.url);\n const minSleepSeconds = Number(originalRequestUrl.searchParams.get('minSleepSeconds')) || 240;\n for (let i = 0; i < minSleepSeconds; i++) {\n await sleep(1000 + Math.floor(Math.random() * 1000));\n const cache = await caches.open('oidc_dummy_cache');\n await cache.put(event.request, response.clone());\n }\n }\n return response;\n};\n\n/**\n * Generates DPoP headers when a DPoP configuration is present.\n */\nasync function generateDpopAsync(\n originalRequest: Request,\n currentDatabase: OidcConfig | null,\n url: string,\n extrasClaims = {},\n) {\n const headersExtras = serializeHeaders(originalRequest.headers);\n if (\n currentDatabase?.demonstratingProofOfPossessionConfiguration &&\n currentDatabase.demonstratingProofOfPossessionJwkJson &&\n (!currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent ||\n (currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent &&\n headersExtras.dpop))\n ) {\n const dpopConfiguration = currentDatabase.demonstratingProofOfPossessionConfiguration;\n const jwk = currentDatabase.demonstratingProofOfPossessionJwkJson;\n const method = originalRequest.method;\n const dpop = await generateJwtDemonstratingProofOfPossessionAsync(self)(dpopConfiguration)(\n jwk,\n method,\n url,\n extrasClaims,\n );\n\n headersExtras.dpop = dpop;\n if (currentDatabase.demonstratingProofOfPossessionNonce != null) {\n headersExtras.nonce = currentDatabase.demonstratingProofOfPossessionNonce;\n }\n }\n return headersExtras;\n}\n\n/**\n * Intercepts fetch requests to inject access tokens and handle token endpoints.\n */\nconst handleFetch = (event: FetchEvent): void => {\n /**\n * Exit early for requests that do not need to have an auth token attached.\n */\n if (shouldBypassDestination(event.request.destination, event.request.mode)) {\n return; // Don't call event.respondWith() - let browser handle naturally\n }\n\n const normalizedUrl = normalizeUrl(event.request.url);\n if (\n !normalizedUrl.includes(keepAliveJsonFilename) &&\n shouldBypassNonOidcRequest(database, normalizedUrl, trustedDomains)\n ) {\n return; // Don't call event.respondWith() - let browser handle naturally\n }\n\n event.respondWith(\n (async (): Promise<Response> => {\n try {\n const originalRequest = event.request;\n const url = normalizedUrl;\n\n // 1) Handle keep-alive requests\n if (url.includes(keepAliveJsonFilename)) {\n return keepAliveAsync(event);\n }\n\n // Check if an access token is available for this request\n const currentDatabasesForRequestAccessToken = getCurrentDatabaseDomain(\n database,\n url,\n trustedDomains,\n );\n\n const authorization = originalRequest.headers.get('authorization');\n let authenticationMode = 'Bearer';\n let key = 'default';\n\n if (authorization) {\n const split = authorization.split(' ');\n authenticationMode = split[0];\n if (split[1]?.includes('ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER_')) {\n key = split[1].split('ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER_')[1];\n }\n }\n\n const currentDatabaseForRequestAccessToken = currentDatabasesForRequestAccessToken?.find(\n c => c.configurationName.endsWith(key),\n );\n\n // Inject the access token into the request if one is available\n if (currentDatabaseForRequestAccessToken?.tokens?.access_token) {\n // Wait for token to become valid (a parallel refresh may be in progress)\n const tokenError = await waitForValidTokens(currentDatabaseForRequestAccessToken);\n if (tokenError) {\n return tokenError;\n }\n\n // Adjust request mode for CORS if configured\n let requestMode = originalRequest.mode;\n if (\n originalRequest.mode !== 'navigate' &&\n currentDatabaseForRequestAccessToken.convertAllRequestsToCorsExceptNavigate\n ) {\n requestMode = 'cors';\n }\n\n // Build request headers\n let headers: { [p: string]: string };\n\n // Skip the access token for navigate requests when setAccessTokenToNavigateRequests is false\n if (\n originalRequest.mode === 'navigate' &&\n !currentDatabaseForRequestAccessToken.setAccessTokenToNavigateRequests\n ) {\n headers = {\n ...serializeHeaders(originalRequest.headers),\n };\n } else {\n if (\n authenticationMode.toLowerCase() === 'dpop' ||\n (!currentDatabaseForRequestAccessToken.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent &&\n currentDatabaseForRequestAccessToken.demonstratingProofOfPossessionConfiguration)\n ) {\n // DPoP mode\n const claimsExtras = {\n ath: await base64urlOfHashOfASCIIEncodingAsync(\n currentDatabaseForRequestAccessToken.tokens.access_token,\n ),\n };\n const dpopHeaders = await generateDpopAsync(\n originalRequest,\n currentDatabaseForRequestAccessToken,\n url,\n claimsExtras,\n );\n headers = {\n ...dpopHeaders,\n authorization: `DPoP ${currentDatabaseForRequestAccessToken.tokens.access_token}`,\n };\n } else {\n // Bearer mode\n headers = {\n ...serializeHeaders(originalRequest.headers),\n authorization: `${authenticationMode} ${currentDatabaseForRequestAccessToken.tokens.access_token}`,\n };\n }\n }\n\n let init: RequestInit;\n if (originalRequest.mode === 'navigate') {\n init = {\n headers: headers,\n };\n } else {\n init = {\n headers: headers,\n mode: requestMode,\n };\n }\n\n const newRequest = new Request(originalRequest, init);\n return fetch(newRequest);\n }\n\n // Pass through non-POST requests without modification\n if (event.request.method !== 'POST') {\n return fetch(originalRequest);\n }\n\n // Handle POST requests to known token/revocation endpoints\n const currentDatabases = getCurrentDatabasesTokenEndpoint(database, url);\n const numberDatabase = currentDatabases.length;\n\n if (numberDatabase > 0) {\n const responsePromise = new Promise<Response>((resolve, reject) => {\n const clonedRequest = originalRequest.clone();\n clonedRequest\n .text()\n .then(async actualBody => {\n let currentDatabase: OidcConfig | null = null;\n try {\n // Replace hidden token placeholders with the real token values\n if (\n actualBody.includes(TOKEN.REFRESH_TOKEN) ||\n actualBody.includes(TOKEN.ACCESS_TOKEN)\n ) {\n let headers = serializeHeaders(originalRequest.headers);\n let newBody = actualBody;\n\n for (let i = 0; i < numberDatabase; i++) {\n const currentDb = currentDatabases[i];\n if (currentDb?.tokens) {\n const claimsExtras = {\n ath: await base64urlOfHashOfASCIIEncodingAsync(\n currentDb.tokens.access_token,\n ),\n };\n headers = await generateDpopAsync(\n originalRequest,\n currentDb,\n url,\n claimsExtras,\n );\n\n const keyRefreshToken = encodeURIComponent(\n `${TOKEN.REFRESH_TOKEN}_${currentDb.configurationName}`,\n );\n if (actualBody.includes(keyRefreshToken)) {\n newBody = newBody.replace(\n keyRefreshToken,\n encodeURIComponent(currentDb.tokens.refresh_token as string),\n );\n currentDatabase = currentDb;\n break;\n }\n\n const keyAccessToken = encodeURIComponent(\n `${TOKEN.ACCESS_TOKEN}_${currentDb.configurationName}`,\n );\n if (actualBody.includes(keyAccessToken)) {\n newBody = newBody.replace(\n keyAccessToken,\n encodeURIComponent(currentDb.tokens.access_token),\n );\n currentDatabase = currentDb;\n break;\n }\n }\n }\n\n const fetchPromise = fetch(originalRequest, {\n body: newBody,\n method: clonedRequest.method,\n headers,\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n\n // Forward revocation requests without modifying the response body\n if (\n currentDatabase?.oidcServerConfiguration?.revocationEndpoint &&\n url.startsWith(\n normalizeUrl(currentDatabase.oidcServerConfiguration.revocationEndpoint),\n )\n ) {\n const resp = await fetchPromise;\n const txt = await resp.text();\n resolve(new Response(txt, resp));\n return;\n }\n\n // Hide real token values in the response\n const hidden = await fetchPromise.then(\n hideTokens(currentDatabase as OidcConfig),\n );\n resolve(hidden);\n return;\n }\n\n // Handle authorization code exchange: replace the PKCE code_verifier placeholder\n const isCodeVerifier = actualBody.includes('code_verifier=');\n if (isCodeVerifier) {\n const currentLoginCallbackConfigurationName =\n extractConfigurationNameFromCodeVerifier(actualBody);\n if (\n !currentLoginCallbackConfigurationName ||\n currentLoginCallbackConfigurationName === ''\n ) {\n throw new Error('No configuration name found in code_verifier');\n }\n currentDatabase = database[currentLoginCallbackConfigurationName];\n let newBody = actualBody;\n const codeVerifier = currentDatabase.codeVerifier;\n if (codeVerifier != null) {\n newBody = replaceCodeVerifier(newBody, codeVerifier);\n }\n\n const headersExtras = await generateDpopAsync(\n originalRequest,\n currentDatabase,\n url,\n );\n const resp = await fetch(originalRequest, {\n body: newBody,\n method: clonedRequest.method,\n headers: headersExtras,\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n const hidden = await hideTokens(currentDatabase)(resp);\n resolve(hidden);\n return;\n }\n\n // Pass through all other POST requests unchanged\n const normalResp = await fetch(originalRequest, {\n body: actualBody,\n method: clonedRequest.method,\n headers: serializeHeaders(originalRequest.headers),\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n resolve(normalResp);\n } catch (err) {\n reject(err);\n }\n })\n .catch(reject);\n });\n\n return responsePromise;\n }\n\n // Default: pass through the request unchanged\n return fetch(originalRequest);\n } catch (err) {\n // Surface unexpected errors as a 500 rather than silently hanging\n console.error('[OidcServiceWorker] handleFetch error:', err);\n return new Response('Service Worker Error', { status: 500 });\n }\n })(),\n );\n};\n\nconst handleMessage = async (event: ExtendableMessageEvent) => {\n const port = event.ports[0];\n const data = event.data as MessageEventData;\n\n if (event.data?.type === 'SKIP_WAITING') {\n await _self.skipWaiting();\n port?.postMessage?.({});\n return;\n } else if (event.data.type === 'claim') {\n _self.clients.claim().then(() => port.postMessage({}));\n return;\n }\n\n const configurationName = data.configurationName.split('#')[0];\n\n if (trustedDomains == null) {\n trustedDomains = {};\n }\n\n const trustedDomain = trustedDomains[configurationName];\n const allowMultiTabLogin = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.allowMultiTabLogin;\n\n const tabId = allowMultiTabLogin ? data.tabId : 'default';\n const configurationNameWithTabId = `${configurationName}#tabId=${tabId}`;\n\n let currentDatabase = database[configurationNameWithTabId];\n if (!currentDatabase) {\n const showAccessToken = Array.isArray(trustedDomain) ? false : trustedDomain.showAccessToken;\n const doNotSetAccessTokenToNavigateRequests = Array.isArray(trustedDomain)\n ? true\n : trustedDomain.setAccessTokenToNavigateRequests;\n const convertAllRequestsToCorsExceptNavigate = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.convertAllRequestsToCorsExceptNavigate;\n const bypassAllNonOidcRequests = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.bypassAllNonOidcRequests;\n\n database[configurationNameWithTabId] = {\n tokens: null,\n state: null,\n codeVerifier: null,\n oidcServerConfiguration: null,\n oidcConfiguration: undefined,\n nonce: null,\n status: null,\n configurationName: configurationNameWithTabId,\n hideAccessToken: !showAccessToken,\n setAccessTokenToNavigateRequests: doNotSetAccessTokenToNavigateRequests ?? true,\n convertAllRequestsToCorsExceptNavigate: convertAllRequestsToCorsExceptNavigate ?? false,\n demonstratingProofOfPossessionNonce: null,\n demonstratingProofOfPossessionJwkJson: null,\n demonstratingProofOfPossessionConfiguration: null,\n demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent: false,\n allowMultiTabLogin: allowMultiTabLogin ?? false,\n bypassAllNonOidcRequests: bypassAllNonOidcRequests ?? false,\n };\n currentDatabase = database[configurationNameWithTabId];\n\n if (!trustedDomains[configurationName]) {\n trustedDomains[configurationName] = [];\n }\n }\n\n switch (data.type) {\n case 'clear':\n currentDatabase.tokens = null;\n currentDatabase.state = null;\n currentDatabase.codeVerifier = null;\n currentDatabase.nonce = null;\n currentDatabase.demonstratingProofOfPossessionNonce = null;\n currentDatabase.demonstratingProofOfPossessionJwkJson = null;\n currentDatabase.demonstratingProofOfPossessionConfiguration = null;\n currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent = false;\n currentDatabase.status = data.data.status;\n port.postMessage({ configurationName });\n return;\n\n case 'init': {\n const oidcServerConfiguration = data.data.oidcServerConfiguration;\n const domains = getDomains(trustedDomain, 'oidc');\n\n if (!domains.some(domain => domain === acceptAnyDomainToken)) {\n [\n oidcServerConfiguration.tokenEndpoint,\n oidcServerConfiguration.revocationEndpoint,\n oidcServerConfiguration.userInfoEndpoint,\n oidcServerConfiguration.issuer,\n ].forEach(u => {\n checkDomain(domains, u);\n });\n }\n\n currentDatabase.oidcServerConfiguration = oidcServerConfiguration;\n currentDatabase.oidcConfiguration = data.data.oidcConfiguration;\n\n if (currentDatabase.demonstratingProofOfPossessionConfiguration == null) {\n const demonstratingProofOfPossessionConfiguration = getDpopConfiguration(trustedDomain);\n if (demonstratingProofOfPossessionConfiguration != null) {\n if (currentDatabase.oidcConfiguration.demonstrating_proof_of_possession) {\n console.warn(\n 'In service worker, demonstrating_proof_of_possession must be configured from trustedDomains file',\n );\n }\n currentDatabase.demonstratingProofOfPossessionConfiguration =\n demonstratingProofOfPossessionConfiguration;\n currentDatabase.demonstratingProofOfPossessionJwkJson = await generateJwkAsync(self)(\n demonstratingProofOfPossessionConfiguration.generateKeyAlgorithm,\n );\n currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent =\n getDpopOnlyWhenDpopHeaderPresent(trustedDomain) ?? false;\n }\n }\n\n if (!currentDatabase.tokens) {\n port.postMessage({\n tokens: null,\n status: currentDatabase.status,\n configurationName,\n version,\n });\n } else {\n const tokens = { ...currentDatabase.tokens };\n if (currentDatabase.hideAccessToken) {\n tokens.access_token = `${TOKEN.ACCESS_TOKEN}_${configurationName}#tabId=${tabId}`;\n }\n if (tokens.refresh_token) {\n tokens.refresh_token = `${TOKEN.REFRESH_TOKEN}_${configurationName}#tabId=${tabId}`;\n }\n if (tokens?.idTokenPayload?.nonce && currentDatabase.nonce != null) {\n tokens.idTokenPayload.nonce = `${TOKEN.NONCE_TOKEN}_${configurationName}#tabId=${tabId}`;\n }\n port.postMessage({\n tokens,\n status: currentDatabase.status,\n configurationName,\n version,\n });\n }\n return;\n }\n\n case 'setDemonstratingProofOfPossessionNonce': {\n currentDatabase.demonstratingProofOfPossessionNonce =\n data.data.demonstratingProofOfPossessionNonce;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getDemonstratingProofOfPossessionNonce': {\n const demonstratingProofOfPossessionNonce =\n currentDatabase.demonstratingProofOfPossessionNonce;\n port.postMessage({\n configurationName,\n demonstratingProofOfPossessionNonce,\n });\n return;\n }\n\n case 'setState': {\n currentDatabase.state = data.data.state;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getState': {\n const state = currentDatabase.state;\n port.postMessage({ configurationName, state });\n return;\n }\n\n case 'setCodeVerifier': {\n currentDatabase.codeVerifier = data.data.codeVerifier;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getCodeVerifier': {\n const codeVerifier =\n currentDatabase.codeVerifier != null\n ? `${TOKEN.CODE_VERIFIER}_${configurationName}#tabId=${tabId}`\n : null;\n port.postMessage({\n configurationName,\n codeVerifier,\n });\n return;\n }\n\n case 'setSessionState': {\n currentDatabase.sessionState = data.data.sessionState;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getSessionState': {\n const sessionState = currentDatabase.sessionState;\n port.postMessage({ configurationName, sessionState });\n return;\n }\n\n case 'setNonce': {\n const nonce = data.data.nonce;\n if (nonce) {\n currentDatabase.nonce = nonce;\n }\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getNonce': {\n const keyNonce = `${TOKEN.NONCE_TOKEN}_${configurationName}#tabId=${tabId}`;\n const nonce = currentDatabase.nonce ? keyNonce : null;\n port.postMessage({ configurationName, nonce });\n return;\n }\n\n default:\n return;\n }\n};\n\n// Event listeners\n_self.addEventListener('fetch', handleFetch);\n_self.addEventListener('message', handleMessage);\n"],"mappings":";AAAA,IAAM,iBAAiB;AAUvB,IAAM,QAAmB;CACvB,eAAe;CACf,cAAc;CACd,aAAa;CACb,eAAe;AACjB;AAQA,IAAM,iBAAqC;CACzC,kCAAkC;CAClC,sBAAsB;CACtB,kBAAkB;AACpB;;;ACnBA,SAAS,WAAW,KAAa;CAC/B,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG;AACr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BAAmB;GACtB,MAAM,eACJ,gBAAgB,gBAAgB,OAC5B,GAAG,MAAM,cAAc,GAAG,kBAAkB,SAAS,UACrD;GACN,KAAK,YAAY;IACf;IACA;GACF,CAAC;GACD;EACF;EAEA,KAAK;GACH,gBAAgB,eAAe,KAAK,KAAK;GACzC,KAAK,YAAY,EAAE,kBAAkB,CAAC;GACtC;EAGF,KAAK,mBAAmB;GACtB,MAAM,eAAe,gBAAgB;GACrC,KAAK,YAAY;IAAE;IAAmB;GAAa,CAAC;GACpD;EACF;EAEA,KAAK,YAAY;GACf,MAAM,QAAQ,KAAK,KAAK;GACxB,IAAI,OACF,gBAAgB,QAAQ;GAE1B,KAAK,YAAY,EAAE,kBAAkB,CAAC;GACtC;EACF;EAEA,KAAK,YAAY;GACf,MAAM,WAAW,GAAG,MAAM,YAAY,GAAG,kBAAkB,SAAS;GACpE,MAAM,QAAQ,gBAAgB,QAAQ,WAAW;GACjD,KAAK,YAAY;IAAE;IAAmB;GAAM,CAAC;GAC7C;EACF;EAEA,SACE;CACJ;AACF;AAGA,MAAM,iBAAiB,SAAS,WAAW;AAC3C,MAAM,iBAAiB,WAAW,aAAa"}
1
+ {"version":3,"file":"OidcServiceWorker.js","names":["getCurrentDatabasesTokenEndpoint"],"sources":["../src/constants.ts","../src/jwt.ts","../src/crypto.ts","../src/dpop.ts","../src/resource.ts","../src/tokenContexts.ts","../src/utils/normalizeUrl.ts","../src/utils/domains.ts","../src/utils/serializeHeaders.ts","../src/utils/shouldBypassDestination.ts","../src/utils/sleep.ts","../src/utils/tokens.ts","../src/utils/waitForValidTokens.ts","../src/oidcConfig.ts","../src/utils/codeVerifier.ts","../src/version.ts","../src/OidcServiceWorker.ts"],"sourcesContent":["const scriptFilename = 'OidcTrustedDomains.js';\nconst acceptAnyDomainToken = '*';\n\ntype TokenType = {\n readonly REFRESH_TOKEN: string;\n readonly ACCESS_TOKEN: string;\n readonly NONCE_TOKEN: string;\n readonly CODE_VERIFIER: string;\n};\n\nconst TOKEN: TokenType = {\n REFRESH_TOKEN: 'REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER',\n ACCESS_TOKEN: 'ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER',\n NONCE_TOKEN: 'NONCE_SECURED_BY_OIDC_SERVICE_WORKER',\n CODE_VERIFIER: 'CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER',\n};\n\ntype TokenRenewModeType = {\n readonly access_token_or_id_token_invalid: string;\n readonly access_token_invalid: string;\n readonly id_token_invalid: string;\n};\n\nconst TokenRenewMode: TokenRenewModeType = {\n access_token_or_id_token_invalid: 'access_token_or_id_token_invalid',\n access_token_invalid: 'access_token_invalid',\n id_token_invalid: 'id_token_invalid',\n};\n\nconst openidWellknownUrlEndWith = '/.well-known/openid-configuration';\n\nexport { acceptAnyDomainToken, openidWellknownUrlEndWith, scriptFilename, TOKEN, TokenRenewMode };\n","// code base on https://coolaj86.com/articles/sign-jwt-webcrypto-vanilla-js/\n\n// String (UCS-2) to Uint8Array\n//\n// because... JavaScript, Strings, and Buffers\n// @ts-ignore\nimport { DemonstratingProofOfPossessionConfiguration } from './types';\n\nfunction strToUint8(str: string) {\n return new TextEncoder().encode(str);\n}\n\n// Binary String to URL-Safe Base64\n//\n// btoa (Binary-to-Ascii) means \"binary string\" to base64\n// @ts-ignore\nfunction binToUrlBase64(bin) {\n return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+/g, '');\n}\n\n// UTF-8 to Binary String\n//\n// Because JavaScript has a strange relationship with strings\n// https://coolaj86.com/articles/base64-unicode-utf-8-javascript-and-you/\n// @ts-ignore\nfunction utf8ToBinaryString(str) {\n const escstr = encodeURIComponent(str);\n // replaces any uri escape sequence, such as %0A,\n // with binary escape, such as 0x0A\n // @ts-ignore\n return escstr.replace(/%([0-9A-F]{2})/g, function (match: string, p1) {\n return String.fromCharCode(parseInt(p1, 16));\n });\n}\n\n// Uint8Array to URL Safe Base64\n//\n// the shortest distant between two encodings... binary string\n// @ts-ignore\nexport const uint8ToUrlBase64 = (uint8: Uint8Array) => {\n let bin = '';\n // @ts-ignore\n uint8.forEach(function (code) {\n bin += String.fromCharCode(code);\n });\n return binToUrlBase64(bin);\n};\n\n// UCS-2 String to URL-Safe Base64\n//\n// btoa doesn't work on UTF-8 strings\n// @ts-ignore\nfunction strToUrlBase64(str) {\n return binToUrlBase64(utf8ToBinaryString(str));\n}\n\nexport const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration =\n {\n importKeyAlgorithm: {\n name: 'ECDSA',\n namedCurve: 'P-256',\n hash: { name: 'ES256' },\n },\n signAlgorithm: { name: 'ECDSA', hash: { name: 'SHA-256' } },\n generateKeyAlgorithm: {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n digestAlgorithm: { name: 'SHA-256' },\n jwtHeaderAlgorithm: 'ES256',\n };\n\n// @ts-ignore\nconst sign =\n (w: any) =>\n async (\n jwk: any,\n headers: any,\n claims: any,\n demonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration,\n jwtHeaderType = 'dpop+jwt',\n ) => {\n // Make a shallow copy of the key\n // (to set ext if it wasn't already set)\n jwk = Object.assign({}, jwk);\n\n // The headers should probably be empty\n headers.typ = jwtHeaderType;\n headers.alg = demonstratingProofOfPossessionConfiguration.jwtHeaderAlgorithm;\n switch (headers.alg) {\n case 'ES256': //if (!headers.kid) {\n // alternate: see thumbprint function below\n headers.jwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };\n //}\n break;\n case 'RS256':\n headers.jwk = { kty: jwk.kty, n: jwk.n, e: jwk.e, kid: headers.kid };\n break;\n default:\n throw new Error('Unknown or not implemented JWS algorithm');\n }\n\n const jws = {\n // @ts-ignore\n // JWT \"headers\" really means JWS \"protected headers\"\n protected: strToUrlBase64(JSON.stringify(headers)),\n // @ts-ignore\n // JWT \"claims\" are really a JSON-defined JWS \"payload\"\n payload: strToUrlBase64(JSON.stringify(claims)),\n };\n\n // To import as EC (ECDSA, P-256, SHA-256, ES256)\n const keyType = demonstratingProofOfPossessionConfiguration.importKeyAlgorithm;\n\n // To make re-exportable as JSON (or DER/PEM)\n const exportable = true;\n\n // Import as a private key that isn't black-listed from signing\n const privileges = ['sign'];\n\n // Actually do the import, which comes out as an abstract key type\n // @ts-ignore\n const privateKey = await w.crypto.subtle.importKey('jwk', jwk, keyType, exportable, privileges);\n // Convert UTF-8 to Uint8Array ArrayBuffer\n // @ts-ignore\n const data = strToUint8(`${jws.protected}.${jws.payload}`);\n\n // The signature and hash should match the bit-entropy of the key\n // https://tools.ietf.org/html/rfc7518#section-3\n const signatureType = demonstratingProofOfPossessionConfiguration.signAlgorithm;\n\n const signature = await w.crypto.subtle.sign(signatureType, privateKey, data);\n // returns an ArrayBuffer containing a JOSE (not X509) signature,\n // which must be converted to Uint8 to be useful\n // @ts-ignore\n jws.signature = uint8ToUrlBase64(new Uint8Array(signature));\n // JWT is just a \"compressed\", \"protected\" JWS\n // @ts-ignore\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n };\n\nexport const JWT = { sign };\n\n// @ts-ignore\nconst generate =\n (w: any) => async (generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams) => {\n const keyType = generateKeyAlgorithm;\n const exportable = true;\n const privileges = ['sign', 'verify'];\n // @ts-ignore\n const key = await w.crypto.subtle.generateKey(keyType, exportable, privileges);\n // returns an abstract and opaque WebCrypto object,\n // which in most cases you'll want to export as JSON to be able to save\n return await w.crypto.subtle.exportKey('jwk', key.privateKey);\n };\n\n// Create a Public Key from a Private Key\n//\n// chops off the private parts\n// @ts-ignore\nconst neuter = jwk => {\n const copy = Object.assign({}, jwk);\n delete copy.d;\n copy.key_ops = ['verify'];\n return copy;\n};\n\nconst EC = {\n generate,\n neuter,\n};\n// @ts-ignore\nconst thumbprint = (w: any) => async (jwk, digestAlgorithm: AlgorithmIdentifier) => {\n let sortedPub;\n // lexigraphically sorted, no spaces\n switch (jwk.kty) {\n case 'EC':\n sortedPub = '{\"crv\":\"CRV\",\"kty\":\"EC\",\"x\":\"X\",\"y\":\"Y\"}'\n .replace('CRV', jwk.crv)\n .replace('X', jwk.x)\n .replace('Y', jwk.y);\n break;\n case 'RSA':\n sortedPub = '{\"e\":\"E\",\"kty\":\"RSA\",\"n\":\"N\"}'.replace('E', jwk.e).replace('N', jwk.n);\n break;\n default:\n throw new Error('Unknown or not implemented JWK type');\n }\n // The hash should match the size of the key,\n // but we're only dealing with P-256\n const hash = await w.crypto.subtle.digest(digestAlgorithm, strToUint8(sortedPub));\n return uint8ToUrlBase64(new Uint8Array(hash));\n};\n\nexport const JWK = { thumbprint };\n\nexport const generateJwkAsync =\n (w: any) => async (generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams) => {\n // @ts-ignore\n const jwk = await EC.generate(w)(generateKeyAlgorithm);\n // console.info('Private Key:', JSON.stringify(jwk));\n // @ts-ignore\n // console.info('Public Key:', JSON.stringify(EC.neuter(jwk)));\n return jwk;\n };\n\nexport const generateJwtDemonstratingProofOfPossessionAsync =\n (w: any) =>\n (demonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration) =>\n async (jwk: any, method = 'POST', url: string, extrasClaims = {}) => {\n const target = new URL(url, w.location?.href);\n target.search = '';\n target.hash = '';\n const claims = {\n // https://www.rfc-editor.org/rfc/rfc9449.html#name-concept\n jti: btoa(w.crypto.randomUUID()),\n htm: method,\n htu: target.href,\n iat: Math.round(Date.now() / 1000),\n ...extrasClaims,\n };\n // @ts-ignore\n const kid = await JWK.thumbprint(w)(\n jwk,\n demonstratingProofOfPossessionConfiguration.digestAlgorithm,\n );\n // @ts-ignore\n const jwt = await JWT.sign(w)(\n jwk,\n { kid: kid },\n claims,\n demonstratingProofOfPossessionConfiguration,\n );\n // console.info('JWT:', jwt);\n return jwt;\n };\n","import { uint8ToUrlBase64 } from './jwt';\n\nexport function textEncodeLite(str: string) {\n const buf = new ArrayBuffer(str.length);\n const bufView = new Uint8Array(buf);\n\n for (let i = 0; i < str.length; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return bufView;\n}\n\nexport function base64urlOfHashOfASCIIEncodingAsync(code: string): Promise<string> {\n return new Promise((resolve, reject) => {\n crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(\n buffer => {\n return resolve(uint8ToUrlBase64(new Uint8Array(buffer)));\n },\n error => reject(error),\n );\n });\n}\n","import { defaultDemonstratingProofOfPossessionConfiguration } from './jwt';\nimport { Domain, DomainDetails } from './types.js';\n\nconst isDpop = (trustedDomain: Domain[] | DomainDetails): boolean => {\n if (Array.isArray(trustedDomain)) {\n return false;\n }\n return trustedDomain.demonstratingProofOfPossession ?? false;\n};\n\nexport const getDpopConfiguration = (trustedDomain: Domain[] | DomainDetails) => {\n if (!isDpop(trustedDomain)) {\n return null;\n }\n\n if (Array.isArray(trustedDomain)) {\n return null;\n }\n\n return (\n trustedDomain.demonstratingProofOfPossessionConfiguration ??\n defaultDemonstratingProofOfPossessionConfiguration\n );\n};\n\nexport const getDpopOnlyWhenDpopHeaderPresent = (trustedDomain: Domain[] | DomainDetails) => {\n if (!isDpop(trustedDomain)) {\n return null;\n }\n\n if (Array.isArray(trustedDomain)) {\n return null;\n }\n\n return trustedDomain.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent ?? true;\n};\n","/** An explicitly permitted OAuth resource and its API destinations. */\nexport interface OidcResourceConfiguration {\n resource: string;\n allowedUrlPrefixes: readonly string[];\n scope?: string;\n audiences?: readonly string[];\n}\n\n/** Worker-only resource refresh routing hint, removed before the provider request. */\nexport const RESOURCE_TOKEN_REQUEST_HEADER = 'x-oidc-resource';\n\n/** Builds an isolated storage/worker context without creating another OIDC client. */\nexport const getResourceContextName = (configurationName: string, resource: string): string =>\n `${configurationName}#resource=${encodeURIComponent(resource)}`;\n\n/** Reads the exact resource identifier from an isolated context name. */\nexport const getContextResource = (configurationName: string): string | undefined => {\n const marker = '#resource=';\n const index = configurationName.indexOf(marker);\n return index < 0 ? undefined : decodeURIComponent(configurationName.slice(index + marker.length));\n};\n\n/** Validates RFC 8707 identifiers without treating them as API URLs or scopes. */\nexport const validateResourceIdentifier = (resource: string): void => {\n if (\n typeof resource !== 'string' ||\n !/^[a-z][a-z\\d+.-]*:/i.test(resource) ||\n resource.includes('#') ||\n /\\s/.test(resource)\n ) {\n throw new Error('A resource must be an absolute URI without whitespace or a fragment.');\n }\n new URL(resource);\n};\n\nconst getApiUrl = (value: string): URL => {\n const url = new URL(value);\n if (\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.username ||\n url.password ||\n url.hash ||\n /%2f|%5c/i.test(url.pathname)\n ) {\n throw new Error(\n 'API destinations must be HTTP(S) URLs without credentials, fragments, or encoded separators.',\n );\n }\n return url;\n};\n\nconst getApiPrefixUrl = (value: string): URL => {\n const prefix = getApiUrl(value);\n if (prefix.search) throw new Error('An API URL prefix must not contain a query.');\n return prefix;\n};\n\n/** Prevents default-token fallback anywhere on an explicitly managed API origin. */\nexport const isResourceOriginManaged = (\n configurations: readonly OidcResourceConfiguration[] | undefined,\n destination: string,\n): boolean => {\n const origin = getApiUrl(destination).origin;\n return (\n configurations?.some(configuration =>\n configuration.allowedUrlPrefixes.some(value => getApiPrefixUrl(value).origin === origin),\n ) ?? false\n );\n};\n\n/** Matches API mappings by parsed origin and path boundaries, never by host suffix. */\nexport const isResourceUrlAllowed = (\n configuration: OidcResourceConfiguration,\n destination: string,\n): boolean => {\n const url = getApiUrl(destination);\n return configuration.allowedUrlPrefixes.some(value => {\n const prefix = getApiPrefixUrl(value);\n const path = prefix.pathname.replace(/\\/+$/, '');\n return (\n url.origin === prefix.origin &&\n (path === '' || url.pathname === path || url.pathname.startsWith(`${path}/`))\n );\n });\n};\n\n/** Validates and retrieves an explicitly registered resource. */\nexport const getResourceConfiguration = (\n configurations: readonly OidcResourceConfiguration[] | undefined,\n resource: string,\n): OidcResourceConfiguration => {\n validateResourceIdentifier(resource);\n const matches =\n configurations?.filter(configuration => configuration.resource === resource) ?? [];\n if (matches.length !== 1 || matches[0].allowedUrlPrefixes.length === 0) {\n throw new Error(\n 'The resource must be registered exactly once with permitted API URL prefixes.',\n );\n }\n for (const prefix of matches[0].allowedUrlPrefixes) {\n isResourceUrlAllowed(matches[0], prefix);\n }\n return matches[0];\n};\n","import { getResourceConfiguration, getResourceContextName } from './resource';\nimport type { Database, OidcConfig } from './types';\n\nexport const getTokenContextEntries = (database: Database): Array<[string, OidcConfig]> =>\n Object.entries(database).flatMap(([key, configuration]): Array<[string, OidcConfig]> => [\n [key, configuration],\n ...Object.entries(configuration.resourceEntries ?? {}),\n ]);\n\nexport const getTokenContexts = (database: Database): OidcConfig[] =>\n getTokenContextEntries(database).map(([, configuration]) => configuration);\n\nexport const getOrCreateResourceContext = (\n configuration: OidcConfig,\n resource: string,\n): OidcConfig => {\n getResourceConfiguration(configuration.oidcConfiguration?.resources, resource);\n configuration.resourceEntries ??= {};\n const name = getResourceContextName(configuration.configurationName, resource);\n configuration.resourceEntries[name] ??= {\n ...configuration,\n configurationName: name,\n resource,\n parentConfiguration: configuration,\n resourceEntries: undefined,\n authorizationScope: undefined,\n requestedScope: undefined,\n demonstratingProofOfPossessionApiNonce: null,\n refreshGrant: undefined,\n tokens: null,\n state: null,\n codeVerifier: null,\n nonce: null,\n status: null,\n hideAccessToken: true,\n generation: 0,\n };\n return configuration.resourceEntries[name];\n};\n","export function normalizeUrl(url: string) {\n try {\n return new URL(url).toString();\n } catch (error) {\n console.error(`Failed to normalize url: ${url}`, error);\n return url;\n }\n}\n","import { acceptAnyDomainToken, openidWellknownUrlEndWith, scriptFilename } from '../constants';\nimport {\n getResourceConfiguration,\n isResourceOriginManaged,\n isResourceUrlAllowed,\n} from '../resource';\nimport { getTokenContextEntries } from '../tokenContexts';\nimport { Database, Domain, DomainDetails, TrustedDomains } from '../types';\nimport { normalizeUrl } from './normalizeUrl';\n\nexport function checkDomain(domains: Domain[], endpoint: string) {\n if (!endpoint) {\n return;\n }\n\n const domain = domains.find(domain => {\n let testable: RegExp;\n\n if (typeof domain === 'string') {\n testable = new RegExp(`^${domain}`);\n } else {\n testable = domain;\n }\n\n return testable.test?.(endpoint);\n });\n if (!domain) {\n throw new Error(\n 'Domain ' + endpoint + ' is not trusted, please add domain in ' + scriptFilename,\n );\n }\n}\n\nexport const getDomains = (\n trustedDomain: Domain[] | DomainDetails,\n type: 'oidc' | 'accessToken',\n) => {\n if (Array.isArray(trustedDomain)) {\n return trustedDomain;\n }\n\n return trustedDomain[`${type}Domains`] ?? trustedDomain.domains ?? [];\n};\n\nexport const getCurrentDatabaseDomain = (\n database: Database,\n url: string,\n trustedDomains: TrustedDomains,\n) => {\n if (url.endsWith(openidWellknownUrlEndWith)) {\n return null;\n }\n const datatases = [];\n for (const [key, currentDatabase] of getTokenContextEntries(database)) {\n const oidcServerConfiguration = currentDatabase.oidcServerConfiguration;\n const resources = currentDatabase.oidcConfiguration?.resources;\n if (currentDatabase.resource) {\n if (!isResourceUrlAllowed(getResourceConfiguration(resources, currentDatabase.resource), url))\n continue;\n } else if (\n resources?.length &&\n (!oidcServerConfiguration?.userInfoEndpoint ||\n url !== normalizeUrl(oidcServerConfiguration.userInfoEndpoint)) &&\n isResourceOriginManaged(resources, url)\n ) {\n continue;\n }\n\n if (!oidcServerConfiguration) {\n continue;\n }\n\n if (\n oidcServerConfiguration.tokenEndpoint &&\n url === normalizeUrl(oidcServerConfiguration.tokenEndpoint)\n ) {\n continue;\n }\n if (\n oidcServerConfiguration.revocationEndpoint &&\n url === normalizeUrl(oidcServerConfiguration.revocationEndpoint)\n ) {\n continue;\n }\n const trustedDomain = trustedDomains == null ? [] : trustedDomains[key.split('#')[0]];\n\n const domains = getDomains(trustedDomain, 'accessToken');\n const domainsToSendTokens = oidcServerConfiguration.userInfoEndpoint\n ? [normalizeUrl(oidcServerConfiguration.userInfoEndpoint), ...domains]\n : [...domains];\n\n let hasToSendToken = false;\n if (domainsToSendTokens.find(f => f === acceptAnyDomainToken)) {\n hasToSendToken = true;\n } else {\n for (let i = 0; i < domainsToSendTokens.length; i++) {\n let domain = domainsToSendTokens[i];\n\n if (typeof domain === 'string') {\n domain = new RegExp(`^${domain}`);\n }\n\n if (domain.test?.(url)) {\n hasToSendToken = true;\n break;\n }\n }\n }\n\n if (hasToSendToken) {\n if (currentDatabase.tokens) {\n datatases.push(currentDatabase);\n }\n }\n }\n return datatases;\n};\n","function serializeHeaders(headers: Headers): Record<string, string> {\n const headersObj: Record<string, string> = {};\n for (const key of headers.keys()) {\n const value = headers.get(key);\n if (value !== null) {\n headersObj[key] = value;\n }\n }\n return headersObj;\n}\nexport { serializeHeaders };\n","const bypassedDestinations = ['image', 'font', 'media', 'document', 'iframe', 'script'];\n\n/**\n * Determines whether a fetch event should be bypassed (not intercepted by the service worker).\n * Navigation requests (mode === 'navigate') are never bypassed, even when their destination\n * is in the bypassed list, so that access tokens can be injected into new-tab navigations.\n */\nexport const shouldBypassDestination = (destination: string, mode: string): boolean => {\n return bypassedDestinations.includes(destination) && mode !== 'navigate';\n};\n","const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\nexport { sleep };\n","/* eslint-disable simple-import-sort/exports */\nimport { TOKEN, TokenRenewMode } from '../constants';\nimport { getResourceConfiguration } from '../resource';\nimport {\n AccessTokenPayload,\n IdTokenPayload,\n OidcConfig,\n OidcConfiguration,\n OidcServerConfiguration,\n Tokens,\n} from '../types';\n\nexport const parseJwt = (payload: string) => {\n return JSON.parse(b64DecodeUnicode(payload.replaceAll(/-/g, '+').replaceAll(/_/g, '/')));\n};\nfunction b64DecodeUnicode(str: string) {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n}\n\nfunction computeTimeLeft(refreshTimeBeforeTokensExpirationInSecond: number, expiresAt: number) {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n return Math.round(expiresAt - refreshTimeBeforeTokensExpirationInSecond - currentTimeUnixSecond);\n}\n\nfunction isTokensValid(tokens: Tokens | null) {\n if (!tokens) {\n return false;\n }\n return computeTimeLeft(0, tokens.expiresAt) > 0;\n}\n\nconst extractTokenPayload = (token?: string) => {\n try {\n if (!token) {\n return null;\n }\n const parts = token.split('.');\n return parts.length === 3 ? parseJwt(parts[1]) : null;\n } catch (e) {\n console.warn(e);\n }\n return null;\n};\n\n// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation (excluding rules #1, #4, #5, #7, #8, #12, and #13 which did not apply).\n// https://github.com/openid/AppAuth-JS/issues/65\nconst isTokensOidcValid = (\n tokens: Tokens,\n nonce: string | null,\n oidcServerConfiguration: OidcServerConfiguration,\n): { isValid: boolean; reason: string } => {\n if (tokens.idTokenPayload) {\n const idTokenPayload = tokens.idTokenPayload;\n // 2: The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) MUST exactly match the value of the iss (issuer) Claim.\n if (idTokenPayload && oidcServerConfiguration.issuer !== idTokenPayload.iss) {\n return {\n isValid: false,\n reason: `Issuer does not match (oidcServerConfiguration issuer) ${oidcServerConfiguration.issuer} !== (idTokenPayload issuer) ${idTokenPayload.iss}`,\n };\n }\n // 3: The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience. The aud (audience) Claim MAY contain an array with more than one element. The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n\n // 6: If the ID Token is received via direct communication between the Client and the Token Endpoint (which it is in this flow), the TLS server validation MAY be used to validate the issuer in place of checking the token signature. The Client MUST validate the signature of all other ID Tokens according to JWS [JWS] using the algorithm specified in the JWT alg Header Parameter. The Client MUST use the keys provided by the Issuer.\n\n // 9: The current time MUST be before the time represented by the exp Claim.\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n if (idTokenPayload && idTokenPayload.exp && idTokenPayload.exp < currentTimeUnixSecond) {\n return {\n isValid: false,\n reason: `Token expired at (idTokenPayload exp) ${idTokenPayload.exp} < (currentTimeUnixSecond) ${currentTimeUnixSecond}`,\n };\n }\n // 10: The iat Claim can be used to reject tokens that were issued too far away from the current time, limiting the amount of time that nonces need to be stored to prevent attacks. The acceptable range is Client specific.\n const timeInSevenDays = 60 * 60 * 24 * 7;\n if (\n idTokenPayload &&\n idTokenPayload.iat &&\n idTokenPayload.iat + timeInSevenDays < currentTimeUnixSecond\n ) {\n return {\n isValid: false,\n reason: `Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${idTokenPayload.iat + timeInSevenDays} < (currentTimeUnixSecond) ${currentTimeUnixSecond}`,\n };\n }\n // 11: If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked to verify that it is the same value as the one that was sent in the Authentication Request. The Client SHOULD check the nonce value for replay attacks. The precise method for detecting replay attacks is Client specific.\n if (idTokenPayload && nonce && idTokenPayload.nonce && idTokenPayload.nonce !== nonce) {\n return {\n isValid: false,\n reason: `Nonce does not match (nonce) ${nonce} !== (idTokenPayload nonce) ${idTokenPayload.nonce}`,\n };\n }\n }\n return { isValid: true, reason: '' };\n};\n\nfunction extractedIssueAt(\n tokens: Tokens,\n accessTokenPayload: AccessTokenPayload | null,\n _idTokenPayload: IdTokenPayload,\n) {\n if (!tokens.issued_at) {\n if (accessTokenPayload && accessTokenPayload.iat) {\n return accessTokenPayload.iat;\n } else if (_idTokenPayload && _idTokenPayload.iat) {\n return _idTokenPayload.iat;\n } else {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n return currentTimeUnixSecond;\n }\n } else if (typeof tokens.issued_at == 'string') {\n return parseInt(tokens.issued_at, 10);\n }\n return tokens.issued_at;\n}\n\nfunction _hideTokens(\n tokens: Tokens,\n currentDatabaseElement: OidcConfig,\n configurationName: string,\n isAuthorizationCode = false,\n) {\n const hasNewIdToken = typeof tokens.id_token === 'string' && tokens.id_token.length > 0;\n const parent = currentDatabaseElement.parentConfiguration;\n if (\n currentDatabaseElement.resource &&\n currentDatabaseElement.refreshGrant === currentDatabaseElement &&\n tokens.refresh_token &&\n tokens.refresh_token === parent?.tokens?.refresh_token\n ) {\n throw new Error(\n 'The provider reused a refresh token across separate authorization transactions; use a multi-resource authorization grant instead.',\n );\n }\n if (!tokens.issued_at) {\n const currentTimeUnixSecond = new Date().getTime() / 1000;\n tokens.issued_at = currentTimeUnixSecond;\n } else if (typeof tokens.issued_at == 'string') {\n tokens.issued_at = parseInt(tokens.issued_at, 10);\n }\n\n const accessTokenPayload = extractTokenPayload(tokens.access_token);\n if (\n currentDatabaseElement.resource ||\n currentDatabaseElement.oidcConfiguration?.resources?.length\n ) {\n tokens.scope ??=\n currentDatabaseElement.requestedScope ??\n currentDatabaseElement.tokens?.scope ??\n currentDatabaseElement.oidcConfiguration?.scope;\n }\n const secureTokens = {\n ...tokens,\n accessTokenPayload,\n };\n if (currentDatabaseElement.hideAccessToken) {\n secureTokens.access_token = `${TOKEN.ACCESS_TOKEN}_${configurationName}`;\n }\n tokens.accessTokenPayload = accessTokenPayload;\n\n // When id_token is not rotated we reuse old id_token\n const oldTokens = currentDatabaseElement.tokens;\n let id_token: string | null;\n if (oldTokens != null && 'id_token' in oldTokens && !('id_token' in tokens)) {\n id_token = oldTokens.id_token;\n } else {\n id_token = tokens.id_token;\n }\n tokens.id_token = id_token;\n\n let _idTokenPayload = null;\n if (id_token) {\n _idTokenPayload = extractTokenPayload(id_token);\n tokens.idTokenPayload = _idTokenPayload != null ? { ..._idTokenPayload } : null;\n if (_idTokenPayload && _idTokenPayload.nonce && currentDatabaseElement.nonce != null) {\n const keyNonce = `${TOKEN.NONCE_TOKEN}_${currentDatabaseElement.configurationName}`;\n _idTokenPayload.nonce = keyNonce;\n }\n secureTokens.idTokenPayload =\n currentDatabaseElement.resource && !hasNewIdToken ? null : _idTokenPayload;\n }\n if (\n currentDatabaseElement.resource &&\n isAuthorizationCode &&\n (!hasNewIdToken ||\n typeof tokens.idTokenPayload?.sub !== 'string' ||\n !tokens.idTokenPayload.sub ||\n (currentDatabaseElement.nonce &&\n tokens.idTokenPayload.nonce !== currentDatabaseElement.nonce.nonce))\n ) {\n throw new Error(\n 'Resource authorization requires a fresh ID token with the expected subject and nonce.',\n );\n }\n if (tokens.refresh_token) {\n secureTokens.refresh_token = `${TOKEN.REFRESH_TOKEN}_${(currentDatabaseElement.refreshGrant ?? currentDatabaseElement).configurationName}`;\n }\n\n tokens.issued_at = extractedIssueAt(tokens, accessTokenPayload, _idTokenPayload);\n\n const expireIn =\n typeof tokens.expires_in == 'string' ? parseInt(tokens.expires_in, 10) : tokens.expires_in;\n\n const idTokenExpiresAt =\n _idTokenPayload && _idTokenPayload.exp ? _idTokenPayload.exp : Number.MAX_VALUE;\n const accessTokenExpiresAt =\n accessTokenPayload && accessTokenPayload.exp\n ? accessTokenPayload.exp\n : tokens.issued_at + expireIn;\n\n let expiresAt: number;\n const tokenRenewMode = currentDatabaseElement.resource\n ? TokenRenewMode.access_token_invalid\n : (currentDatabaseElement.oidcConfiguration as OidcConfiguration).token_renew_mode;\n if (tokenRenewMode === TokenRenewMode.access_token_invalid) {\n expiresAt = accessTokenExpiresAt;\n } else if (tokenRenewMode === TokenRenewMode.id_token_invalid) {\n expiresAt = idTokenExpiresAt;\n } else {\n expiresAt = idTokenExpiresAt < accessTokenExpiresAt ? idTokenExpiresAt : accessTokenExpiresAt;\n }\n secureTokens.expiresAt = expiresAt;\n\n tokens.expiresAt = expiresAt;\n const nonce = currentDatabaseElement.nonce ? currentDatabaseElement.nonce.nonce : null;\n const { isValid, reason } = isTokensOidcValid(\n currentDatabaseElement.resource && !hasNewIdToken\n ? { ...tokens, idTokenPayload: undefined }\n : tokens,\n nonce as string,\n currentDatabaseElement.oidcServerConfiguration as OidcServerConfiguration,\n ); // TODO: Type assertion, could be null.\n if (!isValid) {\n throw Error(`Tokens are not OpenID valid, reason: ${reason}`);\n }\n if (currentDatabaseElement.resource) {\n if (\n typeof tokens.access_token !== 'string' ||\n !tokens.access_token ||\n !Number.isFinite(expiresAt) ||\n !Number.isFinite(tokens.issued_at) ||\n (tokens.refresh_token != null &&\n (typeof tokens.refresh_token !== 'string' || !tokens.refresh_token))\n ) {\n throw new Error('The provider did not return a usable resource token response.');\n }\n const resource = getResourceConfiguration(\n currentDatabaseElement.oidcConfiguration?.resources,\n currentDatabaseElement.resource,\n );\n tokens.scope ??=\n currentDatabaseElement.requestedScope ??\n resource.scope ??\n currentDatabaseElement.oidcConfiguration?.scope;\n secureTokens.scope = tokens.scope;\n if (\n resource.scope &&\n !resource.scope\n .split(/\\s+/)\n .filter(Boolean)\n .every(scope => (tokens.scope ?? '').split(/\\s+/).includes(scope))\n ) {\n throw new Error('The provider did not grant the required resource scopes.');\n }\n const parentSubject = currentDatabaseElement.parentConfiguration?.tokens?.idTokenPayload?.sub;\n const subject = tokens.idTokenPayload?.sub ?? oldTokens?.idTokenPayload?.sub ?? parentSubject;\n if (typeof parentSubject !== 'string' || subject !== parentSubject) {\n throw new Error('Resource authorization must preserve the authenticated subject.');\n }\n if (\n (accessTokenPayload?.iss !== undefined &&\n accessTokenPayload.iss !== currentDatabaseElement.oidcServerConfiguration?.issuer) ||\n (accessTokenPayload &&\n resource.audiences &&\n !resource.audiences.some(audience =>\n (typeof accessTokenPayload.aud === 'string'\n ? [accessTokenPayload.aud]\n : (accessTokenPayload.aud ?? [])\n ).includes(audience),\n ))\n )\n throw new Error('Resource token issuer or configured audience does not match.');\n }\n\n // When refresh_token is not rotated we reuse old refresh_token\n if (oldTokens != null && 'refresh_token' in oldTokens && !('refresh_token' in tokens)) {\n const refreshToken = oldTokens.refresh_token;\n\n currentDatabaseElement.tokens = {\n ...tokens,\n refresh_token: refreshToken,\n };\n } else {\n currentDatabaseElement.tokens = tokens;\n }\n\n currentDatabaseElement.status = 'LOGGED_IN';\n if (currentDatabaseElement.resource) {\n const grant = currentDatabaseElement.refreshGrant ?? currentDatabaseElement;\n const subject =\n tokens.idTokenPayload?.sub ??\n grant.tokens?.idTokenPayload?.sub ??\n currentDatabaseElement.parentConfiguration?.tokens?.idTokenPayload?.sub;\n if (typeof subject !== 'string')\n throw new Error('Resource tokens require an authenticated OIDC subject.');\n if (grant !== currentDatabaseElement && tokens.refresh_token && grant.tokens) {\n grant.tokens.refresh_token = tokens.refresh_token;\n }\n const resourceContext = {\n resource: currentDatabaseElement.resource,\n issuer: currentDatabaseElement.oidcServerConfiguration!.issuer,\n clientId: currentDatabaseElement.oidcConfiguration!.client_id!,\n configurationName: currentDatabaseElement.configurationName.split('#')[0],\n subject,\n grantResource: grant.resource ?? null,\n };\n currentDatabaseElement.tokens!.resourceContext = resourceContext;\n secureTokens.resourceContext = resourceContext;\n }\n return secureTokens;\n}\n\nconst demonstratingProofOfPossessionNonceResponseHeader = 'DPoP-Nonce';\nfunction hideTokens(\n currentDatabaseElement: OidcConfig,\n isCurrent: () => boolean = () => true,\n isGrantCurrent: () => boolean = isCurrent,\n isAuthorizationCode = false,\n) {\n const configurationName = currentDatabaseElement.configurationName;\n return (response: Response) => {\n if (response.status !== 200) {\n return response;\n }\n const newHeaders = new Headers(response.headers);\n if (\n response.headers.has(demonstratingProofOfPossessionNonceResponseHeader) &&\n isGrantCurrent()\n ) {\n currentDatabaseElement.demonstratingProofOfPossessionNonce = response.headers.get(\n demonstratingProofOfPossessionNonceResponseHeader,\n );\n if (\n currentDatabaseElement.refreshGrant &&\n currentDatabaseElement.refreshGrant !== currentDatabaseElement\n ) {\n currentDatabaseElement.refreshGrant.demonstratingProofOfPossessionNonce =\n currentDatabaseElement.demonstratingProofOfPossessionNonce;\n }\n newHeaders.delete(demonstratingProofOfPossessionNonceResponseHeader);\n }\n\n return response.json().then<Response>((tokens: Tokens) => {\n const grant = currentDatabaseElement.refreshGrant;\n if (\n currentDatabaseElement.resource &&\n grant &&\n isGrantCurrent() &&\n grant.tokens &&\n typeof tokens.refresh_token === 'string' &&\n tokens.refresh_token &&\n (grant !== currentDatabaseElement ||\n tokens.refresh_token !==\n currentDatabaseElement.parentConfiguration?.tokens?.refresh_token)\n ) {\n grant.tokens.refresh_token = tokens.refresh_token;\n }\n if (!isCurrent()) {\n throw new Error('The token transaction was cleared before its response.');\n }\n const secureTokens = _hideTokens(\n tokens,\n currentDatabaseElement,\n configurationName,\n isAuthorizationCode,\n );\n const body = JSON.stringify(secureTokens);\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: newHeaders,\n });\n });\n };\n}\n\nexport {\n b64DecodeUnicode,\n computeTimeLeft,\n isTokensValid,\n extractTokenPayload,\n isTokensOidcValid,\n hideTokens,\n _hideTokens,\n};\n","import { OidcConfig } from '../types';\nimport { sleep } from './sleep';\nimport { isTokensValid } from './tokens';\n\nexport const TOKEN_RENEWAL_TIMEOUT_MS = 5000;\nexport const TOKEN_RENEWAL_POLL_INTERVAL_MS = 200;\n\n/**\n * Polls until the tokens in the given config are valid, or until a timeout elapses.\n *\n * @returns `null` when tokens become valid; a synthetic 401 `Response` on timeout or\n * when the tokens are cleared while waiting (e.g. due to a parallel logout).\n */\nexport async function waitForValidTokens(\n config: OidcConfig,\n maxWaitMs = TOKEN_RENEWAL_TIMEOUT_MS,\n pollIntervalMs = TOKEN_RENEWAL_POLL_INTERVAL_MS,\n): Promise<Response | null> {\n const startTime = Date.now();\n while (config.tokens && !isTokensValid(config.tokens)) {\n if (Date.now() - startTime >= maxWaitMs) {\n return new Response(null, {\n status: 401,\n statusText: 'Token expired - service worker renewal timeout',\n });\n }\n await sleep(pollIntervalMs);\n }\n\n if (!config.tokens?.access_token) {\n return new Response(null, {\n status: 401,\n statusText: 'Missing access token',\n });\n }\n\n return null;\n}\n","import { acceptAnyDomainToken } from './constants';\nimport { getTokenContexts } from './tokenContexts';\nimport { Database, Domain, OidcConfig, OidcServerConfiguration, TrustedDomains } from './types';\nimport { getDomains, normalizeUrl } from './utils';\n\nconst getOidcServerUrls = (oidcServerConfiguration: OidcServerConfiguration): string[] => {\n return [\n oidcServerConfiguration.issuer,\n oidcServerConfiguration.authorizationEndpoint,\n oidcServerConfiguration.tokenEndpoint,\n oidcServerConfiguration.revocationEndpoint,\n oidcServerConfiguration.userInfoEndpoint,\n ]\n .filter(Boolean)\n .map(normalizeUrl);\n};\n\nconst isOidcServerRequest = (database: Database, normalizedUrl: string): boolean => {\n return Object.values(database).some(config => {\n const { oidcServerConfiguration } = config || {};\n if (!oidcServerConfiguration) {\n return false;\n }\n\n return getOidcServerUrls(oidcServerConfiguration).some(oidcUrl =>\n normalizedUrl.startsWith(oidcUrl),\n );\n });\n};\n\nconst isDomainMatchingUrl = (domain: Domain, normalizedUrl: string): boolean => {\n if (typeof domain === 'string') {\n domain = new RegExp(`^${domain}`);\n }\n\n return domain.test?.(normalizedUrl) ?? false;\n};\n\nconst isAccessTokenDomainRequest = (\n database: Database,\n normalizedUrl: string,\n trustedDomains: TrustedDomains,\n): boolean => {\n return Object.entries(database).some(([key, currentDatabase]) => {\n if (!currentDatabase.oidcServerConfiguration) {\n return false;\n }\n\n const trustedDomain = trustedDomains?.[key.split('#')[0]] ?? [];\n const domains = getDomains(trustedDomain, 'accessToken');\n\n if (domains.some(domain => domain === acceptAnyDomainToken)) {\n return true;\n }\n\n return domains.some(domain => isDomainMatchingUrl(domain, normalizedUrl));\n });\n};\n\nconst shouldBypassNonOidcRequest = (\n database: Database,\n normalizedUrl: string,\n trustedDomains: TrustedDomains,\n): boolean => {\n const configurations = Object.values(database);\n\n if (configurations.length === 0) {\n return false;\n }\n\n if (!configurations.every(config => config.bypassAllNonOidcRequests)) {\n return false;\n }\n\n if (!configurations.every(config => config.oidcServerConfiguration != null)) {\n return false;\n }\n\n return (\n !isOidcServerRequest(database, normalizedUrl) &&\n !isAccessTokenDomainRequest(database, normalizedUrl, trustedDomains)\n );\n};\n\nconst getMatchingOidcConfigurations = (database: Database, url: string): OidcConfig[] => {\n const normalizedUrl = normalizeUrl(url);\n return getTokenContexts(database).filter(config => {\n const { oidcServerConfiguration } = config || {};\n const { tokenEndpoint, revocationEndpoint } = oidcServerConfiguration || {};\n\n return (\n (tokenEndpoint && normalizedUrl.startsWith(normalizeUrl(tokenEndpoint))) ||\n (revocationEndpoint && normalizedUrl.startsWith(normalizeUrl(revocationEndpoint)))\n );\n });\n};\n\nexport {\n getMatchingOidcConfigurations as getCurrentDatabasesTokenEndpoint,\n isAccessTokenDomainRequest,\n isOidcServerRequest,\n shouldBypassNonOidcRequest,\n};\n","export function replaceCodeVerifier(codeVerifier: string, newCodeVerifier: string): string {\n const regex = /[?&]code_verifier=([^&]+)/i;\n return codeVerifier.replace(regex, `&code_verifier=${newCodeVerifier}`);\n}\n\nexport const extractConfigurationNameFromCodeVerifier = (body: string): string => {\n const regex = /[?&]code_verifier=CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER_([^&]+)/;\n const match = body.match(regex);\n\n return match ? decodeURIComponent(match[1]) : '';\n};\n","export default '7.30.0';\n","import { acceptAnyDomainToken, scriptFilename, TOKEN } from './constants';\nimport { base64urlOfHashOfASCIIEncodingAsync } from './crypto';\nimport { getDpopConfiguration, getDpopOnlyWhenDpopHeaderPresent } from './dpop';\nimport { generateJwkAsync, generateJwtDemonstratingProofOfPossessionAsync } from './jwt';\nimport { getCurrentDatabasesTokenEndpoint, shouldBypassNonOidcRequest } from './oidcConfig';\nimport {\n getContextResource,\n getResourceConfiguration,\n RESOURCE_TOKEN_REQUEST_HEADER,\n} from './resource';\nimport { getOrCreateResourceContext, getTokenContexts } from './tokenContexts';\nimport { Database, MessageEventData, OidcConfig, TrustedDomains } from './types';\nimport {\n checkDomain,\n getCurrentDatabaseDomain,\n getDomains,\n hideTokens,\n normalizeUrl,\n serializeHeaders,\n shouldBypassDestination,\n sleep,\n waitForValidTokens,\n} from './utils';\nimport {\n extractConfigurationNameFromCodeVerifier,\n replaceCodeVerifier,\n} from './utils/codeVerifier';\nimport version from './version';\n\n// @ts-ignore\nif (typeof trustedTypes !== 'undefined' && typeof trustedTypes.createPolicy === 'function') {\n // @ts-ignore\n trustedTypes.createPolicy('default', {\n createScriptURL: function (url: string) {\n if (url === scriptFilename) {\n return url;\n } else {\n throw new Error('Untrusted script URL blocked: ' + url);\n }\n },\n });\n}\n\nconst _self = self as ServiceWorkerGlobalScope & typeof globalThis;\n\n// `trustedDomains` is declared in the externally loaded script (OidcTrustedDomains.js)\ndeclare let trustedDomains: TrustedDomains;\n\n_self.importScripts(scriptFilename);\n\nconst id = Math.round(new Date().getTime() / 1000).toString();\nconsole.log('init service worker with id', id);\nconst keepAliveJsonFilename = 'OidcKeepAliveServiceWorker.json';\nconst database: Database = {};\n\n/**\n * Keeps the service worker alive by responding with a cached response after a sleep.\n */\nconst keepAliveAsync = async (event: FetchEvent) => {\n const originalRequest = event.request;\n const isFromVanilla = originalRequest.headers.has('oidc-vanilla');\n const init = { status: 200, statusText: 'oidc-service-worker' };\n const response = new Response('{}', init);\n\n if (!isFromVanilla) {\n const originalRequestUrl = new URL(originalRequest.url);\n const minSleepSeconds = Number(originalRequestUrl.searchParams.get('minSleepSeconds')) || 240;\n for (let i = 0; i < minSleepSeconds; i++) {\n await sleep(1000 + Math.floor(Math.random() * 1000));\n const cache = await caches.open('oidc_dummy_cache');\n await cache.put(event.request, response.clone());\n }\n }\n return response;\n};\n\n/**\n * Generates DPoP headers when a DPoP configuration is present.\n */\nasync function generateDpopAsync(\n originalRequest: Request,\n currentDatabase: OidcConfig | null,\n url: string,\n extrasClaims = {},\n) {\n const headersExtras = serializeHeaders(originalRequest.headers);\n if (\n currentDatabase?.demonstratingProofOfPossessionConfiguration &&\n currentDatabase.demonstratingProofOfPossessionJwkJson &&\n (!currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent ||\n (currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent &&\n headersExtras.dpop))\n ) {\n const dpopConfiguration = currentDatabase.demonstratingProofOfPossessionConfiguration;\n const jwk = currentDatabase.demonstratingProofOfPossessionJwkJson;\n const method = originalRequest.method;\n const resourceNonce = currentDatabase.resource\n ? url === normalizeUrl(currentDatabase.oidcServerConfiguration!.tokenEndpoint)\n ? currentDatabase.demonstratingProofOfPossessionNonce\n : currentDatabase.demonstratingProofOfPossessionApiNonce\n : undefined;\n const dpop = await generateJwtDemonstratingProofOfPossessionAsync(self)(dpopConfiguration)(\n jwk,\n method,\n url,\n {\n ...extrasClaims,\n ...(resourceNonce ? { nonce: resourceNonce } : {}),\n },\n );\n\n headersExtras.dpop = dpop;\n const nonceHeader =\n resourceNonce ??\n (!currentDatabase.resource ? currentDatabase.demonstratingProofOfPossessionNonce : undefined);\n if (nonceHeader) headersExtras.nonce = nonceHeader;\n }\n return headersExtras;\n}\n\n/**\n * Intercepts fetch requests to inject access tokens and handle token endpoints.\n */\nconst handleFetch = (event: FetchEvent): void => {\n /**\n * Exit early for requests that do not need to have an auth token attached.\n */\n if (shouldBypassDestination(event.request.destination, event.request.mode)) {\n return; // Don't call event.respondWith() - let browser handle naturally\n }\n\n const normalizedUrl = normalizeUrl(event.request.url);\n if (\n !normalizedUrl.includes(keepAliveJsonFilename) &&\n shouldBypassNonOidcRequest(database, normalizedUrl, trustedDomains)\n ) {\n return; // Don't call event.respondWith() - let browser handle naturally\n }\n\n event.respondWith(\n (async (): Promise<Response> => {\n try {\n const originalRequest = event.request;\n const url = normalizedUrl;\n\n // 1) Handle keep-alive requests\n if (url.includes(keepAliveJsonFilename)) {\n return keepAliveAsync(event);\n }\n\n // Check if an access token is available for this request\n const currentDatabasesForRequestAccessToken = getCurrentDatabaseDomain(\n database,\n url,\n trustedDomains,\n );\n\n const authorization = originalRequest.headers.get('authorization');\n let authenticationMode = 'Bearer';\n let key = 'default';\n\n if (authorization) {\n const split = authorization.split(' ');\n authenticationMode = split[0];\n if (split[1]?.includes('ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER_')) {\n key = split[1].split('ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER_')[1];\n }\n }\n\n const currentDatabaseForRequestAccessToken = currentDatabasesForRequestAccessToken?.find(\n c =>\n key.includes('#resource=')\n ? c.configurationName === key\n : !c.resource && c.configurationName.endsWith(key),\n );\n if (key.includes('#resource=') && !currentDatabaseForRequestAccessToken) {\n console.error(\n '[OidcServiceWorker] Resource token destination or context is not permitted.',\n );\n return new Response('Resource token destination or context is not permitted.', {\n status: 403,\n });\n }\n\n // Inject the access token into the request if one is available\n if (currentDatabaseForRequestAccessToken?.tokens?.access_token) {\n // Wait for token to become valid (a parallel refresh may be in progress)\n const tokenError = await waitForValidTokens(currentDatabaseForRequestAccessToken);\n if (tokenError) {\n return tokenError;\n }\n const accessToken = currentDatabaseForRequestAccessToken.tokens!.access_token;\n const generation = currentDatabaseForRequestAccessToken.generation;\n const parentGeneration =\n currentDatabaseForRequestAccessToken.parentConfiguration?.generation;\n\n // Adjust request mode for CORS if configured\n let requestMode = originalRequest.mode;\n if (\n originalRequest.mode !== 'navigate' &&\n currentDatabaseForRequestAccessToken.convertAllRequestsToCorsExceptNavigate\n ) {\n requestMode = 'cors';\n }\n\n // Build request headers\n let headers: { [p: string]: string };\n\n // Skip the access token for navigate requests when setAccessTokenToNavigateRequests is false\n if (\n originalRequest.mode === 'navigate' &&\n !currentDatabaseForRequestAccessToken.setAccessTokenToNavigateRequests\n ) {\n headers = {\n ...serializeHeaders(originalRequest.headers),\n };\n } else {\n if (\n authenticationMode.toLowerCase() === 'dpop' ||\n (!currentDatabaseForRequestAccessToken.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent &&\n currentDatabaseForRequestAccessToken.demonstratingProofOfPossessionConfiguration)\n ) {\n // DPoP mode\n const claimsExtras = {\n ath: await base64urlOfHashOfASCIIEncodingAsync(accessToken),\n };\n const dpopHeaders = await generateDpopAsync(\n originalRequest,\n currentDatabaseForRequestAccessToken,\n url,\n claimsExtras,\n );\n headers = {\n ...dpopHeaders,\n authorization: `DPoP ${accessToken}`,\n };\n } else {\n // Bearer mode\n headers = {\n ...serializeHeaders(originalRequest.headers),\n authorization: `${authenticationMode} ${accessToken}`,\n };\n }\n }\n\n let init: RequestInit;\n if (originalRequest.mode === 'navigate') {\n init = {\n headers: headers,\n };\n } else {\n init = {\n headers: headers,\n mode: requestMode,\n };\n }\n\n const newRequest = new Request(originalRequest, init);\n if (\n currentDatabaseForRequestAccessToken.resource &&\n (currentDatabaseForRequestAccessToken.generation !== generation ||\n currentDatabaseForRequestAccessToken.parentConfiguration?.generation !==\n parentGeneration ||\n currentDatabaseForRequestAccessToken.tokens?.access_token !== accessToken)\n ) {\n console.error('[OidcServiceWorker] The resource token changed before dispatch.');\n return new Response('The resource token changed before dispatch.', { status: 403 });\n }\n const response = await fetch(\n newRequest,\n currentDatabaseForRequestAccessToken.resource ? { redirect: 'error' } : undefined,\n );\n if (\n currentDatabaseForRequestAccessToken.resource &&\n currentDatabaseForRequestAccessToken.generation === generation &&\n currentDatabaseForRequestAccessToken.parentConfiguration?.generation ===\n parentGeneration &&\n response.headers.has('DPoP-Nonce')\n ) {\n currentDatabaseForRequestAccessToken.demonstratingProofOfPossessionApiNonce =\n response.headers.get('DPoP-Nonce');\n }\n return response;\n }\n\n // Pass through non-POST requests without modification\n if (event.request.method !== 'POST') {\n return fetch(originalRequest);\n }\n\n // Handle POST requests to known token/revocation endpoints\n const currentDatabases = getCurrentDatabasesTokenEndpoint(database, url);\n const numberDatabase = currentDatabases.length;\n\n if (numberDatabase > 0) {\n const responsePromise = new Promise<Response>((resolve, reject) => {\n const clonedRequest = originalRequest.clone();\n clonedRequest\n .text()\n .then(async actualBody => {\n let currentDatabase: OidcConfig | null = null;\n try {\n // Replace hidden token placeholders with the real token values\n if (\n actualBody.includes(TOKEN.REFRESH_TOKEN) ||\n actualBody.includes(TOKEN.ACCESS_TOKEN)\n ) {\n let headers = serializeHeaders(originalRequest.headers);\n let newBody = actualBody;\n\n for (let i = 0; i < numberDatabase; i++) {\n const currentDb = currentDatabases[i];\n if (currentDb?.tokens) {\n const claimsExtras = {\n ath: await base64urlOfHashOfASCIIEncodingAsync(\n currentDb.tokens.access_token,\n ),\n };\n const keyRefreshToken = encodeURIComponent(\n `${TOKEN.REFRESH_TOKEN}_${currentDb.configurationName}`,\n );\n if (\n [\n new URLSearchParams(actualBody).get('refresh_token'),\n new URLSearchParams(actualBody).get('token'),\n ].includes(decodeURIComponent(keyRefreshToken))\n ) {\n const form = new URLSearchParams(actualBody);\n const selected = form.getAll('resource');\n const resourceHeader = originalRequest.headers.get(\n RESOURCE_TOKEN_REQUEST_HEADER,\n );\n const isRevocation =\n currentDb.oidcServerConfiguration?.revocationEndpoint &&\n url ===\n normalizeUrl(currentDb.oidcServerConfiguration.revocationEndpoint) &&\n form.has('token');\n if (isRevocation) {\n currentDatabase = currentDb;\n } else if (resourceHeader !== null) {\n const resource = decodeURIComponent(resourceHeader);\n if (selected.length !== 1 || selected[0] !== resource)\n throw new Error('The resource routing hint must match the request.');\n if (!currentDb.oidcConfiguration)\n throw new Error('The resource grant configuration is unavailable.');\n const resourceConfiguration = getResourceConfiguration(\n currentDb.oidcConfiguration.resources,\n resource,\n );\n const grantedScope =\n currentDb.tokens.scope ??\n currentDb.authorizationScope ??\n currentDb.oidcConfiguration.scope;\n const requestedScopes = [\n form.get('scope'),\n resourceConfiguration.scope,\n ].filter((scope): scope is string => typeof scope === 'string');\n if (\n requestedScopes.some(\n scope =>\n !scope\n .split(/\\s+/)\n .filter(Boolean)\n .every(value => grantedScope?.split(/\\s+/).includes(value)),\n )\n ) {\n throw new Error('The resource scope is outside this refresh grant.');\n }\n if (\n currentDb.resource !== undefined\n ? currentDb.resource !== resource\n : !(\n typeof currentDb.oidcConfiguration.resource === 'string'\n ? [currentDb.oidcConfiguration.resource]\n : (currentDb.oidcConfiguration.resource ?? [])\n ).includes(resource)\n )\n throw new Error('The resource is outside this refresh grant.');\n currentDatabase = currentDb.resource\n ? currentDb\n : getOrCreateResourceContext(currentDb, resource);\n currentDatabase.refreshGrant = currentDb;\n currentDatabase.requestedScope = form.get('scope') ?? grantedScope;\n currentDatabase.nonce = currentDb.nonce;\n currentDatabase.demonstratingProofOfPossessionJwkJson =\n currentDb.demonstratingProofOfPossessionJwkJson;\n currentDatabase.demonstratingProofOfPossessionConfiguration =\n currentDb.demonstratingProofOfPossessionConfiguration;\n currentDatabase.demonstratingProofOfPossessionNonce =\n currentDb.demonstratingProofOfPossessionNonce;\n } else if (currentDb.resource) {\n throw new Error(\n 'A resource refresh must select exactly its own resource.',\n );\n } else {\n currentDatabase = currentDb;\n currentDatabase.requestedScope =\n form.get('scope') ?? currentDb.tokens.scope;\n }\n headers = await generateDpopAsync(\n originalRequest,\n currentDatabase,\n url,\n claimsExtras,\n );\n newBody = newBody.replace(\n keyRefreshToken,\n encodeURIComponent(currentDb.tokens.refresh_token as string),\n );\n break;\n }\n const keyAccessToken = encodeURIComponent(\n `${TOKEN.ACCESS_TOKEN}_${currentDb.configurationName}`,\n );\n if (\n new URLSearchParams(actualBody).get('token') ===\n decodeURIComponent(keyAccessToken)\n ) {\n headers = await generateDpopAsync(\n originalRequest,\n currentDb,\n url,\n claimsExtras,\n );\n newBody = newBody.replace(\n keyAccessToken,\n encodeURIComponent(currentDb.tokens.access_token),\n );\n currentDatabase = currentDb;\n break;\n }\n }\n }\n if (!currentDatabase)\n throw new Error(\n 'The token placeholder does not identify an available grant.',\n );\n delete headers[RESOURCE_TOKEN_REQUEST_HEADER];\n const generation = currentDatabase.generation;\n const grant = currentDatabase.refreshGrant ?? currentDatabase;\n const grantGeneration = grant.generation;\n if (\n currentDatabase.resource &&\n url !==\n normalizeUrl(currentDatabase.oidcServerConfiguration!.tokenEndpoint) &&\n url !==\n normalizeUrl(currentDatabase.oidcServerConfiguration!.revocationEndpoint)\n ) {\n throw new Error(\n 'Resource tokens may only be sent to their exact token endpoint.',\n );\n }\n\n const fetchPromise = fetch(originalRequest, {\n body: newBody,\n method: clonedRequest.method,\n headers,\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n\n // Forward revocation requests without modifying the response body\n if (\n currentDatabase?.oidcServerConfiguration?.revocationEndpoint &&\n url.startsWith(\n normalizeUrl(currentDatabase.oidcServerConfiguration.revocationEndpoint),\n )\n ) {\n const resp = await fetchPromise;\n const txt = await resp.text();\n resolve(new Response(txt, resp));\n return;\n }\n\n // Hide real token values in the response\n const hidden = await fetchPromise.then(\n hideTokens(\n currentDatabase,\n () =>\n currentDatabase!.generation === generation &&\n grant.generation === grantGeneration,\n () => grant.generation === grantGeneration,\n ),\n );\n resolve(hidden);\n return;\n }\n\n // Handle authorization code exchange: replace the PKCE code_verifier placeholder\n const isCodeVerifier = actualBody.includes('code_verifier=');\n if (isCodeVerifier) {\n const currentLoginCallbackConfigurationName =\n extractConfigurationNameFromCodeVerifier(actualBody);\n if (\n !currentLoginCallbackConfigurationName ||\n currentLoginCallbackConfigurationName === ''\n ) {\n throw new Error('No configuration name found in code_verifier');\n }\n currentDatabase =\n getTokenContexts(database).find(\n context =>\n context.configurationName === currentLoginCallbackConfigurationName,\n ) ?? null;\n if (!currentDatabase)\n throw new Error(\n 'No available authorization transaction matches the code verifier.',\n );\n if (currentDatabase.resource) {\n const selected = new URLSearchParams(actualBody).getAll('resource');\n if (selected.length !== 1 || selected[0] !== currentDatabase.resource)\n throw new Error('Authorization resource mismatch.');\n if (\n url !== normalizeUrl(currentDatabase.oidcServerConfiguration!.tokenEndpoint)\n )\n throw new Error('Invalid resource token endpoint.');\n currentDatabase.refreshGrant = currentDatabase;\n }\n currentDatabase.requestedScope =\n currentDatabase.authorizationScope ??\n (currentDatabase.resource\n ? getResourceConfiguration(\n currentDatabase.oidcConfiguration?.resources,\n currentDatabase.resource,\n ).scope\n : currentDatabase.oidcConfiguration?.scope);\n const generation = currentDatabase.generation;\n let newBody = actualBody;\n const codeVerifier = currentDatabase.codeVerifier;\n if (codeVerifier != null) {\n newBody = replaceCodeVerifier(newBody, codeVerifier);\n }\n\n const headersExtras = await generateDpopAsync(\n originalRequest,\n currentDatabase,\n url,\n );\n const resp = await fetch(originalRequest, {\n body: newBody,\n method: clonedRequest.method,\n headers: headersExtras,\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n const hidden = await hideTokens(\n currentDatabase,\n () => currentDatabase!.generation === generation,\n undefined,\n true,\n )(resp);\n resolve(hidden);\n return;\n }\n\n // Pass through all other POST requests unchanged\n const normalResp = await fetch(originalRequest, {\n body: actualBody,\n method: clonedRequest.method,\n headers: serializeHeaders(originalRequest.headers),\n mode: clonedRequest.mode,\n cache: clonedRequest.cache,\n redirect: clonedRequest.redirect,\n referrer: clonedRequest.referrer,\n credentials: clonedRequest.credentials,\n integrity: clonedRequest.integrity,\n });\n resolve(normalResp);\n } catch (err) {\n reject(err);\n }\n })\n .catch(reject);\n });\n\n return await responsePromise;\n }\n\n // Default: pass through the request unchanged\n return fetch(originalRequest);\n } catch (err) {\n // Surface unexpected errors as a 500 rather than silently hanging\n console.error('[OidcServiceWorker] handleFetch error:', err);\n return new Response('Service Worker Error', { status: 500 });\n }\n })(),\n );\n};\n\nconst handleMessageAsync = async (event: ExtendableMessageEvent): Promise<void> => {\n const port = event.ports[0];\n const data = event.data as MessageEventData;\n\n if (event.data?.type === 'SKIP_WAITING') {\n await _self.skipWaiting();\n port?.postMessage?.({});\n return;\n } else if (event.data.type === 'claim') {\n _self.clients.claim().then(() => port.postMessage({}));\n return;\n }\n\n const configurationName = data.configurationName.split('#')[0];\n const resource = getContextResource(data.configurationName);\n\n if (trustedDomains == null) {\n trustedDomains = {};\n }\n\n const trustedDomain = trustedDomains[configurationName];\n const allowMultiTabLogin = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.allowMultiTabLogin;\n\n const tabId = allowMultiTabLogin ? data.tabId : 'default';\n const configurationNameWithTabId = `${configurationName}#tabId=${tabId}`;\n\n let currentDatabase = database[configurationNameWithTabId];\n if (!currentDatabase) {\n const showAccessToken = Array.isArray(trustedDomain) ? false : trustedDomain.showAccessToken;\n const doNotSetAccessTokenToNavigateRequests = Array.isArray(trustedDomain)\n ? true\n : trustedDomain.setAccessTokenToNavigateRequests;\n const convertAllRequestsToCorsExceptNavigate = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.convertAllRequestsToCorsExceptNavigate;\n const bypassAllNonOidcRequests = Array.isArray(trustedDomain)\n ? false\n : trustedDomain.bypassAllNonOidcRequests;\n\n database[configurationNameWithTabId] = {\n tokens: null,\n state: null,\n codeVerifier: null,\n oidcServerConfiguration: null,\n oidcConfiguration: undefined,\n nonce: null,\n status: null,\n configurationName: configurationNameWithTabId,\n hideAccessToken: !showAccessToken,\n setAccessTokenToNavigateRequests: doNotSetAccessTokenToNavigateRequests ?? true,\n convertAllRequestsToCorsExceptNavigate: convertAllRequestsToCorsExceptNavigate ?? false,\n demonstratingProofOfPossessionNonce: null,\n demonstratingProofOfPossessionJwkJson: null,\n demonstratingProofOfPossessionConfiguration: null,\n demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent: false,\n allowMultiTabLogin: allowMultiTabLogin ?? false,\n bypassAllNonOidcRequests: bypassAllNonOidcRequests ?? false,\n };\n currentDatabase = database[configurationNameWithTabId];\n\n if (!trustedDomains[configurationName]) {\n trustedDomains[configurationName] = [];\n }\n }\n if (resource !== undefined) {\n try {\n currentDatabase = getOrCreateResourceContext(currentDatabase, resource);\n } catch (error) {\n console.error('[OidcServiceWorker] Invalid resource context:', error);\n port.postMessage({ configurationName, error: 'The resource is not registered.' });\n return;\n }\n }\n\n switch (data.type) {\n case 'clear':\n currentDatabase.generation = (currentDatabase.generation ?? 0) + 1;\n for (const entry of Object.values(currentDatabase.resourceEntries ?? {})) {\n entry.generation = (entry.generation ?? 0) + 1;\n }\n currentDatabase.resourceEntries = undefined;\n currentDatabase.tokens = null;\n currentDatabase.state = null;\n currentDatabase.codeVerifier = null;\n currentDatabase.nonce = null;\n currentDatabase.demonstratingProofOfPossessionNonce = null;\n currentDatabase.demonstratingProofOfPossessionJwkJson = null;\n currentDatabase.demonstratingProofOfPossessionConfiguration = null;\n currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent = false;\n currentDatabase.authorizationScope = undefined;\n currentDatabase.requestedScope = undefined;\n currentDatabase.demonstratingProofOfPossessionApiNonce = null;\n currentDatabase.status = data.data.status;\n port.postMessage({ configurationName });\n return;\n\n case 'init': {\n const oidcServerConfiguration = data.data.oidcServerConfiguration;\n const domains = getDomains(trustedDomain, 'oidc');\n\n if (!domains.some(domain => domain === acceptAnyDomainToken)) {\n [\n oidcServerConfiguration.tokenEndpoint,\n oidcServerConfiguration.revocationEndpoint,\n oidcServerConfiguration.userInfoEndpoint,\n oidcServerConfiguration.issuer,\n ].forEach(u => {\n checkDomain(domains, u);\n });\n }\n\n currentDatabase.oidcServerConfiguration = oidcServerConfiguration;\n currentDatabase.oidcConfiguration = data.data.oidcConfiguration;\n if (data.data.where === 'loginAsync')\n currentDatabase.authorizationScope = currentDatabase.oidcConfiguration.scope;\n if (resource !== undefined)\n getResourceConfiguration(currentDatabase.oidcConfiguration.resources, resource);\n\n if (currentDatabase.demonstratingProofOfPossessionConfiguration == null) {\n const parent = currentDatabase.parentConfiguration;\n if (parent?.demonstratingProofOfPossessionJwkJson) {\n currentDatabase.demonstratingProofOfPossessionJwkJson =\n parent.demonstratingProofOfPossessionJwkJson;\n currentDatabase.demonstratingProofOfPossessionConfiguration =\n parent.demonstratingProofOfPossessionConfiguration;\n }\n const demonstratingProofOfPossessionConfiguration = getDpopConfiguration(trustedDomain);\n if (\n demonstratingProofOfPossessionConfiguration != null &&\n currentDatabase.demonstratingProofOfPossessionConfiguration == null\n ) {\n if (currentDatabase.oidcConfiguration.demonstrating_proof_of_possession) {\n console.warn(\n 'In service worker, demonstrating_proof_of_possession must be configured from trustedDomains file',\n );\n }\n currentDatabase.demonstratingProofOfPossessionConfiguration =\n demonstratingProofOfPossessionConfiguration;\n currentDatabase.demonstratingProofOfPossessionJwkJson = await generateJwkAsync(self)(\n demonstratingProofOfPossessionConfiguration.generateKeyAlgorithm,\n );\n currentDatabase.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent =\n getDpopOnlyWhenDpopHeaderPresent(trustedDomain) ?? false;\n }\n }\n\n if (!currentDatabase.tokens) {\n port.postMessage({\n tokens: null,\n status: currentDatabase.status,\n configurationName,\n version,\n resourceTokenManagement: true,\n resourceContexts: Object.keys(currentDatabase.resourceEntries ?? {}),\n });\n } else {\n const tokens = {\n ...currentDatabase.tokens,\n idTokenPayload: currentDatabase.tokens.idTokenPayload\n ? { ...currentDatabase.tokens.idTokenPayload }\n : undefined,\n };\n if (currentDatabase.hideAccessToken) {\n tokens.access_token = `${TOKEN.ACCESS_TOKEN}_${currentDatabase.configurationName}`;\n }\n if (tokens.refresh_token) {\n tokens.refresh_token = `${TOKEN.REFRESH_TOKEN}_${(currentDatabase.refreshGrant ?? currentDatabase).configurationName}`;\n }\n if (tokens?.idTokenPayload?.nonce && currentDatabase.nonce != null) {\n tokens.idTokenPayload.nonce = `${TOKEN.NONCE_TOKEN}_${currentDatabase.configurationName}`;\n }\n port.postMessage({\n tokens,\n status: currentDatabase.status,\n configurationName,\n version,\n resourceTokenManagement: true,\n resourceContexts: Object.keys(currentDatabase.resourceEntries ?? {}),\n });\n }\n return;\n }\n\n case 'setDemonstratingProofOfPossessionNonce': {\n currentDatabase.demonstratingProofOfPossessionNonce =\n data.data.demonstratingProofOfPossessionNonce;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getDemonstratingProofOfPossessionNonce': {\n const demonstratingProofOfPossessionNonce =\n currentDatabase.demonstratingProofOfPossessionNonce;\n port.postMessage({\n configurationName,\n demonstratingProofOfPossessionNonce,\n });\n return;\n }\n\n case 'setState': {\n currentDatabase.state = data.data.state;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getState': {\n const state = currentDatabase.state;\n port.postMessage({ configurationName, state });\n return;\n }\n\n case 'setCodeVerifier': {\n currentDatabase.codeVerifier = data.data.codeVerifier;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getCodeVerifier': {\n const codeVerifier =\n currentDatabase.codeVerifier != null\n ? `${TOKEN.CODE_VERIFIER}_${currentDatabase.configurationName}`\n : null;\n port.postMessage({\n configurationName,\n codeVerifier,\n });\n return;\n }\n\n case 'setSessionState': {\n currentDatabase.sessionState = data.data.sessionState;\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getSessionState': {\n const sessionState = currentDatabase.sessionState;\n port.postMessage({ configurationName, sessionState });\n return;\n }\n\n case 'setNonce': {\n const nonce = data.data.nonce;\n if (nonce) {\n if (\n !currentDatabase.resource &&\n currentDatabase.nonce &&\n nonce.nonce !== currentDatabase.nonce.nonce\n ) {\n currentDatabase.generation = (currentDatabase.generation ?? 0) + 1;\n for (const entry of Object.values(currentDatabase.resourceEntries ?? {})) {\n entry.generation = (entry.generation ?? 0) + 1;\n }\n currentDatabase.resourceEntries = undefined;\n }\n currentDatabase.nonce = nonce;\n }\n port.postMessage({ configurationName });\n return;\n }\n\n case 'getNonce': {\n const keyNonce = `${TOKEN.NONCE_TOKEN}_${currentDatabase.configurationName}`;\n const nonce = currentDatabase.nonce ? keyNonce : null;\n port.postMessage({ configurationName, nonce });\n return;\n }\n\n default:\n return;\n }\n};\n\nconst handleMessage = async (event: ExtendableMessageEvent): Promise<void> => {\n try {\n await handleMessageAsync(event);\n } catch (error) {\n console.error('[OidcServiceWorker] Message failed:', error);\n event.ports?.[0]?.postMessage({\n configurationName: event.data?.configurationName,\n error: error instanceof Error ? error.message : 'The worker could not process this message.',\n });\n }\n};\n\n// Event listeners\n_self.addEventListener('fetch', handleFetch);\n_self.addEventListener('message', handleMessage);\n"],"mappings":";;CAAA,IAAM,iBAAiB;CAUvB,IAAM,QAAmB;EACvB,eAAe;EACf,cAAc;EACd,aAAa;EACb,eAAe;CACjB;CAQA,IAAM,iBAAqC;EACzC,kCAAkC;EAClC,sBAAsB;EACtB,kBAAkB;CACpB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MAAM,cAAc,0BAA0B,CAAC;AAC/C,QAAA,MAAM,oBAAoB,MAAM,CAAC;AAEjC,KAAK,SAAS,GAAG;IACf,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,QAAA,MAAM,KAAK,EAAE,SAKZ,CAAC;AAEF,KAAK,kBAAkB,GAAG;IACxB,QAAQ,CAAC,gCAAgC,EAAE,MAAM,CAAC;IAClD,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CACnC,CAAC;AAEF,QAAA,MAAM,cAAc,EAAE,kBAIrB,CAAC;AAEF,QAAA,MAAM,yBAAyB,sCAAsC,CAAC;AAEtE,OAAO,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,cAAc,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAEA,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,2BAQzC;AAED,wBAAgB,mCAAmC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CASjF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dpop.d.ts","sourceRoot":"","sources":["../src/dpop.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AASnD,eAAO,MAAM,oBAAoB,GAAI,eAAe,MAAM,EAAE,GAAG,aAAa,4EAa3E,CAAC;AAEF,eAAO,MAAM,gCAAgC,GAAI,eAAe,MAAM,EAAE,GAAG,aAAa,mBAUvF,CAAC"}
@@ -0,0 +1 @@
1
+ {"version":3,"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WlF,CAAC;AAEF,OAAO,EACL,6BAA6B,IAAI,gCAAgC,EACjE,0BAA0B,EAC1B,mBAAmB,EACnB,0BAA0B,GAC3B,CAAC"}
@@ -1,2 +1,140 @@
1
- export * from './src/protocol.js'
2
- export {}
1
+ import { MessageData, MessageEventData, MessageEventType, Nonce, OidcConfiguration, OidcServerConfiguration, Status } from './types';
2
+ export type { MessageData, MessageEventData, MessageEventType, Nonce, OidcConfiguration, OidcServerConfiguration, Status, };
3
+ /**
4
+ * Semver-protected version of the service worker `postMessage` protocol.
5
+ *
6
+ * - The `MAJOR` component changes only on a breaking change to any of the
7
+ * exports in this module.
8
+ * - The `MINOR` component changes when new (additive) message types or
9
+ * helpers are introduced.
10
+ * - The `PATCH` component changes for documentation or non-behavioural
11
+ * tweaks.
12
+ */
13
+ export declare const PROTOCOL_VERSION: "1.1.0";
14
+ export type { OidcResourceConfiguration } from './resource';
15
+ export { getContextResource, getResourceConfiguration, getResourceContextName, isResourceOriginManaged, isResourceUrlAllowed, RESOURCE_TOKEN_REQUEST_HEADER, validateResourceIdentifier, } from './resource';
16
+ /**
17
+ * Every supported service worker message type.
18
+ *
19
+ * The values are also the literal string used on the wire as
20
+ * `MessageEventData.type` and must therefore remain stable across patch and
21
+ * minor versions of the protocol.
22
+ */
23
+ export declare const ServiceWorkerMessageType: {
24
+ /** Lifecycle: tells the SW to skip the `waiting` state. */
25
+ readonly SKIP_WAITING: "SKIP_WAITING";
26
+ /** Lifecycle: asks the SW to claim the current page. */
27
+ readonly CLAIM: "claim";
28
+ /** Resets the session entry kept inside the SW for a configuration. */
29
+ readonly CLEAR: "clear";
30
+ /** Initialises a configuration entry inside the SW. */
31
+ readonly INIT: "init";
32
+ readonly SET_STATE: "setState";
33
+ readonly GET_STATE: "getState";
34
+ readonly SET_CODE_VERIFIER: "setCodeVerifier";
35
+ readonly GET_CODE_VERIFIER: "getCodeVerifier";
36
+ readonly SET_SESSION_STATE: "setSessionState";
37
+ readonly GET_SESSION_STATE: "getSessionState";
38
+ readonly SET_NONCE: "setNonce";
39
+ readonly GET_NONCE: "getNonce";
40
+ readonly SET_DPOP_NONCE: "setDemonstratingProofOfPossessionNonce";
41
+ readonly GET_DPOP_NONCE: "getDemonstratingProofOfPossessionNonce";
42
+ readonly SET_DPOP_JWK: "setDemonstratingProofOfPossessionJwk";
43
+ readonly GET_DPOP_JWK: "getDemonstratingProofOfPossessionJwk";
44
+ };
45
+ export type ServiceWorkerMessageTypeKey = keyof typeof ServiceWorkerMessageType;
46
+ export type ServiceWorkerMessageTypeValue = (typeof ServiceWorkerMessageType)[ServiceWorkerMessageTypeKey];
47
+ /**
48
+ * Structural shape of a message sent to the service worker. The shape is
49
+ * identical to {@link MessageEventData} but typed against the public
50
+ * {@link ServiceWorkerMessageTypeValue} union and with optional fields where
51
+ * the underlying SW tolerates them.
52
+ */
53
+ export interface ServiceWorkerMessage<TData extends Partial<MessageData> | null = Partial<MessageData> | null> {
54
+ type: ServiceWorkerMessageTypeValue | 'SKIP_WAITING' | 'claim';
55
+ configurationName: string;
56
+ data: TData;
57
+ /**
58
+ * Optional tab identifier injected by the high-level helpers. Consumers
59
+ * sending raw messages can omit it; the SW falls back to `'default'`.
60
+ */
61
+ tabId?: string;
62
+ }
63
+ /**
64
+ * Generic envelope used by every response. Each individual message type may
65
+ * extend it with additional, well-known fields (see PROTOCOL.md).
66
+ */
67
+ export interface ServiceWorkerResponse {
68
+ /** Resource isolation capability provided by protocol 1.1 workers. */
69
+ resourceTokenManagement?: boolean;
70
+ /** Worker-owned context names, without token or key material. */
71
+ resourceContexts?: string[];
72
+ configurationName?: string;
73
+ /** Set by the SW when it cannot service the request. */
74
+ error?: unknown;
75
+ [key: string]: unknown;
76
+ }
77
+ /**
78
+ * Stable internal token placeholders. They are returned by the service
79
+ * worker in lieu of secret values (access/refresh tokens, nonces and code
80
+ * verifier) so consumers never see the cleartext.
81
+ */
82
+ export declare const TOKEN_PLACEHOLDERS: {
83
+ readonly ACCESS_TOKEN: "ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER";
84
+ readonly REFRESH_TOKEN: "REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER";
85
+ readonly NONCE_TOKEN: "NONCE_SECURED_BY_OIDC_SERVICE_WORKER";
86
+ readonly CODE_VERIFIER: "CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER";
87
+ };
88
+ /** Prefix used for every DPoP placeholder returned by the SW. */
89
+ export declare const DPOP_TOKEN_PLACEHOLDER_PREFIX: "DPOP_SECURED_BY_OIDC_SERVICE_WORKER";
90
+ /**
91
+ * Browser storage key conventions used by the OIDC client when no service
92
+ * worker is available, or as a fallback alongside the SW. They are exported
93
+ * so external integrations can read/clean up the same entries.
94
+ */
95
+ export declare const STORAGE_KEY_PREFIX: {
96
+ /** sessionStorage – per-tab tab identifier (`oidc.tabId.<configurationName>`). */
97
+ readonly TAB_ID: "oidc.tabId.";
98
+ /** sessionStorage – `oidc.state.<configurationName>`. */
99
+ readonly STATE: "oidc.state.";
100
+ /** sessionStorage – `oidc.nonce.<configurationName>`. */
101
+ readonly NONCE: "oidc.nonce.";
102
+ /** sessionStorage – `oidc.code_verifier.<configurationName>`. */
103
+ readonly CODE_VERIFIER: "oidc.code_verifier.";
104
+ /** localStorage – `oidc.login.<configurationName>`. */
105
+ readonly LOGIN_PARAMS: "oidc.login.";
106
+ /** sessionStorage – `oidc.sw.version_mismatch_reload.<configurationName>`. */
107
+ readonly SW_VERSION_MISMATCH_RELOAD: "oidc.sw.version_mismatch_reload.";
108
+ };
109
+ /** sessionStorage key tracking the SW controllerchange reload counter. */
110
+ export declare const SW_CONTROLLER_CHANGE_RELOAD_COUNT_KEY: "oidc.sw.controllerchange_reload_count";
111
+ /**
112
+ * Builds a typed sessionStorage / localStorage key from one of the known
113
+ * prefixes and a configuration name. The function is intentionally
114
+ * single-purpose so we never lose the prefix-based stability guarantee.
115
+ */
116
+ export declare const buildStorageKey: (prefix: (typeof STORAGE_KEY_PREFIX)[keyof typeof STORAGE_KEY_PREFIX], configurationName: string) => string;
117
+ /**
118
+ * Builds the stable placeholder string the SW returns instead of an
119
+ * access/refresh/nonce/code-verifier secret. Useful for consumers that need
120
+ * to detect whether a value comes from the SW.
121
+ */
122
+ export declare const buildSecuredTokenPlaceholder: (placeholder: (typeof TOKEN_PLACEHOLDERS)[keyof typeof TOKEN_PLACEHOLDERS], configurationName: string, tabId?: string) => string;
123
+ /**
124
+ * Builds the placeholder returned for DPoP-secured access tokens
125
+ * (`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_<config>#tabId=<tabId>`).
126
+ */
127
+ export declare const buildDpopSecuredPlaceholder: (configurationName: string, tabId?: string) => string;
128
+ /**
129
+ * Type guard returning `true` when the provided value is one of the
130
+ * supported, public service worker message types.
131
+ */
132
+ export declare const isServiceWorkerMessageType: (value: unknown) => value is ServiceWorkerMessageTypeValue;
133
+ /**
134
+ * Internal wire-level type, re-exported for legacy parity. New code should
135
+ * prefer {@link ServiceWorkerMessageTypeValue}.
136
+ *
137
+ * @internal
138
+ */
139
+ export type ServiceWorkerMessageEventType = MessageEventType;
140
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,EACL,iBAAiB,EACjB,uBAAuB,EACvB,MAAM,EACP,MAAM,SAAS,CAAC;AAEjB,YAAY,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,EACL,iBAAiB,EACjB,uBAAuB,EACvB,MAAM,GACP,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,gBAAgB,EAAG,OAAgB,CAAC;AAEjD,YAAY,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EACL,kBAAkB,EAClB,wBAAwB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