diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 462d9bed..5e229a19 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -23,8 +23,21 @@ jobs: - name: Build run: dotnet build --configuration Release --no-restore - - name: Initialize Testing Stack - run: docker compose up -d + - uses: supabase/setup-cli@v1 + with: + version: latest + + # - name: Initialize Testing Stack + # run: docker compose up -d + + - name: Install Python dependencies + run: python -m pip install --upgrade pip cryptography + + - name: Generate Supabase signing key + run: python supabase/generate_signing_key.py + + - name: Supabase Testing Stack + run: supabase start - name: Test run: dotnet test --no-restore diff --git a/Gotrue/AdminClient.cs b/Gotrue/AdminClient.cs index 3e1c95a8..2aa02180 100644 --- a/Gotrue/AdminClient.cs +++ b/Gotrue/AdminClient.cs @@ -2,146 +2,220 @@ using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; +using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Interfaces; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuth; using Supabase.Gotrue.Responses; +using Supabase.Gotrue.Responses.CustomProviders; +using Supabase.Gotrue.Responses.OAuth; namespace Supabase.Gotrue { - /// - /// Admin client for interacting with the Gotrue API. Intended for use on - /// servers or other secure environments. - /// - /// This client does NOT manage user sessions or track any other state. - /// - public class AdminClient : IGotrueAdminClient - { - /// - /// The initialized client options. - /// - public ClientOptions Options { get; } - - /// - /// Initialize the client with a service key. - /// - /// A valid JWT. Must be a full-access API key (e.g. 'service_role' or 'supabase_admin'). - /// - public AdminClient(string serviceKey, ClientOptions? options = null) - { - _serviceKey = serviceKey; - - options ??= new ClientOptions(); - Options = options; - _api = new Api(options.Url, options.Headers); - } - - /// - /// Headers sent to the API on every request. - /// - public Func>? GetHeaders - { - get => _api.GetHeaders; - set => _api.GetHeaders = value; - } - - /// - /// The underlying API requests object that sends the requests - /// - private readonly IGotrueApi _api; - - /// - /// The service key used to authenticate with the API. - /// - private readonly string _serviceKey; - - /// - public Task GetUserById(string userId) => _api.GetUserById(_serviceKey, userId); - - /// - public Task GetUser(string jwt) => _api.GetUser(jwt); - - /// - public async Task InviteUserByEmail(string email, InviteUserByEmailOptions? options = null) - { - var response = await _api.InviteUserByEmail(email, _serviceKey, options); - response.ResponseMessage?.EnsureSuccessStatusCode(); - return true; - } - - /// - public async Task DeleteUser(string uid) - { - var result = await _api.DeleteUser(uid, _serviceKey); - result.ResponseMessage?.EnsureSuccessStatusCode(); - return true; - } - - /// - public Task CreateUser(string email, string password, AdminUserAttributes? attributes = null) - { - attributes ??= new AdminUserAttributes(); - attributes.Email = email; - attributes.Password = password; - - return CreateUser(attributes); - } - - /// - public Task CreateUser(AdminUserAttributes attributes) => _api.CreateUser(_serviceKey, attributes); - - /// - public Task?> ListUsers(string? filter = null, string? sortBy = null, Constants.SortOrder sortOrder = Constants.SortOrder.Descending, int? page = null, int? perPage = null) - { - return _api.ListUsers(_serviceKey, filter, sortBy, sortOrder, page, perPage); - } - - /// - public Task UpdateUserById(string userId, AdminUserAttributes userData) - { - return _api.UpdateUserById(_serviceKey, userId, userData); - } - - /// - public async Task GenerateLink(GenerateLinkOptions options) - { - var response = await _api.GenerateLink(_serviceKey, options); - response.ResponseMessage?.EnsureSuccessStatusCode(); - - if (response.Content is null) - return null; - - var result = JsonConvert.DeserializeObject(response.Content); - return result; - } - - /// - public async Task ListFactors(MfaAdminListFactorsParams listFactorsParams) - { - var response = await _api.ListFactors(_serviceKey, listFactorsParams); - response.ResponseMessage?.EnsureSuccessStatusCode(); - - if (response.Content is null) - return null; - - var result = JsonConvert.DeserializeObject>(response.Content); - var listFactorsResponse = new MfaAdminListFactorsResponse - { - Factors = result - }; - - return listFactorsResponse; - } - - public async Task DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams) - { - return await _api.DeleteFactor(_serviceKey, deleteFactorParams); - } - - /// - public async Task Update(UserAttributes attributes) - { - var result = await _api.UpdateUser(_serviceKey, attributes); - return result; - } - } + /// + /// Admin client for interacting with the Gotrue API. Intended for use on + /// servers or other secure environments. + /// + /// This client does NOT manage user sessions or track any other state. + /// + public class AdminClient : IGotrueAdminClient + { + /// + /// The initialized client options. + /// + public ClientOptions Options { get; } + + /// + /// Initialize the client with a service key. + /// + /// A valid JWT. Must be a full-access API key (e.g. 'service_role' or 'supabase_admin'). + /// + public AdminClient(string serviceKey, ClientOptions? options = null) + { + _serviceKey = serviceKey; + + options ??= new ClientOptions(); + Options = options; + _api = new Api(options.Url, options.Headers, options.Timeout); + } + + /// + /// Headers sent to the API on every request. + /// + public Func>? GetHeaders + { + get => _api.GetHeaders; + set => _api.GetHeaders = value; + } + + /// + /// The underlying API requests object that sends the requests + /// + private readonly IGotrueApi _api; + + /// + /// The service key used to authenticate with the API. + /// + private readonly string _serviceKey; + + /// + public Task GetUserById(string userId) => _api.GetUserById(_serviceKey, userId); + + /// + public Task GetUser(string jwt) => _api.GetUser(jwt); + + /// + public async Task InviteUserByEmail( + string email, + InviteUserByEmailOptions? options = null + ) + { + var response = await _api.InviteUserByEmail(email, _serviceKey, options); + response.ResponseMessage?.EnsureSuccessStatusCode(); + return true; + } + + /// + public async Task DeleteUser(string uid, bool softDelete = false) + { + var result = await _api.DeleteUser(uid, _serviceKey, softDelete); + result.ResponseMessage?.EnsureSuccessStatusCode(); + return true; + } + + /// + public Task CreateUser( + string email, + string password, + AdminUserAttributes? attributes = null + ) + { + attributes ??= new AdminUserAttributes(); + attributes.Email = email; + attributes.Password = password; + + return CreateUser(attributes); + } + + /// + public Task CreateUser(AdminUserAttributes attributes) => + _api.CreateUser(_serviceKey, attributes); + + /// + public Task?> ListUsers( + string? filter = null, + string? sortBy = null, + Constants.SortOrder sortOrder = Constants.SortOrder.Descending, + int? page = null, + int? perPage = null + ) + { + return _api.ListUsers(_serviceKey, filter, sortBy, sortOrder, page, perPage); + } + + /// + public Task UpdateUserById(string userId, AdminUserAttributes userData) + { + return _api.UpdateUserById(_serviceKey, userId, userData); + } + + /// + public async Task GenerateLink(GenerateLinkOptions options) + { + var response = await _api.GenerateLink(_serviceKey, options); + response.ResponseMessage?.EnsureSuccessStatusCode(); + + if (response.Content is null) + return null; + + var result = JsonConvert.DeserializeObject(response.Content); + return result; + } + + /// + public async Task ListFactors( + MfaAdminListFactorsParams listFactorsParams + ) + { + var response = await _api.ListFactors(_serviceKey, listFactorsParams); + response.ResponseMessage?.EnsureSuccessStatusCode(); + + if (response.Content is null) + return null; + + var result = JsonConvert.DeserializeObject>(response.Content); + var listFactorsResponse = new MfaAdminListFactorsResponse { Factors = result }; + + return listFactorsResponse; + } + + public async Task DeleteFactor( + MfaAdminDeleteFactorParams deleteFactorParams + ) + { + return await _api.DeleteFactor(_serviceKey, deleteFactorParams); + } + + // Admin OAuth Client Management + /// + public Task ListOAuthClients() => _api.ListOAuthClients(_serviceKey); + + /// + public Task CreateOAuthClient(CreateOAuthClient client) => + _api.CreateOAuthClient(_serviceKey, client); + + /// + public Task GetOAuthClient(string clientId) => + _api.GetOAuthClient(_serviceKey, clientId); + + /// + public Task UpdateOAuthClient(string clientId, UpdateOAuthClient client) => + _api.UpdateOAuthClient(_serviceKey, clientId, client); + + /// + public async Task DeleteOAuthClient(string clientId) + { + var result = await _api.DeleteOAuthClient(_serviceKey, clientId); + result.ResponseMessage?.EnsureSuccessStatusCode(); + return true; + } + + /// + public Task RegenerateOAuthClientSecret(string clientId) => + _api.RegenerateOAuthClientSecret(_serviceKey, clientId); + + // Admin Custom Provider Management + /// + public Task ListCustomProviders() => + _api.ListCustomProviders(_serviceKey); + + /// + public Task CreateCustomProvider(CreateCustomProvider provider) => + _api.CreateCustomProvider(_serviceKey, provider); + + /// + public Task GetCustomProvider(string providerId) => + _api.GetCustomProvider(_serviceKey, providerId); + + /// + public Task UpdateCustomProvider( + string providerId, + UpdateCustomProvider provider + ) => _api.UpdateCustomProvider(_serviceKey, providerId, provider); + + /// + public async Task DeleteCustomProvider(string providerId) + { + var result = await _api.DeleteCustomProvider(_serviceKey, providerId); + result.ResponseMessage?.EnsureSuccessStatusCode(); + return true; + } + + /// + public async Task Update(UserAttributes attributes) + { + var result = await _api.UpdateUser(_serviceKey, attributes); + return result; + } + } } diff --git a/Gotrue/Api.cs b/Gotrue/Api.cs index 76e14ce0..28c781d7 100644 --- a/Gotrue/Api.cs +++ b/Gotrue/Api.cs @@ -2,15 +2,18 @@ using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Supabase.Core; -using Supabase.Core.Attributes; using Supabase.Core.Extensions; +using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Exceptions; using Supabase.Gotrue.Interfaces; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuth; +using Supabase.Gotrue.OAuthAuthorization; using Supabase.Gotrue.Responses; +using Supabase.Gotrue.Responses.CustomProviders; +using Supabase.Gotrue.Responses.OAuth; using static Supabase.Gotrue.Constants; namespace Supabase.Gotrue @@ -49,11 +52,17 @@ protected Dictionary Headers /// /// /// - public Api(string url, Dictionary? headers = null) + /// + public Api(string url, Dictionary? headers = null, int? timeout = null) { Url = url; headers ??= new Dictionary(); _headers = headers; + + if (timeout != null) + { + Helpers.CreateHttpClient((int)timeout); + } } /// @@ -79,6 +88,11 @@ public Api(string url, Dictionary? headers = null) { body.Add("data", options.Data); } + + if (!string.IsNullOrEmpty(options.CaptchaToken)) + { + body.Add("gotrue_meta_security", new Dictionary { { "captcha_token", options.CaptchaToken! } }); + } } var response = await Helpers.MakeRequest(HttpMethod.Post, endpoint, body, Headers); @@ -310,7 +324,7 @@ public async Task SignInWithOtp(SignInWithPasswordlessP /// public Task SendMagicLinkEmail(string email, SignInOptions? options = null) { - var data = new Dictionary { { "email", email } }; + var body = new Dictionary { { "email", email } }; var endpoint = $"{Url}/magiclink"; @@ -320,9 +334,14 @@ public Task SendMagicLinkEmail(string email, SignInOptions? option { endpoint = Helpers.AddQueryParams(endpoint, new Dictionary { { "redirect_to", options.RedirectTo! } }).ToString(); } + + if (!string.IsNullOrEmpty(options.CaptchaToken)) + { + body.Add("gotrue_meta_security", new Dictionary { { "captcha_token", options.CaptchaToken! } }); + } } - return Helpers.MakeRequest(HttpMethod.Post, endpoint, data, Headers); + return Helpers.MakeRequest(HttpMethod.Post, endpoint, body, Headers); } /// @@ -340,6 +359,9 @@ public Task InviteUserByEmail(string email, string jwt, InviteUser if (options?.Data != null) body["data"] = options.Data; + if (!string.IsNullOrEmpty(options?.CaptchaToken)) + body.Add("gotrue_meta_security", new Dictionary { { "captcha_token", options!.CaptchaToken! } }); + return Helpers.MakeRequest(HttpMethod.Post, url, body, CreateAuthedRequestHeaders(jwt)); } @@ -374,6 +396,11 @@ public Task InviteUserByEmail(string email, string jwt, InviteUser { body.Add("data", options.Data); } + + if (!string.IsNullOrEmpty(options.CaptchaToken)) + { + body.Add("gotrue_meta_security", new Dictionary { { "captcha_token", options.CaptchaToken! } }); + } } return Helpers.MakeRequest(HttpMethod.Post, endpoint, body, Headers); @@ -556,7 +583,15 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt /// public Task Challenge(string jwt, MfaChallengeParams mfaChallengeParams) { - return Helpers.MakeRequest(HttpMethod.Post, $"{Url}/factors/{mfaChallengeParams.FactorId}/challenge", null, CreateAuthedRequestHeaders(jwt)); + var body = new Dictionary(); + if (!string.IsNullOrEmpty(mfaChallengeParams.FriendlyName)) + body.Add("friendly_name", mfaChallengeParams.FriendlyName); + if (!string.IsNullOrEmpty(mfaChallengeParams.Channel)) + body.Add("channel", mfaChallengeParams.Channel); + if (mfaChallengeParams.WebAuthn != null) + body.Add("webauthn", mfaChallengeParams.WebAuthn); + + return Helpers.MakeRequest(HttpMethod.Post, $"{Url}/factors/{mfaChallengeParams.FactorId}/challenge", body.Count > 0 ? body : null, CreateAuthedRequestHeaders(jwt)); } /// @@ -568,6 +603,9 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt { "challenge_id", mfaVerifyParams.ChallengeId } }; + if (mfaVerifyParams.WebAuthn != null) + body.Add("webauthn", mfaVerifyParams.WebAuthn); + return Helpers.MakeRequest(HttpMethod.Post, $"{Url}/factors/{mfaVerifyParams.FactorId}/verify", body, CreateAuthedRequestHeaders(jwt)); } @@ -589,6 +627,125 @@ public Task ListFactors(string jwt, MfaAdminListFactorsParams list return Helpers.MakeRequest(HttpMethod.Delete, $"{Url}/admin/users/{deleteFactorParams.UserId}/factors/{deleteFactorParams.Id}", null, CreateAuthedRequestHeaders(jwt)); } + // Admin OAuth Client Management + /// + public async Task ListOAuthClients(string jwt) + { + var response = await Helpers.MakeRequest( + HttpMethod.Get, + $"{Url}/admin/oauth/clients", + null, + CreateAuthedRequestHeaders(jwt) + ); + return JsonConvert.DeserializeObject(response.Content!) + ?? new OAuthClientResponse(); + } + + /// + public Task CreateOAuthClient(string jwt, CreateOAuthClient client) => + Helpers.MakeRequest( + HttpMethod.Post, + $"{Url}/admin/oauth/clients", + client, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task GetOAuthClient(string jwt, string clientId) => + Helpers.MakeRequest( + HttpMethod.Get, + $"{Url}/admin/oauth/clients/{clientId}", + null, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task UpdateOAuthClient( + string jwt, + string clientId, + UpdateOAuthClient client + ) => + Helpers.MakeRequest( + HttpMethod.Put, + $"{Url}/admin/oauth/clients/{clientId}", + client, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task DeleteOAuthClient(string jwt, string clientId) => + Helpers.MakeRequest( + HttpMethod.Delete, + $"{Url}/admin/oauth/clients/{clientId}", + null, + CreateAuthedRequestHeaders(jwt) + ); + + /// + public Task RegenerateOAuthClientSecret(string jwt, string clientId) => + Helpers.MakeRequest( + HttpMethod.Post, + $"{Url}/admin/oauth/clients/{clientId}/regenerate_secret", + null, + CreateAuthedRequestHeaders(jwt) + )!; + + // Admin Custom Provider Management + /// + public async Task ListCustomProviders(string jwt) + { + var response = await Helpers.MakeRequest( + HttpMethod.Get, + $"{Url}/admin/custom-providers", + null, + CreateAuthedRequestHeaders(jwt) + ); + return JsonConvert.DeserializeObject(response.Content!)!; + } + + /// + public Task CreateCustomProvider( + string jwt, + CreateCustomProvider provider + ) => + Helpers.MakeRequest( + HttpMethod.Post, + $"{Url}/admin/custom-providers", + provider, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task GetCustomProvider(string jwt, string providerId) => + Helpers.MakeRequest( + HttpMethod.Get, + $"{Url}/admin/custom-providers/{providerId}", + null, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task UpdateCustomProvider( + string jwt, + string providerId, + UpdateCustomProvider provider + ) => + Helpers.MakeRequest( + HttpMethod.Put, + $"{Url}/admin/custom-providers/{providerId}", + provider, + CreateAuthedRequestHeaders(jwt) + )!; + + /// + public Task DeleteCustomProvider(string jwt, string providerId) => + Helpers.MakeRequest( + HttpMethod.Delete, + $"{Url}/admin/custom-providers/{providerId}", + null, + CreateAuthedRequestHeaders(jwt) + ); + /// public async Task LinkIdentity(string token, Provider provider, SignInOptions options) { @@ -735,15 +892,29 @@ public Task Reauthenticate(string userJwt) return Helpers.MakeRequest(HttpMethod.Get, $"{Url}/reauthenticate", null, CreateAuthedRequestHeaders(userJwt)); } + /// + /// Resends a confirmation code to a user's email or phone. + /// + /// + /// + public Task Resend(ResendParams resendParams) + { + return Helpers.MakeRequest(HttpMethod.Post, $"{Url}/resend", resendParams, Headers); + } + /// /// Delete a user /// /// The user uid you want to remove. /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// /// - public Task DeleteUser(string uid, string jwt) + public Task DeleteUser(string uid, string jwt, bool softDelete = false) { - var data = new Dictionary(); + var data = new Dictionary + { + { "should_soft_delete", softDelete } + }; return Helpers.MakeRequest(HttpMethod.Delete, $"{Url}/admin/users/{uid}", data, CreateAuthedRequestHeaders(jwt)); } @@ -790,5 +961,98 @@ public Task GenerateLink(string jwt, GenerateLinkOptions options) return Helpers.MakeRequest(HttpMethod.Post, $"{Url}/token?grant_type=refresh_token", data, Headers.MergeLeft(headers)); } + + /// + /// Retrieves details about an OAuth authorization request. + /// Used to display consent information to the user. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// This method returns one of two response types: + /// - OAuthAuthorizationDetails: User needs to consent - show consent page with client info + /// - OAuthRedirect: User already consented - redirect immediately to the OAuth client + /// + /// Use type checking to distinguish between the responses: + /// Check if Detail is not null to show consent page, otherwise redirect to Redirect.RedirectUrl + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID from the authorization request + /// Authorization details or redirect URL depending on consent status + public Task GetAuthorizationDetails(string jwt, string authorizationId) => + Helpers.MakeRequest( + HttpMethod.Get, + $"{Url}/oauth/authorizations/{authorizationId}", + null, + CreateAuthedRequestHeaders(jwt) + ); + + /// + /// Approves an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After approval, the user's consent is stored and an authorization code is generated. + /// The response contains a complete redirect URL with the authorization code and state. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID to approve + /// Optional parameters. If skipBrowserRedirect is false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling). + /// Redirect URL to send the user back to the OAuth client with authorization code + public Task ApproveAuthorization(string jwt, string authorizationId) => + Helpers.MakeRequest( + HttpMethod.Post, + $"{Url}/oauth/authorizations/{authorizationId}/consent", + new Dictionary { { "action", "approve"} }, + CreateAuthedRequestHeaders(jwt) + ); + + /// + /// Denies an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After denial, the response contains a redirect URL with an OAuth error + /// (access_denied) to inform the OAuth client that the user rejected the request. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID to deny + /// Optional parameters. If skipBrowserRedirect is false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling). + /// Redirect URL to send the user back to the OAuth client with error information + public Task DenyAuthorization(string jwt, string authorizationId) => + Helpers.MakeRequest( + HttpMethod.Post, + $"{Url}/oauth/authorizations/{authorizationId}/consent", + new Dictionary { { "action", "deny"} }, + CreateAuthedRequestHeaders(jwt) + ); + + /// + /// Lists all OAuth grants that the authenticated user has authorized. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// Response with array of OAuth grants with client information and granted scopes + public Task?> ListGrants(string jwt) => + Helpers.MakeRequest>( + HttpMethod.Get, + $"{Url}/user/oauth/grants", + null, + CreateAuthedRequestHeaders(jwt) + ); + + /// + /// Revokes a user's OAuth grant for a specific client. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// Revocation marks consent as revoked, deletes active sessions for that OAuth client, + /// and invalidates associated refresh tokens. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The OAuth grant identifier to revoke + /// Empty response on successful revocation + public Task RevokeGrant(string jwt, string clientId) => + Helpers.MakeRequest( + HttpMethod.Delete, + $"{Url}/user/oauth/grants?client_id={clientId}", + null, + CreateAuthedRequestHeaders(jwt) + ); } } diff --git a/Gotrue/Client.cs b/Gotrue/Client.cs index ae898fc2..6a52363d 100644 --- a/Gotrue/Client.cs +++ b/Gotrue/Client.cs @@ -8,6 +8,8 @@ using Supabase.Gotrue.Exceptions; using Supabase.Gotrue.Interfaces; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuthAuthorization; +using Supabase.Gotrue.Responses; using static Supabase.Gotrue.Constants; using static Supabase.Gotrue.Constants.AuthState; using static Supabase.Gotrue.Exceptions.FailureHint.Reason; @@ -77,7 +79,7 @@ public Client(ClientOptions? options = null) { options ??= new ClientOptions(); Options = options; - _api = new Api(options.Url, options.Headers); + _api = new Api(options.Url, options.Headers, options.Timeout); if (options.AutoRefreshToken) { @@ -462,6 +464,12 @@ public async Task Reauthenticate() return response.ResponseMessage?.IsSuccessStatusCode ?? false; } + /// + public Task Resend(ResendParams resendParams) + { + return _api.Resend(resendParams); + } + /// public async Task ResetPasswordForEmail(string email) { @@ -831,7 +839,7 @@ public void Shutdown() var challengeResponse = await _api.Challenge(CurrentSession.AccessToken, new MfaChallengeParams { - FactorId = mfaChallengeAndVerifyParams.FactorId + FactorId = mfaChallengeAndVerifyParams.FactorId, }); if (challengeResponse == null) @@ -843,7 +851,7 @@ public void Shutdown() { FactorId = mfaChallengeAndVerifyParams.FactorId, Code = mfaChallengeAndVerifyParams.Code, - ChallengeId = challengeResponse.Id + ChallengeId = challengeResponse.Id, }); if (result == null || string.IsNullOrEmpty(result.AccessToken)) @@ -927,5 +935,54 @@ public void Shutdown() return Task.FromResult(response); } + + /// + public Task GetAuthorizationDetails(string authorizationId) + { + if (CurrentSession == null || string.IsNullOrEmpty(CurrentSession.AccessToken)) + throw new GotrueException("Not Logged in.", NoSessionFound); + + return _api.GetAuthorizationDetails(CurrentSession.AccessToken, authorizationId); + } + + /// + public Task ApproveAuthorization(string authorizationId) + { + if (CurrentSession == null || string.IsNullOrEmpty(CurrentSession.AccessToken)) + throw new GotrueException("Not Logged in.", NoSessionFound); + + return _api.ApproveAuthorization(CurrentSession.AccessToken, authorizationId); + } + + /// + public Task DenyAuthorization(string authorizationId) + + { + if (CurrentSession == null || string.IsNullOrEmpty(CurrentSession.AccessToken)) + throw new GotrueException("Not Logged in.", NoSessionFound); + + return _api.DenyAuthorization(CurrentSession.AccessToken, authorizationId); + } + + /// + public Task?> ListGrants() + { + if (CurrentSession == null || string.IsNullOrEmpty(CurrentSession.AccessToken)) + throw new GotrueException("Not Logged in.", NoSessionFound); + + return _api.ListGrants(CurrentSession.AccessToken); + } + + /// + public async Task RevokeGrant(string grantId) + { + if (CurrentSession == null || string.IsNullOrEmpty(CurrentSession.AccessToken)) + throw new GotrueException("Not Logged in.", NoSessionFound); + + var response = await _api.RevokeGrant(CurrentSession.AccessToken, grantId); + response.ResponseMessage?.EnsureSuccessStatusCode(); + + return true; + } } } diff --git a/Gotrue/ClientOptions.cs b/Gotrue/ClientOptions.cs index a46aef35..f86849ca 100644 --- a/Gotrue/ClientOptions.cs +++ b/Gotrue/ClientOptions.cs @@ -54,5 +54,7 @@ public class ClientOptions /// confirmed emails - mirrors the Gotrue server's configuration. /// public bool AllowUnconfirmedUserSessions { get; set; } + + public int Timeout { get; set; } = 100_000; } } diff --git a/Gotrue/CustomProviders/CreateCustomProvider.cs b/Gotrue/CustomProviders/CreateCustomProvider.cs new file mode 100644 index 00000000..7e702918 --- /dev/null +++ b/Gotrue/CustomProviders/CreateCustomProvider.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.CustomProviders +{ + /// + /// Represents an Admin Custom Provider. + /// + public class CreateCustomProvider + { + /// Provider type. + [JsonProperty("provider_type")] + public CustomProviderType? ProviderType { get; set; } + + /// Provider identifier, e.g. custom:mycompany. + [JsonProperty("identifier")] + public string? Identifier { get; set; } + + /// Human-readable name. + [JsonProperty("name")] + public string? Name { get; set; } + + /// OAuth client ID. + [JsonProperty("client_id")] + public string? ClientId { get; set; } + + /// OAuth client secret (write-only, not returned in responses). + [JsonProperty("client_secret")] + public string? ClientSecret { get; set; } + + /// Additional client IDs accepted during token validation. + [JsonProperty("acceptable_client_ids")] + public List? AcceptableClientIds { get; set; } + + /// OAuth scopes requested during authorization. + [JsonProperty("scopes")] + public List? Scopes { get; set; } + + /// Whether PKCE is enabled. + [JsonProperty("pkce_enabled")] + public bool? PkceEnabled { get; set; } + + /// Mapping of provider attributes to Supabase user attributes. + [JsonProperty("attribute_mapping")] + public Dictionary? AttributeMapping { get; set; } + + /// Additional parameters sent with the authorization request. + [JsonProperty("authorization_params")] + public Dictionary? AuthorizationParams { get; set; } + + /// Whether the provider is enabled. + [JsonProperty("enabled")] + public bool? Enabled { get; set; } + + /// Whether email is optional for this provider. + [JsonProperty("email_optional")] + public bool? EmailOptional { get; set; } + + /// OIDC issuer URL. + [JsonProperty("issuer")] + public string? Issuer { get; set; } + + /// OIDC discovery URL. + [JsonProperty("discovery_url")] + public string? DiscoveryUrl { get; set; } + + /// Whether to skip nonce check (OIDC). + [JsonProperty("skip_nonce_check")] + public bool? SkipNonceCheck { get; set; } + + /// OAuth2 authorization URL. + [JsonProperty("authorization_url")] + public string? AuthorizationUrl { get; set; } + + /// OAuth2 token URL. + [JsonProperty("token_url")] + public string? TokenUrl { get; set; } + + /// OAuth2 userinfo URL. + [JsonProperty("userinfo_url")] + public string? UserinfoUrl { get; set; } + + /// JWKS URI for token verification. + [JsonProperty("jwks_uri")] + public string? JwksUri { get; set; } + } +} diff --git a/Gotrue/CustomProviders/CustomProviderType.cs b/Gotrue/CustomProviders/CustomProviderType.cs new file mode 100644 index 00000000..c99ad588 --- /dev/null +++ b/Gotrue/CustomProviders/CustomProviderType.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.CustomProviders +{ + /// + /// Represents the type of a custom authentication provider. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum CustomProviderType + { + [EnumMember(Value = "oauth2")] + OAuth2, + + [EnumMember(Value = "oidc")] + Oidc, + } +} diff --git a/Gotrue/CustomProviders/UpdateCustomProvider.cs b/Gotrue/CustomProviders/UpdateCustomProvider.cs new file mode 100644 index 00000000..28cd08de --- /dev/null +++ b/Gotrue/CustomProviders/UpdateCustomProvider.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.CustomProviders +{ + /// + /// Represents a customizable provider configuration intended for update operations. + /// This class encapsulates various properties that define how a custom provider + /// should be configured, including authentication-related details, mappings, + /// authorization parameters, and endpoints. + /// + public class UpdateCustomProvider + { + /// Human-readable name. + [JsonProperty("name")] + public string? Name { get; set; } + + /// OAuth client ID. + [JsonProperty("client_id")] + public string? ClientId { get; set; } + + /// OAuth client secret (write-only, not returned in responses). + [JsonProperty("client_secret")] + public string? ClientSecret { get; set; } + + /// Additional client IDs accepted during token validation. + [JsonProperty("acceptable_client_ids")] + public List? AcceptableClientIds { get; set; } + + /// OAuth scopes requested during authorization. + [JsonProperty("scopes")] + public List? Scopes { get; set; } + + /// Whether PKCE is enabled. + [JsonProperty("pkce_enabled")] + public bool? PkceEnabled { get; set; } + + /// Mapping of provider attributes to Supabase user attributes. + [JsonProperty("attribute_mapping")] + public Dictionary? AttributeMapping { get; set; } + + /// Additional parameters sent with the authorization request. + [JsonProperty("authorization_params")] + public Dictionary? AuthorizationParams { get; set; } + + /// Whether the provider is enabled. + [JsonProperty("enabled")] + public bool? Enabled { get; set; } + + /// Whether email is optional for this provider. + [JsonProperty("email_optional")] + public bool? EmailOptional { get; set; } + + /// OIDC issuer URL. + [JsonProperty("issuer")] + public string? Issuer { get; set; } + + /// OIDC discovery URL. + [JsonProperty("discovery_url")] + public string? DiscoveryUrl { get; set; } + + /// Whether to skip nonce check (OIDC). + [JsonProperty("skip_nonce_check")] + public bool? SkipNonceCheck { get; set; } + + /// OAuth2 authorization URL. + [JsonProperty("authorization_url")] + public string? AuthorizationUrl { get; set; } + + /// OAuth2 token URL. + [JsonProperty("token_url")] + public string? TokenUrl { get; set; } + + /// OAuth2 userinfo URL. + [JsonProperty("userinfo_url")] + public string? UserinfoUrl { get; set; } + + /// JWKS URI for token verification. + [JsonProperty("jwks_uri")] + public string? JwksUri { get; set; } + } +} diff --git a/Gotrue/Exceptions/FailureReason.cs b/Gotrue/Exceptions/FailureReason.cs index b984475c..31aa550a 100644 --- a/Gotrue/Exceptions/FailureReason.cs +++ b/Gotrue/Exceptions/FailureReason.cs @@ -88,7 +88,16 @@ public enum Reason /// The sso provider ID was incorrect or does not exist /// SsoProviderNotFound, - MfaChallengeUnverified + MfaChallengeUnverified, + /// + /// 502, 503, 504: Standard server/gateway errors + /// + NetworkError, + /// + /// Indicates an error related to Cloudflare network connectivity or operation. + /// 520-524, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.) + /// + CloudflareNetworkError, } /// @@ -106,6 +115,7 @@ public static Reason DetectReason(GotrueException gte) 400 when gte.Content.Contains("Invalid login") => UserBadLogin, 400 when gte.Content.Contains("Email not confirmed") => UserEmailNotConfirmed, 400 when gte.Content.Contains("Invalid Refresh Token") => InvalidRefreshToken, + 400 when gte.Content.Contains("Refresh token is not valid") => InvalidRefreshToken, 400 when gte.Content.Contains("Phone") => UserBadPhoneNumber, 400 when gte.Content.Contains("phone") => UserBadPhoneNumber, 400 when gte.Content.Contains("Email") => UserBadEmailAddress, @@ -123,6 +133,15 @@ 422 when gte.Content.Contains("email") && gte.Content.Contains("password") => Us 422 when gte.Content.Contains("Password") => UserBadPassword, 422 when gte.Content.Contains("password") => UserBadPassword, 429 => UserTooManyRequests, + 502 => NetworkError, + 503 => NetworkError, + 504 => NetworkError, + 520 => CloudflareNetworkError, + 521 => CloudflareNetworkError, + 522 => CloudflareNetworkError, + 523 => CloudflareNetworkError, + 524 => CloudflareNetworkError, + 530 => CloudflareNetworkError, _ => Unknown }; diff --git a/Gotrue/Gotrue.csproj b/Gotrue/Gotrue.csproj index 8d152266..dfb4de62 100644 --- a/Gotrue/Gotrue.csproj +++ b/Gotrue/Gotrue.csproj @@ -61,4 +61,7 @@ + + + \ No newline at end of file diff --git a/Gotrue/Helpers.cs b/Gotrue/Helpers.cs index bcee01b7..b12513ba 100644 --- a/Gotrue/Helpers.cs +++ b/Gotrue/Helpers.cs @@ -145,7 +145,12 @@ internal static Uri AddQueryParams(string url, Dictionary data) return builder.Uri; } - private static readonly HttpClient Client = new HttpClient(); + private static HttpClient _client = new HttpClient(); + + internal static void CreateHttpClient(int timeout) + { + _client = new HttpClient { Timeout = TimeSpan.FromMilliseconds(timeout) }; + } /// /// Helper to make a request using the defined parameters to an API Endpoint and coerce into a model. @@ -205,7 +210,7 @@ internal static async Task MakeRequest(HttpMethod method, string u try { - using var response = await Client.SendAsync(requestMessage).ConfigureAwait(false); + using var response = await _client.SendAsync(requestMessage).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { diff --git a/Gotrue/Interfaces/IGotrueAdminClient.cs b/Gotrue/Interfaces/IGotrueAdminClient.cs index 4d7a0b0d..5d27813e 100644 --- a/Gotrue/Interfaces/IGotrueAdminClient.cs +++ b/Gotrue/Interfaces/IGotrueAdminClient.cs @@ -1,110 +1,164 @@ using System.Threading.Tasks; -using Supabase.Core.Attributes; using Supabase.Core.Interfaces; +using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuth; using Supabase.Gotrue.Responses; +using Supabase.Gotrue.Responses.CustomProviders; +using Supabase.Gotrue.Responses.OAuth; namespace Supabase.Gotrue.Interfaces { - /// - /// Interface for the Gotrue Admin Client (auth). - /// - /// - public interface IGotrueAdminClient : IGettableHeaders - where TUser : User - { - /// - /// Creates a user using the admin key (not the anonymous key). - /// Used in trusted server environments, not client apps. - /// - /// - /// - Task CreateUser(AdminUserAttributes attributes); - - /// - /// Creates a user using the admin key (not the anonymous key). - /// Used in trusted server environments, not client apps. - /// - /// - /// - /// - /// - Task CreateUser(string email, string password, AdminUserAttributes? attributes = null); - - /// - /// Creates a user using the admin key (not the anonymous key). - /// Used in trusted server environments, not client apps. - /// - Task DeleteUser(string uid); - - /// - /// Gets a user from a user's JWT. This is using the GoTrue server to validate a user's JWT. - /// - /// - /// - Task GetUser(string jwt); - - /// - /// Gets a user by ID from the server using the admin key (not the anonymous key). - /// - /// - /// - Task GetUserById(string userId); - - /// - /// Sends an email to the user. - /// - /// - /// - /// - Task InviteUserByEmail(string email, InviteUserByEmailOptions? options = null); - - /// - /// Lists users - /// - /// A string for example part of the email - /// Snake case string of the given key, currently only created_at is supported - /// asc or desc, if null desc is used - /// page to show for pagination - /// items per page for pagination - /// - Task?> ListUsers(string? filter = null, string? sortBy = null, Constants.SortOrder sortOrder = Constants.SortOrder.Descending, int? page = null, - int? perPage = null); - - /// - /// Updates a User using the service key - /// - /// - /// - public Task Update(UserAttributes attributes); - - /// - /// Update user by Id - /// - /// - /// - /// - public Task UpdateUserById(string userId, AdminUserAttributes userData); - - /// - /// Generates email links and OTPs to be sent via a custom email provider. - /// - /// Options for this call. `Password` is required for , `Data` is an optional parameter for . - /// - public Task GenerateLink(GenerateLinkOptions options); - - /// - /// Lists all factors associated to a specific user. - /// - /// A object that contains the user id. - /// A list of that this user has enabled. - public Task ListFactors(MfaAdminListFactorsParams listFactorsParams); - - /// - /// Deletes a factor on a user. This will log the user out of all active sessions if the deleted factor was verified. - /// - /// A object that contains the user id. - /// A containing the deleted factor id. - public Task DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams); - } + /// + /// Interface for the Gotrue Admin Client (auth). + /// + /// + public interface IGotrueAdminClient : IGettableHeaders + where TUser : User + { + /// + /// Creates a user using the admin key (not the anonymous key). + /// Used in trusted server environments, not client apps. + /// + /// + /// + Task CreateUser(AdminUserAttributes attributes); + + /// + /// Creates a user using the admin key (not the anonymous key). + /// Used in trusted server environments, not client apps. + /// + /// + /// + /// + /// + Task CreateUser( + string email, + string password, + AdminUserAttributes? attributes = null + ); + + /// + /// Creates a user using the admin key (not the anonymous key). + /// Used in trusted server environments, not client apps. + /// + Task DeleteUser(string uid, bool softDelete = false); + + /// + /// Gets a user from a user's JWT. This is using the GoTrue server to validate a user's JWT. + /// + /// + /// + Task GetUser(string jwt); + + /// + /// Gets a user by ID from the server using the admin key (not the anonymous key). + /// + /// + /// + Task GetUserById(string userId); + + /// + /// Sends an email to the user. + /// + /// + /// + /// + Task InviteUserByEmail(string email, InviteUserByEmailOptions? options = null); + + /// + /// Lists users + /// + /// A string for example part of the email + /// Snake case string of the given key, currently only created_at is supported + /// asc or desc, if null desc is used + /// page to show for pagination + /// items per page for pagination + /// + Task?> ListUsers( + string? filter = null, + string? sortBy = null, + Constants.SortOrder sortOrder = Constants.SortOrder.Descending, + int? page = null, + int? perPage = null + ); + + /// + /// Updates a User using the service key + /// + /// + /// + public Task Update(UserAttributes attributes); + + /// + /// Update user by Id + /// + /// + /// + /// + public Task UpdateUserById(string userId, AdminUserAttributes userData); + + /// + /// Generates email links and OTPs to be sent via a custom email provider. + /// + /// Options for this call. `Password` is required for , `Data` is an optional parameter for . + /// + public Task GenerateLink(GenerateLinkOptions options); + + /// + /// Lists all factors associated to a specific user. + /// + /// A object that contains the user id. + /// A list of that this user has enabled. + public Task ListFactors( + MfaAdminListFactorsParams listFactorsParams + ); + + /// + /// Deletes a factor on a user. This will log the user out of all active sessions if the deleted factor was verified. + /// + /// A object that contains the user id. + /// A containing the deleted factor id. + public Task DeleteFactor( + MfaAdminDeleteFactorParams deleteFactorParams + ); + + // Admin OAuth Client Management + /// Lists all OAuth clients. + Task ListOAuthClients(); + + /// Creates a new OAuth client. + Task CreateOAuthClient(CreateOAuthClient client); + + /// Gets an OAuth client by ID. + Task GetOAuthClient(string clientId); + + /// Updates an OAuth client. + Task UpdateOAuthClient(string clientId, UpdateOAuthClient client); + + /// Deletes an OAuth client. + Task DeleteOAuthClient(string clientId); + + /// Regenerates the client secret for an OAuth client. + Task RegenerateOAuthClientSecret(string clientId); + + // Admin Custom Provider Management + /// Lists all custom providers. + Task ListCustomProviders(); + + /// Creates a new custom provider. + Task CreateCustomProvider(CreateCustomProvider provider); + + /// Gets a custom provider by ID. + Task GetCustomProvider(string providerId); + + /// Updates a custom provider. + Task UpdateCustomProvider( + string providerId, + UpdateCustomProvider provider + ); + + /// Deletes a custom provider. + Task DeleteCustomProvider(string providerId); + } } diff --git a/Gotrue/Interfaces/IGotrueApi.cs b/Gotrue/Interfaces/IGotrueApi.cs index 6f76baca..ffb5c938 100644 --- a/Gotrue/Interfaces/IGotrueApi.cs +++ b/Gotrue/Interfaces/IGotrueApi.cs @@ -1,75 +1,197 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Supabase.Core.Interfaces; +using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuth; +using Supabase.Gotrue.OAuthAuthorization; using Supabase.Gotrue.Responses; +using Supabase.Gotrue.Responses.CustomProviders; +using Supabase.Gotrue.Responses.OAuth; using static Supabase.Gotrue.Constants; #pragma warning disable CS1591 namespace Supabase.Gotrue.Interfaces { - public interface IGotrueApi : IGettableHeaders - where TUser : User - where TSession : Session - { - Task CreateUser(string jwt, AdminUserAttributes? attributes = null); - Task DeleteUser(string uid, string jwt); - Task GetUser(string jwt); - Task GetUserById(string jwt, string userId); - Task InviteUserByEmail(string email, string jwt, InviteUserByEmailOptions? options = null); - Task?> ListUsers(string jwt, string? filter = null, string? sortBy = null, SortOrder sortOrder = SortOrder.Descending, int? page = null, int? perPage = null); - Task RefreshAccessToken(string accessToken, string refreshToken); - Task ResetPasswordForEmail(string email); - Task ResetPasswordForEmail(ResetPasswordForEmailOptions options); - Task SendMagicLinkEmail(string email, SignInOptions? options = null); - Task SendMobileOTP(string phone); - Task SignInWithIdToken(Provider provider, string idToken, string? accessToken = null, string? nonce = null, string? captchaToken = null); - Task SignInWithEmail(string email, string password); - Task SignInWithPhone(string phone, string password); - Task SignInWithOtp(SignInWithPasswordlessEmailOptions options); - Task SignInWithOtp(SignInWithPasswordlessPhoneOptions options); - Task SignInAnonymously(SignInAnonymouslyOptions? options = null); - Task SignInWithSSO(Guid providerId, SignInWithSSOOptions? options = null); - Task SignInWithSSO(string domain, SignInWithSSOOptions? options = null); - Task SignOut(string jwt, SignOutScope scope = SignOutScope.Global); - Task SignUpWithEmail(string email, string password, SignUpOptions? options = null); - Task SignUpWithPhone(string phone, string password, SignUpOptions? options = null); - Task UpdateUser(string jwt, UserAttributes attributes); - Task UpdateUserById(string jwt, string userId, UserAttributes userData); - Task VerifyMobileOTP(string phone, string token, MobileOtpType type); - Task VerifyEmailOTP(string email, string token, EmailOtpType type); - Task VerifyTokenHash(string tokenHash, EmailOtpType type); - Task Reauthenticate(string userJwt); - ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? options = null); - Task ExchangeCodeForSession(string codeVerifier, string authCode); - Task Settings(); - Task GenerateLink(string jwt, GenerateLinkOptions options); - Task Enroll(string jwt, MfaEnrollParams mfaEnrollParams); - Task Challenge(string jwt, MfaChallengeParams mfaChallengeParams); - Task Verify(string jwt, MfaVerifyParams mfaVerifyParams); - Task Unenroll(string jwt, MfaUnenrollParams mfaVerifyParams); - Task ListFactors(string jwt, MfaAdminListFactorsParams listFactorsParams); - Task DeleteFactor(string jwt, MfaAdminDeleteFactorParams deleteFactorParams); + public interface IGotrueApi : IGettableHeaders + where TUser : User + where TSession : Session + { + Task CreateUser(string jwt, AdminUserAttributes? attributes = null); + Task DeleteUser(string uid, string jwt, bool softDelete = false); + Task GetUser(string jwt); + Task GetUserById(string jwt, string userId); + Task InviteUserByEmail( + string email, + string jwt, + InviteUserByEmailOptions? options = null + ); + Task?> ListUsers( + string jwt, + string? filter = null, + string? sortBy = null, + SortOrder sortOrder = SortOrder.Descending, + int? page = null, + int? perPage = null + ); + Task RefreshAccessToken(string accessToken, string refreshToken); + Task ResetPasswordForEmail(string email); + Task ResetPasswordForEmail( + ResetPasswordForEmailOptions options + ); + Task SendMagicLinkEmail(string email, SignInOptions? options = null); + Task SendMobileOTP(string phone); + Task SignInWithIdToken( + Provider provider, + string idToken, + string? accessToken = null, + string? nonce = null, + string? captchaToken = null + ); + Task SignInWithEmail(string email, string password); + Task SignInWithPhone(string phone, string password); + Task SignInWithOtp(SignInWithPasswordlessEmailOptions options); + Task SignInWithOtp(SignInWithPasswordlessPhoneOptions options); + Task SignInAnonymously(SignInAnonymouslyOptions? options = null); + Task SignInWithSSO(Guid providerId, SignInWithSSOOptions? options = null); + Task SignInWithSSO(string domain, SignInWithSSOOptions? options = null); + Task SignOut(string jwt, SignOutScope scope = SignOutScope.Global); + Task SignUpWithEmail( + string email, + string password, + SignUpOptions? options = null + ); + Task SignUpWithPhone( + string phone, + string password, + SignUpOptions? options = null + ); + Task UpdateUser(string jwt, UserAttributes attributes); + Task UpdateUserById(string jwt, string userId, UserAttributes userData); + Task VerifyMobileOTP(string phone, string token, MobileOtpType type); + Task VerifyEmailOTP(string email, string token, EmailOtpType type); + Task VerifyTokenHash(string tokenHash, EmailOtpType type); + Task Reauthenticate(string userJwt); + Task Resend(ResendParams resendParams); + ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? options = null); + Task ExchangeCodeForSession(string codeVerifier, string authCode); + Task Settings(); + Task GenerateLink(string jwt, GenerateLinkOptions options); + Task Enroll(string jwt, MfaEnrollParams mfaEnrollParams); + Task Challenge(string jwt, MfaChallengeParams mfaChallengeParams); + Task Verify(string jwt, MfaVerifyParams mfaVerifyParams); + Task Unenroll(string jwt, MfaUnenrollParams mfaVerifyParams); + Task ListFactors(string jwt, MfaAdminListFactorsParams listFactorsParams); + Task DeleteFactor( + string jwt, + MfaAdminDeleteFactorParams deleteFactorParams + ); + Task ListOAuthClients(string jwt); + Task CreateOAuthClient(string jwt, CreateOAuthClient client); + Task GetOAuthClient(string jwt, string clientId); + Task UpdateOAuthClient(string jwt, string clientId, UpdateOAuthClient client); + Task DeleteOAuthClient(string jwt, string clientId); + Task RegenerateOAuthClientSecret(string jwt, string clientId); + Task ListCustomProviders(string jwt); + Task CreateCustomProvider(string jwt, CreateCustomProvider provider); + Task GetCustomProvider(string jwt, string providerId); + Task UpdateCustomProvider( + string jwt, + string providerId, + UpdateCustomProvider provider + ); + Task DeleteCustomProvider(string jwt, string providerId); + + /// + /// Links an oauth identity to an existing user. + /// + /// This method requires the PKCE flow. + /// + /// User's token + /// Provider to Link + /// + /// + Task LinkIdentity( + string token, + Provider provider, + SignInOptions options + ); + + /// + /// Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + /// + /// User's token + /// Identity to be unlinked + /// + Task UnlinkIdentity(string token, UserIdentity userIdentity); + + #region OAuth /// - /// Links an oauth identity to an existing user. + /// Retrieves details about an OAuth authorization request. + /// Used to display consent information to the user. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// This method returns one of two response types: + /// - OAuthAuthorizationDetails: User needs to consent - show consent page with client info + /// - OAuthRedirect: User already consented - redirect immediately to the OAuth client /// - /// This method requires the PKCE flow. + /// Use type checking to distinguish between the responses: + /// Check if Detail is not null to show consent page, otherwise redirect to Redirect.RedirectUrl + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID from the authorization request + /// Authorization details or redirect URL depending on consent status + public Task GetAuthorizationDetails(string jwt, string authorizationId); + + /// + /// Approves an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After approval, the user's consent is stored and an authorization code is generated. + /// The response contains a complete redirect URL with the authorization code and state. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID to approve + /// Optional parameters. If skipBrowserRedirect is false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling). + /// Redirect URL to send the user back to the OAuth client with authorization code + public Task ApproveAuthorization(string jwt, string authorizationId); + + /// + /// Denies an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After denial, the response contains a redirect URL with an OAuth error + /// (access_denied) to inform the OAuth client that the user rejected the request. + /// + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The authorization ID to deny + /// Optional parameters. If skipBrowserRedirect is false (default), automatically redirects the browser to the OAuth client. If true, returns the redirect_url without automatic redirect (useful for custom handling). + /// Redirect URL to send the user back to the OAuth client with error information + public Task DenyAuthorization(string jwt, string authorizationId); + + /// + /// Lists all OAuth grants that the authenticated user has authorized. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. /// - /// User's token - /// Provider to Link - /// - /// - Task LinkIdentity(string token, Provider provider, SignInOptions options); + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// Response with array of OAuth grants with client information and granted scopes + public Task?> ListGrants(string jwt); /// - /// Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + /// Revokes a user's OAuth grant for a specific client. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// Revocation marks consent as revoked, deletes active sessions for that OAuth client, + /// and invalidates associated refresh tokens. /// - /// User's token - /// Identity to be unlinked - /// - Task UnlinkIdentity(string token, UserIdentity userIdentity); - } + /// A valid JWT. Must be a full-access API key (e.g. service_role key). + /// The OAuth grant identifier to revoke + /// Empty response on successful revocation + public Task RevokeGrant(string jwt, string clientId); + #endregion + } } diff --git a/Gotrue/Interfaces/IGotrueClient.cs b/Gotrue/Interfaces/IGotrueClient.cs index 3b74aff0..178e985b 100644 --- a/Gotrue/Interfaces/IGotrueClient.cs +++ b/Gotrue/Interfaces/IGotrueClient.cs @@ -1,8 +1,11 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Supabase.Core.Interfaces; using Supabase.Gotrue.Exceptions; using Supabase.Gotrue.Mfa; +using Supabase.Gotrue.OAuthAuthorization; +using Supabase.Gotrue.Responses; using static Supabase.Gotrue.Constants; #pragma warning disable CS1591 @@ -355,6 +358,7 @@ public interface IGotrueClient : IGettableHeaders /// /// Task Reauthenticate(); + Task Resend(ResendParams resendParams); /// /// Signs out and invalidates all sessions for a user. @@ -522,5 +526,65 @@ public interface IGotrueClient : IGettableHeaders #endregion + #region OAuth + + /// + /// Retrieves details about an OAuth authorization request. + /// Used to display consent information to the user. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// This method returns one of two response types: + /// - OAuthAuthorizationDetails: User needs to consent - show consent page with client info + /// - OAuthRedirect: User already consented - redirect immediately to the OAuth client + /// + /// Use type checking to distinguish between the responses: + /// Check if Detail is not null to show consent page, otherwise redirect to Redirect.RedirectUrl + /// + /// The authorization ID from the authorization request + /// Authorization details or redirect URL depending on consent status + public Task GetAuthorizationDetails(string authorizationId); + + /// + /// Approves an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After approval, the user's consent is stored and an authorization code is generated. + /// The response contains a complete redirect URL with the authorization code and state. + /// + /// The authorization ID to approve + /// Redirect URL to send the user back to the OAuth client with authorization code + public Task ApproveAuthorization(string authorizationId); + + /// + /// Denies an OAuth authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// After denial, the response contains a redirect URL with an OAuth error + /// (access_denied) to inform the OAuth client that the user rejected the request. + /// + /// The authorization ID to deny + /// Redirect URL to send the user back to the OAuth client with error information + public Task DenyAuthorization(string authorizationId); + + /// + /// Lists all OAuth grants that the authenticated user has authorized. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// Response with array of OAuth grants with client information and granted scopes + public Task?> ListGrants(); + + /// + /// Revokes a user's OAuth grant for a specific client. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// Revocation marks consent as revoked, deletes active sessions for that OAuth client, + /// and invalidates associated refresh tokens. + /// + /// The OAuth grant identifier to revoke + /// Empty response on successful revocation + public Task RevokeGrant(string clientId); + + #endregion + } } diff --git a/Gotrue/Interfaces/IGotrueStatelessClient.cs b/Gotrue/Interfaces/IGotrueStatelessClient.cs index 538a912e..f1c8351e 100644 --- a/Gotrue/Interfaces/IGotrueStatelessClient.cs +++ b/Gotrue/Interfaces/IGotrueStatelessClient.cs @@ -44,7 +44,7 @@ public interface IGotrueStatelessClient /// this token needs role 'supabase_admin' or 'service_role' /// /// - Task DeleteUser(string uid, string serviceRoleToken, StatelessClientOptions options); + Task DeleteUser(string uid, string serviceRoleToken, StatelessClientOptions options, bool softDelete = false); /// /// Logs in an existing user via a third-party provider. diff --git a/Gotrue/InviteUserByEmailOptions.cs b/Gotrue/InviteUserByEmailOptions.cs index d7a9406e..ac58fcd1 100644 --- a/Gotrue/InviteUserByEmailOptions.cs +++ b/Gotrue/InviteUserByEmailOptions.cs @@ -16,5 +16,10 @@ public class InviteUserByEmailOptions /// A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. /// public Dictionary? Data { get; set; } + + /// + /// Verification token received when the user completes the captcha on the site. + /// + public string? CaptchaToken { get; set; } } } \ No newline at end of file diff --git a/Gotrue/Mfa/MfaChallengeAndVerifyParams.cs b/Gotrue/Mfa/MfaChallengeAndVerifyParams.cs index c4b73576..606593e4 100644 --- a/Gotrue/Mfa/MfaChallengeAndVerifyParams.cs +++ b/Gotrue/Mfa/MfaChallengeAndVerifyParams.cs @@ -1,8 +1,18 @@ -namespace Supabase.Gotrue.Mfa +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Mfa { public class MfaChallengeAndVerifyParams { + [JsonProperty("factor_id")] public string FactorId { get; set; } + [JsonProperty("code")] public string Code { get; set; } + [JsonProperty("friendly_name")] + public string? FriendlyName { get; set; } + [JsonProperty("channel")] + public string? Channel { get; set; } + [JsonProperty("webauthn")] + public WebAuthnChallengeParams? WebAuthn { get; set; } } } \ No newline at end of file diff --git a/Gotrue/Mfa/MfaChallengeParams.cs b/Gotrue/Mfa/MfaChallengeParams.cs index e47eaca4..2ab9d83f 100644 --- a/Gotrue/Mfa/MfaChallengeParams.cs +++ b/Gotrue/Mfa/MfaChallengeParams.cs @@ -1,8 +1,34 @@ -namespace Supabase.Gotrue.Mfa +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Mfa { public class MfaChallengeParams { // Id of the factor to be challenged. Returned in enroll(). + [JsonProperty("factor_id")] public string FactorId { get; set; } + + // Friendly name of the factor, useful for distinguishing between factors + [JsonProperty("friendly_name")] + public string? FriendlyName { get; set; } + + // Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors + [JsonProperty("channel")] + public string? Channel { get; set; } + + // WebAuthn parameters for WebAuthn factor challenge + [JsonProperty("webauthn")] + public WebAuthnChallengeParams? WebAuthn { get; set; } + } + + public class WebAuthnChallengeParams + { + // Relying party ID + [JsonProperty("rp_id")] + public string? RpId { get; set; } + + // Relying party origins + [JsonProperty("rp_origins")] + public string[]? RpOrigins { get; set; } } } \ No newline at end of file diff --git a/Gotrue/Mfa/MfaEnrollParams.cs b/Gotrue/Mfa/MfaEnrollParams.cs index feb5d35e..7e2e20f5 100644 --- a/Gotrue/Mfa/MfaEnrollParams.cs +++ b/Gotrue/Mfa/MfaEnrollParams.cs @@ -1,9 +1,16 @@ -namespace Supabase.Gotrue.Mfa +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Mfa { public class MfaEnrollParams { + [JsonProperty("factor_type")] public string FactorType { get; set; } + + [JsonProperty("issuer")] public string? Issuer { get; set; } + + [JsonProperty("friendly_name")] public string? FriendlyName { get; set; } } } \ No newline at end of file diff --git a/Gotrue/Mfa/MfaVerifyParams.cs b/Gotrue/Mfa/MfaVerifyParams.cs index 322f385f..f1a388c9 100644 --- a/Gotrue/Mfa/MfaVerifyParams.cs +++ b/Gotrue/Mfa/MfaVerifyParams.cs @@ -1,14 +1,25 @@ -namespace Supabase.Gotrue.Mfa +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Mfa { public class MfaVerifyParams { // ID of the factor being verified. Returned in enroll() + [JsonProperty("factor_id")] public string FactorId { get; set; } // ID of the challenge being verified. Returned in challenge() + [JsonProperty("challenge_id")] public string ChallengeId { get; set; } // Verification code provided by the user + [JsonProperty("code")] public string Code { get; set; } + + /// + /// For WebAuthn verification + /// + [JsonProperty("webauthn")] + public object? WebAuthn { get; set; } } } \ No newline at end of file diff --git a/Gotrue/OAuth/CreateOAuthClient.cs b/Gotrue/OAuth/CreateOAuthClient.cs new file mode 100644 index 00000000..a95de128 --- /dev/null +++ b/Gotrue/OAuth/CreateOAuthClient.cs @@ -0,0 +1,43 @@ +using Newtonsoft.Json; +using Supabase.Gotrue.Responses.OAuth; + +namespace Supabase.Gotrue.OAuth +{ + /// + /// Represents the data required to create a new OAuth client. + /// + public class CreateOAuthClient + { + /// Human-readable name of the OAuth client. + [JsonProperty("client_name")] + public string? ClientName { get; set; } + + /// URI of the OAuth client. + [JsonProperty("client_uri")] + public string? ClientUri { get; set; } + + /// URI of the OAuth client's logo. + [JsonProperty("logo_uri")] + public string? LogoUri { get; set; } + + /// Array of allowed redirect URIs. + [JsonProperty("redirect_uris")] + public string[]? RedirectUrls { get; set; } + + /// Array of allowed grant types. + [JsonProperty("grant_types")] + public OAuthClientGrantType[]? GrantTypes { get; set; } + + /// Array of allowed response types. + [JsonProperty("response_types")] + public string? ResponsType { get; set; } + + /// Scope of the OAuth client. + [JsonProperty("scope")] + public string? Scope { get; set; } + + /// Token endpoint authentication method. + [JsonProperty("token_endpoint_auth_method")] + public OAuthClientTokenEndpoint? TokenEndpoint { get; set; } + } +} diff --git a/Gotrue/OAuth/OAuthClientGrantType.cs b/Gotrue/OAuth/OAuthClientGrantType.cs new file mode 100644 index 00000000..c8eb7776 --- /dev/null +++ b/Gotrue/OAuth/OAuthClientGrantType.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.OAuth +{ + /// + /// Represents the OAuth grant types supported by the client. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OAuthClientGrantType + { + [EnumMember(Value = "authorization_code")] + AuthorizationCode, + + [EnumMember(Value = "refresh_token")] + RefreshToken, + } +} diff --git a/Gotrue/OAuth/OAuthClientTokenEndpoint.cs b/Gotrue/OAuth/OAuthClientTokenEndpoint.cs new file mode 100644 index 00000000..744afab2 --- /dev/null +++ b/Gotrue/OAuth/OAuthClientTokenEndpoint.cs @@ -0,0 +1,22 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.OAuth +{ + /// + /// Represents the token endpoint authentication methods for OAuth clients. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OAuthClientTokenEndpoint + { + [EnumMember(Value = "none")] + None, + + [EnumMember(Value = "client_secret_basic")] + ClientSecretBasic, + + [EnumMember(Value = "client_secret_post")] + ClientSecretPost, + } +} diff --git a/Gotrue/OAuth/UpdateOAuthClient.cs b/Gotrue/OAuth/UpdateOAuthClient.cs new file mode 100644 index 00000000..2f6ca943 --- /dev/null +++ b/Gotrue/OAuth/UpdateOAuthClient.cs @@ -0,0 +1,51 @@ +using Newtonsoft.Json; +using Supabase.Gotrue.Responses.OAuth; + +namespace Supabase.Gotrue.OAuth +{ + /// + /// Represents the data required to update an OAuth client. + /// + public class UpdateOAuthClient + { + /// Human-readable name of the OAuth client. + [JsonProperty("client_name")] + public string? ClientName { get; set; } + + /// URI of the OAuth client. + [JsonProperty("client_uri")] + public string? ClientUri { get; set; } + + /// URI of the OAuth client's logo. + [JsonProperty("logo_uri")] + public string? LogoUri { get; set; } + + /// Array of allowed redirect URIs. + [JsonProperty("redirect_uris")] + public string[]? RedirectUrls { get; set; } + + /// Array of allowed grant types. + [JsonProperty("grant_types")] + public OAuthClientGrantType[]? GrantTypes { get; set; } + + /// Token endpoint authentication method. + [JsonProperty("token_endpoint_auth_method")] + public OAuthClientTokenEndpoint? TokenEndpoint { get; set; } + + /// + /// Creates an instance of from the given . + /// + /// The source containing the values to populate the . + /// A new instance of populated with the corresponding properties from the . + public static UpdateOAuthClient From(OAuthClient client) => + new UpdateOAuthClient + { + ClientName = client.ClientName, + ClientUri = client.ClientUri, + LogoUri = client.LogoUri, + RedirectUrls = client.RedirectUris, + GrantTypes = client.GrantTypes, + TokenEndpoint = client.TokenEndpointAuthMethod, + }; + } +} diff --git a/Gotrue/OAuthAuthorization/OAuthAuthorizationClient.cs b/Gotrue/OAuthAuthorization/OAuthAuthorizationClient.cs new file mode 100644 index 00000000..304058ad --- /dev/null +++ b/Gotrue/OAuthAuthorization/OAuthAuthorizationClient.cs @@ -0,0 +1,35 @@ +using Newtonsoft.Json; + +namespace Supabase.Gotrue.OAuthAuthorization +{ + /// + /// OAuth client details in an authorization request. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + public class OAuthAuthorizationClient + { + /// + /// Unique identifier for the OAuth client (UUID). + /// + [JsonProperty("id")] + public string Id { get; set; } + + /// + /// Human-readable name of the OAuth client. + /// + [JsonProperty("name")] + public string Name { get; set; } + + /// + /// URI of the OAuth client's website. + /// + [JsonProperty("uri")] + public string Uri { get; set; } + + /// + /// URI of the OAuth client's logo. + /// + [JsonProperty("logo_uri")] + public string LogoUri { get; set; } + } +} \ No newline at end of file diff --git a/Gotrue/OAuthAuthorization/OAuthAuthorizationDetail.cs b/Gotrue/OAuthAuthorization/OAuthAuthorizationDetail.cs new file mode 100644 index 00000000..8e023abb --- /dev/null +++ b/Gotrue/OAuthAuthorization/OAuthAuthorizationDetail.cs @@ -0,0 +1,48 @@ +using Newtonsoft.Json; + +namespace Supabase.Gotrue.OAuthAuthorization +{ + /// + /// OAuth authorization details when user needs to provide consent. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// This response includes all information needed to display a consent page: + /// client details, user info, requested scopes, and where the user will be redirected. + /// + /// Note: is the base URI (e.g., "https://app.com/callback") without + /// query parameters. After consent, you'll receive a complete redirect_url with + /// the authorization code and state parameters appended. + /// + public class OAuthAuthorizationDetail + { + /// + /// The authorization ID used to approve or deny the request. + /// + [JsonProperty("authorization_id")] + public string AuthorizationId { get; set; } + + /// + /// The OAuth client's registered redirect URI (base URI without query parameters). + /// + [JsonProperty("redirect_uri")] + public string RedirectUri { get; set; } + + /// + /// OAuth client requesting authorization. + /// + [JsonProperty("client")] + public OAuthAuthorizationClient Client { get; set; } + + /// + /// User object associated with the authorization. + /// + [JsonProperty("user")] + public OAuthAuthorizationUser User { get; set; } + + /// + /// Space-separated list of requested scopes (e.g., "openid profile email"). + /// + [JsonProperty("scope")] + public string Scope { get; set; } + } +} \ No newline at end of file diff --git a/Gotrue/OAuthAuthorization/OAuthAuthorizationGrant.cs b/Gotrue/OAuthAuthorization/OAuthAuthorizationGrant.cs new file mode 100644 index 00000000..62692a7a --- /dev/null +++ b/Gotrue/OAuthAuthorization/OAuthAuthorizationGrant.cs @@ -0,0 +1,29 @@ +using Newtonsoft.Json; + +namespace Supabase.Gotrue.OAuthAuthorization +{ + /// + /// An OAuth grant representing a user's authorization of an OAuth client. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + public class OAuthAuthorizationGrant + { + /// + /// OAuth client information + /// + [JsonProperty("client")] + public OAuthAuthorizationClient Client { get; set; } + + /// + /// Array of scopes granted to this client + /// + [JsonProperty("scopes")] + public string[] Scopes { get; set; } + + /// + /// Timestamp when the grant was created (ISO 8601 date-time) + /// + [JsonProperty("granted_at")] + public string GrantedAt { get; set; } + } +} \ No newline at end of file diff --git a/Gotrue/OAuthAuthorization/OAuthAuthorizationRedirect.cs b/Gotrue/OAuthAuthorization/OAuthAuthorizationRedirect.cs new file mode 100644 index 00000000..9d5ed44b --- /dev/null +++ b/Gotrue/OAuthAuthorization/OAuthAuthorizationRedirect.cs @@ -0,0 +1,27 @@ +using Newtonsoft.Json; + +namespace Supabase.Gotrue.OAuthAuthorization +{ + + /// + /// OAuth redirect response when user has already consented or after consent decision. + /// Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + /// + /// This response is returned in three scenarios: + /// 1. User already consented to these scopes (auto-approved) + /// 2. User just approved the authorization request + /// 3. User just denied the authorization request + /// + /// The `redirect_url` is a complete URL ready for redirecting the user back to the + /// OAuth client, including authorization code (on success) or error (on denial) in + /// query parameters, along with the state parameter if one was provided. + /// + public class OAuthAuthorizationRedirect + { + /// + /// Complete redirect URL with authorization code and state parameters (e.g., "https://app.com/callback?code=xxx&state=yyy") + /// + [JsonProperty("redirect_url")] + public string RedirectUrl { get; set; } + } +} \ No newline at end of file diff --git a/Gotrue/OAuthAuthorization/OAuthAuthorizationUser.cs b/Gotrue/OAuthAuthorization/OAuthAuthorizationUser.cs new file mode 100644 index 00000000..8fcd0e73 --- /dev/null +++ b/Gotrue/OAuthAuthorization/OAuthAuthorizationUser.cs @@ -0,0 +1,22 @@ +using Newtonsoft.Json; + +namespace Supabase.Gotrue.OAuthAuthorization +{ + /// + /// User object associated with the authorization + /// + public class OAuthAuthorizationUser + { + /// + /// User ID (UUID) + /// + [JsonProperty("id")] + public string Id { get; set; } + + /// + /// User email + /// + [JsonProperty("email")] + public string Email { get; set; } + } +} \ No newline at end of file diff --git a/Gotrue/ResendParams.cs b/Gotrue/ResendParams.cs new file mode 100644 index 00000000..bd391be0 --- /dev/null +++ b/Gotrue/ResendParams.cs @@ -0,0 +1,99 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Supabase.Core.Attributes; +using Supabase.Core.Extensions; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace Supabase.Gotrue +{ + /// + /// Parameters for the Resend API. + /// + public class ResendParams + { + /// + /// The type of resend. + /// + [JsonConverter(typeof(ResendTypeConverter))] + public enum ResendType + { + /// Signup resend. + [MapTo("signup")] + Signup, + /// Signup resend. + [MapTo("signup")] + SignUp, + /// Invite resend. + [MapTo("invite")] + Invite, + /// Magic link resend. + [MapTo("magiclink")] + MagicLink, + /// Email change resend. + [MapTo("email_change")] + EmailChange, + /// SMS recovery resend. + [MapTo("recovery")] + Recovery + } + + /// + /// Custom converter to handle MapTo attributes for the ResendType enum. + /// + public class ResendTypeConverter : JsonConverter + { + /// + public override void WriteJson(JsonWriter writer, ResendType value, JsonSerializer serializer) + { + var field = value.GetType().GetField(value.ToString()); + var attribute = field?.GetCustomAttributes(typeof(MapToAttribute), false).FirstOrDefault() as MapToAttribute; + writer.WriteValue(attribute?.Mapping ?? value.ToString().ToLower()); + } + + /// + public override ResendType ReadJson(JsonReader reader, System.Type objectType, ResendType existingValue, bool hasExistingValue, JsonSerializer serializer) + { + // Implementation for reading if needed, but not strictly required for this API + return ResendType.Signup; + } + } + + /// + /// The email address to resend to. + /// + [JsonProperty("email")] + public string? Email { get; set; } + + /// + /// The phone number to resend to. + /// + [JsonProperty("phone")] + public string? Phone { get; set; } + + /// + /// The type of resend. + /// + [JsonProperty("type")] + public ResendType Type { get; set; } + + /// + /// Verification token received when the user completes the captcha on the site. + /// + [JsonProperty("captchaToken")] + public string? CaptchaToken { get; set; } + + /// + /// A URL or mobile address to send the user to after they are confirmed. + /// + [JsonProperty("redirectTo")] + public string? RedirectTo { get; set; } + + /// + /// A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + /// + [JsonProperty("data")] + public Dictionary? Data { get; set; } + } +} diff --git a/Gotrue/Responses/CustomProviders/CustomProvider.cs b/Gotrue/Responses/CustomProviders/CustomProvider.cs new file mode 100644 index 00000000..56517a88 --- /dev/null +++ b/Gotrue/Responses/CustomProviders/CustomProvider.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Responses.CustomProviders +{ + /// + /// Represents a custom identity provider with configuration details and metadata. + /// + public class CustomProvider + { + /// Unique identifier (UUID). + [JsonProperty("id")] + public string? Id { get; set; } + + /// Provider type. + [JsonProperty("provider_type")] + public string? ProviderType { get; set; } + + /// Provider identifier, e.g. custom:mycompany. + [JsonProperty("identifier")] + public string? Identifier { get; set; } + + /// Human-readable name. + [JsonProperty("name")] + public string? Name { get; set; } + + /// OAuth client ID. + [JsonProperty("client_id")] + public string? ClientId { get; set; } + + /// Additional client IDs accepted during token validation. + [JsonProperty("acceptable_client_ids")] + public List? AcceptableClientIds { get; set; } + + /// OAuth scopes requested during authorization. + [JsonProperty("scopes")] + public List? Scopes { get; set; } + + /// Whether PKCE is enabled. + [JsonProperty("pkce_enabled")] + public bool? PkceEnabled { get; set; } + + /// Mapping of provider attributes to Supabase user attributes. + [JsonProperty("attribute_mapping")] + public Dictionary? AttributeMapping { get; set; } + + /// Additional parameters sent with the authorization request. + [JsonProperty("authorization_params")] + public Dictionary? AuthorizationParams { get; set; } + + /// Whether the provider is enabled. + [JsonProperty("enabled")] + public bool? Enabled { get; set; } + + /// Whether email is optional for this provider. + [JsonProperty("email_optional")] + public bool? EmailOptional { get; set; } + + /// OIDC issuer URL. + [JsonProperty("issuer")] + public string? Issuer { get; set; } + + /// OIDC discovery URL. + [JsonProperty("discovery_url")] + public string? DiscoveryUrl { get; set; } + + /// Whether to skip nonce check (OIDC). + [JsonProperty("skip_nonce_check")] + public bool? SkipNonceCheck { get; set; } + + /// OAuth2 authorization URL. + [JsonProperty("authorization_url")] + public string? AuthorizationUrl { get; set; } + + /// OAuth2 token URL. + [JsonProperty("token_url")] + public string? TokenUrl { get; set; } + + /// OAuth2 userinfo URL. + [JsonProperty("userinfo_url")] + public string? UserinfoUrl { get; set; } + + /// JWKS URI for token verification. + [JsonProperty("jwks_uri")] + public string? JwksUri { get; set; } + + /// OIDC discovery document (OIDC providers only). + [JsonProperty("discovery_document")] + public OIDCDiscoveryDocumentResponse? DiscoveryDocument { get; set; } + + /// Timestamp when the provider was created. + [JsonProperty("created_at")] + public DateTime? CreatedAt { get; set; } + + /// Timestamp when the provider was last updated. + [JsonProperty("updated_at")] + public DateTime? UpdatedAt { get; set; } + } +} diff --git a/Gotrue/Responses/CustomProviders/CustomProviderResponse.cs b/Gotrue/Responses/CustomProviders/CustomProviderResponse.cs new file mode 100644 index 00000000..aa672788 --- /dev/null +++ b/Gotrue/Responses/CustomProviders/CustomProviderResponse.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Responses.CustomProviders +{ + /// + /// Represents a response containing a list of custom providers. + /// + public class CustomProviderResponse + { + /// + /// Gets or sets the list of custom providers available in the response. + /// + [JsonProperty("providers")] + public List? Providers { get; set; } + } +} diff --git a/Gotrue/Responses/CustomProviders/OIDCDiscoveryDocumentResponse.cs b/Gotrue/Responses/CustomProviders/OIDCDiscoveryDocumentResponse.cs new file mode 100644 index 00000000..5918d388 --- /dev/null +++ b/Gotrue/Responses/CustomProviders/OIDCDiscoveryDocumentResponse.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Responses.CustomProviders +{ + /// + /// Represents the discovery document response obtained from an OpenID Connect (OIDC) provider. + /// This class is used to map configuration details of the OIDC provider that + /// are required for authentication and authorization workflows. + /// + public class OIDCDiscoveryDocumentResponse + { + /// The issuer identifier. + [JsonProperty("issuer")] + public string? Issuer { get; set; } + + /// URL of the authorization endpoint. + [JsonProperty("authorization_endpoint")] + public string? AuthorizationEndpoint { get; set; } + + /// URL of the token endpoint. + [JsonProperty("token_endpoint")] + public string? TokenEndpoint { get; set; } + + /// URL of the JSON Web Key Set. + [JsonProperty("jwks_uri")] + public string? JwksUri { get; set; } + + /// URL of the userinfo endpoint. + [JsonProperty("userinfo_endpoint")] + public string? UserinfoEndpoint { get; set; } + + /// URL of the revocation endpoint. + [JsonProperty("revocation_endpoint")] + public string? RevocationEndpoint { get; set; } + + /// List of supported scopes. + [JsonProperty("supported_scopes")] + public List? SupportedScopes { get; set; } + + /// List of supported response types. + [JsonProperty("supported_response_types")] + public List? SupportedResponseTypes { get; set; } + + /// List of supported subject types. + [JsonProperty("supported_subject_types")] + public List? SupportedSubjectTypes { get; set; } + + /// List of supported ID token signing algorithms. + [JsonProperty("supported_id_token_signing_algs")] + public List? SupportedIdTokenSigningAlgs { get; set; } + } +} diff --git a/Gotrue/Responses/OAuth/OAuthClient.cs b/Gotrue/Responses/OAuth/OAuthClient.cs new file mode 100644 index 00000000..fa15717b --- /dev/null +++ b/Gotrue/Responses/OAuth/OAuthClient.cs @@ -0,0 +1,68 @@ +using System; +using Newtonsoft.Json; +using Supabase.Gotrue.OAuth; + +namespace Supabase.Gotrue.Responses.OAuth +{ + /// + /// Represents an Admin OAuth Client. + /// + public class OAuthClient + { + /// Unique identifier for the OAuth client. + [JsonProperty("client_id")] + public string? ClientId { get; set; } + + /// Human-readable name of the OAuth client. + [JsonProperty("client_name")] + public string? ClientName { get; set; } + + /// Client secret (only returned on registration and regeneration). + [JsonProperty("client_secret")] + public string? ClientSecret { get; set; } + + /// Type of OAuth client. + [JsonProperty("client_type")] + public OAuthClientType? ClientType { get; set; } + + /// Token endpoint authentication method. + [JsonProperty("token_endpoint_auth_method")] + public OAuthClientTokenEndpoint? TokenEndpointAuthMethod { get; set; } + + /// Registration type of the client. + [JsonProperty("registration_type")] + public OAuthClientRegistrationType? RegistrationType { get; set; } + + /// URI of the OAuth client. + [JsonProperty("client_uri")] + public string? ClientUri { get; set; } + + /// URI of the OAuth client's logo. + [JsonProperty("logo_uri")] + public string? LogoUri { get; set; } + + /// Array of allowed redirect URIs. + [JsonProperty("redirect_uris")] + public string[]? RedirectUris { get; set; } + + /// Array of allowed grant types. + [JsonProperty("grant_types")] + public OAuthClientGrantType[]? GrantTypes { get; set; } + + /// Array of allowed response types. + [JsonProperty("response_types")] + public OAuthClientResponseType[]? ResponseTypes { get; set; } + + /// Scope of the OAuth client. + [JsonProperty("scope")] + public string? Scope { get; set; } + + /// Timestamp when the client was created. + [JsonProperty("created_at")] + public DateTime? CreatedAt { get; set; } + + /// Timestamp when the client was last updated. + [JsonProperty("updated_at")] + public DateTime? UpdatedAt { get; set; } + } +} diff --git a/Gotrue/Responses/OAuth/OAuthClientRegistrationType.cs b/Gotrue/Responses/OAuth/OAuthClientRegistrationType.cs new file mode 100644 index 00000000..37584c80 --- /dev/null +++ b/Gotrue/Responses/OAuth/OAuthClientRegistrationType.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.Responses.OAuth +{ + /// + /// Represents the registration type of the OAuth client. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OAuthClientRegistrationType + { + [EnumMember(Value = "dynamic")] + Dynamic, + + [EnumMember(Value = "manual")] + Manual, + } +} diff --git a/Gotrue/Responses/OAuth/OAuthClientResponse.cs b/Gotrue/Responses/OAuth/OAuthClientResponse.cs new file mode 100644 index 00000000..3971e3b4 --- /dev/null +++ b/Gotrue/Responses/OAuth/OAuthClientResponse.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Gotrue.Responses.OAuth +{ + /// + /// Represents a response containing a list of OAuth clients. + /// + public class OAuthClientResponse + { + /// Represents a collection of OAuth clients. + [JsonProperty("clients")] + public List Clients { get; set; } = new List(); + } +} diff --git a/Gotrue/Responses/OAuth/OAuthClientResponseType.cs b/Gotrue/Responses/OAuth/OAuthClientResponseType.cs new file mode 100644 index 00000000..69dbc6bd --- /dev/null +++ b/Gotrue/Responses/OAuth/OAuthClientResponseType.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.Responses.OAuth +{ + /// + /// Represents the OAuth response types supported by the client. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OAuthClientResponseType + { + [EnumMember(Value = "code")] + Code, + } +} diff --git a/Gotrue/Responses/OAuth/OAuthClientType.cs b/Gotrue/Responses/OAuth/OAuthClientType.cs new file mode 100644 index 00000000..9aea29ea --- /dev/null +++ b/Gotrue/Responses/OAuth/OAuthClientType.cs @@ -0,0 +1,19 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Supabase.Gotrue.Responses.OAuth +{ + /// + /// Represents the type of OAuth client. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OAuthClientType + { + [EnumMember(Value = "public")] + Public, + + [EnumMember(Value = "confidential")] + Confidential, + } +} diff --git a/Gotrue/Session.cs b/Gotrue/Session.cs index c87b588c..698aa712 100644 --- a/Gotrue/Session.cs +++ b/Gotrue/Session.cs @@ -49,5 +49,11 @@ public class Session [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + /// + /// The timestamp when the access token will expire. Calculated from and . + /// + [JsonIgnore] + public long ExpiresAt => ((DateTimeOffset)CreatedAt).ToUnixTimeSeconds() + ExpiresIn; } } \ No newline at end of file diff --git a/Gotrue/SignInOptions.cs b/Gotrue/SignInOptions.cs index 4223345d..c30169a4 100644 --- a/Gotrue/SignInOptions.cs +++ b/Gotrue/SignInOptions.cs @@ -13,6 +13,11 @@ public class SignInOptions /// public string? RedirectTo { get; set; } + /// + /// Verification token received when the user completes the captcha on the site. + /// + public string? CaptchaToken { get; set; } + /// /// A space-separated list of scopes granted to the OAuth application. /// diff --git a/Gotrue/StatelessClient.cs b/Gotrue/StatelessClient.cs index 129b26d4..5c1f0ba5 100644 --- a/Gotrue/StatelessClient.cs +++ b/Gotrue/StatelessClient.cs @@ -46,7 +46,10 @@ public class StatelessClient : IGotrueStatelessClient var api = GetApi(options); var challengeResponse = await api.Challenge(jwt, new MfaChallengeParams { - FactorId = mfaChallengeAndVerifyParams.FactorId + FactorId = mfaChallengeAndVerifyParams.FactorId, + FriendlyName = mfaChallengeAndVerifyParams.FriendlyName, + Channel = mfaChallengeAndVerifyParams.Channel, + WebAuthn = mfaChallengeAndVerifyParams.WebAuthn }); if (challengeResponse != null) @@ -132,7 +135,7 @@ public class StatelessClient : IGotrueStatelessClient } /// - public IGotrueApi GetApi(StatelessClientOptions options) => new Api(options.Url, options.Headers); + public IGotrueApi GetApi(StatelessClientOptions options) => new Api(options.Url, options.Headers, options.Timeout); /// public Task SignUp(string email, string password, StatelessClientOptions options, SignUpOptions? signUpOptions = null) => SignUp(SignUpType.Email, email, password, options, signUpOptions); @@ -314,9 +317,9 @@ public async Task ResetPasswordForEmail(string email, StatelessClientOptio } /// - public async Task DeleteUser(string uid, string serviceRoleToken, StatelessClientOptions options) + public async Task DeleteUser(string uid, string serviceRoleToken, StatelessClientOptions options, bool softDelete = false) { - var result = await GetApi(options).DeleteUser(uid, serviceRoleToken); + var result = await GetApi(options).DeleteUser(uid, serviceRoleToken, softDelete); result.ResponseMessage?.EnsureSuccessStatusCode(); return true; } @@ -397,6 +400,8 @@ public class StatelessClientOptions /// confirmed emails - mirrors the Gotrue server's configuration. /// public bool AllowUnconfirmedUserSessions { get; set; } + + public int Timeout { get; set; } = 100_000; } } } diff --git a/Gotrue/User.cs b/Gotrue/User.cs index 1e534722..3dfccbff 100644 --- a/Gotrue/User.cs +++ b/Gotrue/User.cs @@ -65,6 +65,9 @@ public class User [JsonProperty("banned_until")] public DateTime? BannedUntil { get; set; } + [JsonProperty("deleted_at")] + public DateTime? DeletedAt { get; set; } + [JsonProperty("is_anonymous")] public bool IsAnonymous { get; set; } @@ -73,6 +76,9 @@ public class User [JsonProperty("user_metadata")] public Dictionary UserMetadata { get; set; } = new Dictionary(); + + [JsonProperty("is_sso_user")] + public bool IsSsoUser { get; set; } } /// @@ -142,6 +148,15 @@ public class UserAttributes [JsonProperty("password")] public string? Password { get; set; } + /// + /// The user's current password + /// + /// This is only ever present when the user is resetting + /// their password and GOTRUE_SECURITY_UPDATE_PASSWORD_REQUIRE_CURRENT_PASSWORD is true. + /// + [JsonProperty("current_password")] + public string? CurrentPassword { get; set; } + [JsonProperty("phone")] public string? Phone { get; set; } diff --git a/GotrueTests/AnonKeyClientFailureTests.cs b/GotrueTests/AnonKeyClientFailureTests.cs index 41335a69..14cbe20b 100644 --- a/GotrueTests/AnonKeyClientFailureTests.cs +++ b/GotrueTests/AnonKeyClientFailureTests.cs @@ -40,7 +40,7 @@ private bool AuthStateIsEmpty() public void TestInitializer() { _persistence = new TestSessionPersistence(); - _client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); + _client = TestUtils.Client(); _client.SetPersistence(_persistence); _client.AddDebugListener(LogDebug); _client.AddStateChangedListener(AuthStateListener); @@ -175,6 +175,18 @@ await ThrowsExceptionAsync(async () => IsNotNull(result); }); } + + [TestMethod("Client: Throws Exception on Timeout occurrence")] + public async Task ClientThrowsExceptionOnTimeout() + { + var user = $"{RandomString(12)}@supabase.io"; + _client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 2}); + + await ThrowsExceptionAsync(async () => + { + await _client.SignIn(user, PASSWORD); + }); + } } } diff --git a/GotrueTests/AnonKeyClientTests.cs b/GotrueTests/AnonKeyClientTests.cs index 02b35239..8ac70f88 100644 --- a/GotrueTests/AnonKeyClientTests.cs +++ b/GotrueTests/AnonKeyClientTests.cs @@ -42,7 +42,7 @@ private bool AuthStateIsEmpty() public void TestInitializer() { _persistence = new TestSessionPersistence(); - _client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); + _client = TestUtils.Client(); _client.SetPersistence(_persistence); _client.AddDebugListener(LogDebug); _client.AddStateChangedListener(AuthStateListener); @@ -56,6 +56,7 @@ private void VerifyGoodSession(Session session) IsNotNull(session.AccessToken); IsNotNull(session.RefreshToken); IsNotNull(session.User); + IsTrue(session.ExpiresAt > ((DateTimeOffset)session.CreatedAt).ToUnixTimeSeconds()); } private void VerifySignedOut() @@ -89,7 +90,7 @@ public async Task SaveAndLoadUser() var newPersistence = new TestSessionPersistence(); newPersistence.SaveSession(session); - IGotrueClient newClient = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); + IGotrueClient newClient = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1"}); newClient.SetPersistence(newPersistence); newClient.AddDebugListener(LogDebug); newClient.AddStateChangedListener(AuthStateListener); @@ -270,10 +271,10 @@ public async Task ClientSendsMagicLoginEmailAlias() public async Task ClientReturnsAuthUrlForProvider() { var result1 = await _client.SignIn(Constants.Provider.Google); - AreEqual("http://localhost:9999/authorize?provider=google", result1.Uri.ToString()); + AreEqual("http://127.0.0.1:54321/auth/v1/authorize?provider=google", result1.Uri.ToString()); var result2 = await _client.SignIn(Constants.Provider.Google, new SignInOptions { Scopes = "special scopes please" }); - AreEqual("http://localhost:9999/authorize?provider=google&scopes=special+scopes+please", result2.Uri.ToString()); + AreEqual("http://127.0.0.1:54321/auth/v1/authorize?provider=google&scopes=special+scopes+please", result2.Uri.ToString()); } [TestMethod("Client: Returns Verification Code for Provider")] @@ -403,7 +404,8 @@ public async Task ClientLinkIdentityPKCE() var result = await _client.LinkIdentity(Constants.Provider.Github, new SignInOptions { - FlowType = Constants.OAuthFlowType.PKCE + FlowType = Constants.OAuthFlowType.PKCE, + RedirectTo = "http://localhost:3000" }); IsFalse(string.IsNullOrEmpty(result.PKCEVerifier)); @@ -481,5 +483,91 @@ public async Task ClientCanSetSession() // As this is being forced to regenerate, the original should be different than the cached. AreNotEqual(refreshToken, _client.CurrentSession.RefreshToken); } + + + [TestMethod("Client: Resend")] + public async Task Resend() + { + var email = $"{RandomString(12)}@supabase.io"; + + var response = await _client.Resend(new ResendParams + { + Email = email, + Type = ResendParams.ResendType.Signup + }); + + IsNotNull(response); + IsTrue(response.ResponseMessage?.IsSuccessStatusCode ?? false); + } + + // [TestMethod("Client: Get Authorization Details")] + // public async Task GetAuthorizationDetails() + // { + // var email = $"ssrdkyzhfijc@supabase.io"; + // var emailSession = await _client.SignIn(email, PASSWORD); + // VerifyGoodSession(emailSession); + // + // var authorizationDetail = await _client.GetAuthorizationDetails("test-authorization-id-012"); + // + // IsNotNull(authorizationDetail); + // AreEqual("test-authorization-id-012", authorizationDetail.AuthorizationId); + // AreEqual(email, authorizationDetail.User.Email); + // _stateChanges.Clear(); + // } + // + // [TestMethod("Client: Approve Authorization")] + // public async Task ApproveAuthorization() + // { + // var email = $"ssrdkyzhfijc@supabase.io"; + // var emailSession = await _client.SignIn(email, PASSWORD); + // VerifyGoodSession(emailSession); + // + // var consentResponse = await _client.ApproveAuthorization("test-authorization-id-013"); + // + // IsNotNull(consentResponse); + // IsNotNull(consentResponse.RedirectUrl); + // _stateChanges.Clear(); + // } + // + // [TestMethod("Client: Deny Authorization")] + // public async Task DenyAuthorization() + // { + // var email = $"ssrdkyzhfijc@supabase.io"; + // var emailSession = await _client.SignIn(email, PASSWORD); + // VerifyGoodSession(emailSession); + // + // var consentResponse = await _client.DenyAuthorization("test-authorization-id-014"); + // + // IsNotNull(consentResponse); + // IsNotNull(consentResponse.RedirectUrl); + // _stateChanges.Clear(); + // } + // + // [TestMethod("Client: List Grants")] + // public async Task ListGrants() + // { + // var email = $"ssrdkyzhfijc@supabase.io"; + // var emailSession = await _client.SignIn(email, PASSWORD); + // VerifyGoodSession(emailSession); + // + // var grantsResponse = await _client.ListGrants(); + // + // IsNotNull(grantsResponse); + // _stateChanges.Clear(); + // } + // + // [TestMethod("Client: Revoke Grant")] + // public async Task RevokeGrant() + // { + // var email = $"ssrdkyzhfijc@supabase.io"; + // var emailSession = await _client.SignIn(email, PASSWORD); + // VerifyGoodSession(emailSession); + // + // var authorizationDetail = await _client.GetAuthorizationDetails("test-authorization-id-012"); + // var grantsResponse = await _client.RevokeGrant(authorizationDetail.Client.Id); + // + // IsTrue(grantsResponse); + // _stateChanges.Clear(); + // } } } \ No newline at end of file diff --git a/GotrueTests/ConfigurationFailureTests.cs b/GotrueTests/ConfigurationFailureTests.cs index 7ab63c0e..ce5f4e58 100644 --- a/GotrueTests/ConfigurationFailureTests.cs +++ b/GotrueTests/ConfigurationFailureTests.cs @@ -36,7 +36,7 @@ public async Task BadUrlTest() [TestMethod("Bad service key message")] public async Task BadServiceApiKeyTest() { - IGotrueAdminClient adminClient = new AdminClient("bad_service_key", new ClientOptions { AllowUnconfirmedUserSessions = true }); + IGotrueAdminClient adminClient = new AdminClient("bad_service_key", new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1"}); AreEqual(true, ((AdminClient)adminClient).Options.AllowUnconfirmedUserSessions); var x = await ThrowsExceptionAsync(async () => @@ -46,5 +46,17 @@ public async Task BadServiceApiKeyTest() AreEqual(AdminTokenRequired, x.Reason); } + + [TestMethod("Timeout error")] + public async Task TimeoutTest() + { + IGotrueAdminClient adminClient = new AdminClient(GenerateServiceRoleToken(), new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 1}); + AreEqual(true, ((AdminClient)adminClient).Options.AllowUnconfirmedUserSessions); + + await ThrowsExceptionAsync(async () => + { + await adminClient.ListUsers(); + }); + } } } diff --git a/GotrueTests/GotrueTests.csproj b/GotrueTests/GotrueTests.csproj index 381f7049..e4384864 100644 --- a/GotrueTests/GotrueTests.csproj +++ b/GotrueTests/GotrueTests.csproj @@ -1,9 +1,13 @@ - net8.0 + net10.0 false + + latest + + enable diff --git a/GotrueTests/MfaClientTests.cs b/GotrueTests/MfaClientTests.cs index 8eb50471..993dfbb2 100644 --- a/GotrueTests/MfaClientTests.cs +++ b/GotrueTests/MfaClientTests.cs @@ -26,8 +26,8 @@ public class MfaClientTests [TestInitialize] public void TestInitializer() { - _client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); - _adminClient = new AdminClient(_serviceKey, new ClientOptions { AllowUnconfirmedUserSessions = true }); + _client = TestUtils.Client(); + _adminClient = TestUtils.AdminClient(); } [TestMethod("MFA: Complete flow")] @@ -51,7 +51,8 @@ public async Task MfaFlow() var challengeResponse = await _client.Challenge(new MfaChallengeParams { - FactorId = enrollResponse.Id + FactorId = enrollResponse.Id, + FriendlyName = "Challenge test" }); IsNotNull(challengeResponse.Id); diff --git a/GotrueTests/NetworkTests.cs b/GotrueTests/NetworkTests.cs index 56c3b591..56d47326 100644 --- a/GotrueTests/NetworkTests.cs +++ b/GotrueTests/NetworkTests.cs @@ -27,7 +27,7 @@ private void AuthStateListener(IGotrueClient sender, Constants.Au [TestMethod("Good Ping Check")] public async Task GoodPingTest() { - var clientOptions = new ClientOptions { AllowUnconfirmedUserSessions = true }; + var clientOptions = new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1"}; var client = new Client(clientOptions); client.Online = false; var status = new NetworkStatus(); @@ -85,7 +85,7 @@ public async Task BadNetworkChecks() [TestMethod("Network Not Available For User Refresh")] public async Task BadTokenRefresh() { - var client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); + var client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1"}); client.AddDebugListener(TestUtils.LogDebug); client.AddStateChangedListener(AuthStateListener); client.Online = true; diff --git a/GotrueTests/ServiceRoleTests.cs b/GotrueTests/ServiceRoleTests.cs index 4c0b8ca7..81bc5e55 100644 --- a/GotrueTests/ServiceRoleTests.cs +++ b/GotrueTests/ServiceRoleTests.cs @@ -2,13 +2,15 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; +using Microsoft.IdentityModel.Tokens; using Microsoft.VisualStudio.TestTools.UnitTesting; using Supabase.Gotrue; -using Supabase.Gotrue.Exceptions; +using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Interfaces; -using static Supabase.Gotrue.Constants; +using Supabase.Gotrue.OAuth; using static GotrueTests.TestUtils; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; +using static Supabase.Gotrue.Constants; namespace GotrueTests { @@ -23,7 +25,7 @@ public class ServiceRoleTests [TestInitialize] public void TestInitializer() { - _client = new AdminClient(_serviceKey, new ClientOptions { AllowUnconfirmedUserSessions = true }); + _client = TestUtils.AdminClient(); } [TestMethod("Service Role: Update User")] @@ -175,6 +177,20 @@ public async Task DeletesUser() IsTrue(result); } + + [TestMethod("Service Role: Soft Delete User")] + public async Task SoftDeletesUser() + { + var email = $"{RandomString(12)}@supabase.io"; + var user = await _client.CreateUser(email, PASSWORD); + var uid = user.Id; + + var result = await _client.DeleteUser(uid ?? throw new InvalidOperationException(), true); + var deletedUser = await _client.GetUserById(uid); + + IsTrue(result); + Assert.IsNotNull(deletedUser.DeletedAt); + } [TestMethod("Nonce generation and verification")] public void NonceGeneration() @@ -274,5 +290,281 @@ public async Task GenerateEmailChangeLink() var result2 = await _client.GenerateLink(options2); AreEqual(result2.VerificationType, "email_change_new"); } - } -} \ No newline at end of file + + [TestMethod("Service Role: Create OAuth Client")] + public async Task CreateOAuthClient() + { + var name = $"Test Client {RandomString(6)}"; + var client = new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + }; + + var createdClient = await _client.CreateOAuthClient(client); + IsNotNull(createdClient); + IsNotNull(createdClient.ClientId); + AreEqual(name, createdClient.ClientName); + IsNotNull(createdClient.ClientSecret); + + await _client.DeleteOAuthClient(createdClient.ClientId); + } + + [TestMethod("Service Role: Get OAuth Client")] + public async Task GetOAuthClient() + { + var name = $"Test Client {RandomString(6)}"; + var createdClient = await _client.CreateOAuthClient( + new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + } + ); + + var fetchedClient = await _client.GetOAuthClient(createdClient.ClientId); + IsNotNull(fetchedClient); + AreEqual(createdClient.ClientId, fetchedClient.ClientId); + AreEqual(name, fetchedClient.ClientName); + + await _client.DeleteOAuthClient(createdClient.ClientId); + } + + [TestMethod("Service Role: List OAuth Clients")] + public async Task ListOAuthClients() + { + var name = $"Test Client {RandomString(6)}"; + var createdClient = await _client.CreateOAuthClient( + new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + } + ); + + var clients = await _client.ListOAuthClients(); + + IsNotNull(clients); + IsTrue(clients.Clients.Exists(c => c.ClientId == createdClient.ClientId)); + + await _client.DeleteOAuthClient(createdClient.ClientId); + } + + [TestMethod("Service Role: Update OAuth Client")] + public async Task UpdateOAuthClient() + { + var name = $"Test Client {RandomString(6)}"; + var createdClient = await _client.CreateOAuthClient( + new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + } + ); + + var newName = $"Updated {name}"; + var updateClient = Supabase.Gotrue.OAuth.UpdateOAuthClient.From(createdClient); + updateClient.ClientName = newName; + + var updatedClient = await _client.UpdateOAuthClient( + createdClient.ClientId, + updateClient + ); + + IsNotNull(updatedClient); + AreEqual(newName, updatedClient.ClientName); + + await _client.DeleteOAuthClient(createdClient.ClientId); + } + + [TestMethod("Service Role: Regenerate OAuth Client Secret")] + public async Task RegenerateOAuthClientSecret() + { + var name = $"Test Client {RandomString(6)}"; + var createdClient = await _client.CreateOAuthClient( + new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + } + ); + + var regeneratedClient = await _client.RegenerateOAuthClientSecret( + createdClient.ClientId + ); + IsNotNull(regeneratedClient); + IsNotNull(regeneratedClient.ClientSecret); + AreNotEqual(createdClient.ClientSecret, regeneratedClient.ClientSecret); + + await _client.DeleteOAuthClient(createdClient.ClientId); + } + + [TestMethod("Service Role: Delete OAuth Client")] + public async Task DeleteOAuthClient() + { + var name = $"Test Client {RandomString(6)}"; + var createdClient = await _client.CreateOAuthClient( + new CreateOAuthClient + { + ClientName = name, + RedirectUrls = ["https://localhost:3000"], + } + ); + + var result = await _client.DeleteOAuthClient(createdClient.ClientId); + IsTrue(result); + + var clients = await _client.ListOAuthClients(); + var results = + clients.Clients.IsNullOrEmpty() + || !clients.Clients.Exists(c => c.ClientId == createdClient.ClientId); + IsTrue(results); + } + + [TestMethod("Service Role: Create Custom Provider")] + public async Task CreateCustomProvider() + { + var name = $"Test Provider {RandomString(6)}"; + var identifier = $"custom:{Guid.NewGuid().ToString("N")}"; + var createdProvider = await _client.CreateCustomProvider( + new CreateCustomProvider + { + Name = name, + ProviderType = CustomProviderType.Oidc, + Identifier = identifier, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = + "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + } + ); + + IsNotNull(createdProvider); + IsNotNull(createdProvider.Id); + AreEqual(name, createdProvider.Name); + AreEqual("oidc", createdProvider.ProviderType); + + await _client.DeleteCustomProvider(createdProvider.Identifier); + } + + [TestMethod("Service Role: Get Custom Provider")] + public async Task GetCustomProvider() + { + var name = $"Test Provider {RandomString(6)}"; + var identifier = $"custom:{Guid.NewGuid().ToString("N")}"; + var createdProvider = await _client.CreateCustomProvider( + new CreateCustomProvider() + { + Name = name, + ProviderType = CustomProviderType.Oidc, + Identifier = identifier, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = + "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + } + ); + + var fetchedProvider = await _client.GetCustomProvider(createdProvider.Identifier); + IsNotNull(fetchedProvider); + AreEqual(createdProvider.Id, fetchedProvider.Id); + AreEqual(name, fetchedProvider.Name); + + await _client.DeleteCustomProvider(createdProvider.Identifier); + + } + + [TestMethod("Service Role: List Custom Providers")] + public async Task ListCustomProviders() + { + var name = $"Test Provider {RandomString(6)}"; + var identifier = $"custom:{Guid.NewGuid().ToString("N")}"; + var createdProvider = await _client.CreateCustomProvider( + new CreateCustomProvider() + { + Name = name, + ProviderType = CustomProviderType.Oidc, + Identifier = identifier, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = + "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + } + ); + + var providers = await _client.ListCustomProviders(); + IsNotNull(providers); + IsTrue(providers.Providers.Exists(p => p.Id == createdProvider.Id)); + + await _client.DeleteCustomProvider(createdProvider.Identifier); + } + + [TestMethod("Service Role: Update Custom Provider")] + public async Task UpdateCustomProvider() + { + var name = $"Test Provider {RandomString(6)}"; + var identifier = $"custom:{Guid.NewGuid().ToString("N")}"; + var createdProvider = await _client.CreateCustomProvider( + new CreateCustomProvider() + { + Name = name, + ProviderType = CustomProviderType.Oidc, + Identifier = identifier, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = + "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + } + ); + + var newName = $"Updated {name}"; + var updateProvider = new UpdateCustomProvider() + { + Name = newName, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + }; + var updatedProvider = await _client.UpdateCustomProvider( + createdProvider.Identifier, + updateProvider + ); + + IsNotNull(updatedProvider); + AreEqual(newName, updatedProvider.Name); + + await _client.DeleteCustomProvider(createdProvider.Identifier); + } + + [TestMethod("Service Role: Delete Custom Provider")] + public async Task DeleteCustomProvider() + { + var name = $"Test Provider {RandomString(6)}"; + var identifier = $"custom:{Guid.NewGuid().ToString("N")}"; + var createdProvider = await _client.CreateCustomProvider( + new CreateCustomProvider() + { + Name = name, + ProviderType = CustomProviderType.Oidc, + Identifier = identifier, + ClientId = "clientid", + ClientSecret = "clientsecret", + Issuer = "https://67vrg.wiremockapi.cloud", + DiscoveryUrl = + "https://67vrg.wiremockapi.cloud/.well-known/openid-configuration", + } + ); + + var result = await _client.DeleteCustomProvider(createdProvider.Identifier); + IsTrue(result); + + var providers = await _client.ListCustomProviders(); + IsFalse(providers.Providers.Exists(p => p.Id == createdProvider.Id)); + } + } +} diff --git a/GotrueTests/StatelessClientTests.cs b/GotrueTests/StatelessClientTests.cs index a0deb8e9..ad511647 100644 --- a/GotrueTests/StatelessClientTests.cs +++ b/GotrueTests/StatelessClientTests.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IdentityModel.Tokens.Jwt; using System.Linq; -using System.Text; using System.Threading.Tasks; -using Microsoft.IdentityModel.Tokens; using Microsoft.VisualStudio.TestTools.UnitTesting; +using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; using Supabase.Gotrue; using Supabase.Gotrue.Exceptions; using Supabase.Gotrue.Interfaces; @@ -27,7 +25,7 @@ public class StatelessClientTests private IGotrueStatelessClient _client; - private static StatelessClientOptions Options { get => new StatelessClientOptions() { AllowUnconfirmedUserSessions = true }; } + private static StatelessClientOptions Options { get => new StatelessClientOptions() { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 5000}; } private static string RandomString(int length) { @@ -45,24 +43,7 @@ private static string GetRandomPhoneNumber() private string GenerateServiceRoleToken() { - var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("37c304f8-51aa-419a-a1af-06154e63707a")); // using GOTRUE_JWT_SECRET - - var tokenDescriptor = new SecurityTokenDescriptor - { - IssuedAt = DateTime.UtcNow, - Expires = DateTime.UtcNow.AddDays(7), - SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature), - Claims = new Dictionary() - { - { - "role", "service_role" - } - } - }; - - var tokenHandler = new JwtSecurityTokenHandler(); - var securityToken = tokenHandler.CreateToken(tokenDescriptor); - return tokenHandler.WriteToken(securityToken); + return TestUtils.GenerateServiceRoleToken(); } @@ -197,10 +178,10 @@ public async Task SendsMagicLoginEmailAlias() public void ReturnsAuthUrlForProvider() { var result1 = _client.SignIn(Provider.Google, Options); - Assert.AreEqual("http://localhost:9999/authorize?provider=google", result1.Uri.ToString()); + Assert.AreEqual("http://127.0.0.1:54321/auth/v1/authorize?provider=google", result1.Uri.ToString()); var result2 = _client.SignIn(Provider.Google, Options, new SignInOptions { Scopes = "special scopes please" }); - Assert.AreEqual("http://localhost:9999/authorize?provider=google&scopes=special+scopes+please", result2.Uri.ToString()); + Assert.AreEqual("http://127.0.0.1:54321/auth/v1/authorize?provider=google&scopes=special+scopes+please", result2.Uri.ToString()); } [TestMethod("StatelessClient: Update user")] @@ -260,8 +241,24 @@ public async Task DeletesUser() var serviceRoleKey = GenerateServiceRoleToken(); var result = await _client.DeleteUser(uid, serviceRoleKey, Options); + + Assert.ThrowsExceptionAsync(async () => await _client.GetUserById(serviceRoleKey, Options, uid)); + Assert.IsTrue(result); + } + + [TestMethod("StatelessClient: Soft Deletes User")] + public async Task SoftDeletesUser() + { + var user = $"{RandomString(12)}@supabase.io"; + var session = await _client.SignUp(user, PASSWORD, Options); + var uid = session.User.Id; + + var serviceRoleKey = GenerateServiceRoleToken(); + var result = await _client.DeleteUser(uid, serviceRoleKey, Options, true); + var deletedUser = await _client.GetUserById(serviceRoleKey, Options, uid); Assert.IsTrue(result); + Assert.IsNotNull(deletedUser.DeletedAt); } [TestMethod("StatelessClient: Sends Reset Password Email")] @@ -444,5 +441,19 @@ public async Task MfaEnroll() factors = await _client.ListFactors(session.AccessToken, Options); Assert.IsTrue(factors.Totp.Count == 0); } + + [TestMethod("StatelessClient: Timeout error")] + public async Task SignsUpUserTimeout() + { + + var client = new StatelessClient(); + var options = new StatelessClientOptions() { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 1}; + var email = $"{RandomString(12)}@supabase.io"; + + await ThrowsExceptionAsync(async () => + { + await client.SignUp(email, PASSWORD, options); + }); + } } } diff --git a/GotrueTests/TestUtils.cs b/GotrueTests/TestUtils.cs index f1b40dbd..17044cfd 100644 --- a/GotrueTests/TestUtils.cs +++ b/GotrueTests/TestUtils.cs @@ -2,9 +2,13 @@ using System.Collections.Generic; using System.Diagnostics; using System.IdentityModel.Tokens.Jwt; +using System.IO; using System.Linq; -using System.Text; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text.Json; using Microsoft.IdentityModel.Tokens; +using Supabase.Gotrue; namespace GotrueTests { @@ -14,6 +18,10 @@ public static class TestUtils public const string PASSWORD = "I@M@SuperP@ssWord"; + public static Client Client() => new(new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 10000}); + + public static AdminClient AdminClient() => new(GenerateServiceRoleToken(), new ClientOptions { AllowUnconfirmedUserSessions = true, Url = "http://127.0.0.1:54321/auth/v1", Timeout = 10000}); + public static void LogDebug(string message, Exception e) { Debug.WriteLine(message); @@ -46,9 +54,26 @@ public static int RandomNumber(int minValue = 0, int maxValue = 1000) return Random.Next(minValue, maxValue); } + // public static string GenerateServiceRoleToken() + // { + // var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("37c304f8-51aa-419a-a1af-06154e63707a")); // using GOTRUE_JWT_SECRET + + // var tokenDescriptor = new SecurityTokenDescriptor + // { + // IssuedAt = DateTime.UtcNow, + // Expires = DateTime.UtcNow.AddDays(7), + // SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature), + // Claims = new Dictionary() { { "role", "service_role" } } + // }; + + // var tokenHandler = new JwtSecurityTokenHandler(); + // var securityToken = tokenHandler.CreateToken(tokenDescriptor); + // return tokenHandler.WriteToken(securityToken); + // } + public static string GenerateServiceRoleToken() { - var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("37c304f8-51aa-419a-a1af-06154e63707a")); // using GOTRUE_JWT_SECRET + var signingKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("super-secret-jwt-token-with-at-least-32-characters-long")); var tokenDescriptor = new SecurityTokenDescriptor { @@ -63,5 +88,85 @@ public static string GenerateServiceRoleToken() return tokenHandler.WriteToken(securityToken); } + + private static string GetRepoRoot() + { + // Start from where the process is running and walk upwards until we find the solution file + for (var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); dir != null; dir = dir.Parent) + { + if (File.Exists(Path.Combine(dir.FullName, "Supabase.Gotrue.sln"))) + return dir.FullName; + } + + // Fallback: start from the assembly location + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent) + { + if (File.Exists(Path.Combine(dir.FullName, "Supabase.Gotrue.sln"))) + return dir.FullName; + } + + throw new InvalidOperationException("Repo root not found (Supabase.Gotrue.sln missing in parent chain)."); + } + + private static string GetJwkJson() + { + var path = Path.Combine(GetRepoRoot(), "supabase", "signing_keys.json"); + + return File.ReadAllText(path); + } + + private static ECDsaSecurityKey CreateEcdsaSecurityKeyFromJwksJson(string jwksJson) + { + using var doc = JsonDocument.Parse(jwksJson); + + if (doc.RootElement.ValueKind != JsonValueKind.Array || doc.RootElement.GetArrayLength() < 1) + throw new InvalidOperationException("JWKS JSON must be an array with at least one JWK object."); + + var jwk = doc.RootElement[0]; + + var kty = jwk.GetProperty("kty").GetString(); + var crv = jwk.GetProperty("crv").GetString(); + var alg = jwk.TryGetProperty("alg", out var algProp) ? algProp.GetString() : null; + + if (!string.Equals(kty, "EC", StringComparison.OrdinalIgnoreCase)) + throw new NotSupportedException($"Unsupported kty '{kty}'. Expected 'EC'."); + + if (!string.Equals(crv, "P-256", StringComparison.OrdinalIgnoreCase)) + throw new NotSupportedException($"Unsupported crv '{crv}'. Expected 'P-256' for ES256."); + + if (alg is not null && !string.Equals(alg, "ES256", StringComparison.OrdinalIgnoreCase)) + throw new NotSupportedException($"JWK alg is '{alg}', but this code expects 'ES256'."); + + var x = Base64UrlDecode(jwk.GetProperty("x").GetString() ?? throw new InvalidOperationException("Missing JWK 'x'.")); + var y = Base64UrlDecode(jwk.GetProperty("y").GetString() ?? throw new InvalidOperationException("Missing JWK 'y'.")); + var d = Base64UrlDecode(jwk.GetProperty("d").GetString() ?? throw new InvalidOperationException("Missing JWK 'd' (private key).")); + + var kid = jwk.TryGetProperty("kid", out var kidProp) ? kidProp.GetString() : null; + if (string.IsNullOrWhiteSpace(kid)) + throw new InvalidOperationException("Missing JWK 'kid'."); + + var ecParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = new ECPoint { X = x, Y = y }, + D = d + }; + + var ecdsa = ECDsa.Create(ecParams); + return new ECDsaSecurityKey(ecdsa) { KeyId = kid }; + } + + private static byte[] Base64UrlDecode(string input) + { + string s = input.Replace('-', '+').Replace('_', '/'); + switch (s.Length % 4) + { + case 2: s += "=="; break; + case 3: s += "="; break; + case 0: break; + default: throw new FormatException("Invalid base64url string length."); + } + return Convert.FromBase64String(s); + } } } diff --git a/supabase/.gitignore b/supabase/.gitignore new file mode 100644 index 00000000..ad9264f0 --- /dev/null +++ b/supabase/.gitignore @@ -0,0 +1,8 @@ +# Supabase +.branches +.temp + +# dotenvx +.env.keys +.env.local +.env.*.local diff --git a/supabase/config.toml b/supabase/config.toml new file mode 100644 index 00000000..e4497509 --- /dev/null +++ b/supabase/config.toml @@ -0,0 +1,386 @@ +# For detailed configuration reference documentation, visit: +# https://supabase.com/docs/guides/local-development/cli/config +# A string used to distinguish different Supabase projects on the same host. Defaults to the +# working directory name when running `supabase init`. +project_id = "supabase-csharp" + +[api] +enabled = true +# Port to use for the API URL. +port = 54321 +# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API +# endpoints. `public` and `graphql_public` schemas are included by default. +schemas = ["public", "graphql_public"] +# Extra schemas to add to the search_path of every request. +extra_search_path = ["public", "extensions"] +# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size +# for accidental or malicious requests. +max_rows = 1000 + +[api.tls] +# Enable HTTPS endpoints locally using a self-signed certificate. +enabled = false +# Paths to self-signed certificate pair. +# cert_path = "../certs/my-cert.pem" +# key_path = "../certs/my-key.pem" + +[db] +# Port to use for the local database URL. +port = 54322 +# Port used by db diff command to initialize the shadow database. +shadow_port = 54320 +# Maximum amount of time to wait for health check when starting the local database. +health_timeout = "2m" +# The database major version to use. This has to be the same as your remote database's. Run `SHOW +# server_version;` on the remote database to check. +major_version = 17 + +[db.pooler] +enabled = false +# Port to use for the local connection pooler. +port = 54329 +# Specifies when a server connection can be reused by other clients. +# Configure one of the supported pooler modes: `transaction`, `session`. +pool_mode = "transaction" +# How many server connections to allow per user/database pair. +default_pool_size = 20 +# Maximum number of client connections allowed. +max_client_conn = 100 + +# [db.vault] +# secret_key = "env(SECRET_VALUE)" + +[db.migrations] +# If disabled, migrations will be skipped during a db push or reset. +enabled = true +# Specifies an ordered list of schema files that describe your database. +# Supports glob patterns relative to supabase directory: "./schemas/*.sql" +schema_paths = [] + +[db.seed] +# If enabled, seeds the database after migrations during a db reset. +enabled = true +# Specifies an ordered list of seed files to load during db reset. +# Supports glob patterns relative to supabase directory: "./seeds/*.sql" +sql_paths = ["./seed.sql"] + +[db.network_restrictions] +# Enable management of network restrictions. +enabled = false +# List of IPv4 CIDR blocks allowed to connect to the database. +# Defaults to allow all IPv4 connections. Set empty array to block all IPs. +allowed_cidrs = ["0.0.0.0/0"] +# List of IPv6 CIDR blocks allowed to connect to the database. +# Defaults to allow all IPv6 connections. Set empty array to block all IPs. +allowed_cidrs_v6 = ["::/0"] + +[realtime] +enabled = false +# Bind realtime via either IPv4 or IPv6. (default: IPv4) +# ip_version = "IPv6" +# The maximum length in bytes of HTTP request headers. (default: 4096) +# max_header_length = 4096 + +[studio] +enabled = true +# Port to use for Supabase Studio. +port = 54323 +# External URL of the API server that frontend connects to. +api_url = "http://127.0.0.1" +# OpenAI API Key to use for Supabase AI in the Supabase Studio. +openai_api_key = "env(OPENAI_API_KEY)" + +# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they +# are monitored, and you can view the emails that would have been sent from the web interface. +[inbucket] +enabled = true +# Port to use for the email testing server web interface. +port = 54324 +# Uncomment to expose additional ports for testing user applications that send emails. +# smtp_port = 54325 +# pop3_port = 54326 +# admin_email = "admin@email.com" +# sender_name = "Admin" + +[storage] +enabled = false +# The maximum file size allowed (e.g. "5MB", "500KB"). +file_size_limit = "50MiB" + +# Uncomment to configure local storage buckets +# [storage.buckets.images] +# public = false +# file_size_limit = "50MiB" +# allowed_mime_types = ["image/png", "image/jpeg"] +# objects_path = "./images" + +# Allow connections via S3 compatible clients +[storage.s3_protocol] +enabled = true + +# Image transformation API is available to Supabase Pro plan. +# [storage.image_transformation] +# enabled = true + +# Store analytical data in S3 for running ETL jobs over Iceberg Catalog +# This feature is only available on the hosted platform. +[storage.analytics] +enabled = false +max_namespaces = 5 +max_tables = 10 +max_catalogs = 2 + +# Analytics Buckets is available to Supabase Pro plan. +# [storage.analytics.buckets.my-warehouse] + +# Store vector embeddings in S3 for large and durable datasets +# This feature is only available on the hosted platform. +[storage.vector] +enabled = false +max_buckets = 10 +max_indexes = 5 + +# Vector Buckets is available to Supabase Pro plan. +# [storage.vector.buckets.documents-openai] + +[auth] +enabled = true +# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used +# in emails. +site_url = "http://127.0.0.1:3000" +# A list of *exact* URLs that auth providers are permitted to redirect to post authentication. +additional_redirect_urls = ["https://127.0.0.1:3000"] +# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). +jwt_expiry = 3600 +# JWT issuer URL. If not set, defaults to the local API URL (http://127.0.0.1:/auth/v1). +# jwt_issuer = "" +# Path to JWT signing key. DO NOT commit your signing keys file to git. +signing_keys_path = "./signing_keys.json" +# If disabled, the refresh token will never expire. +enable_refresh_token_rotation = true +# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. +# Requires enable_refresh_token_rotation = true. +refresh_token_reuse_interval = 10 +# Allow/disallow new user signups to your project. +enable_signup = true +# Allow/disallow anonymous sign-ins to your project. +enable_anonymous_sign_ins = true +# Allow/disallow testing manual linking of accounts +enable_manual_linking = true +# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more. +minimum_password_length = 6 +# Passwords that do not meet the following requirements will be rejected as weak. Supported values +# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols` +password_requirements = "" + +[auth.rate_limit] +# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled. +email_sent = 2 +# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled. +sms_sent = 30 +# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true. +anonymous_users = 30 +# Number of sessions that can be refreshed in a 5 minute interval per IP address. +token_refresh = 150 +# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users). +sign_in_sign_ups = 30 +# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address. +token_verifications = 30 +# Number of Web3 logins that can be made in a 5 minute interval per IP address. +web3 = 30 + +# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`. +# [auth.captcha] +# enabled = true +# provider = "hcaptcha" +# secret = "" + +[auth.email] +# Allow/disallow new user signups via email to your project. +enable_signup = true +# If enabled, a user will be required to confirm any email change on both the old, and new email +# addresses. If disabled, only the new email is required to confirm. +double_confirm_changes = true +# If enabled, users need to confirm their email address before signing in. +enable_confirmations = false +# If enabled, users will need to reauthenticate or have logged in recently to change their password. +secure_password_change = false +# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. +max_frequency = "1s" +# Number of characters used in the email OTP. +otp_length = 6 +# Number of seconds before the email OTP expires (defaults to 1 hour). +otp_expiry = 3600 + +# Use a production-ready SMTP server +# [auth.email.smtp] +# enabled = true +# host = "smtp.sendgrid.net" +# port = 587 +# user = "apikey" +# pass = "env(SENDGRID_API_KEY)" +# admin_email = "admin@email.com" +# sender_name = "Admin" + +# Uncomment to customize email template +# [auth.email.template.invite] +# subject = "You have been invited" +# content_path = "./supabase/templates/invite.html" + +# Uncomment to customize notification email template +# [auth.email.notification.password_changed] +# enabled = true +# subject = "Your password has been changed" +# content_path = "./templates/password_changed_notification.html" + +[auth.sms] +# Allow/disallow new user signups via SMS to your project. +enable_signup = true +# If enabled, users need to confirm their phone number before signing in. +enable_confirmations = false +# Template for sending OTP to users +#template = "Your code is {{ .Code }}" +template = "12345" +# Controls the minimum amount of time that must pass before sending another sms otp. +max_frequency = "5s" + +# Use pre-defined map of phone number to OTP for testing. +# [auth.sms.test_otp] +# 4152127777 = "123456" + +# Configure logged in session timeouts. +# [auth.sessions] +# Force log out after the specified duration. +# timebox = "24h" +# Force log out if the user has been inactive longer than the specified duration. +# inactivity_timeout = "8h" + +# This hook runs before a new user is created and allows developers to reject the request based on the incoming user object. +# [auth.hook.before_user_created] +# enabled = true +# uri = "pg-functions://postgres/auth/before-user-created-hook" + +# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. +# [auth.hook.custom_access_token] +# enabled = true +# uri = "pg-functions:////" + +# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. +[auth.sms.twilio] +enabled = true +account_sid = "empty" +message_service_sid = "empty" +# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +# Multi-factor-authentication is available to Supabase Pro plan. +[auth.mfa] +# Control how many MFA factors can be enrolled at once per user. +max_enrolled_factors = 10 + +# Control MFA via App Authenticator (TOTP) +[auth.mfa.totp] +enroll_enabled = true +verify_enabled = true + +# Configure MFA via Phone Messaging +[auth.mfa.phone] +enroll_enabled = false +verify_enabled = false +otp_length = 6 +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +# Configure MFA via WebAuthn +# [auth.mfa.web_authn] +# enroll_enabled = true +# verify_enabled = true + +# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, +# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, +# `twitter`, `x`, `slack`, `spotify`, `workos`, `zoom`. +# [auth.external.apple] +[auth.external.github] +enabled = true +client_id = "empty" +# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +# Overrides the default auth redirectUrl. +redirect_uri = "" +# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, +# or any other third-party OIDC providers. +url = "" +# If enabled, the nonce check will be skipped. Required for local sign in with Google auth. +skip_nonce_check = false +# If enabled, it will allow the user to successfully authenticate when the provider does not return an email address. +email_optional = false + +# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard. +# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting. +[auth.web3.solana] +enabled = false + +# Use Firebase Auth as a third-party provider alongside Supabase Auth. +[auth.third_party.firebase] +enabled = false +# project_id = "my-firebase-project" + +# Use Auth0 as a third-party provider alongside Supabase Auth. +[auth.third_party.auth0] +enabled = false +# tenant = "my-auth0-tenant" +# tenant_region = "us" + +# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth. +[auth.third_party.aws_cognito] +enabled = false +# user_pool_id = "my-user-pool-id" +# user_pool_region = "us-east-1" + +# Use Clerk as a third-party provider alongside Supabase Auth. +[auth.third_party.clerk] +enabled = false +# Obtain from https://clerk.com/setup/supabase +# domain = "example.clerk.accounts.dev" + +# OAuth server configuration +[auth.oauth_server] +# Enable OAuth server functionality +enabled = true +# Path for OAuth consent flow UI +authorization_url_path = "/oauth/consent" +# Allow dynamic client registration +allow_dynamic_registration = false + +[edge_runtime] +enabled = false +# Supported request policies: `oneshot`, `per_worker`. +# `per_worker` (default) — enables hot reload during local development. +# `oneshot` — fallback mode if hot reload causes issues (e.g. in large repos or with symlinks). +policy = "per_worker" +# Port to attach the Chrome inspector for debugging edge functions. +inspector_port = 8083 +# The Deno major version to use. +deno_version = 2 + +# [edge_runtime.secrets] +# secret_key = "env(SECRET_VALUE)" + +[analytics] +enabled = false +port = 54327 +# Configure one of the supported backends: `postgres`, `bigquery`. +backend = "postgres" + +# Experimental features may be deprecated any time +[experimental] +# Configures Postgres storage engine to use OrioleDB (S3) +orioledb_version = "" +# Configures S3 bucket URL, eg. .s3-.amazonaws.com +s3_host = "env(S3_HOST)" +# Configures S3 bucket region, eg. us-east-1 +s3_region = "env(S3_REGION)" +# Configures AWS_ACCESS_KEY_ID for S3 bucket +s3_access_key = "env(S3_ACCESS_KEY)" +# Configures AWS_SECRET_ACCESS_KEY for S3 bucket +s3_secret_key = "env(S3_SECRET_KEY)" diff --git a/supabase/generate_signing_key.py b/supabase/generate_signing_key.py new file mode 100644 index 00000000..ba315183 --- /dev/null +++ b/supabase/generate_signing_key.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import base64 +import json +import uuid +from pathlib import Path + +from cryptography.hazmat.primitives.asymmetric import ec + + +def base64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def find_solution_dir(start: Path | None = None) -> Path: + start = (start or Path.cwd()).resolve() + + for path in [start, *start.parents]: + if any(path.glob("*.sln")): + return path + + raise FileNotFoundError("Could not find a .sln file in the current directory tree.") + + +def main() -> None: + solution_dir = find_solution_dir() + output_dir = solution_dir / "supabase" + output_dir.mkdir(parents=True, exist_ok=True) + + private_key = ec.generate_private_key(ec.SECP256R1()) + numbers = private_key.private_numbers() + public_numbers = numbers.public_numbers + + # Convert integers to fixed 32-byte values for P-256 + d = numbers.private_value.to_bytes(32, "big") + x = public_numbers.x.to_bytes(32, "big") + y = public_numbers.y.to_bytes(32, "big") + + jwk = { + "kty": "EC", + "kid": str(uuid.uuid4()), + "use": "sig", + "key_ops": ["sign", "verify"], + "alg": "ES256", + "ext": True, + "d": base64url(d), + "crv": "P-256", + "x": base64url(x), + "y": base64url(y), + } + + output_path = output_dir / "signing_keys.json" + output_path.write_text(json.dumps([jwk], indent=2) + "\n", encoding="utf-8") + + print(f"Saved to: {output_path}") + + +if __name__ == "__main__": + main() diff --git a/supabase/signing_keys.json b/supabase/signing_keys.json new file mode 100644 index 00000000..cb44e10e --- /dev/null +++ b/supabase/signing_keys.json @@ -0,0 +1,17 @@ +[ + { + "kty": "EC", + "kid": "5ad71f76-a965-40fd-93b3-9607b7133bb6", + "use": "sig", + "key_ops": [ + "sign", + "verify" + ], + "alg": "ES256", + "ext": true, + "d": "Q6fdlSPbby5Mbx6VSyUMWm3CZlpnAmcr9048BNRY8-Y", + "crv": "P-256", + "x": "W3ov8UejVn2s9mU3VVDYxNRvgln3bRlg4VsvuBk_OHU", + "y": "-8uyb2ns07nx7AgU7Dc9d1D14pE3DcE4B_Efj1pGcxw" + } +] diff --git a/supabase/snippets/Untitled query 738.sql b/supabase/snippets/Untitled query 738.sql new file mode 100644 index 00000000..b1d08a51 --- /dev/null +++ b/supabase/snippets/Untitled query 738.sql @@ -0,0 +1,167 @@ +delete from auth.oauth_consents +where client_id in ( + '11111111-1111-1111-1111-111111111111', + '33333333-3333-3333-3333-333333333333', + '55555555-5555-5555-5555-555555555555', + '99999999-9999-9999-9999-999999999999', + 'aaaaaaaa-0000-0000-0000-000000000000' +); + +delete from auth.oauth_authorizations +where authorization_id in ( + 'test-authorization-id', + 'test-authorization-id-002', + 'test-authorization-id-003', + 'test-authorization-id-004', + 'test-authorization-id-005', + 'test-authorization-id-006', + 'test-authorization-id-007', + 'test-authorization-id-008', + 'test-authorization-id-009', + 'test-authorization-id-010', + 'test-authorization-id-011' +); + +delete from auth.oauth_authorizations +where client_id in ( + '11111111-1111-1111-1111-111111111111', + '33333333-3333-3333-3333-333333333333', + '55555555-5555-5555-5555-555555555555', + '99999999-9999-9999-9999-999999999999', + 'aaaaaaaa-0000-0000-0000-000000000000' +); + +delete from auth.oauth_clients +where id in ( + '11111111-1111-1111-1111-111111111111', + '33333333-3333-3333-3333-333333333333', + '55555555-5555-5555-5555-555555555555', + '99999999-9999-9999-9999-999999999999', + 'aaaaaaaa-0000-0000-0000-000000000000' +); + +insert into auth.oauth_clients ( + id, + client_secret_hash, + registration_type, + redirect_uris, + grant_types, + client_name, + client_uri, + logo_uri, + client_type, + token_endpoint_auth_method, + created_at, + updated_at, + deleted_at +) +values ( + 'aaaaaaaa-0000-0000-0000-000000000000', + 'mock-secret-hash-009', + 'dynamic', + 'http://localhost:3000/callback', + 'authorization_code,refresh_token', + 'Mock OAuth Client 009', + 'http://localhost:3000', + 'http://localhost:3000/logo.png', + 'confidential', + 'client_secret_post', + now(), + now(), + null +); + +insert into auth.oauth_authorizations ( + id, + authorization_id, + client_id, + user_id, + redirect_uri, + scope, + state, + resource, + code_challenge, + code_challenge_method, + response_type, + status, + authorization_code, + created_at, + expires_at, + approved_at, + nonce +) +values +( + 'aaaaaaaa-1111-1111-1111-111111111111', + 'test-authorization-id-009', + 'aaaaaaaa-0000-0000-0000-000000000000', + '8860434d-6126-4238-b18f-f0ddb615e19e', + 'http://localhost:3000/callback', + 'openid email profile', + 'test-state-009', + null, + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + 's256', + 'code', + 'pending', + null, + now(), + now() + interval '30 minutes', + null, + 'test-nonce-009' +), +( + 'aaaaaaaa-2222-2222-2222-222222222222', + 'test-authorization-id-010', + 'aaaaaaaa-0000-0000-0000-000000000000', + '8860434d-6126-4238-b18f-f0ddb615e19e', + 'http://localhost:3000/callback', + 'openid email profile', + 'test-state-010', + null, + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + 's256', + 'code', + 'pending', + null, + now(), + now() + interval '30 minutes', + null, + 'test-nonce-010' +), +( + 'aaaaaaaa-3333-3333-3333-333333333333', + 'test-authorization-id-011', + 'aaaaaaaa-0000-0000-0000-000000000000', + '8860434d-6126-4238-b18f-f0ddb615e19e', + 'http://localhost:3000/callback', + 'openid email profile', + 'test-state-011', + null, + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + 's256', + 'code', + 'pending', + null, + now(), + now() + interval '30 minutes', + null, + 'test-nonce-011' +); + +insert into auth.oauth_consents ( + id, + user_id, + client_id, + scopes, + granted_at, + revoked_at +) +values ( + 'aaaaaaaa-4444-4444-4444-444444444444', + '8860434d-6126-4238-b18f-f0ddb615e19e', + 'aaaaaaaa-0000-0000-0000-000000000000', + 'openid email profile', + now(), + null +); \ No newline at end of file