88 lines
2.8 KiB
Dart
88 lines
2.8 KiB
Dart
import "dart:convert";
|
|
import "dart:io";
|
|
import "package:cli_tools/config.dart";
|
|
import "package:http/http.dart" as http;
|
|
import "package:lasuite_docs_proxy/models/settings.dart";
|
|
import "package:shelf/shelf.dart";
|
|
import "package:shelf/shelf_io.dart";
|
|
import "package:shelf_router/shelf_router.dart";
|
|
|
|
void main(List<String> argsRaw) async {
|
|
final parser = ConfigParser()
|
|
..addOption("socket", abbr: "s", mandatory: true)
|
|
..addOption("authUri", abbr: "a", mandatory: true)
|
|
..addOption("minioUri", abbr: "m", mandatory: true);
|
|
|
|
final args = parser.parse(argsRaw);
|
|
final settings = Settings.fromJson(<String, dynamic>{
|
|
for (final opt in args.options) opt: args.option(opt),
|
|
});
|
|
|
|
final handler = const Pipeline()
|
|
.addMiddleware(logRequests())
|
|
.addHandler(
|
|
(Router()..get("/media/<path|.*>", (
|
|
Request request,
|
|
String path,
|
|
) async {
|
|
final authResponse = await http.get(
|
|
settings.authUri,
|
|
headers: {
|
|
...request.headers,
|
|
'x-original-url': request.requestedUri.toString(),
|
|
},
|
|
);
|
|
|
|
if (authResponse.statusCode != 200) {
|
|
return Response(
|
|
authResponse.statusCode,
|
|
body: json.encode({
|
|
"error":
|
|
"An error occurred when calling `authUri`: ${authResponse.body}.",
|
|
}),
|
|
headers: {HttpHeaders.contentTypeHeader: "application/json"},
|
|
);
|
|
}
|
|
|
|
final authHeaders = {
|
|
for (final header in [
|
|
'authorization',
|
|
'x-amz-date',
|
|
'x-amz-content-sha256',
|
|
])
|
|
if (authResponse.headers[header] case final value?)
|
|
header: value,
|
|
};
|
|
|
|
final minioUrl = settings.minioUri.replace(
|
|
path: "/lasuite-docs/$path",
|
|
query: request.url.query,
|
|
);
|
|
|
|
final minioResponse = await http.get(
|
|
minioUrl,
|
|
headers: {...authHeaders},
|
|
);
|
|
|
|
return Response(
|
|
minioResponse.statusCode,
|
|
body: minioResponse.bodyBytes,
|
|
headers: {
|
|
...minioResponse.headers,
|
|
'content-security-policy': "default-src 'none'",
|
|
},
|
|
);
|
|
}))
|
|
.call,
|
|
);
|
|
|
|
final server = HttpServer.listenOn(
|
|
await ServerSocket.bind(
|
|
InternetAddress(settings.socket, type: InternetAddressType.unix),
|
|
0,
|
|
),
|
|
);
|
|
|
|
serveRequests(server, handler);
|
|
print("Proxy listening at ${server.address.address}");
|
|
}
|