Skip to content

From upstream: imporve oauth provider UI/UX (#2983) - #3

Merged
lonely-4 merged 12 commits into
AmethystDev-Labs:mainfrom
QuantumNous:main
Feb 22, 2026
Merged

From upstream: imporve oauth provider UI/UX (#2983)#3
lonely-4 merged 12 commits into
AmethystDev-Labs:mainfrom
QuantumNous:main

Conversation

@lonely-4

Copy link
Copy Markdown
Member
  • feat: imporve UI/UX

  • fix: stabilize provider enabled toggle and polish custom OAuth settings UX

  • fix: add access policy/message templates and persist advanced fields reliably

  • fix: move template fill actions below fields and keep advanced form flow cleaner

seefs001 and others added 9 commits February 22, 2026 15:41
* feat: imporve UI/UX

* fix: stabilize provider enabled toggle and polish custom OAuth settings UX

* fix: add access policy/message templates and persist advanced fields reliably

* fix: move template fill actions below fields and keep advanced form flow cleaner
…service layer

Restructure the task relay system for better separation of concerns:
- Extract task billing into service/task_billing.go with unified settlement flow
- Move task polling loop from controller to service/task_polling.go (supports Suno + video platforms)
- Split RelayTask into fetch/submit paths with dedicated retry logic (taskSubmitWithRetry)
- Add TaskDto, TaskResponse generics, and FetchReq to dto/task.go
- Add taskcommon/helpers.go for shared task adaptor utilities
- Remove controller/task_video.go (logic consolidated into service layer)
- Update all task adaptors (ali, doubao, gemini, hailuo, jimeng, kling, sora, suno, vertex, vidu)
- Simplify frontend task logs to use new TaskDto response format
Add three billing lifecycle methods to the TaskAdaptor interface:
- EstimateBilling: compute OtherRatios from user request before pricing
- AdjustBillingOnSubmit: adjust ratios from upstream submit response
- AdjustBillingOnComplete: determine final quota at task terminal state

Introduce BaseBilling as embeddable no-op default for adaptors without
custom billing. Move Sora/Ali OtherRatios logic from shared validation
into per-adaptor EstimateBilling implementations.

Add TaskBillingContext to persist pricing params (model_price, group_ratio,
other_ratios) in task private data for async polling settlement.

Extract RecalculateTaskQuota as a general-purpose delta settlement
function and unify polling billing via settleTaskBillingOnComplete
(adaptor-first, then token-based fallback).
- Renamed RelayTask function to RelayTaskFetch for clarity.
- Updated routing in relay-router.go and video-router.go to use RelayTaskFetch for fetch operations.
- Enhanced error handling in RelayTaskFetch function.
- Adjusted task data conversion in TaskAdaptor to include task ID.
- Updated the remix handling in ResolveOriginTask to prioritize extracting OtherRatios from the BillingContext of the original task if available.
- Retained the previous logic for extracting seconds and size from task data as a fallback.
- Improved clarity and maintainability of the remix logic by separating the new and old approaches.
- Enhanced the RelayTask function to utilize a locked channel when available, allowing for better reuse during retries.
- Updated error handling to ensure proper context setup for the selected channel.
- Clarified comments in ResolveOriginTask regarding channel locking and retry behavior.
- Introduced a new field in TaskRelayInfo to store the locked channel object, improving type safety and reducing import cycles.
… conflicts

Replace all bare task.Update() (DB.Save) calls with UpdateWithStatus(),
which adds a WHERE status = ? guard to prevent concurrent processes from
overwriting each other's state transitions.

Key changes:

model/task.go:
- Add taskSnapshot struct with Equal() method for change detection
- Add Snapshot() method to capture pre-update state
- Add UpdateWithStatus(fromStatus) using DB.Where().Save() for CAS
  semantics with full-struct save (no explicit field listing needed)

model/midjourney.go:
- Add UpdateWithStatus(fromStatus string) with same CAS pattern

service/task_polling.go (updateVideoSingleTask):
- Snapshot before processing upstream response; skip DB write if unchanged
- Terminal transitions (SUCCESS/FAILURE) use UpdateWithStatus CAS:
  billing/refund only executes if this process wins the transition
- Non-terminal updates also use UpdateWithStatus to prevent overwriting
  a concurrent terminal transition back to IN_PROGRESS
- Defer settleTaskBillingOnComplete to after CAS check (shouldSettle flag)

relay/relay_task.go (tryRealtimeFetch):
- Add snapshot + change detection; use UpdateWithStatus for CAS safety

controller/midjourney.go (UpdateMidjourneyTaskBulk):
- Capture preStatus before mutations; use UpdateWithStatus CAS
- Gate refund (IncreaseUserQuota) on CAS success (won && shouldReturnQuota)

This prevents the multi-instance race condition where:
1. Instance A reads task (IN_PROGRESS), fetches upstream (still IN_PROGRESS)
2. Instance B reads same task, fetches upstream (now SUCCESS), writes SUCCESS
3. Instance A's bare Save() overwrites SUCCESS back to IN_PROGRESS
…gration tests

- Updated UpdateWithStatus method to use Model().Select("*").Updates() for conditional updates, preventing GORM's INSERT fallback.
- Introduced comprehensive integration tests for UpdateWithStatus, covering scenarios for winning and losing CAS updates, as well as concurrent updates.
- Added task_cas_test.go to validate the new behavior and ensure data integrity during concurrent state transitions.
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @Starry-Sky-World, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the custom OAuth provider functionality by introducing advanced access control policies, improving the configuration user experience, and adding support for OIDC Discovery. Users can now define granular access rules based on user information and customize denial messages. The UI for managing custom OAuth providers has been refined, including automatic endpoint discovery and better organization of advanced settings.

Highlights

  • Enhanced Custom OAuth Provider Management: Introduced new fields for custom OAuth providers including Icon, AccessPolicy, and AccessDeniedMessage to support richer configuration and user experience.
  • OIDC Discovery Integration: Added functionality to fetch and automatically populate OAuth provider settings from an OIDC Discovery endpoint, simplifying setup for administrators.
  • Granular Access Control Policies: Implemented a robust access policy mechanism allowing administrators to define JSON-based rules for user access based on information retrieved from the OAuth provider, along with customizable denial messages.
  • Improved UI/UX for Custom OAuth Settings: Refined the custom OAuth settings interface with a more intuitive layout, including a toggle for enabling/disabling providers, a preview for icons, and template suggestions for access policies and denial messages.
  • Dynamic OAuth Provider Icons: Integrated dynamic icon rendering for custom OAuth providers across login, registration, and account management pages, supporting react-icons/si keys, image URLs, and emojis.
Changelog
  • controller/custom_oauth.go
    • Added context, io, net/url, strings, time imports.
    • Included Icon, AccessPolicy, and AccessDeniedMessage fields in CustomOAuthProviderResponse, CreateCustomOAuthProviderRequest, and UpdateCustomOAuthProviderRequest structs.
    • Implemented FetchCustomOAuthDiscovery function to retrieve OIDC discovery documents.
    • Updated CreateCustomOAuthProvider and UpdateCustomOAuthProvider to handle new fields.
    • Added ProviderIcon to GetUserOAuthBindings response.
  • controller/misc.go
    • Added Id and Icon fields to CustomOAuthInfo struct for status endpoint.
  • controller/oauth.go
    • Corrected indentation for user update fields in findOrCreateOAuthUser.
    • Added handling for AccessDeniedError in handleOAuthError.
  • model/custom_oauth_provider.go
    • Added fmt and github.com/QuantumNous/new-api/common imports.
    • Defined accessPolicyPayload and accessConditionItem structs for access control.
    • Added supportedAccessPolicyOps map for policy validation.
    • Included Icon, AccessPolicy, and AccessDeniedMessage fields in CustomOAuthProvider model.
    • Implemented validation logic for AccessPolicy JSON structure and its conditions in validateCustomOAuthProvider and validateAccessPolicyPayload.
  • oauth/generic.go
    • Added stdjson, errors, regexp, strconv, github.com/QuantumNous/new-api/common, and github.com/samber/lo imports.
    • Defined accessPolicy, accessCondition, and accessPolicyFailure structs for runtime policy evaluation.
    • Added supportedAccessPolicyOps slice.
    • Changed json.Unmarshal to common.Unmarshal for token response parsing.
    • Implemented access policy evaluation logic in GetUserInfo function.
    • Added Extra field to OAuthUser to store provider slug.
    • Implemented helper functions: parseAccessPolicy, validateAccessPolicy, validateAccessCondition, evaluateAccessPolicy, evaluateAccessCondition, normalizePolicyOp, gjsonResultToValue, compareAny, toFloat, valueInSlice, containsValue, and renderAccessDeniedMessage.
  • oauth/types.go
    • Added AccessDeniedError struct for custom access denial messages.
  • router/api-router.go
    • Added POST /api/custom-oauth-provider/discovery route, restricted to root users.
  • web/src/components/auth/LoginForm.jsx
    • Imported getOAuthProviderIcon helper.
    • Introduced hasCustomOAuthProviders and hasOAuthLoginOptions constants.
    • Updated custom OAuth button to display provider icon using getOAuthProviderIcon.
    • Simplified conditional rendering for OAuth login options.
  • web/src/components/auth/RegisterForm.jsx
    • Imported getOAuthProviderIcon and onCustomOAuthClicked helpers.
    • Added customOAuthLoading state for custom OAuth buttons.
    • Implemented handleCustomOAuthClick function.
    • Introduced hasCustomOAuthProviders and hasOAuthRegisterOptions constants.
    • Rendered custom OAuth providers in the registration form with dynamic icons.
    • Simplified conditional rendering for OAuth registration options.
  • web/src/components/settings/CustomOAuthSetting.jsx
    • Imported Collapse, Switch, IconRefresh from @douyinfe/semi-ui and getOAuthProviderIcon helper.
    • Defined OAUTH_PRESET_ICONS, PRESET_RESET_VALUES, DISCOVERY_FIELD_LABELS, ACCESS_POLICY_TEMPLATES, and ACCESS_DENIED_TEMPLATES constants.
    • Refactored state management with mergeFormValues, getLatestFormValues, normalizeBaseUrl, inferBaseUrlFromProvider, resetDiscoveryState, and closeModal.
    • Enhanced handleEdit to pre-fill preset and base URL, and reset discovery state.
    • Implemented handleFetchFromDiscovery to fetch and apply OIDC discovery configuration.
    • Updated handlePresetChange and handleBaseUrlChange to use new helper functions and reset discovery state.
    • Added applyAccessPolicyTemplate and applyDeniedTemplate functions for quick template filling.
    • Added an 'Icon' column to the providers table with icon rendering.
    • Redesigned the modal footer to include an enabled switch and separate action buttons.
    • Added a Banner to display information from OIDC discovery.
    • Reorganized form fields, added well_known input, and an icon input with a live preview.
    • Introduced a Collapse component for '高级选项' (Advanced Options), containing AuthStyle, AccessPolicy (with templates), and AccessDeniedMessage (with templates).
    • Updated handleSubmit to use getLatestFormValues and correctly handle new fields.
  • web/src/components/settings/personal/cards/AccountManagement.jsx
    • Imported getOAuthProviderIcon helper.
    • Updated isCustomOAuthBound and getCustomOAuthBinding to ensure numeric comparison for provider IDs.
    • Replaced static IconLock with dynamic getOAuthProviderIcon for displaying custom OAuth provider icons.
  • web/src/helpers/render.jsx
    • Imported numerous react-icons/si components for various OAuth providers.
    • Created oauthProviderIconMap to map icon names to corresponding react-icons/si components.
    • Implemented helper functions isHttpUrl, isSimpleEmoji, and normalizeOAuthIconKey.
    • Developed getOAuthProviderIcon function to render icons based on a key (for react-icons/si), a full image URL, or an emoji, with a fallback to a default icon.
Activity
  • The pull request started with a feature implementation to improve UI/UX.
  • Subsequent commits focused on stabilizing the provider enabled toggle and polishing the custom OAuth settings user experience.
  • Further changes introduced access policy and message templates, ensuring advanced fields are reliably persisted.
  • The final adjustments involved moving template fill actions below their respective fields and cleaning up the advanced form flow for better usability.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly enhances the custom OAuth provider system, adding a flexible access policy engine and OIDC discovery support. However, the new OIDC discovery feature introduces a critical Server-Side Request Forgery (SSRF) vulnerability. While restricted to root administrators, it lacks proper validation of target URLs, potentially allowing requests to internal network resources. Additionally, I recommend optimizing the access policy message rendering by pre-compiling the regular expressions used for template variable replacement.

httpReq.Header.Set("Accept", "application/json")

client := &http.Client{Timeout: 20 * time.Second}
resp, err := client.Do(httpReq)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The FetchCustomOAuthDiscovery function is vulnerable to Server-Side Request Forgery (SSRF). It allows a root administrator to specify an arbitrary URL (WellKnownURL or IssuerURL) which the server then fetches using http.Client.Do on line 172. There is no validation to ensure that the target URL does not point to internal network resources or cloud metadata services (e.g., 169.254.169.254). Although this endpoint is restricted to root administrators, it could be exploited via CSRF or if a root account is compromised to pivot into the internal network and access sensitive services.

Comment thread oauth/generic.go
config *model.CustomOAuthProvider
}

type accessPolicy struct {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It is recommended to define the regular expressions used for access policy message rendering as global variables to avoid repeated compilation during the authentication flow.

var (
	currentPattern  = regexp.MustCompile(`\\{\\{current\\.([^}]+)\\}\\}`)
	requiredPattern = regexp.MustCompile(`\\{\\{required\\.([^}]+)\\}\\}`)
)

type accessPolicy struct {

Comment thread oauth/generic.go
Comment on lines +641 to +642
currentPattern := regexp.MustCompile(`\{\{current\.([^}]+)\}\}`)
message = currentPattern.ReplaceAllStringFunc(message, func(token string) string {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use the pre-compiled global regular expression instead of compiling it here.

	message = currentPattern.ReplaceAllStringFunc(message, func(token string) string {

Comment thread oauth/generic.go
Comment on lines +654 to +655
requiredPattern := regexp.MustCompile(`\{\{required\.([^}]+)\}\}`)
message = requiredPattern.ReplaceAllStringFunc(message, func(token string) string {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use the pre-compiled global regular expression instead of compiling it here.

	message = requiredPattern.ReplaceAllStringFunc(message, func(token string) string {

…try fix for async tasks

1. Async task model redirection (aligned with sync tasks):
   - Integrate ModelMappedHelper in RelayTaskSubmit after model name
     determination, populating OriginModelName / UpstreamModelName on RelayInfo.
   - All task adaptors now send UpstreamModelName to upstream providers:
     - Gemini & Vertex: BuildRequestURL uses UpstreamModelName.
     - Doubao & Ali: BuildRequestBody conditionally overwrites body.Model.
     - Vidu, Kling, Hailuo, Jimeng: convertToRequestPayload accepts RelayInfo
       and unconditionally uses info.UpstreamModelName.
     - Sora: BuildRequestBody parses JSON and multipart bodies to replace
       the "model" field with UpstreamModelName.
   - Frontend log visibility: LogTaskConsumption and taskBillingOther now
     emit is_model_mapped / upstream_model_name in the "other" JSON field.
   - Billing safety: RecalculateTaskQuotaByTokens reads model name from
     BillingContext.OriginModelName (via taskModelName) instead of
     task.Data["model"], preventing billing leaks from upstream model names.

2. Per-call billing (TaskPricePatches lifecycle):
   - Rename TaskBillingContext.ModelName → OriginModelName; add PerCallBilling
     bool field, populated from TaskPricePatches at submission time.
   - settleTaskBillingOnComplete short-circuits when PerCallBilling is true,
     skipping both adaptor adjustments and token-based recalculation.
   - Remove ModelName from TaskSubmitResult; use relayInfo.OriginModelName
     consistently in controller/relay.go for billing context and logging.

3. Multipart retry boundary mismatch fix:
   - Root cause: after Sora (or OpenAI audio) rebuilds a multipart body with a
     new boundary and overwrites c.Request.Header["Content-Type"], subsequent
     calls to ParseMultipartFormReusable on retry would parse the cached
     original body with the wrong boundary, causing "NextPart: EOF".
   - Fix: ParseMultipartFormReusable now caches the original Content-Type in
     gin context key "_original_multipart_ct" on first call and reuses it for
     all subsequent parses, making multipart parsing retry-safe globally.
   - Sora adaptor reverted to the standard pattern (direct header set/get),
     which is now safe thanks to the root fix.

4. Tests:
   - task_billing_test.go: update makeTask to use OriginModelName; add
     PerCallBilling settlement tests (skip adaptor adjust, skip token recalc);
     add non-per-call adaptor adjustment test with refund verification.
@lonely-4

Copy link
Copy Markdown
Member Author

/gemini review

@lonely-4

Copy link
Copy Markdown
Member Author

@gemini-code-assist review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This is an excellent and substantial pull request that significantly improves the OAuth provider functionality and refactors core components for asynchronous tasks. The introduction of access policies and OIDC discovery for custom OAuth providers is a major feature enhancement, and the implementation is robust, including backend validation and a polished user interface.

The refactoring of the task relaying and polling logic into dedicated services is a standout improvement. This greatly enhances code organization, maintainability, and correctness. Key highlights of the refactoring include:

  • Improved Concurrency Control: The adoption of Compare-And-Swap (CAS) updates (UpdateWithStatus) effectively prevents race conditions during concurrent task status updates.
  • Robust Billing Lifecycle: The new TaskAdaptor interface and the centralized billing logic in service/task_billing.go create a clear and reliable lifecycle for pre-consumption, settlement, and refunds for async tasks.
  • Better Abstraction: Separating public-facing task IDs from upstream provider IDs and introducing helpers like GetUpstreamTaskID() and GetResultURL() improves abstraction and future-proofs the data model.
  • Clearer Code Structure: Moving complex logic out of controllers and into dedicated service files (task_polling.go, task_billing.go) and common helpers (taskcommon/helpers.go) follows best practices and makes the codebase much easier to navigate.

The frontend changes are equally impressive, providing a much-improved user experience for configuring custom OAuth providers, complete with presets, discovery, and access policy templates. The updates to the logging and task tables to reflect the new data model are also well-executed.

Overall, this is a high-quality contribution that demonstrates a deep understanding of the system's architecture and a commitment to improving its long-term health. The changes are well-designed, correctly implemented, and thoroughly tested. Great work!

@lonely-4
lonely-4 merged commit b20e715 into AmethystDev-Labs:main Feb 22, 2026
@lonely-4

Copy link
Copy Markdown
Member Author

@gemini-code-assist 这个修改了什么?

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

This pull request delivers a comprehensive overhaul of the custom OAuth provider system, significantly enhancing its configurability, security, and user experience. It introduces advanced access control capabilities, streamlines the setup process through OIDC discovery, and refactors the backend for asynchronous task management to ensure more reliable billing and status updates. The frontend has been updated to reflect these new features with an improved, more intuitive interface.

Highlights

  • Enhanced Custom OAuth Provider Management: Introduced new fields for custom OAuth providers including Icon, AccessPolicy, and AccessDeniedMessage to support richer configuration and user experience. This allows for dynamic icon rendering across the application and granular access control.
  • OIDC Discovery Integration: Added functionality to fetch and automatically populate OAuth provider settings from an OIDC Discovery endpoint, simplifying setup for administrators. The UI now includes a dedicated button to retrieve configuration from a well-known URL or issuer URL.
  • Granular Access Control Policies: Implemented a robust access policy mechanism allowing administrators to define JSON-based rules for user access based on information retrieved from the OAuth provider. This includes support for logical operators (AND/OR) and various comparison operators, along with customizable denial messages using templates.
  • Refactored Asynchronous Task Polling and Billing: The core logic for polling and billing of asynchronous tasks (like video and music generation) has been moved to a new service layer. This includes centralized functions for refunding, recalculating quotas, and logging, ensuring more robust and consistent billing processes, especially with concurrent updates.
  • Improved UI/UX for Custom OAuth Settings: Refined the custom OAuth settings interface with a more intuitive layout, including a toggle for enabling/disabling providers, a live preview for icons, and template suggestions for access policies and denial messages. Advanced options are now organized within a collapsible section.
  • Dynamic OAuth Provider Icons: Integrated dynamic icon rendering for custom OAuth providers across login, registration, and account management pages. This supports react-icons/si keys, image URLs, and emojis, providing a more visually appealing and customizable experience.
  • Robust Task Status Updates with CAS: Implemented Compare-And-Swap (CAS) logic for updating task statuses in the database, preventing race conditions during concurrent polling and ensuring accurate billing adjustments (refunds or recalculations) based on the task's prior state.
Changelog
  • common/gin.go
    • Fixed ParseMultipartFormReusable to use the original Content-Type to prevent boundary mismatches in multipart form processing.
  • controller/custom_oauth.go
    • Added Icon, AccessPolicy, and AccessDeniedMessage fields to custom OAuth provider DTOs and updated CRUD operations to support them.
    • Implemented FetchCustomOAuthDiscovery to retrieve OIDC discovery documents.
    • Included ProviderIcon in GetUserOAuthBindings response.
  • controller/midjourney.go
    • Introduced preStatus for Midjourney tasks and utilized UpdateWithStatus for conditional updates, improving quota refund accuracy.
  • controller/misc.go
    • Added Id and Icon fields to CustomOAuthInfo for enabled custom providers in the status endpoint.
  • controller/oauth.go
    • Corrected indentation for user update fields.
    • Added handling for AccessDeniedError to provide custom denial messages.
  • controller/relay.go
    • Refactored RelayTask to separate task submission and fetching logic, introducing RelayTaskFetch and respondTaskError.
    • Implemented robust retry logic, billing settlement, and task insertion within the task relay process.
  • controller/task.go
    • Moved task polling logic to a new service layer (service.TaskPollingLoop).
    • Modified GetAllTask and GetUserTask to convert model tasks to DTOs, including username information.
  • controller/task_video.go
    • Removed, as its functionality has been refactored and moved to the new service layer.
  • controller/video_proxy.go
    • Refactored error handling to use videoProxyError for consistent OpenAI-style error responses.
    • Updated video URL generation to use task.GetUpstreamTaskID() and task.GetResultURL() for improved task tracking.
  • controller/video_proxy_gemini.go
    • Replaced json.Unmarshal and json.Marshal with common.Unmarshal and common.Marshal.
    • Adopted taskcommon.EncodeLocalTaskID and taskcommon.DecodeLocalTaskID for task ID handling.
    • Updated FetchTask and ConvertToOpenAIVideo to use task.GetUpstreamTaskID().
  • dto/suno.go
    • Removed TaskData interface, FetchReq struct, TaskSuccessCode, TaskResponse, and TaskDto as they were relocated to dto/task.go.
  • dto/task.go
    • Introduced TaskData interface, TaskSuccessCode, TaskResponse, TaskDto, and FetchReq struct.
    • Expanded TaskDto with additional fields for comprehensive task representation.
  • logger/logger.go
    • Replaced json.Marshal with common.Marshal in LogJson for consistency.
  • main.go
    • Wired service.GetTaskAdaptorFunc to relay.GetTaskAdaptor to resolve import cycles in task polling.
  • middleware/auth.go
    • Added TokenOrUserAuth middleware to allow both session and API token authentication for certain endpoints.
  • model/custom_oauth_provider.go
    • Added accessPolicyPayload, accessConditionItem, and supportedAccessPolicyOps for defining and validating access policies.
    • Included Icon, AccessPolicy, and AccessDeniedMessage fields in the CustomOAuthProvider model.
    • Implemented validation logic for the AccessPolicy JSON structure.
  • model/log.go
    • Added RecordTaskBillingLogParams and RecordTaskBillingLog for detailed task-specific billing logs.
  • model/midjourney.go
    • Added UpdateWithStatus method for conditional updates of Midjourney tasks, ensuring atomic state transitions.
  • model/task.go
    • Updated JSON marshaling/unmarshaling to use common.Marshal and common.Unmarshal.
    • Introduced TaskPrivateData and TaskBillingContext for detailed task metadata and billing context.
    • Added GetUpstreamTaskID, GetResultURL, and GenerateTaskID helper methods.
    • Implemented taskSnapshot and Equal for state comparison, and UpdateWithStatus for robust conditional updates.
    • Removed deprecated bulk update functions and SumUsedTaskQuota.
  • model/task_cas_test.go
    • Added new test file for taskSnapshot and UpdateWithStatus (CAS) functionality.
  • model/token.go
    • Changed IncreaseTokenQuota parameter name to tokenId for clarity.
  • oauth/generic.go
    • Introduced accessPolicy, accessCondition, accessPolicyFailure structs for runtime policy evaluation.
    • Implemented access policy evaluation logic within GetUserInfo.
    • Added Extra field to OAuthUser for provider slug.
    • Included helper functions for access policy parsing and evaluation.
  • oauth/types.go
    • Added AccessDeniedError struct for custom access denial messages.
  • relay/channel/adapter.go
    • Expanded TaskAdaptor interface with EstimateBilling, AdjustBillingOnSubmit, and AdjustBillingOnComplete for granular billing adjustments.
  • relay/channel/task/ali/adaptor.go
    • Embedded taskcommon.BaseBilling for default billing behavior.
    • Updated request validation and body building to use context-stored request data and info.UpstreamModelName.
    • Implemented EstimateBilling for Ali video tasks.
  • relay/channel/task/doubao/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building to use info.UpstreamModelName and common.Marshal.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/channel/task/gemini/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building and task ID handling to use taskcommon helpers and info.UpstreamModelName.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/channel/task/hailuo/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building and task ID handling to use info.UpstreamModelName and common.Marshal.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/channel/task/jimeng/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building and task ID handling to use info.UpstreamModelName and common.Marshal.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/channel/task/kling/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building and task ID handling to use info.UpstreamModelName and common.Marshal.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/channel/task/sora/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated validateRemixRequest to store request in context.
    • Implemented EstimateBilling for Sora tasks.
    • Modified BuildRequestBody to handle JSON and multipart forms for model mapping.
    • Updated DoResponse to use info.PublicTaskID and return upstream ID.
    • Adjusted ConvertToOpenAIVideo to set id to task.TaskID.
  • relay/channel/task/suno/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building to get request from context and use common.Marshal.
    • Modified DoResponse to use info.PublicTaskID and return upstream ID.
  • relay/channel/task/taskcommon/helpers.go
    • Added new file with common helper functions for task adaptors, including UnmarshalMetadata, DefaultString, DefaultInt, EncodeLocalTaskID, DecodeLocalTaskID, BuildProxyURL, and BaseBilling for default billing implementations.
  • relay/channel/task/vertex/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request URL/header building to use info.UpstreamModelName and common.Unmarshal.
    • Implemented EstimateBilling for Vertex tasks.
    • Modified DoResponse to use info.PublicTaskID.
    • Updated FetchTask and ConvertToOpenAIVideo to use task.GetUpstreamTaskID() and task.GetResultURL().
  • relay/channel/task/vidu/adaptor.go
    • Embedded taskcommon.BaseBilling.
    • Updated request body building and task ID handling to use info.UpstreamModelName and common.Marshal.
    • Modified DoResponse to use info.PublicTaskID.
  • relay/common/relay_info.go
    • Added ForcePreConsume to RelayInfo to enforce full pre-consumption for async tasks.
    • Initialized TaskRelayInfo for task formats.
    • Added PublicTaskID and LockedChannel to TaskRelayInfo.
    • Updated TaskSubmitReq.UnmarshalMetadata to use common.Marshal and common.Unmarshal.
  • relay/common/relay_utils.go
    • Removed info.PriceData.OtherRatios setting for Sora from ValidateMultipartDirect, as it's now handled by the adaptor's EstimateBilling.
  • relay/helper/price.go
    • Changed ModelPriceHelperPerCall return type to types.PriceData.
    • Added FreeModel check to ModelPriceHelperPerCall.
  • relay/relay_task.go
    • Refactored RelayTaskSubmit into ResolveOriginTask and RelayTaskSubmit for clearer separation of concerns.
    • ResolveOriginTask now handles remix logic, channel locking, and OtherRatios extraction.
    • RelayTaskSubmit manages adaptor validation, model mapping, public task ID generation, price calculation, billing estimation, pre-consumption, request handling, and response parsing.
    • Introduced TaskSubmitResult and recalcQuotaFromRatios for dynamic quota recalculation.
    • Updated videoFetchByIDRespBodyBuilder to use tryRealtimeFetch and TaskModel2Dto.
    • Added tryRealtimeFetch, detectVideoFormat, mapTaskStatusToSimple helper functions.
    • Expanded TaskModel2Dto with more fields.
  • router/api-router.go
    • Added POST /api/custom-oauth-provider/discovery route, restricted to root users.
  • router/relay-router.go
    • Changed /suno fetch routes to use controller.RelayTaskFetch.
  • router/video-router.go
    • Added middleware.TokenOrUserAuth() for the /v1/videos/:task_id/content route, allowing both session and API token authentication.
    • Changed video fetch routes to use controller.RelayTaskFetch.
  • service/billing_session.go
    • Added ForcePreConsume check to shouldTrust to disable trust bypass for async tasks, ensuring full pre-consumption.
  • service/error.go
    • Added TaskErrorFromAPIError to convert NewAPIError to TaskError.
  • service/log_info_generate.go
    • Changed GenerateMjOtherInfo parameter type to types.PriceData.
  • service/task_billing.go
    • Added new file centralizing task-related billing logic, including LogTaskConsumption, RefundTaskQuota, RecalculateTaskQuota, and RecalculateTaskQuotaByTokens.
  • service/task_billing_test.go
    • Added new test file for the task billing functions, covering refunds, recalculations, and CAS-guarded billing scenarios.
  • service/task_polling.go
    • Added new file containing the main task polling loop, dispatching updates by platform, and handling Suno and video task updates.
    • Introduced TaskPollingAdaptor interface and GetTaskAdaptorFunc for dependency injection.
    • Implemented updateVideoSingleTask with CAS logic for robust status updates and billing settlement.
  • types/price_data.go
    • Removed PerCallPriceData and added Quota field to PriceData for consistent billing information.
  • web/src/components/auth/LoginForm.jsx
    • Integrated getOAuthProviderIcon for dynamic icon rendering.
    • Updated OAuth login options rendering based on custom providers.
  • web/src/components/auth/RegisterForm.jsx
    • Integrated getOAuthProviderIcon and onCustomOAuthClicked.
    • Added loading states for custom OAuth buttons and updated registration options rendering.
  • web/src/components/settings/CustomOAuthSetting.jsx
    • Redesigned the custom OAuth settings UI with Collapse, Switch, and IconRefresh.
    • Added OIDC discovery integration with handleFetchFromDiscovery.
    • Implemented dynamic icon preview and template suggestions for access policies and denial messages.
    • Refactored state management for improved form handling.
  • web/src/components/settings/personal/cards/AccountManagement.jsx
    • Integrated getOAuthProviderIcon for custom OAuth provider icons.
    • Ensured numeric comparison for provider IDs in binding checks.
  • web/src/components/table/task-logs/TaskLogsColumnDefs.jsx
    • Removed showUserInfoFunc parameter.
    • Updated Tag components by removing prefixIcon.
    • Changed dataIndex for user column to username and simplified rendering.
    • Updated video preview logic to use record.result_url.
  • web/src/components/table/task-logs/index.jsx
    • Removed UserInfoModal.
  • web/src/components/table/task-logs/modals/ContentModal.jsx
    • Removed autoPlay and crossOrigin attributes from the video tag.
  • web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
    • Added LogTypeRefund (6) to various render functions for consumption logs.
    • Included refund-specific content for the content column.
  • web/src/components/table/usage-logs/UsageLogsFilters.jsx
    • Added LogTypeRefund (6) as an option in the log type filter.
  • web/src/helpers/render.jsx
    • Imported numerous react-icons/si components.
    • Implemented getOAuthProviderIcon for dynamic icon rendering based on keys, URLs, or emojis.
  • web/src/hooks/usage-logs/useUsageLogsData.jsx
    • Updated log expansion data conditions to include LogTypeRefund.
    • Added refund-specific entries and adjusted conditions for request conversion and local count mode.
  • web/src/i18n/locales/*.json
    • Updated translations for various new and modified UI elements and log types, including '任务ID', '创建成功', '失败原因', '更新成功', '确认解绑', '自动检测', '输出价格', '退款', '错误详情', '异步任务退款', '失败原因'.
Activity
  • The pull request started with a feature implementation to improve UI/UX.
  • Subsequent commits focused on stabilizing the provider enabled toggle and polishing the custom OAuth settings user experience.
  • Further changes introduced access policy and message templates, ensuring advanced fields are reliably persisted.
  • The final adjustments involved moving template fill actions below their respective fields and cleaning up the advanced form flow for better usability.
  • A bot review identified a potential Server-Side Request Forgery (SSRF) vulnerability in FetchCustomOAuthDiscovery due to arbitrary URL fetching without validation, despite being root-restricted.
  • The bot also recommended defining regular expressions for access policy message rendering as global variables to avoid repeated compilation and improve performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants