@sebspark/test-iap 0.1.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.
- package/LICENSE +201 -0
- package/README.md +147 -0
- package/dist/index.d.mts +34 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +397 -0
- package/dist/index.mjs +372 -0
- package/dist/start.mjs +287 -0
- package/package.json +32 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/server.ts
|
|
9
|
+
import http from "http";
|
|
10
|
+
import https from "https";
|
|
11
|
+
import net from "net";
|
|
12
|
+
|
|
13
|
+
// src/jwt.ts
|
|
14
|
+
import { randomUUID } from "crypto";
|
|
15
|
+
import { SignJWT } from "jose";
|
|
16
|
+
|
|
17
|
+
// src/keys.ts
|
|
18
|
+
import {
|
|
19
|
+
calculateJwkThumbprint,
|
|
20
|
+
exportJWK,
|
|
21
|
+
generateKeyPair
|
|
22
|
+
} from "jose";
|
|
23
|
+
var generateKey = async () => {
|
|
24
|
+
const { publicKey, privateKey } = await generateKeyPair("RS256");
|
|
25
|
+
const jwk = await exportJWK(publicKey);
|
|
26
|
+
jwk.kid = await calculateJwkThumbprint(jwk);
|
|
27
|
+
jwk.alg = "RS256";
|
|
28
|
+
return { publicKey, privateKey, jwk };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// src/jwt.ts
|
|
32
|
+
var _key;
|
|
33
|
+
var getKey = async () => {
|
|
34
|
+
if (!_key) {
|
|
35
|
+
_key = await generateKey();
|
|
36
|
+
}
|
|
37
|
+
return _key;
|
|
38
|
+
};
|
|
39
|
+
var defaultClaims = () => ({
|
|
40
|
+
jti: randomUUID(),
|
|
41
|
+
sub: randomUUID(),
|
|
42
|
+
groups: [],
|
|
43
|
+
aud: ["SEB"],
|
|
44
|
+
sid: randomUUID()
|
|
45
|
+
});
|
|
46
|
+
var createJwt = async (claims) => {
|
|
47
|
+
const payload = { ...defaultClaims(), ...claims };
|
|
48
|
+
const hasUser = Object.prototype.hasOwnProperty.call(payload, "user");
|
|
49
|
+
const hasPreferred = Object.prototype.hasOwnProperty.call(
|
|
50
|
+
payload,
|
|
51
|
+
"preferred_username"
|
|
52
|
+
);
|
|
53
|
+
if (hasUser && !hasPreferred && typeof payload.user === "string") {
|
|
54
|
+
payload.preferred_username = payload.user;
|
|
55
|
+
}
|
|
56
|
+
if (hasUser) {
|
|
57
|
+
delete payload.user;
|
|
58
|
+
}
|
|
59
|
+
const key = await getKey();
|
|
60
|
+
const { alg, kid } = key.jwk;
|
|
61
|
+
return await new SignJWT(payload).setIssuedAt().setNotBefore("0s").setExpirationTime("5m").setProtectedHeader({ alg, kid, typ: "JWT" }).sign(key.privateKey);
|
|
62
|
+
};
|
|
63
|
+
var getRemoteJwt = async (remoteUrl, claims) => {
|
|
64
|
+
const url = new URL(remoteUrl);
|
|
65
|
+
for (const [name, val] of Object.entries(claims)) {
|
|
66
|
+
url.searchParams.set(name, val);
|
|
67
|
+
}
|
|
68
|
+
const res = await fetch(url);
|
|
69
|
+
const text = await res.text();
|
|
70
|
+
if (!res.ok)
|
|
71
|
+
throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`);
|
|
72
|
+
return text;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/utils.ts
|
|
76
|
+
var defaultPort = (target) => {
|
|
77
|
+
if (target.protocol === "https:" || target.protocol === "wss:") return 443;
|
|
78
|
+
return 80;
|
|
79
|
+
};
|
|
80
|
+
var toHttpBase = (target) => {
|
|
81
|
+
if (target.protocol.startsWith("ws")) {
|
|
82
|
+
const p = target.protocol === "wss:" ? "https:" : "http:";
|
|
83
|
+
return `${p}//${target.host}`;
|
|
84
|
+
}
|
|
85
|
+
return target.toString();
|
|
86
|
+
};
|
|
87
|
+
var toWsBase = (target) => {
|
|
88
|
+
if (target.protocol.startsWith("http")) {
|
|
89
|
+
const p = target.protocol === "https:" ? "wss:" : "ws:";
|
|
90
|
+
return `${p}//${target.host}`;
|
|
91
|
+
}
|
|
92
|
+
return target.toString();
|
|
93
|
+
};
|
|
94
|
+
var getHeader = (headers, name) => {
|
|
95
|
+
const lc = name.toLowerCase();
|
|
96
|
+
const key = Object.keys(headers).find((k) => k.toLowerCase() === lc);
|
|
97
|
+
return key ? headers[key] : void 0;
|
|
98
|
+
};
|
|
99
|
+
var hasHeader = (headers, name) => {
|
|
100
|
+
const lc = name.toLowerCase();
|
|
101
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === lc);
|
|
102
|
+
};
|
|
103
|
+
var setHeader = (headers, name, value) => {
|
|
104
|
+
headers[name.toLowerCase()] = value;
|
|
105
|
+
};
|
|
106
|
+
var flattenHeaders = (headers) => {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
109
|
+
if (v == null) continue;
|
|
110
|
+
if (Array.isArray(v)) {
|
|
111
|
+
for (const val of v) {
|
|
112
|
+
out.push(`${k}: ${val}`);
|
|
113
|
+
}
|
|
114
|
+
} else {
|
|
115
|
+
out.push(`${k}: ${String(v)}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
};
|
|
120
|
+
var IntrospectionError = class extends Error {
|
|
121
|
+
constructor(header) {
|
|
122
|
+
super(`Could not introspect header '${header}'`);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
var parseAuthorizationHeader = (header) => {
|
|
126
|
+
try {
|
|
127
|
+
const [, access_token] = header.trim().split(/\s+/, 2);
|
|
128
|
+
const buffer = Buffer.from(access_token, "base64url");
|
|
129
|
+
const json = JSON.parse(buffer.toString("utf8"));
|
|
130
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
131
|
+
throw new Error("access_token must be base64url encoded JSON object");
|
|
132
|
+
}
|
|
133
|
+
return json;
|
|
134
|
+
} catch {
|
|
135
|
+
throw new IntrospectionError(header);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// src/introspection.ts
|
|
140
|
+
var introspect = async (config, headers) => {
|
|
141
|
+
const authorizationHeader = getHeader(headers, "authorization");
|
|
142
|
+
if (!authorizationHeader) {
|
|
143
|
+
return headers;
|
|
144
|
+
}
|
|
145
|
+
const claims = parseAuthorizationHeader(authorizationHeader);
|
|
146
|
+
const mode = config.mode || (config.downstream ? "downstream" : "local");
|
|
147
|
+
const access_token = await (mode === "local" ? createJwt(claims) : getRemoteJwt(config.downstream, claims));
|
|
148
|
+
return { ...headers, authorization: `Bearer ${access_token}` };
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
// src/server.ts
|
|
152
|
+
var createProxyServer = (config) => {
|
|
153
|
+
if (!config.target)
|
|
154
|
+
throw new Error(
|
|
155
|
+
"config.target must be set, e.g. http://core:3000 or ws://gateway:4000"
|
|
156
|
+
);
|
|
157
|
+
const target = new URL(config.target);
|
|
158
|
+
const httpClient = target.protocol === "https:" || target.protocol === "wss:" ? https : http;
|
|
159
|
+
const server = http.createServer(async (req, res) => {
|
|
160
|
+
try {
|
|
161
|
+
const upstream = new URL(req.url ?? "/", toHttpBase(target));
|
|
162
|
+
const introspected = await introspect(config, req.headers);
|
|
163
|
+
if (!introspected.host) introspected.host = upstream.host;
|
|
164
|
+
const proxyReq = httpClient.request(
|
|
165
|
+
{
|
|
166
|
+
protocol: upstream.protocol,
|
|
167
|
+
hostname: upstream.hostname,
|
|
168
|
+
port: upstream.port || String(defaultPort(target)),
|
|
169
|
+
method: req.method,
|
|
170
|
+
path: upstream.pathname + upstream.search,
|
|
171
|
+
headers: introspected
|
|
172
|
+
},
|
|
173
|
+
(proxyRes) => {
|
|
174
|
+
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
|
|
175
|
+
proxyRes.pipe(res, { end: true });
|
|
176
|
+
}
|
|
177
|
+
);
|
|
178
|
+
proxyReq.on("error", () => {
|
|
179
|
+
if (!res.writableEnded) {
|
|
180
|
+
res.writeHead(502);
|
|
181
|
+
res.end("proxy error");
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
req.pipe(proxyReq, { end: true });
|
|
185
|
+
} catch (err) {
|
|
186
|
+
const payload = {
|
|
187
|
+
name: err instanceof Error ? err.name : "Error",
|
|
188
|
+
message: err instanceof Error ? err.message : String(err),
|
|
189
|
+
stack: err instanceof Error ? err.stack : void 0
|
|
190
|
+
};
|
|
191
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
192
|
+
res.end(JSON.stringify(payload));
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
server.on("upgrade", async (req, socket, head) => {
|
|
196
|
+
try {
|
|
197
|
+
const introspected = await introspect(config, req.headers);
|
|
198
|
+
if (!hasHeader(introspected, "upgrade"))
|
|
199
|
+
setHeader(introspected, "upgrade", "websocket");
|
|
200
|
+
if (!hasHeader(introspected, "connection"))
|
|
201
|
+
setHeader(introspected, "connection", "Upgrade");
|
|
202
|
+
setHeader(introspected, "host", target.host);
|
|
203
|
+
const port = Number(target.port) || defaultPort(target);
|
|
204
|
+
const upstream = net.connect(port, target.hostname, () => {
|
|
205
|
+
const wsBase = new URL(req.url ?? "/", toWsBase(target));
|
|
206
|
+
const lines = [
|
|
207
|
+
`GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,
|
|
208
|
+
`Host: ${target.host}`,
|
|
209
|
+
...flattenHeaders(introspected),
|
|
210
|
+
"",
|
|
211
|
+
""
|
|
212
|
+
];
|
|
213
|
+
upstream.write(lines.join("\r\n"));
|
|
214
|
+
if (head?.length) upstream.write(head);
|
|
215
|
+
socket.pipe(upstream).pipe(socket);
|
|
216
|
+
});
|
|
217
|
+
upstream.on("error", () => socket.destroy());
|
|
218
|
+
socket.on("error", () => upstream.destroy());
|
|
219
|
+
} catch (err) {
|
|
220
|
+
const payload = {
|
|
221
|
+
name: err instanceof Error ? err.name : "Error",
|
|
222
|
+
message: err instanceof Error ? err.message : String(err),
|
|
223
|
+
stack: err instanceof Error ? err.stack : void 0
|
|
224
|
+
};
|
|
225
|
+
const body = Buffer.from(JSON.stringify(payload));
|
|
226
|
+
socket.write(
|
|
227
|
+
`HTTP/1.1 500 Internal Server Error
|
|
228
|
+
Connection: close
|
|
229
|
+
Content-Type: application/json
|
|
230
|
+
Content-Length: ${body.length}
|
|
231
|
+
`
|
|
232
|
+
);
|
|
233
|
+
socket.write(body);
|
|
234
|
+
socket.destroy();
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
return server;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/test-iap-container.ts
|
|
241
|
+
import assert from "assert";
|
|
242
|
+
import fs from "fs";
|
|
243
|
+
import path2 from "path";
|
|
244
|
+
import {
|
|
245
|
+
AbstractStartedContainer,
|
|
246
|
+
GenericContainer
|
|
247
|
+
} from "testcontainers";
|
|
248
|
+
|
|
249
|
+
// src/build-helpers.ts
|
|
250
|
+
import { createRequire } from "module";
|
|
251
|
+
import path from "path";
|
|
252
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
253
|
+
var getThisFileUrl = () => {
|
|
254
|
+
if (typeof __filename !== "undefined") {
|
|
255
|
+
return pathToFileURL(__filename).href;
|
|
256
|
+
}
|
|
257
|
+
return (0, eval)("import.meta.url");
|
|
258
|
+
};
|
|
259
|
+
var getThisDir = () => path.dirname(fileURLToPath(getThisFileUrl()));
|
|
260
|
+
var getRequireCompat = () => typeof __require === "function" ? __require : createRequire(getThisFileUrl());
|
|
261
|
+
var resolveNearSelf = (specifier) => {
|
|
262
|
+
const req = getRequireCompat();
|
|
263
|
+
return req.resolve(specifier, { paths: [getThisDir()] });
|
|
264
|
+
};
|
|
265
|
+
var tryResolveNearSelf = (specifier) => {
|
|
266
|
+
try {
|
|
267
|
+
return resolveNearSelf(specifier);
|
|
268
|
+
} catch {
|
|
269
|
+
return void 0;
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// src/test-iap-container.ts
|
|
274
|
+
var TestIapContainer = class {
|
|
275
|
+
baseImage = "node:22-alpine";
|
|
276
|
+
port = 3e3;
|
|
277
|
+
target;
|
|
278
|
+
mode;
|
|
279
|
+
downstream;
|
|
280
|
+
network;
|
|
281
|
+
withBaseImage(image) {
|
|
282
|
+
this.baseImage = image;
|
|
283
|
+
return this;
|
|
284
|
+
}
|
|
285
|
+
withPort(port) {
|
|
286
|
+
this.port = port;
|
|
287
|
+
return this;
|
|
288
|
+
}
|
|
289
|
+
withTarget(url) {
|
|
290
|
+
const u = new URL(url);
|
|
291
|
+
assert(
|
|
292
|
+
["http:", "https:", "ws:", "wss:"].includes(u.protocol),
|
|
293
|
+
"target must be absolute http(s):// or ws(s)://"
|
|
294
|
+
);
|
|
295
|
+
this.target = u.toString();
|
|
296
|
+
return this;
|
|
297
|
+
}
|
|
298
|
+
withMode(mode) {
|
|
299
|
+
this.mode = mode;
|
|
300
|
+
return this;
|
|
301
|
+
}
|
|
302
|
+
withDownstream(url) {
|
|
303
|
+
const u = new URL(url);
|
|
304
|
+
assert(
|
|
305
|
+
["http:", "https:"].includes(u.protocol),
|
|
306
|
+
"downstream must be absolute http(s)://"
|
|
307
|
+
);
|
|
308
|
+
this.downstream = u.toString();
|
|
309
|
+
return this;
|
|
310
|
+
}
|
|
311
|
+
withNetwork(network) {
|
|
312
|
+
this.network = network;
|
|
313
|
+
return this;
|
|
314
|
+
}
|
|
315
|
+
async start() {
|
|
316
|
+
assert(this.target, "withTarget(...) is required");
|
|
317
|
+
const resolvedMode = this.mode ?? (this.downstream ? "downstream" : "local");
|
|
318
|
+
if (resolvedMode === "downstream") {
|
|
319
|
+
assert(
|
|
320
|
+
this.downstream,
|
|
321
|
+
"withDownstream(...) is required when mode=downstream"
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
const distDir = path2.join(getThisDir(), "../dist");
|
|
325
|
+
assert(fs.existsSync(distDir), `dist directory not found: ${distDir}`);
|
|
326
|
+
const startMjs = path2.join(distDir, "start.mjs");
|
|
327
|
+
const startJs = path2.join(distDir, "start.js");
|
|
328
|
+
const hasStartMjs = fs.existsSync(startMjs);
|
|
329
|
+
const hasStartJs = fs.existsSync(startJs);
|
|
330
|
+
if (!hasStartMjs && !hasStartJs) {
|
|
331
|
+
throw new Error(`Could not find ${startMjs} or ${startJs}`);
|
|
332
|
+
}
|
|
333
|
+
const entry = hasStartMjs ? "/app/dist/start.mjs" : "/app/dist/start.js";
|
|
334
|
+
const josePkgPath = tryResolveNearSelf("jose/package.json");
|
|
335
|
+
if (!josePkgPath) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
'Could not resolve "jose" next to @sebspark/test-iap. Ensure "jose" is installed as a dependency in the same project that installs @sebspark/test-iap.'
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const joseDir = path2.dirname(josePkgPath);
|
|
341
|
+
const binds = [
|
|
342
|
+
{ source: distDir, target: "/app/dist" },
|
|
343
|
+
{ source: joseDir, target: "/app/node_modules/jose" }
|
|
344
|
+
];
|
|
345
|
+
const env = {
|
|
346
|
+
TARGET: this.target,
|
|
347
|
+
MODE: resolvedMode,
|
|
348
|
+
PORT: String(this.port)
|
|
349
|
+
};
|
|
350
|
+
if (resolvedMode === "downstream" && this.downstream) {
|
|
351
|
+
env.DOWNSTREAM = this.downstream;
|
|
352
|
+
}
|
|
353
|
+
const gc = new GenericContainer(this.baseImage).withWorkingDir("/app").withBindMounts(binds).withExposedPorts(this.port).withEnvironment(env).withCommand(["node", entry]);
|
|
354
|
+
if (this.network) gc.withNetwork(this.network);
|
|
355
|
+
const started = await gc.start();
|
|
356
|
+
return new StartedTestIapContainer(started, this.port);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
var StartedTestIapContainer = class extends AbstractStartedContainer {
|
|
360
|
+
constructor(started, internalPort) {
|
|
361
|
+
super(started);
|
|
362
|
+
this.internalPort = internalPort;
|
|
363
|
+
}
|
|
364
|
+
getEndpoint() {
|
|
365
|
+
return `${this.getHost()}:${this.getMappedPort(this.internalPort)}`;
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
export {
|
|
369
|
+
StartedTestIapContainer,
|
|
370
|
+
TestIapContainer,
|
|
371
|
+
createProxyServer
|
|
372
|
+
};
|
package/dist/start.mjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// src/start.ts
|
|
2
|
+
import assert from "assert";
|
|
3
|
+
|
|
4
|
+
// src/server.ts
|
|
5
|
+
import http from "http";
|
|
6
|
+
import https from "https";
|
|
7
|
+
import net from "net";
|
|
8
|
+
|
|
9
|
+
// src/jwt.ts
|
|
10
|
+
import { randomUUID } from "crypto";
|
|
11
|
+
import { SignJWT } from "jose";
|
|
12
|
+
|
|
13
|
+
// src/keys.ts
|
|
14
|
+
import {
|
|
15
|
+
calculateJwkThumbprint,
|
|
16
|
+
exportJWK,
|
|
17
|
+
generateKeyPair
|
|
18
|
+
} from "jose";
|
|
19
|
+
var generateKey = async () => {
|
|
20
|
+
const { publicKey, privateKey } = await generateKeyPair("RS256");
|
|
21
|
+
const jwk = await exportJWK(publicKey);
|
|
22
|
+
jwk.kid = await calculateJwkThumbprint(jwk);
|
|
23
|
+
jwk.alg = "RS256";
|
|
24
|
+
return { publicKey, privateKey, jwk };
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// src/jwt.ts
|
|
28
|
+
var _key;
|
|
29
|
+
var getKey = async () => {
|
|
30
|
+
if (!_key) {
|
|
31
|
+
_key = await generateKey();
|
|
32
|
+
}
|
|
33
|
+
return _key;
|
|
34
|
+
};
|
|
35
|
+
var defaultClaims = () => ({
|
|
36
|
+
jti: randomUUID(),
|
|
37
|
+
sub: randomUUID(),
|
|
38
|
+
groups: [],
|
|
39
|
+
aud: ["SEB"],
|
|
40
|
+
sid: randomUUID()
|
|
41
|
+
});
|
|
42
|
+
var createJwt = async (claims) => {
|
|
43
|
+
const payload = { ...defaultClaims(), ...claims };
|
|
44
|
+
const hasUser = Object.prototype.hasOwnProperty.call(payload, "user");
|
|
45
|
+
const hasPreferred = Object.prototype.hasOwnProperty.call(
|
|
46
|
+
payload,
|
|
47
|
+
"preferred_username"
|
|
48
|
+
);
|
|
49
|
+
if (hasUser && !hasPreferred && typeof payload.user === "string") {
|
|
50
|
+
payload.preferred_username = payload.user;
|
|
51
|
+
}
|
|
52
|
+
if (hasUser) {
|
|
53
|
+
delete payload.user;
|
|
54
|
+
}
|
|
55
|
+
const key = await getKey();
|
|
56
|
+
const { alg, kid } = key.jwk;
|
|
57
|
+
return await new SignJWT(payload).setIssuedAt().setNotBefore("0s").setExpirationTime("5m").setProtectedHeader({ alg, kid, typ: "JWT" }).sign(key.privateKey);
|
|
58
|
+
};
|
|
59
|
+
var getRemoteJwt = async (remoteUrl, claims) => {
|
|
60
|
+
const url = new URL(remoteUrl);
|
|
61
|
+
for (const [name, val] of Object.entries(claims)) {
|
|
62
|
+
url.searchParams.set(name, val);
|
|
63
|
+
}
|
|
64
|
+
const res = await fetch(url);
|
|
65
|
+
const text = await res.text();
|
|
66
|
+
if (!res.ok)
|
|
67
|
+
throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`);
|
|
68
|
+
return text;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/utils.ts
|
|
72
|
+
var defaultPort = (target) => {
|
|
73
|
+
if (target.protocol === "https:" || target.protocol === "wss:") return 443;
|
|
74
|
+
return 80;
|
|
75
|
+
};
|
|
76
|
+
var toHttpBase = (target) => {
|
|
77
|
+
if (target.protocol.startsWith("ws")) {
|
|
78
|
+
const p = target.protocol === "wss:" ? "https:" : "http:";
|
|
79
|
+
return `${p}//${target.host}`;
|
|
80
|
+
}
|
|
81
|
+
return target.toString();
|
|
82
|
+
};
|
|
83
|
+
var toWsBase = (target) => {
|
|
84
|
+
if (target.protocol.startsWith("http")) {
|
|
85
|
+
const p = target.protocol === "https:" ? "wss:" : "ws:";
|
|
86
|
+
return `${p}//${target.host}`;
|
|
87
|
+
}
|
|
88
|
+
return target.toString();
|
|
89
|
+
};
|
|
90
|
+
var getHeader = (headers, name) => {
|
|
91
|
+
const lc = name.toLowerCase();
|
|
92
|
+
const key = Object.keys(headers).find((k) => k.toLowerCase() === lc);
|
|
93
|
+
return key ? headers[key] : void 0;
|
|
94
|
+
};
|
|
95
|
+
var hasHeader = (headers, name) => {
|
|
96
|
+
const lc = name.toLowerCase();
|
|
97
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === lc);
|
|
98
|
+
};
|
|
99
|
+
var setHeader = (headers, name, value) => {
|
|
100
|
+
headers[name.toLowerCase()] = value;
|
|
101
|
+
};
|
|
102
|
+
var flattenHeaders = (headers) => {
|
|
103
|
+
const out = [];
|
|
104
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
105
|
+
if (v == null) continue;
|
|
106
|
+
if (Array.isArray(v)) {
|
|
107
|
+
for (const val of v) {
|
|
108
|
+
out.push(`${k}: ${val}`);
|
|
109
|
+
}
|
|
110
|
+
} else {
|
|
111
|
+
out.push(`${k}: ${String(v)}`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
};
|
|
116
|
+
var IntrospectionError = class extends Error {
|
|
117
|
+
constructor(header) {
|
|
118
|
+
super(`Could not introspect header '${header}'`);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
var parseAuthorizationHeader = (header) => {
|
|
122
|
+
try {
|
|
123
|
+
const [, access_token] = header.trim().split(/\s+/, 2);
|
|
124
|
+
const buffer = Buffer.from(access_token, "base64url");
|
|
125
|
+
const json = JSON.parse(buffer.toString("utf8"));
|
|
126
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
127
|
+
throw new Error("access_token must be base64url encoded JSON object");
|
|
128
|
+
}
|
|
129
|
+
return json;
|
|
130
|
+
} catch {
|
|
131
|
+
throw new IntrospectionError(header);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
// src/introspection.ts
|
|
136
|
+
var introspect = async (config2, headers) => {
|
|
137
|
+
const authorizationHeader = getHeader(headers, "authorization");
|
|
138
|
+
if (!authorizationHeader) {
|
|
139
|
+
return headers;
|
|
140
|
+
}
|
|
141
|
+
const claims = parseAuthorizationHeader(authorizationHeader);
|
|
142
|
+
const mode = config2.mode || (config2.downstream ? "downstream" : "local");
|
|
143
|
+
const access_token = await (mode === "local" ? createJwt(claims) : getRemoteJwt(config2.downstream, claims));
|
|
144
|
+
return { ...headers, authorization: `Bearer ${access_token}` };
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// src/server.ts
|
|
148
|
+
var createProxyServer = (config2) => {
|
|
149
|
+
if (!config2.target)
|
|
150
|
+
throw new Error(
|
|
151
|
+
"config.target must be set, e.g. http://core:3000 or ws://gateway:4000"
|
|
152
|
+
);
|
|
153
|
+
const target = new URL(config2.target);
|
|
154
|
+
const httpClient = target.protocol === "https:" || target.protocol === "wss:" ? https : http;
|
|
155
|
+
const server2 = http.createServer(async (req, res) => {
|
|
156
|
+
try {
|
|
157
|
+
const upstream = new URL(req.url ?? "/", toHttpBase(target));
|
|
158
|
+
const introspected = await introspect(config2, req.headers);
|
|
159
|
+
if (!introspected.host) introspected.host = upstream.host;
|
|
160
|
+
const proxyReq = httpClient.request(
|
|
161
|
+
{
|
|
162
|
+
protocol: upstream.protocol,
|
|
163
|
+
hostname: upstream.hostname,
|
|
164
|
+
port: upstream.port || String(defaultPort(target)),
|
|
165
|
+
method: req.method,
|
|
166
|
+
path: upstream.pathname + upstream.search,
|
|
167
|
+
headers: introspected
|
|
168
|
+
},
|
|
169
|
+
(proxyRes) => {
|
|
170
|
+
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
|
|
171
|
+
proxyRes.pipe(res, { end: true });
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
proxyReq.on("error", () => {
|
|
175
|
+
if (!res.writableEnded) {
|
|
176
|
+
res.writeHead(502);
|
|
177
|
+
res.end("proxy error");
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
req.pipe(proxyReq, { end: true });
|
|
181
|
+
} catch (err) {
|
|
182
|
+
const payload = {
|
|
183
|
+
name: err instanceof Error ? err.name : "Error",
|
|
184
|
+
message: err instanceof Error ? err.message : String(err),
|
|
185
|
+
stack: err instanceof Error ? err.stack : void 0
|
|
186
|
+
};
|
|
187
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
188
|
+
res.end(JSON.stringify(payload));
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
server2.on("upgrade", async (req, socket, head) => {
|
|
192
|
+
try {
|
|
193
|
+
const introspected = await introspect(config2, req.headers);
|
|
194
|
+
if (!hasHeader(introspected, "upgrade"))
|
|
195
|
+
setHeader(introspected, "upgrade", "websocket");
|
|
196
|
+
if (!hasHeader(introspected, "connection"))
|
|
197
|
+
setHeader(introspected, "connection", "Upgrade");
|
|
198
|
+
setHeader(introspected, "host", target.host);
|
|
199
|
+
const port2 = Number(target.port) || defaultPort(target);
|
|
200
|
+
const upstream = net.connect(port2, target.hostname, () => {
|
|
201
|
+
const wsBase = new URL(req.url ?? "/", toWsBase(target));
|
|
202
|
+
const lines = [
|
|
203
|
+
`GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,
|
|
204
|
+
`Host: ${target.host}`,
|
|
205
|
+
...flattenHeaders(introspected),
|
|
206
|
+
"",
|
|
207
|
+
""
|
|
208
|
+
];
|
|
209
|
+
upstream.write(lines.join("\r\n"));
|
|
210
|
+
if (head?.length) upstream.write(head);
|
|
211
|
+
socket.pipe(upstream).pipe(socket);
|
|
212
|
+
});
|
|
213
|
+
upstream.on("error", () => socket.destroy());
|
|
214
|
+
socket.on("error", () => upstream.destroy());
|
|
215
|
+
} catch (err) {
|
|
216
|
+
const payload = {
|
|
217
|
+
name: err instanceof Error ? err.name : "Error",
|
|
218
|
+
message: err instanceof Error ? err.message : String(err),
|
|
219
|
+
stack: err instanceof Error ? err.stack : void 0
|
|
220
|
+
};
|
|
221
|
+
const body = Buffer.from(JSON.stringify(payload));
|
|
222
|
+
socket.write(
|
|
223
|
+
`HTTP/1.1 500 Internal Server Error
|
|
224
|
+
Connection: close
|
|
225
|
+
Content-Type: application/json
|
|
226
|
+
Content-Length: ${body.length}
|
|
227
|
+
`
|
|
228
|
+
);
|
|
229
|
+
socket.write(body);
|
|
230
|
+
socket.destroy();
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
return server2;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// src/start.ts
|
|
237
|
+
var { PORT, TARGET, MODE, DOWNSTREAM } = process.env;
|
|
238
|
+
var port = PORT && !Number.isNaN(Number(PORT)) ? Number(PORT) : 3e3;
|
|
239
|
+
assert(TARGET, "TARGET must be set");
|
|
240
|
+
var targetUrl;
|
|
241
|
+
try {
|
|
242
|
+
targetUrl = new URL(TARGET);
|
|
243
|
+
} catch {
|
|
244
|
+
throw new Error(
|
|
245
|
+
"TARGET must be an absolute URL, e.g. http://core:3000 or ws://gateway:4000"
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
var allowedTargetProtocols = /* @__PURE__ */ new Set(["http:", "https:", "ws:", "wss:"]);
|
|
249
|
+
assert(
|
|
250
|
+
allowedTargetProtocols.has(targetUrl.protocol),
|
|
251
|
+
"TARGET must start with http(s):// or ws(s)://"
|
|
252
|
+
);
|
|
253
|
+
var resolvedMode;
|
|
254
|
+
if (MODE === "local" || MODE === "downstream") {
|
|
255
|
+
resolvedMode = MODE;
|
|
256
|
+
} else {
|
|
257
|
+
resolvedMode = DOWNSTREAM ? "downstream" : "local";
|
|
258
|
+
}
|
|
259
|
+
var downstreamUrl;
|
|
260
|
+
if (resolvedMode === "downstream") {
|
|
261
|
+
assert(
|
|
262
|
+
DOWNSTREAM,
|
|
263
|
+
"DOWNSTREAM must be set when MODE=downstream (or when inferred)"
|
|
264
|
+
);
|
|
265
|
+
try {
|
|
266
|
+
const u = new URL(DOWNSTREAM);
|
|
267
|
+
const allowedDownstreamProtocols = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
268
|
+
assert(
|
|
269
|
+
allowedDownstreamProtocols.has(u.protocol),
|
|
270
|
+
"DOWNSTREAM must start with http(s)://"
|
|
271
|
+
);
|
|
272
|
+
downstreamUrl = u.toString();
|
|
273
|
+
} catch {
|
|
274
|
+
throw new Error(
|
|
275
|
+
"DOWNSTREAM must be an absolute URL, e.g. https://jwks.example.com/api/token"
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
var config = {
|
|
280
|
+
target: targetUrl.toString(),
|
|
281
|
+
mode: resolvedMode,
|
|
282
|
+
downstream: downstreamUrl ?? ""
|
|
283
|
+
};
|
|
284
|
+
var server = createProxyServer(config);
|
|
285
|
+
server.listen(port, () => {
|
|
286
|
+
console.log(`IAP listening on :${port} \u2192 ${config.target} (${config.mode})`);
|
|
287
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sebspark/test-iap",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "yarn build:index && yarn build:start",
|
|
13
|
+
"build:index": "tsup-node src/index.ts --format esm,cjs --dts",
|
|
14
|
+
"build:start": "tsup-node src/start.ts --format esm",
|
|
15
|
+
"dev": "tsc --watch --noEmit",
|
|
16
|
+
"lint": "biome check .",
|
|
17
|
+
"test": "vitest run --passWithNoTests --coverage",
|
|
18
|
+
"pretest:e2e": "yarn build",
|
|
19
|
+
"test:e2e": "vitest --config vitest.config.e2e.ts --run",
|
|
20
|
+
"typecheck": "vitest --typecheck.only --passWithNoTests"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"jose": "^6.0.12",
|
|
24
|
+
"testcontainers": "^11.5.1"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/ws": "^8.18.1",
|
|
28
|
+
"nock": "^14.0.9",
|
|
29
|
+
"tsconfig": "*",
|
|
30
|
+
"ws": "^8.18.3"
|
|
31
|
+
}
|
|
32
|
+
}
|