3x-ui/tools/openapigen/walker_test.go

71 lines
2.4 KiB
Go
Raw Normal View History

feat(happ): generate Crypt5 subscription links locally (#6494) * feat(clients): add stateless Happ link generator Generate Happ provider links from the current effective subscription source without caching results. Reject unsafe provider responses and redact failure diagnostics. * fix(clients): reject duplicate Happ provider fields Parse Happ provider objects token by token so duplicate supported keys cannot be silently overwritten by encoding/json. * feat(clients): expose on-demand Happ link API Expose a no-store client endpoint backed by the Happ link generator and keep its generated OpenAPI contract synchronized. * fix(openapi): exclude service interfaces from generated types Keep dependency-injection interfaces out of the frontend API surface while preserving allowed response schemas. * feat(clients): add stateless Happ QR presentation Generate Happ links only for the active modal scope and retire late responses so Standard remains immediately available. Add focused component coverage and localized retry guidance across every locale. * fix(clients): cover overlapping Happ generations Prove the cancellation cleanup is required by resolving a retired request while its replacement remains pending. Also wait for Regenerate to leave loading state before exercising the existing action. * fix(clients): harden Happ link handling Validate generated responses before rendering and hide actions during unresolved requests. Strengthen route, redirect, timeout, and lint regression coverage with mutation-sensitive tests. * fix(clients): gate Happ link generation behind operator opt-in - add a fail-closed happLinkEnable setting - enforce the gate before and after provider requests - add locked Happ QR state with privacy disclosure and settings link - cover backend, frontend, settings, and i18n regressions * fix(frontend): guard oversized Happ QR codes Keep valid long crypt5 links copyable while suppressing QR rendering and image actions above the encoder's UTF-8 byte limit. Add localized guidance and boundary coverage. * fix(clients): log the sanitized transport error for Happ link failures Every fail() call in HappService.Generate passed a string literal as the detail, so the sanitizer written for provider errors only ever saw constants, and an operator following the QR modal's "check Logs" hint found nothing beyond reason=transport. Transport and body-read errors now flow through sanitizeHappDetail, which also redacts cookie/session pairs. Drop TestHappLinkEnableDefaultsOffWithoutPersistingRow: it pinned a getter and its constant default, which the Generate gate test already drives. * fix(frontend): size the Happ QR cap to level L and keep the QR modal mounted on close HAPP_QR_MAX_BYTES was the level-M capacity (2331) while QrPanel encodes at errorLevel "L", whose version-40 byte-mode capacity is 2953, so valid links between 2332 and 2953 bytes lost their QR. The cap now matches the encoder and a test renders the real QrPanel at the boundary. Keying the modal content on `open` remounted it on every close, which cut the Modal's exit transition and made the openSubId sync unreachable, so `loading` never turned on for the subLinks fetch and a client without a subscription link flashed noLinks on reopen. `open` leaves the key and the sync block now also resets the Happ state. * chore(clients): request Happ crypt5 links from api-v3 crypto.happ.su serves api-v2.php and api-v3.php side by side. Probed with the same payloads, both take {"url"} over a JSON POST, answer {"encrypted_link":"happ://crypt5/..."} of identical length with the same crypt5 key marker, and fail the same way: 400 "No url provided.", 500 "Invalid URL format.", 405 on GET. Happ's own generator page is branded "URL Encryption v3", so the panel follows it. The parser and the link validator are unchanged. * feat: add local generation of encrypted Happ links - Implemented functionality to generate encrypted Happ links locally without network dependency. - Added validation for URL length and format to ensure compliance with processing limits. - Introduced new error handling for invalid URLs and control characters. - Updated translations for various languages to reflect changes in Happ link generation. - Created unit tests to validate the encryption process and ensure session keys and nonces are unique. * fix(frontend): match the tuic memo deps to the non-optional subSettings The Happ branch reads subSettings non-optionally in ClientQrModalContent (happLinkEnable and the WireGuard/AmneziaWG publicHost memos), so React Compiler infers subSettings.publicHost. The TUIC memo merged in from main still listed subSettings?.publicHost, which fails oxlint's preserve-manual-memoization rule and makes the compiler skip optimizing the component. make verify stopped at lint-fe on the branch head. * chore(happ): trim the pinned-key provenance comment to two lines CLAUDE.md caps a comment block at two lines. The bare URL line repeated the repository and file the next line already names, so it is folded into that line (review LOW on happ_crypto.go). --------- Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-13 03:44:55 -07:00
package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestWalkPackagesExportsAllowedStructsWithoutDIInterfaces(t *testing.T) {
dir := t.TempDir()
source := `package service
type HappLinkGenerator interface {
Generate()
}
type HappLinkResult struct {
EncryptedLink string
}
`
if err := os.WriteFile(filepath.Join(dir, "service.go"), []byte(source), 0o644); err != nil {
t.Fatalf("write service fixture: %v", err)
}
schemas, aliases, err := walkPackages([]packageRequest{{
Path: dir,
StructAllow: setOf("HappLinkResult"),
}})
if err != nil {
t.Fatalf("walk packages: %v", err)
}
var generated bytes.Buffer
if err := emitTypes(&generated, schemas, aliases); err != nil {
t.Fatalf("emit types: %v", err)
}
apiSurface := generated.String()
if !strings.Contains(apiSurface, "export interface HappLinkResult") {
t.Fatalf("generated types omit allowed response schema:\n%s", apiSurface)
}
if strings.Contains(apiSurface, "HappLinkGenerator") {
t.Fatalf("generated types expose DI interface:\n%s", apiSurface)
}
}
func TestKeepAliveOverrideEmitsNumberOrString(t *testing.T) {
dir := t.TempDir()
source := "package model\ntype Client struct { KeepAlive *int `json:\"keepAlive,omitempty\"` }\n"
if err := os.WriteFile(filepath.Join(dir, "client.go"), []byte(source), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
union := TypeRef{Kind: KindUnion, Variants: []TypeRef{{Kind: KindInt}, {Kind: KindString}}}
schemas, _, err := walkPackages([]packageRequest{{Path: dir, StructAllow: setOf("Client"), Overrides: map[string][]walkOverride{"Client": {{Field: "KeepAlive", Type: union}}}}})
if err != nil {
t.Fatalf("walk fixture: %v", err)
}
var types bytes.Buffer
if err := emitTypes(&types, schemas, nil); err != nil || !strings.Contains(types.String(), "keepAlive?: number | string;") {
t.Fatalf("generated TypeScript keepAlive = %s, err = %v", types.String(), err)
}
var zod bytes.Buffer
if err := emitZod(&zod, schemas, nil); err != nil || !strings.Contains(zod.String(), "z.union([z.number().int(), z.string()]).optional()") {
t.Fatalf("generated Zod keepAlive = %s, err = %v", zod.String(), err)
}
var schema bytes.Buffer
if err := emitJSONSchema(&schema, schemas, nil); err != nil || !strings.Contains(schema.String(), `"oneOf"`) {
t.Fatalf("generated JSON schema keepAlive = %s, err = %v", schema.String(), err)
}
}