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