initial commit

This commit is contained in:
Henry Hiles 2025-06-18 10:32:03 -04:00
commit 217621daac
No known key found for this signature in database
21 changed files with 1401 additions and 0 deletions

View file

@ -0,0 +1,17 @@
import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:matrixgate/models/matrix_user.dart";
import "package:riverpod/riverpod.dart";
class AuthCodeController extends Notifier<IMap<String, MatrixUser>> {
@override
IMap<String, MatrixUser> build() => const IMap.empty();
void set(String name, MatrixUser user) =>
state = state.update(name, (_) => user, ifAbsent: () => user);
void remove(String name) => state = state.remove(name);
static final provider =
NotifierProvider<AuthCodeController, IMap<String, MatrixUser>>(
AuthCodeController.new,
);
}

View file

@ -0,0 +1,16 @@
import "package:args/args.dart";
import "package:matrixgate/models/settings.dart";
import "package:riverpod/riverpod.dart";
class SettingsController extends Notifier<Settings?> {
@override
Settings? build() => null;
void set(ArgResults args) => state = Settings.fromJson(<String, dynamic>{
for (final opt in args.options) opt: args.option(opt),
});
static final provider = NotifierProvider<SettingsController, Settings?>(
SettingsController.new,
);
}

159
lib/helpers/api_helper.dart Normal file
View file

@ -0,0 +1,159 @@
import "dart:io";
import "dart:convert";
import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart";
import "package:matrixgate/controllers/auth_code_controller.dart";
import "package:matrixgate/controllers/settings_controller.dart";
import "package:shelf/shelf.dart";
import "package:http/http.dart" as http;
import "package:matrixgate/models/matrix_user.dart";
import "package:riverpod/riverpod.dart";
class ApiHelper {
final Ref ref;
ApiHelper(this.ref);
Future<Response> handleLogin(Request request) async {
final body = await request.readAsString();
final data = Uri.splitQueryString(body);
final settings = ref.read(SettingsController.provider)!;
final username = data["username"];
final password = data["password"];
final redirectUri = data["redirect_uri"];
final state = data["state"] ?? "";
final loginRes = await http.post(
Uri.https(settings.homeserver, "_matrix/client/v3/login"),
body: json.encode({
"type": "m.login.password",
"identifier": {"type": "m.id.user", "user": username},
"password": password,
}),
);
if (loginRes.statusCode != 200) {
return Response.forbidden("Login failed");
}
final loginData = json.decode(loginRes.body);
final userId = loginData["user_id"];
final accessToken = loginData["access_token"];
final openidRes = await http.post(
Uri.https(
settings.homeserver,
"_matrix/client/v3/user/$userId/openid/request",
),
headers: {"Authorization": "Bearer $accessToken"},
);
if (openidRes.statusCode != 200) {
return Response.forbidden(
"OpenID request failed, status code ${openidRes.statusCode}",
);
}
final openidToken = json.decode(openidRes.body)["access_token"];
final code = base64Url.encode(
List<int>.generate(16, (_) => DateTime.now().millisecond % 256),
);
ref
.read(AuthCodeController.provider.notifier)
.set(code, MatrixUser(userId: userId, matrixToken: openidToken));
return Response.found("$redirectUri?code=$code&state=$state");
}
Future<Response> tokenHandler(Request request) async {
final settings = ref.read(SettingsController.provider)!;
final body = Uri.splitQueryString(await request.readAsString());
final code = body["code"];
final codes = ref.read(AuthCodeController.provider);
if (code == null || !codes.containsKey(code)) {
return Response(400, body: "Invalid code");
}
final user = codes[code]!;
ref.read(AuthCodeController.provider.notifier).remove(code);
final jwt = JWT(
{
"exp":
DateTime.now().add(Duration(minutes: 10)).millisecondsSinceEpoch ~/
1000,
"iat": DateTime.now().millisecondsSinceEpoch ~/ 1000,
},
subject: user.userId,
issuer: ref.read(SettingsController.provider)!.issuer,
audience: Audience([body["client_id"]!]),
);
final token = jwt.sign(
SecretKey(
await File.fromUri(Uri.file(settings.jwtSecretFile)).readAsString(),
),
algorithm: JWTAlgorithm.HS256,
);
return Response.ok(
json.encode({
"id_token": token,
"token_type": "Bearer",
"expires_in": 600,
}),
headers: {"Content-Type": "application/json"},
);
}
Future<Response> userinfoHandler(Request request) async {
final auth = request.headers["authorization"];
if (auth == null || !auth.startsWith("Bearer ")) {
return Response.forbidden(
json.encode({"error": "missing_token"}),
headers: {"content-type": "application/json"},
);
}
final token = auth.substring(7);
final matrixResp = await http.get(
Uri.https(
ref.read(SettingsController.provider)!.homeserver,
"_matrix/federation/v1/openid/userinfo",
),
headers: {"Authorization": "Bearer $token"},
);
if (matrixResp.statusCode != 200) {
return Response.forbidden(
json.encode({"error": "invalid_token"}),
headers: {"content-type": "application/json"},
);
}
return Response.ok(matrixResp.body);
}
Response jwks(_) => Response.ok(json.encode({"keys": []}));
Response openidConfiguration(_) {
final settings = ref.read(SettingsController.provider)!;
return Response.ok(
json.encode({
"issuer": settings.issuer,
"authorization_endpoint": settings.authorizeEndpoint,
"token_endpoint": "${settings.issuer}/token",
"userinfo_endpoint": "${settings.issuer}/userInfo",
"jwks_uri": "${settings.issuer}/jwks.json",
"response_types_supported": ["code"],
"subject_types_supported": ["public"],
"id_token_signing_alg_values_supported": ["HS256"],
}),
headers: {"Content-Type": "application/json"},
);
}
static final provider = Provider<ApiHelper>(ApiHelper.new);
}

