@sebspark/test-iap 1.0.31 → 1.0.33
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.
- package/CHANGELOG.md +12 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{server-ByjdsPOZ.mjs → server-BB-bWajA.mjs} +22 -7
- package/dist/server-BB-bWajA.mjs.map +1 -0
- package/dist/start.mjs +1 -1
- package/dist/start.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/server-ByjdsPOZ.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @sebspark/test-iap
|
|
2
2
|
|
|
3
|
+
## 1.0.33
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- ebb88d9: chore(deps): bump jose from 6.2.14 to 6.2.15
|
|
8
|
+
|
|
9
|
+
## 1.0.32
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 176ea40: Introspection now fails with a clear error when `mode` is `downstream` but no downstream URL is configured, instead of calling the remote JWT endpoint with `undefined`. Non-string `Authorization` headers are rejected explicitly with `IntrospectionError`. Internal type assertions were replaced with narrowing.
|
|
14
|
+
|
|
3
15
|
## 1.0.31
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/server.ts","../src/test-iap-container.ts"],"mappings":";;KAOY;UACK;EACf;EACA,OAAO;EACP;;qBCGW,oBAAiB,QAAY,gBAAW,KAAA,cAAA,KAAA,wBAAA,KAAA;qBCDxC;UACH;UAEA;UACA;UACA;UACA;UACA;UACA;EAED,cAAc;EAId,SAAS;EAKT,WAAW;EAUX,SAAS,MAAM;EAKf,eAAe;EAUf,YAAY,SAAS;EAKrB,WAAW,QAAQ;EAKb,SAAS,QAAQ;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/server.ts","../src/test-iap-container.ts"],"mappings":";;KAOY;UACK;EACf;EACA,OAAO;EACP;;qBCGW,oBAAiB,QAAY,gBAAW,KAAA,cAAA,KAAA,wBAAA,KAAA;qBCDxC;UACH;UAEA;UACA;UACA;UACA;UACA;UACA;EAED,cAAc;EAId,SAAS;EAKT,WAAW;EAUX,SAAS,MAAM;EAKf,eAAe;EAUf,YAAY,SAAS;EAKrB,WAAW,QAAQ;EAKb,SAAS,QAAQ;;qBAqEnB,gCAAgC;mBAGxB;EAFnB,YACE,SAAS,sBACQ;EAIZ"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createProxyServer } from "./server-
|
|
1
|
+
import { t as createProxyServer } from "./server-BB-bWajA.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import assert from "node:assert";
|
|
4
4
|
import fs from "node:fs";
|
|
@@ -83,7 +83,8 @@ var TestIapContainer = class {
|
|
|
83
83
|
return this;
|
|
84
84
|
}
|
|
85
85
|
async start() {
|
|
86
|
-
|
|
86
|
+
const { target } = this;
|
|
87
|
+
assert(target, "withTarget(...) is required");
|
|
87
88
|
const resolvedMode = this.mode ?? (this.downstream ? "downstream" : "local");
|
|
88
89
|
if (resolvedMode === "downstream") assert(this.downstream, "withDownstream(...) is required when mode=downstream");
|
|
89
90
|
const distDir = path.join(getThisDir(), "../dist");
|
|
@@ -105,7 +106,7 @@ var TestIapContainer = class {
|
|
|
105
106
|
target: "/app/node_modules/jose"
|
|
106
107
|
}];
|
|
107
108
|
const env = {
|
|
108
|
-
TARGET:
|
|
109
|
+
TARGET: target,
|
|
109
110
|
MODE: resolvedMode,
|
|
110
111
|
PORT: String(this.port)
|
|
111
112
|
};
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/build-helpers.ts","../src/test-iap-container.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\n/**\n * Works in both CJS and ESM without tripping bundlers:\n * - CJS: derives from __filename\n * - ESM: evals import.meta.url so it's not statically analyzed\n */\nexport const getThisFileUrl = (): string => {\n if (typeof __filename !== 'undefined') {\n return pathToFileURL(__filename).href\n }\n // biome-ignore lint/security/noGlobalEval: needed for cjs/esm compatibility\n // biome-ignore lint/complexity/noCommaOperator: needed for cjs/esm compatibility\n return (0, eval)('import.meta.url')
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/build-helpers.ts","../src/test-iap-container.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\n/**\n * Works in both CJS and ESM without tripping bundlers:\n * - CJS: derives from __filename\n * - ESM: evals import.meta.url so it's not statically analyzed\n */\nexport const getThisFileUrl = (): string => {\n if (typeof __filename !== 'undefined') {\n return pathToFileURL(__filename).href\n }\n // biome-ignore lint/security/noGlobalEval: needed for cjs/esm compatibility\n // biome-ignore lint/complexity/noCommaOperator: needed for cjs/esm compatibility\n return (0, eval)('import.meta.url')\n}\n\n/** Directory of the current compiled file (e.g., your package's dist dir) */\nexport const getThisDir = (): string =>\n path.dirname(fileURLToPath(getThisFileUrl()))\n\n/** A require() that works in both CJS and ESM builds */\nexport const getRequireCompat = (): ReturnType<typeof createRequire> =>\n typeof require === 'function' ? require : createRequire(getThisFileUrl())\n\n/**\n * Resolve a module specifier relative to this package’s installed location.\n * Example: resolveNearSelf('jose/package.json')\n */\nexport const resolveNearSelf = (specifier: string): string => {\n const req = getRequireCompat()\n return req.resolve(specifier, { paths: [getThisDir()] })\n}\n\n/** Safe resolve: returns undefined if not found */\nexport const tryResolveNearSelf = (specifier: string): string | undefined => {\n try {\n return resolveNearSelf(specifier)\n } catch {\n return undefined\n }\n}\n","import assert from 'node:assert'\nimport fs from 'node:fs'\n// src/test-iap-container.ts\nimport path from 'node:path'\nimport {\n AbstractStartedContainer,\n GenericContainer,\n type StartedNetwork,\n type StartedTestContainer,\n} from 'testcontainers'\nimport { getThisDir, tryResolveNearSelf } from './build-helpers'\nimport type { Mode } from './types'\n\nexport class TestIapContainer {\n private baseImage =\n 'node:26.13.0-alpine@sha256:c6ad9e9c1d80f6eb607c26b4b0a132ff7a2344fad1c78ea3baa2a7d4c8de6d94'\n private port = 3000\n private target?: string\n private mode?: Mode\n private downstream?: string\n private network?: StartedNetwork\n private labels: Record<string, string> = {}\n\n public withBaseImage(image: string) {\n this.baseImage = image\n return this\n }\n public withPort(port: number) {\n this.port = port\n return this\n }\n\n public withTarget(url: string) {\n const u = new URL(url)\n assert(\n ['http:', 'https:', 'ws:', 'wss:'].includes(u.protocol),\n 'target must be absolute http(s):// or ws(s)://'\n )\n this.target = u.toString()\n return this\n }\n\n public withMode(mode: Mode) {\n this.mode = mode\n return this\n }\n\n public withDownstream(url: string) {\n const u = new URL(url)\n assert(\n ['http:', 'https:'].includes(u.protocol),\n 'downstream must be absolute http(s)://'\n )\n this.downstream = u.toString()\n return this\n }\n\n public withNetwork(network: StartedNetwork) {\n this.network = network\n return this\n }\n\n public withLabels(labels: Record<string, string>) {\n this.labels = labels\n return this\n }\n\n public async start(): Promise<StartedTestIapContainer> {\n const { target } = this\n assert(target, 'withTarget(...) is required')\n\n const resolvedMode: Mode =\n this.mode ?? (this.downstream ? 'downstream' : 'local')\n if (resolvedMode === 'downstream') {\n assert(\n this.downstream,\n 'withDownstream(...) is required when mode=downstream'\n )\n }\n\n // directory of the installed package's compiled files (dist)\n const distDir = path.join(getThisDir(), '../dist')\n assert(fs.existsSync(distDir), `dist directory not found: ${distDir}`)\n\n // prefer start.mjs, then start.js\n const startMjs = path.join(distDir, 'start.mjs')\n const startJs = path.join(distDir, 'start.js')\n\n const hasStartMjs = fs.existsSync(startMjs)\n const hasStartJs = fs.existsSync(startJs)\n\n if (!hasStartMjs && !hasStartJs) {\n throw new Error(`Could not find ${startMjs} or ${startJs}`)\n }\n\n const entry = hasStartMjs ? '/app/dist/start.mjs' : '/app/dist/start.js'\n\n // mount dist + the installed 'jose' module so imports work inside the container\n const josePkgPath = tryResolveNearSelf('jose/package.json')\n if (!josePkgPath) {\n throw new Error(\n 'Could not resolve \"jose\" next to @sebspark/test-iap. ' +\n 'Ensure \"jose\" is installed as a dependency in the same project that installs @sebspark/test-iap.'\n )\n }\n const joseDir = path.dirname(josePkgPath)\n\n const binds = [\n { source: distDir, target: '/app/dist' },\n { source: joseDir, target: '/app/node_modules/jose' },\n ]\n\n const env: Record<string, string> = {\n TARGET: target,\n MODE: resolvedMode,\n PORT: String(this.port),\n }\n if (resolvedMode === 'downstream' && this.downstream) {\n env.DOWNSTREAM = this.downstream\n }\n\n const gc = new GenericContainer(this.baseImage)\n .withWorkingDir('/app')\n .withBindMounts(binds)\n .withExposedPorts(this.port)\n .withEnvironment(env)\n .withLabels(this.labels)\n .withCommand(['node', entry])\n\n if (this.network) gc.withNetwork(this.network)\n\n const started = await gc.start()\n return new StartedTestIapContainer(started, this.port)\n }\n}\n\nexport class StartedTestIapContainer extends AbstractStartedContainer {\n constructor(\n started: StartedTestContainer,\n private readonly internalPort: number\n ) {\n super(started)\n }\n public getEndpoint() {\n return `${this.getHost()}:${this.getMappedPort(this.internalPort)}`\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AASA,MAAa,uBAA+B;CAC1C,IAAI,OAAO,eAAe,aACxB,OAAO,cAAc,UAAU,CAAC,CAAC;CAInC,QAAQ,GAAG,KAAA,CAAM,iBAAiB;AACpC;;AAGA,MAAa,mBACX,KAAK,QAAQ,cAAc,eAAe,CAAC,CAAC;;AAG9C,MAAa,yBACX,OAAA,cAAmB,aAAA,YAAuB,cAAc,eAAe,CAAC;;;;;AAM1E,MAAa,mBAAmB,cAA8B;CAE5D,OADY,iBACH,CAA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SAAS,UAAU;EAE7C,MAAM,cAAc,GAAG,WAAW,QAAQ;EAC1C,MAAM,aAAa,GAAG,WAAW,OAAO;EAExC,IAAI,CAAC,eAAe,CAAC,YACnB,MAAM,IAAI,MAAM,kBAAkB,SAAS,MAAM,SAAS;EAG5D,MAAM,QAAQ,cAAc,wBAAwB;EAGpD,MAAM,cAAc,mBAAmB,mBAAmB;EAC1D,IAAI,CAAC,aACH,MAAM,IAAI,MACR,2JAEF;EAEF,MAAM,UAAU,KAAK,QAAQ,WAAW;EAExC,MAAM,QAAQ,CACZ;GAAE,QAAQ;GAAS,QAAQ;EAAY,GACvC;GAAE,QAAQ;GAAS,QAAQ;EAAyB,CACtD;EAEA,MAAM,MAA8B;GAClC,QAAQ;GACR,MAAM;GACN,MAAM,OAAO,KAAK,IAAI;EACxB;EACA,IAAI,iBAAiB,gBAAgB,KAAK,YACxC,IAAI,aAAa,KAAK;EAGxB,MAAM,KAAK,IAAI,iBAAiB,KAAK,SAAS,CAAC,CAC5C,eAAe,MAAM,CAAC,CACtB,eAAe,KAAK,CAAC,CACrB,iBAAiB,KAAK,IAAI,CAAC,CAC3B,gBAAgB,GAAG,CAAC,CACpB,WAAW,KAAK,MAAM,CAAC,CACvB,YAAY,CAAC,QAAQ,KAAK,CAAC;EAE9B,IAAI,KAAK,SAAS,GAAG,YAAY,KAAK,OAAO;EAG7C,OAAO,IAAI,wBAAwB,MADb,GAAG,MAAM,GACa,KAAK,IAAI;CACvD;AACF;AAEA,IAAa,0BAAb,cAA6C,yBAAyB;CAGjD;CAFnB,YACE,SACA,cACA;EACA,MAAM,OAAO;EAFI,KAAA,eAAA;CAGnB;CACA,cAAqB;EACnB,OAAO,GAAG,KAAK,QAAQ,EAAE,GAAG,KAAK,cAAc,KAAK,YAAY;CAClE;AACF"}
|
|
@@ -3,16 +3,24 @@ import https from "node:https";
|
|
|
3
3
|
import net from "node:net";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { SignJWT, calculateJwkThumbprint, exportJWK, generateKeyPair } from "jose";
|
|
6
|
+
import assert from "node:assert";
|
|
6
7
|
// src/keys.ts
|
|
7
8
|
const generateKey = async () => {
|
|
8
9
|
const { publicKey, privateKey } = await generateKeyPair("RS256");
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
const exported = await exportJWK(publicKey);
|
|
11
|
+
const { n, e } = exported;
|
|
12
|
+
assert(n && e, "exported RSA public JWK must have n and e");
|
|
13
|
+
const kid = await calculateJwkThumbprint(exported);
|
|
12
14
|
return {
|
|
13
15
|
publicKey,
|
|
14
16
|
privateKey,
|
|
15
|
-
jwk
|
|
17
|
+
jwk: {
|
|
18
|
+
...exported,
|
|
19
|
+
n,
|
|
20
|
+
e,
|
|
21
|
+
kid,
|
|
22
|
+
alg: "RS256"
|
|
23
|
+
}
|
|
16
24
|
};
|
|
17
25
|
};
|
|
18
26
|
// src/jwt.ts
|
|
@@ -47,7 +55,7 @@ const createJwt = async (claims) => {
|
|
|
47
55
|
};
|
|
48
56
|
const getRemoteJwt = async (remoteUrl, claims) => {
|
|
49
57
|
const url = new URL(remoteUrl);
|
|
50
|
-
for (const [name, val] of Object.entries(claims)) url.searchParams.set(name, val);
|
|
58
|
+
for (const [name, val] of Object.entries(claims)) url.searchParams.set(name, String(val));
|
|
51
59
|
const res = await fetch(url);
|
|
52
60
|
const text = await res.text();
|
|
53
61
|
if (!res.ok) throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`);
|
|
@@ -104,11 +112,18 @@ const parseAuthorizationHeader = (header) => {
|
|
|
104
112
|
}
|
|
105
113
|
};
|
|
106
114
|
// src/introspection.ts
|
|
115
|
+
const getAccessToken = async (mode, downstream, claims) => {
|
|
116
|
+
if (mode === "local") return createJwt(claims);
|
|
117
|
+
if (!downstream) throw new Error("downstream URL is required when mode is downstream");
|
|
118
|
+
return getRemoteJwt(downstream, claims);
|
|
119
|
+
};
|
|
107
120
|
const introspect = async (config, headers) => {
|
|
108
121
|
const authorizationHeader = getHeader(headers, "authorization");
|
|
109
122
|
if (!authorizationHeader) return headers;
|
|
123
|
+
if (typeof authorizationHeader !== "string") throw new IntrospectionError(String(authorizationHeader));
|
|
110
124
|
const claims = parseAuthorizationHeader(authorizationHeader);
|
|
111
|
-
const
|
|
125
|
+
const mode = config.mode || (config.downstream ? "downstream" : "local");
|
|
126
|
+
const access_token = await getAccessToken(mode, config.downstream, claims);
|
|
112
127
|
return {
|
|
113
128
|
...headers,
|
|
114
129
|
authorization: `Bearer ${access_token}`
|
|
@@ -207,4 +222,4 @@ Content-Length: ${body.length}
|
|
|
207
222
|
};
|
|
208
223
|
export { createProxyServer as t };
|
|
209
224
|
|
|
210
|
-
//# sourceMappingURL=server-
|
|
225
|
+
//# sourceMappingURL=server-BB-bWajA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-BB-bWajA.mjs","names":[],"sources":["../src/keys.ts","../src/jwt.ts","../src/utils.ts","../src/introspection.ts","../src/server.ts"],"sourcesContent":["import assert from 'node:assert'\nimport {\n calculateJwkThumbprint,\n exportJWK,\n generateKeyPair,\n type JWK_RSA_Public,\n} from 'jose'\n\ntype JWK = JWK_RSA_Public & { alg: string; kid: string }\n\nexport interface Key {\n publicKey: CryptoKey\n privateKey: CryptoKey\n jwk: JWK\n}\n\nexport const generateKey = async (): Promise<Key> => {\n const { publicKey, privateKey } = await generateKeyPair('RS256')\n const exported = await exportJWK(publicKey)\n const { n, e } = exported\n assert(n && e, 'exported RSA public JWK must have n and e')\n const kid = await calculateJwkThumbprint(exported)\n const jwk: JWK = { ...exported, n, e, kid, alg: 'RS256' }\n\n return { publicKey, privateKey, jwk }\n}\n","import { randomUUID } from 'node:crypto'\nimport { SignJWT } from 'jose'\nimport { generateKey, type Key } from './keys'\nimport type { JsonObject } from './types'\n\nlet _key: Key | undefined\nexport const getKey = async (): Promise<Key> => {\n if (!_key) {\n _key = await generateKey()\n }\n return _key\n}\n\nconst defaultClaims = (): JsonObject => ({\n jti: randomUUID(),\n sub: randomUUID(),\n groups: [],\n aud: ['SEB'],\n sid: randomUUID(),\n})\n\nexport const createJwt = async (claims: JsonObject) => {\n const payload = { ...defaultClaims(), ...claims }\n\n // Map user -> preferred_username (and remove user)\n const hasUser = Object.hasOwn(payload, 'user')\n const hasPreferred = Object.hasOwn(payload, 'preferred_username')\n\n if (hasUser && !hasPreferred && typeof payload.user === 'string') {\n payload.preferred_username = payload.user\n }\n if (hasUser) {\n delete payload.user\n }\n\n const key = await getKey()\n const { alg, kid } = key.jwk\n return await new SignJWT(payload)\n .setIssuedAt()\n .setNotBefore('0s')\n .setExpirationTime('5m')\n .setProtectedHeader({ alg, kid, typ: 'JWT' })\n .sign(key.privateKey)\n}\n\nexport const getRemoteJwt = async (remoteUrl: string, claims: JsonObject) => {\n const url = new URL(remoteUrl)\n\n for (const [name, val] of Object.entries(claims)) {\n url.searchParams.set(name, String(val))\n }\n\n const res = await fetch(url)\n const text = await res.text()\n if (!res.ok)\n throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`)\n\n return text\n}\n","import type { Headers, JsonObject } from './types'\n\nexport const defaultPort = (target: URL) => {\n if (target.protocol === 'https:' || target.protocol === 'wss:') return 443\n return 80\n}\n\nexport const toHttpBase = (target: URL) => {\n if (target.protocol.startsWith('ws')) {\n const p = target.protocol === 'wss:' ? 'https:' : 'http:'\n return `${p}//${target.host}`\n }\n return target.toString()\n}\n\nexport const toWsBase = (target: URL) => {\n if (target.protocol.startsWith('http')) {\n const p = target.protocol === 'https:' ? 'wss:' : 'ws:'\n return `${p}//${target.host}`\n }\n return target.toString()\n}\n\nexport const getHeader = (headers: Headers, name: string) => {\n const lc = name.toLowerCase()\n const key = Object.keys(headers).find((k) => k.toLowerCase() === lc)\n return key ? headers[key] : undefined\n}\n\nexport const hasHeader = (headers: Headers, name: string) => {\n const lc = name.toLowerCase()\n return Object.keys(headers).some((k) => k.toLowerCase() === lc)\n}\n\nexport const setHeader = (headers: Headers, name: string, value: string) => {\n // normalize to lowercase keys for raw write; Node’s http accepts either\n headers[name.toLowerCase()] = value\n}\n\nexport const flattenHeaders = (headers: Headers) => {\n const out: string[] = []\n for (const [k, v] of Object.entries(headers)) {\n if (v == null) continue\n\n if (Array.isArray(v)) {\n for (const val of v) {\n out.push(`${k}: ${val}`)\n }\n } else {\n out.push(`${k}: ${String(v)}`)\n }\n }\n return out\n}\n\nexport class IntrospectionError extends Error {\n constructor(header: string) {\n super(`Could not introspect header '${header}'`)\n }\n}\n\nexport const parseAuthorizationHeader = (header: string) => {\n try {\n const [, access_token] = header.trim().split(/\\s+/, 2)\n const buffer = Buffer.from(access_token, 'base64url')\n const json: JsonObject = JSON.parse(buffer.toString('utf8'))\n if (!json || typeof json !== 'object' || Array.isArray(json)) {\n throw new Error('access_token must be base64url encoded JSON object')\n }\n\n return json\n } catch {\n throw new IntrospectionError(header)\n }\n}\n","import { createJwt, getRemoteJwt } from './jwt'\nimport type { Headers, JsonObject, Mode, ProxyConfig } from './types'\nimport {\n getHeader,\n IntrospectionError,\n parseAuthorizationHeader,\n} from './utils'\n\nconst getAccessToken = async (\n mode: Mode,\n downstream: string | undefined,\n claims: JsonObject\n) => {\n if (mode === 'local') return createJwt(claims)\n if (!downstream) {\n throw new Error('downstream URL is required when mode is downstream')\n }\n return getRemoteJwt(downstream, claims)\n}\n\nexport const introspect = async (\n config: ProxyConfig,\n headers: Headers\n): Promise<Headers> => {\n const authorizationHeader = getHeader(headers, 'authorization')\n if (!authorizationHeader) {\n return headers\n }\n if (typeof authorizationHeader !== 'string') {\n throw new IntrospectionError(String(authorizationHeader))\n }\n\n const claims = parseAuthorizationHeader(authorizationHeader)\n const mode: Mode = config.mode || (config.downstream ? 'downstream' : 'local')\n const access_token = await getAccessToken(mode, config.downstream, claims)\n\n return { ...headers, authorization: `Bearer ${access_token}` }\n}\n","import http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { introspect } from './introspection'\nimport type { ProxyConfig } from './types'\nimport {\n defaultPort,\n flattenHeaders,\n hasHeader,\n setHeader,\n toHttpBase,\n toWsBase,\n} from './utils'\n\nexport const createProxyServer = (config: ProxyConfig) => {\n if (!config.target)\n throw new Error(\n 'config.target must be set, e.g. http://core:3000 or ws://gateway:4000'\n )\n\n const target = new URL(config.target)\n\n const httpClient =\n target.protocol === 'https:' || target.protocol === 'wss:' ? https : http\n\n const server = http.createServer(async (req, res) => {\n try {\n // compute upstream URL (preserve path+query)\n /* istanbul ignore next */\n const upstream = new URL(req.url ?? '/', toHttpBase(target))\n\n // let your IAP logic rewrite headers (e.g., mint/replace Authorization)\n const introspected = await introspect(config, req.headers)\n // ensure Host header matches upstream host\n if (!introspected.host) introspected.host = upstream.host\n\n /* istanbul ignore next */\n const upstreamPort = upstream.port || String(defaultPort(target))\n const proxyReq = httpClient.request(\n {\n protocol: upstream.protocol,\n hostname: upstream.hostname,\n port: upstreamPort,\n method: req.method,\n path: upstream.pathname + upstream.search,\n headers: introspected,\n },\n (proxyRes) => {\n /* istanbul ignore next */\n res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers)\n proxyRes.pipe(res, { end: true })\n }\n )\n\n proxyReq.on('error', () => {\n /* istanbul ignore else */\n if (!res.writableEnded) {\n res.writeHead(502)\n res.end('proxy error')\n }\n })\n\n req.pipe(proxyReq, { end: true })\n } catch (err) {\n /* istanbul ignore next */\n const errName = err instanceof Error ? err.name : 'Error'\n /* istanbul ignore next */\n const errMsg = err instanceof Error ? err.message : String(err)\n /* istanbul ignore next */\n const errStack = err instanceof Error ? err.stack : undefined\n const payload = { name: errName, message: errMsg, stack: errStack }\n res.writeHead(500, { 'content-type': 'application/json' })\n res.end(JSON.stringify(payload))\n }\n })\n\n server.on('upgrade', async (req, socket, head) => {\n try {\n const introspected = await introspect(config, req.headers)\n // ensure Upgrade/Connection headers are present for WS\n /* istanbul ignore next */\n if (!hasHeader(introspected, 'upgrade'))\n setHeader(introspected, 'upgrade', 'websocket')\n /* istanbul ignore next */\n if (!hasHeader(introspected, 'connection'))\n setHeader(introspected, 'connection', 'Upgrade')\n setHeader(introspected, 'host', target.host)\n\n /* istanbul ignore next */\n const port = Number(target.port) || defaultPort(target)\n const upstream = net.connect(port, target.hostname, () => {\n /* istanbul ignore next */\n const wsUrl = req.url ?? '/'\n const wsBase = new URL(wsUrl, toWsBase(target))\n const lines: string[] = [\n `GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,\n `Host: ${target.host}`,\n ...flattenHeaders(introspected),\n '',\n '',\n ]\n upstream.write(lines.join('\\r\\n'))\n /* istanbul ignore next */\n if (head?.length) upstream.write(head)\n\n // bi-directional pipe\n socket.pipe(upstream).pipe(socket)\n })\n\n /* istanbul ignore next */\n upstream.on('error', () => socket.destroy())\n /* istanbul ignore next */\n socket.on('error', () => upstream.destroy())\n } catch (err) {\n /* istanbul ignore next */\n const errName = err instanceof Error ? err.name : 'Error'\n /* istanbul ignore next */\n const errMsg = err instanceof Error ? err.message : String(err)\n /* istanbul ignore next */\n const errStack = err instanceof Error ? err.stack : undefined\n const payload = { name: errName, message: errMsg, stack: errStack }\n const body = Buffer.from(JSON.stringify(payload))\n socket.write(\n `HTTP/1.1 500 Internal Server Error\nConnection: close\nContent-Type: application/json\nContent-Length: ${body.length}\n`\n )\n socket.write(body)\n socket.destroy()\n }\n })\n\n return server\n}\n"],"mappings":";;;;;;;AAgBA,MAAa,cAAc,YAA0B;CACnD,MAAM,EAAE,WAAW,eAAe,MAAM,gBAAgB,OAAO;CAC/D,MAAM,WAAW,MAAM,UAAU,SAAS;CAC1C,MAAM,EAAE,GAAG,MAAM;CACjB,OAAO,KAAK,GAAG,2CAA2C;CAC1D,MAAM,MAAM,MAAM,uBAAuB,QAAQ;CAGjD,OAAO;EAAE;EAAW;EAAY,KAAA;GAFb,GAAG;GAAU;GAAG;GAAG;GAAK,KAAK;EAEd;CAAE;AACtC;;ACpBA,IAAI;AACJ,MAAa,SAAS,YAA0B;CAC9C,IAAI,CAAC,MACH,OA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O,OAAO,WAAW,OAAO,OAAO;KACvC,SAAS,OAAO;KAChB,GAAG,eAAe,YAAY;KAC9B;KACA;IACF;IACA,SAAS,MAAM,MAAM,KAAK,MAAM,CAAC;;IAEjC,IAAI,MAAM,QAAQ,SAAS,MAAM,IAAI;IAGrC,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,MAAM;GACnC,CAAC;;GAGD,SAAS,GAAG,eAAe,OAAO,QAAQ,CAAC;;GAE3C,OAAO,GAAG,eAAe,SAAS,QAAQ,CAAC;EAC7C,SAAS,KAAK;GAOZ,MAAM,UAAU;IAAE,MALF,eAAe,QAAQ,IAAI,OAAO;IAKjB,SAHlB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAGZ,OADjC,eAAe,QAAQ,IAAI,QAAQ,KAAA;GACc;GAClE,MAAM,OAAO,OAAO,KAAK,KAAK,UAAU,OAAO,CAAC;GAChD,OAAO,MACL;;;kBAGU,KAAK,OAAO;CAExB;GACA,OAAO,MAAM,IAAI;GACjB,OAAO,QAAQ;EACjB;CACF,CAAC;CAED,OAAO;AACT"}
|
package/dist/start.mjs
CHANGED
package/dist/start.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.mjs","names":[],"sources":["../src/start.ts"],"sourcesContent":["import assert from 'node:assert'\nimport { createProxyServer } from './server'\nimport type { ProxyConfig } from './types'\n\n// Read env and normalize the listen port\nconst { PORT, TARGET, MODE, DOWNSTREAM } = process.env\nconst port = PORT && !Number.isNaN(Number(PORT)) ? Number(PORT) : 3000\n\n// TARGET must be an absolute URL (http/https/ws/wss)\nassert(TARGET, 'TARGET must be set')\nlet targetUrl: URL\ntry {\n targetUrl = new URL(TARGET
|
|
1
|
+
{"version":3,"file":"start.mjs","names":[],"sources":["../src/start.ts"],"sourcesContent":["import assert from 'node:assert'\nimport { createProxyServer } from './server'\nimport type { ProxyConfig } from './types'\n\n// Read env and normalize the listen port\nconst { PORT, TARGET, MODE, DOWNSTREAM } = process.env\nconst port = PORT && !Number.isNaN(Number(PORT)) ? Number(PORT) : 3000\n\n// TARGET must be an absolute URL (http/https/ws/wss)\nassert(TARGET, 'TARGET must be set')\nlet targetUrl: URL\ntry {\n targetUrl = new URL(TARGET)\n} catch {\n throw new Error(\n 'TARGET must be an absolute URL, e.g. http://core:3000 or ws://gateway:4000'\n )\n}\nconst allowedTargetProtocols = new Set(['http:', 'https:', 'ws:', 'wss:'])\nassert(\n allowedTargetProtocols.has(targetUrl.protocol),\n 'TARGET must start with http(s):// or ws(s)://'\n)\n\n// Resolve mode:\n// - explicit MODE wins if valid\n// - otherwise infer: DOWNSTREAM set → downstream, else local\nlet resolvedMode: 'local' | 'downstream'\nif (MODE === 'local' || MODE === 'downstream') {\n resolvedMode = MODE\n} else {\n resolvedMode = DOWNSTREAM ? 'downstream' : 'local'\n}\n\n// If downstream mode, validate DOWNSTREAM is an absolute https? URL\nlet downstreamUrl: string | undefined\nif (resolvedMode === 'downstream') {\n assert(\n DOWNSTREAM,\n 'DOWNSTREAM must be set when MODE=downstream (or when inferred)'\n )\n try {\n const u = new URL(DOWNSTREAM)\n const allowedDownstreamProtocols = new Set(['http:', 'https:'])\n assert(\n allowedDownstreamProtocols.has(u.protocol),\n 'DOWNSTREAM must start with http(s)://'\n )\n downstreamUrl = u.toString()\n } catch {\n throw new Error(\n 'DOWNSTREAM must be an absolute URL, e.g. https://jwks.example.com/api/token'\n )\n }\n}\n\n// Build proxy config consumed by the server\nconst config: ProxyConfig = {\n target: targetUrl.toString(),\n mode: resolvedMode,\n downstream: downstreamUrl ?? '',\n}\n\n// Start the proxy server\nconst server = createProxyServer(config)\nserver.listen(port, () => {\n console.log(`IAP listening on :${port} → ${config.target} (${config.mode})`)\n})\n"],"mappings":";;;AAKA,MAAM,EAAE,MAAM,QAAQ,MAAM,eAAe,QAAQ;AACnD,MAAM,OAAO,QAAQ,CAAC,OAAO,MAAM,OAAO,IAAI,CAAC,IAAI,OAAO,IAAI,IAAI;AAGlE,OAAO,QAAQ,oBAAoB;AACnC,IAAI;AACJ,IAAI;CACF,YAAY,IAAI,IAAI,MAAM;AAC5B,QAAQ;CACN,MAAM,IAAI,MACR,4EACF;AACF;AAEA,wBACE,IAFiC,IAAI;CAAC;CAAS;CAAU;CAAO;AAAM,CAEjD,EAAA,CAAE,IAAI,UAAU,QAAQ,GAC7C,+CACF;AAKA,IAAI;AACJ,IAAI,SAAS,WAAW,SAAS,cAC/B,eAAe;KAEf,eAAe,aAAa,eAAe;AAI7C,IAAI;AACJ,IAAI,iBAAiB,cAAc;CACjC,OACE,YACA,gEACF;CACA,IAAI;EACF,MAAM,IAAI,IAAI,IAAI,UAAU;EAE5B,wBACE,IAFqC,IAAI,CAAC,SAAS,QAAQ,CAElC,EAAA,CAAE,IAAI,EAAE,QAAQ,GACzC,uCACF;EACA,gBAAgB,EAAE,SAAS;CAC7B,QAAQ;EACN,MAAM,IAAI,MACR,6EACF;CACF;AACF;AAGA,MAAM,SAAsB;CAC1B,QAAQ,UAAU,SAAS;CAC3B,MAAM;CACN,YAAY,iBAAiB;AAC/B;AAGe,kBAAkB,MAC5B,CAAC,CAAC,OAAO,YAAY;CACxB,QAAQ,IAAI,qBAAqB,KAAK,KAAK,OAAO,OAAO,IAAI,OAAO,KAAK,EAAE;AAC7E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sebspark/test-iap",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.33",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -17,25 +17,25 @@
|
|
|
17
17
|
"scripts": {
|
|
18
18
|
"build": "spark-build src/index.ts src/start.ts",
|
|
19
19
|
"dev": "tsc --watch --noEmit",
|
|
20
|
-
"lint": "biome check .",
|
|
20
|
+
"lint": "biome check --write .",
|
|
21
21
|
"test": "vitest run --passWithNoTests --coverage --fsModuleCachePath node_modules/.vitest-cache",
|
|
22
22
|
"pretest:e2e": "yarn build",
|
|
23
23
|
"test:e2e": "vitest --config vitest.config.e2e.ts --run --fsModuleCachePath node_modules/.vitest-cache",
|
|
24
|
-
"typecheck": "vitest --typecheck.only --passWithNoTests --run"
|
|
24
|
+
"typecheck": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run --fsModuleCachePath node_modules/.vitest-cache"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"jose": "6.2.
|
|
27
|
+
"jose": "6.2.15",
|
|
28
28
|
"testcontainers": "12.2.1"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@biomejs/biome": "2.6.4",
|
|
32
|
-
"@sebspark/tsconfig": "3.0.
|
|
32
|
+
"@sebspark/tsconfig": "3.0.29",
|
|
33
33
|
"@types/ws": "8.18.2",
|
|
34
34
|
"nock": "15.0.5",
|
|
35
35
|
"typescript": "7.0.2",
|
|
36
36
|
"vite": "8.3.5",
|
|
37
37
|
"vitest": "5.0.5",
|
|
38
|
-
"ws": "8.22.
|
|
38
|
+
"ws": "8.22.1"
|
|
39
39
|
},
|
|
40
40
|
"repository": {
|
|
41
41
|
"type": "git",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-ByjdsPOZ.mjs","names":[],"sources":["../src/keys.ts","../src/jwt.ts","../src/utils.ts","../src/introspection.ts","../src/server.ts"],"sourcesContent":["import {\n calculateJwkThumbprint,\n exportJWK,\n generateKeyPair,\n type JWK_RSA_Public,\n} from 'jose'\n\ntype JWK = JWK_RSA_Public & { alg: string; kid: string }\n\nexport interface Key {\n publicKey: CryptoKey\n privateKey: CryptoKey\n jwk: JWK\n}\n\nexport const generateKey = async (): Promise<Key> => {\n const { publicKey, privateKey } = await generateKeyPair('RS256')\n const jwk = await exportJWK(publicKey)\n jwk.kid = await calculateJwkThumbprint(jwk)\n jwk.alg = 'RS256'\n\n return { publicKey, privateKey, jwk: jwk as JWK }\n}\n","import { randomUUID } from 'node:crypto'\nimport { SignJWT } from 'jose'\nimport { generateKey, type Key } from './keys'\nimport type { JsonObject } from './types'\n\nlet _key: Key | undefined\nexport const getKey = async (): Promise<Key> => {\n if (!_key) {\n _key = await generateKey()\n }\n return _key\n}\n\nconst defaultClaims = (): JsonObject => ({\n jti: randomUUID(),\n sub: randomUUID(),\n groups: [],\n aud: ['SEB'],\n sid: randomUUID(),\n})\n\nexport const createJwt = async (claims: JsonObject) => {\n const payload = { ...defaultClaims(), ...claims }\n\n // Map user -> preferred_username (and remove user)\n const hasUser = Object.hasOwn(payload, 'user')\n const hasPreferred = Object.hasOwn(payload, 'preferred_username')\n\n if (hasUser && !hasPreferred && typeof payload.user === 'string') {\n payload.preferred_username = payload.user\n }\n if (hasUser) {\n delete (payload as { user?: string }).user\n }\n\n const key = await getKey()\n const { alg, kid } = key.jwk\n return await new SignJWT(payload)\n .setIssuedAt()\n .setNotBefore('0s')\n .setExpirationTime('5m')\n .setProtectedHeader({ alg, kid, typ: 'JWT' })\n .sign(key.privateKey)\n}\n\nexport const getRemoteJwt = async (remoteUrl: string, claims: JsonObject) => {\n const url = new URL(remoteUrl)\n\n for (const [name, val] of Object.entries(claims)) {\n url.searchParams.set(name, val as string)\n }\n\n const res = await fetch(url)\n const text = await res.text()\n if (!res.ok)\n throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`)\n\n return text\n}\n","import type { Headers, JsonObject } from './types'\n\nexport const defaultPort = (target: URL) => {\n if (target.protocol === 'https:' || target.protocol === 'wss:') return 443\n return 80\n}\n\nexport const toHttpBase = (target: URL) => {\n if (target.protocol.startsWith('ws')) {\n const p = target.protocol === 'wss:' ? 'https:' : 'http:'\n return `${p}//${target.host}`\n }\n return target.toString()\n}\n\nexport const toWsBase = (target: URL) => {\n if (target.protocol.startsWith('http')) {\n const p = target.protocol === 'https:' ? 'wss:' : 'ws:'\n return `${p}//${target.host}`\n }\n return target.toString()\n}\n\nexport const getHeader = (headers: Headers, name: string) => {\n const lc = name.toLowerCase()\n const key = Object.keys(headers).find((k) => k.toLowerCase() === lc)\n return key ? headers[key] : undefined\n}\n\nexport const hasHeader = (headers: Headers, name: string) => {\n const lc = name.toLowerCase()\n return Object.keys(headers).some((k) => k.toLowerCase() === lc)\n}\n\nexport const setHeader = (headers: Headers, name: string, value: string) => {\n // normalize to lowercase keys for raw write; Node’s http accepts either\n headers[name.toLowerCase()] = value\n}\n\nexport const flattenHeaders = (headers: Headers) => {\n const out: string[] = []\n for (const [k, v] of Object.entries(headers)) {\n if (v == null) continue\n\n if (Array.isArray(v)) {\n for (const val of v) {\n out.push(`${k}: ${val}`)\n }\n } else {\n out.push(`${k}: ${String(v)}`)\n }\n }\n return out\n}\n\nexport class IntrospectionError extends Error {\n constructor(header: string) {\n super(`Could not introspect header '${header}'`)\n }\n}\n\nexport const parseAuthorizationHeader = (header: string) => {\n try {\n const [, access_token] = header.trim().split(/\\s+/, 2)\n const buffer = Buffer.from(access_token, 'base64url')\n const json: JsonObject = JSON.parse(buffer.toString('utf8'))\n if (!json || typeof json !== 'object' || Array.isArray(json)) {\n throw new Error('access_token must be base64url encoded JSON object')\n }\n\n return json\n } catch {\n throw new IntrospectionError(header)\n }\n}\n","import { createJwt, getRemoteJwt } from './jwt'\nimport type { Headers, Mode, ProxyConfig } from './types'\nimport { getHeader, parseAuthorizationHeader } from './utils'\n\nexport const introspect = async (\n config: ProxyConfig,\n headers: Headers\n): Promise<Headers> => {\n const authorizationHeader = getHeader(headers, 'authorization') as string\n if (!authorizationHeader) {\n return headers\n }\n\n const claims = parseAuthorizationHeader(authorizationHeader)\n const mode: Mode = config.mode || (config.downstream ? 'downstream' : 'local')\n const access_token = await (mode === 'local'\n ? createJwt(claims)\n : getRemoteJwt(config.downstream as string, claims))\n\n return { ...headers, authorization: `Bearer ${access_token}` }\n}\n","import http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { introspect } from './introspection'\nimport type { ProxyConfig } from './types'\nimport {\n defaultPort,\n flattenHeaders,\n hasHeader,\n setHeader,\n toHttpBase,\n toWsBase,\n} from './utils'\n\nexport const createProxyServer = (config: ProxyConfig) => {\n if (!config.target)\n throw new Error(\n 'config.target must be set, e.g. http://core:3000 or ws://gateway:4000'\n )\n\n const target = new URL(config.target)\n\n const httpClient =\n target.protocol === 'https:' || target.protocol === 'wss:' ? https : http\n\n const server = http.createServer(async (req, res) => {\n try {\n // compute upstream URL (preserve path+query)\n /* istanbul ignore next */\n const upstream = new URL(req.url ?? '/', toHttpBase(target))\n\n // let your IAP logic rewrite headers (e.g., mint/replace Authorization)\n const introspected = await introspect(config, req.headers)\n // ensure Host header matches upstream host\n if (!introspected.host) introspected.host = upstream.host\n\n /* istanbul ignore next */\n const upstreamPort = upstream.port || String(defaultPort(target))\n const proxyReq = httpClient.request(\n {\n protocol: upstream.protocol,\n hostname: upstream.hostname,\n port: upstreamPort,\n method: req.method,\n path: upstream.pathname + upstream.search,\n headers: introspected,\n },\n (proxyRes) => {\n /* istanbul ignore next */\n res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers)\n proxyRes.pipe(res, { end: true })\n }\n )\n\n proxyReq.on('error', () => {\n /* istanbul ignore else */\n if (!res.writableEnded) {\n res.writeHead(502)\n res.end('proxy error')\n }\n })\n\n req.pipe(proxyReq, { end: true })\n } catch (err) {\n /* istanbul ignore next */\n const errName = err instanceof Error ? err.name : 'Error'\n /* istanbul ignore next */\n const errMsg = err instanceof Error ? err.message : String(err)\n /* istanbul ignore next */\n const errStack = err instanceof Error ? err.stack : undefined\n const payload = { name: errName, message: errMsg, stack: errStack }\n res.writeHead(500, { 'content-type': 'application/json' })\n res.end(JSON.stringify(payload))\n }\n })\n\n server.on('upgrade', async (req, socket, head) => {\n try {\n const introspected = await introspect(config, req.headers)\n // ensure Upgrade/Connection headers are present for WS\n /* istanbul ignore next */\n if (!hasHeader(introspected, 'upgrade'))\n setHeader(introspected, 'upgrade', 'websocket')\n /* istanbul ignore next */\n if (!hasHeader(introspected, 'connection'))\n setHeader(introspected, 'connection', 'Upgrade')\n setHeader(introspected, 'host', target.host)\n\n /* istanbul ignore next */\n const port = Number(target.port) || defaultPort(target)\n const upstream = net.connect(port, target.hostname, () => {\n /* istanbul ignore next */\n const wsUrl = req.url ?? '/'\n const wsBase = new URL(wsUrl, toWsBase(target))\n const lines: string[] = [\n `GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,\n `Host: ${target.host}`,\n ...flattenHeaders(introspected),\n '',\n '',\n ]\n upstream.write(lines.join('\\r\\n'))\n /* istanbul ignore next */\n if (head?.length) upstream.write(head)\n\n // bi-directional pipe\n socket.pipe(upstream).pipe(socket)\n })\n\n /* istanbul ignore next */\n upstream.on('error', () => socket.destroy())\n /* istanbul ignore next */\n socket.on('error', () => upstream.destroy())\n } catch (err) {\n /* istanbul ignore next */\n const errName = err instanceof Error ? err.name : 'Error'\n /* istanbul ignore next */\n const errMsg = err instanceof Error ? err.message : String(err)\n /* istanbul ignore next */\n const errStack = err instanceof Error ? err.stack : undefined\n const payload = { name: errName, message: errMsg, stack: errStack }\n const body = Buffer.from(JSON.stringify(payload))\n socket.write(\n `HTTP/1.1 500 Internal Server Error\nConnection: close\nContent-Type: application/json\nContent-Length: ${body.length}\n`\n )\n socket.write(body)\n socket.destroy()\n }\n })\n\n return server\n}\n"],"mappings":";;;;;;AAeA,MAAa,cAAc,YAA0B;CACnD,MAAM,EAAE,WAAW,eAAe,MAAM,gBAAgB,OAAO;CAC/D,MAAM,MAAM,MAAM,UAAU,SAAS;CACrC,IAAI,MAAM,MAAM,uBAAuB,GAAG;CAC1C,IAAI,MAAM;CAEV,OAAO;EAAE;EAAW;EAAiB;CAAW;AAClD;;ACjBA,IAAI;AACJ,MAAa,SAAS,YAA0B;CAC9C,IAAI,CAAC,MACH,OAAO,MAAM,YAAY;CAE3B,OAAO;AACT;AAEA,MAAM,uBAAmC;CACvC,KAAK,WAAW;CAChB,KAAK,WAAW;CACh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