View file

@ -0,0 +1,15 @@
import "package:freezed_annotation/freezed_annotation.dart";
part "matrix_user.freezed.dart";
part "matrix_user.g.dart";
@freezed
abstract class MatrixUser with _$MatrixUser {
const factory MatrixUser({
required String userId,
required String matrixToken,
}) = _MatrixUser;
factory MatrixUser.fromJson(Map<String, dynamic> json) =>
_$MatrixUserFromJson(json);
}

View file

@ -0,0 +1,151 @@
// dart format width=80
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'matrix_user.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$MatrixUser {
String get userId; String get matrixToken;
/// Create a copy of MatrixUser
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$MatrixUserCopyWith<MatrixUser> get copyWith => _$MatrixUserCopyWithImpl<MatrixUser>(this as MatrixUser, _$identity);
/// Serializes this MatrixUser to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is MatrixUser&&(identical(other.userId, userId) || other.userId == userId)&&(identical(other.matrixToken, matrixToken) || other.matrixToken == matrixToken));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,userId,matrixToken);
@override
String toString() {
return 'MatrixUser(userId: $userId, matrixToken: $matrixToken)';
}
}
/// @nodoc
abstract mixin class $MatrixUserCopyWith<$Res> {
factory $MatrixUserCopyWith(MatrixUser value, $Res Function(MatrixUser) _then) = _$MatrixUserCopyWithImpl;
@useResult
$Res call({
String userId, String matrixToken
});
}
/// @nodoc
class _$MatrixUserCopyWithImpl<$Res>
implements $MatrixUserCopyWith<$Res> {
_$MatrixUserCopyWithImpl(this._self, this._then);
final MatrixUser _self;
final $Res Function(MatrixUser) _then;
/// Create a copy of MatrixUser
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? userId = null,Object? matrixToken = null,}) {
return _then(_self.copyWith(
userId: null == userId ? _self.userId : userId // ignore: cast_nullable_to_non_nullable
as String,matrixToken: null == matrixToken ? _self.matrixToken : matrixToken // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _MatrixUser implements MatrixUser {
const _MatrixUser({required this.userId, required this.matrixToken});
factory _MatrixUser.fromJson(Map<String, dynamic> json) => _$MatrixUserFromJson(json);
@override final String userId;
@override final String matrixToken;
/// Create a copy of MatrixUser
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$MatrixUserCopyWith<_MatrixUser> get copyWith => __$MatrixUserCopyWithImpl<_MatrixUser>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$MatrixUserToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _MatrixUser&&(identical(other.userId, userId) || other.userId == userId)&&(identical(other.matrixToken, matrixToken) || other.matrixToken == matrixToken));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,userId,matrixToken);
@override
String toString() {
return 'MatrixUser(userId: $userId, matrixToken: $matrixToken)';
}
}
/// @nodoc
abstract mixin class _$MatrixUserCopyWith<$Res> implements $MatrixUserCopyWith<$Res> {
factory _$MatrixUserCopyWith(_MatrixUser value, $Res Function(_MatrixUser) _then) = __$MatrixUserCopyWithImpl;
@override @useResult
$Res call({
String userId, String matrixToken
});
}
/// @nodoc
class __$MatrixUserCopyWithImpl<$Res>
implements _$MatrixUserCopyWith<$Res> {
__$MatrixUserCopyWithImpl(this._self, this._then);
final _MatrixUser _self;
final $Res Function(_MatrixUser) _then;
/// Create a copy of MatrixUser
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? userId = null,Object? matrixToken = null,}) {
return _then(_MatrixUser(
userId: null == userId ? _self.userId : userId // ignore: cast_nullable_to_non_nullable
as String,matrixToken: null == matrixToken ? _self.matrixToken : matrixToken // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
// dart format on

View file

@ -0,0 +1,18 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'matrix_user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_MatrixUser _$MatrixUserFromJson(Map<String, dynamic> json) => _MatrixUser(
userId: json['userId'] as String,
matrixToken: json['matrixToken'] as String,
);
Map<String, dynamic> _$MatrixUserToJson(_MatrixUser instance) =>
<String, dynamic>{
'userId': instance.userId,
'matrixToken': instance.matrixToken,
};

20
lib/models/settings.dart Normal file
View file

@ -0,0 +1,20 @@
import "package:freezed_annotation/freezed_annotation.dart";
part "settings.freezed.dart";
part "settings.g.dart";
@freezed
abstract class Settings with _$Settings {
const factory Settings({
required String? socket,
required String address,
required String port,
required String homeserver,
required String issuer,
required String jwtSecretFile,
required String authorizeEndpoint,
}) = _Settings;
factory Settings.fromJson(Map<String, dynamic> json) =>
_$SettingsFromJson(json);
}

View file

@ -0,0 +1,166 @@
// dart format width=80
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'settings.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$Settings {
String? get socket; String get address; String get port; String get homeserver; String get issuer; String get jwtSecretFile; String get authorizeEndpoint;
/// Create a copy of Settings
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SettingsCopyWith<Settings> get copyWith => _$SettingsCopyWithImpl<Settings>(this as Settings, _$identity);
/// Serializes this Settings to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is Settings&&(identical(other.socket, socket) || other.socket == socket)&&(identical(other.address, address) || other.address == address)&&(identical(other.port, port) || other.port == port)&&(identical(other.homeserver, homeserver) || other.homeserver == homeserver)&&(identical(other.issuer, issuer) || other.issuer == issuer)&&(identical(other.jwtSecretFile, jwtSecretFile) || other.jwtSecretFile == jwtSecretFile)&&(identical(other.authorizeEndpoint, authorizeEndpoint) || other.authorizeEndpoint == authorizeEndpoint));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,socket,address,port,homeserver,issuer,jwtSecretFile,authorizeEndpoint);
@override
String toString() {
return 'Settings(socket: $socket, address: $address, port: $port, homeserver: $homeserver, issuer: $issuer, jwtSecretFile: $jwtSecretFile, authorizeEndpoint: $authorizeEndpoint)';
}
}
/// @nodoc
abstract mixin class $SettingsCopyWith<$Res> {
factory $SettingsCopyWith(Settings value, $Res Function(Settings) _then) = _$SettingsCopyWithImpl;
@useResult
$Res call({
String? socket, String address, String port, String homeserver, String issuer, String jwtSecretFile, String authorizeEndpoint
});
}
/// @nodoc
class _$SettingsCopyWithImpl<$Res>
implements $SettingsCopyWith<$Res> {
_$SettingsCopyWithImpl(this._self, this._then);
final Settings _self;
final $Res Function(Settings) _then;
/// Create a copy of Settings
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? socket = freezed,Object? address = null,Object? port = null,Object? homeserver = null,Object? issuer = null,Object? jwtSecretFile = null,Object? authorizeEndpoint = null,}) {
return _then(_self.copyWith(
socket: freezed == socket ? _self.socket : socket // ignore: cast_nullable_to_non_nullable
as String?,address: null == address ? _self.address : address // ignore: cast_nullable_to_non_nullable
as String,port: null == port ? _self.port : port // ignore: cast_nullable_to_non_nullable
as String,homeserver: null == homeserver ? _self.homeserver : homeserver // ignore: cast_nullable_to_non_nullable
as String,issuer: null == issuer ? _self.issuer : issuer // ignore: cast_nullable_to_non_nullable
as String,jwtSecretFile: null == jwtSecretFile ? _self.jwtSecretFile : jwtSecretFile // ignore: cast_nullable_to_non_nullable
as String,authorizeEndpoint: null == authorizeEndpoint ? _self.authorizeEndpoint : authorizeEndpoint // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _Settings implements Settings {
const _Settings({required this.socket, required this.address, required this.port, required this.homeserver, required this.issuer, required this.jwtSecretFile, required this.authorizeEndpoint});
factory _Settings.fromJson(Map<String, dynamic> json) => _$SettingsFromJson(json);
@override final String? socket;
@override final String address;
@override final String port;
@override final String homeserver;
@override final String issuer;
@override final String jwtSecretFile;
@override final String authorizeEndpoint;
/// Create a copy of Settings
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SettingsCopyWith<_Settings> get copyWith => __$SettingsCopyWithImpl<_Settings>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$SettingsToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _Settings&&(identical(other.socket, socket) || other.socket == socket)&&(identical(other.address, address) || other.address == address)&&(identical(other.port, port) || other.port == port)&&(identical(other.homeserver, homeserver) || other.homeserver == homeserver)&&(identical(other.issuer, issuer) || other.issuer == issuer)&&(identical(other.jwtSecretFile, jwtSecretFile) || other.jwtSecretFile == jwtSecretFile)&&(identical(other.authorizeEndpoint, authorizeEndpoint) || other.authorizeEndpoint == authorizeEndpoint));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,socket,address,port,homeserver,issuer,jwtSecretFile,authorizeEndpoint);
@override
String toString() {
return 'Settings(socket: $socket, address: $address, port: $port, homeserver: $homeserver, issuer: $issuer, jwtSecretFile: $jwtSecretFile, authorizeEndpoint: $authorizeEndpoint)';
}
}
/// @nodoc
abstract mixin class _$SettingsCopyWith<$Res> implements $SettingsCopyWith<$Res> {
factory _$SettingsCopyWith(_Settings value, $Res Function(_Settings) _then) = __$SettingsCopyWithImpl;
@override @useResult
$Res call({
String? socket, String address, String port, String homeserver, String issuer, String jwtSecretFile, String authorizeEndpoint
});
}
/// @nodoc
class __$SettingsCopyWithImpl<$Res>
implements _$SettingsCopyWith<$Res> {
__$SettingsCopyWithImpl(this._self, this._then);
final _Settings _self;
final $Res Function(_Settings) _then;
/// Create a copy of Settings
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? socket = freezed,Object? address = null,Object? port = null,Object? homeserver = null,Object? issuer = null,Object? jwtSecretFile = null,Object? authorizeEndpoint = null,}) {
return _then(_Settings(
socket: freezed == socket ? _self.socket : socket // ignore: cast_nullable_to_non_nullable
as String?,address: null == address ? _self.address : address // ignore: cast_nullable_to_non_nullable
as String,port: null == port ? _self.port : port // ignore: cast_nullable_to_non_nullable
as String,homeserver: null == homeserver ? _self.homeserver : homeserver // ignore: cast_nullable_to_non_nullable
as String,issuer: null == issuer ? _self.issuer : issuer // ignore: cast_nullable_to_non_nullable
as String,jwtSecretFile: null == jwtSecretFile ? _self.jwtSecretFile : jwtSecretFile // ignore: cast_nullable_to_non_nullable
as String,authorizeEndpoint: null == authorizeEndpoint ? _self.authorizeEndpoint : authorizeEndpoint // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
// dart format on

View file

@ -0,0 +1,27 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'settings.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_Settings _$SettingsFromJson(Map<String, dynamic> json) => _Settings(
socket: json['socket'] as String?,
address: json['address'] as String,
port: json['port'] as String,
homeserver: json['homeserver'] as String,
issuer: json['issuer'] as String,
jwtSecretFile: json['jwtSecretFile'] as String,
authorizeEndpoint: json['authorizeEndpoint'] as String,
);
Map<String, dynamic> _$SettingsToJson(_Settings instance) => <String, dynamic>{
'socket': instance.socket,
'address': instance.address,
'port': instance.port,
'homeserver': instance.homeserver,
'issuer': instance.issuer,
'jwtSecretFile': instance.jwtSecretFile,
'authorizeEndpoint': instance.authorizeEndpoint,
};