From 9a363b188c09af661a661fc9716a78d58ceeb9f8 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 04:06:01 -0800 Subject: [PATCH] Add ChatGPT account sign-in for model profiles --- agent/chatgpt_guard.go | 42 ++ agent/chatgpt_guard_test.go | 39 + agent/chatgpt_plan_provider.go | 307 ++++++++ agent/chatgpt_plan_provider_test.go | 252 +++++++ agent/provider.go | 49 +- chatgptauth/README.md | 10 + chatgptauth/auth.go | 382 ++++++++++ chatgptauth/auth_test.go | 211 ++++++ chatgptplan/README.md | 18 + chatgptplan/client.go | 329 +++++++++ chatgptplan/client_test.go | 117 +++ chatgptplan/errors.go | 71 ++ chatgptplan/errors_test.go | 63 ++ chatgptplan/models.go | 71 ++ chatgptplan/models_test.go | 47 ++ db/chatgpt_accounts.go | 241 +++++++ db/chatgpt_accounts_test.go | 125 ++++ db/chatgpt_profiles_test.go | 158 ++++ db/config.go | 25 +- db/migrations/0020_chatgpt_accounts.sql | 19 + db/migrations/0021_chatgpt_profiles.sql | 5 + db/migrations/0022_openrouter_profiles.sql | 3 + db/schema.sql | 27 +- db/secrets.go | 5 +- go.mod | 6 + go.sum | 6 + server/chatgpt_callback_port_test.go | 21 + server/chatgpt_lifecycle.go | 102 +++ server/chatgpt_lifecycle_test.go | 124 ++++ server/chatgpt_oauth.go | 791 +++++++++++++++++++++ server/chatgpt_oauth_test.go | 554 +++++++++++++++ server/chatgpt_profile_pg_test.go | 79 ++ server/chatgpt_provider.go | 78 ++ server/chatgpt_provider_test.go | 67 ++ server/dto.go | 35 +- server/server.go | 72 +- server/server_mgmt.go | 58 +- web/src/app/(main)/system/llm/page.tsx | 250 +++++-- web/src/components/chatgpt-usage-error.tsx | 18 + web/src/components/transcript.tsx | 3 + web/src/i18n/locales/tr.json | 44 +- web/src/i18n/locales/zh-CN.json | 44 +- web/src/lib/api.ts | 8 + web/src/lib/types.ts | 5 +- 44 files changed, 4892 insertions(+), 89 deletions(-) create mode 100644 agent/chatgpt_guard.go create mode 100644 agent/chatgpt_guard_test.go create mode 100644 agent/chatgpt_plan_provider.go create mode 100644 agent/chatgpt_plan_provider_test.go create mode 100644 chatgptauth/README.md create mode 100644 chatgptauth/auth.go create mode 100644 chatgptauth/auth_test.go create mode 100644 chatgptplan/README.md create mode 100644 chatgptplan/client.go create mode 100644 chatgptplan/client_test.go create mode 100644 chatgptplan/errors.go create mode 100644 chatgptplan/errors_test.go create mode 100644 chatgptplan/models.go create mode 100644 chatgptplan/models_test.go create mode 100644 db/chatgpt_accounts.go create mode 100644 db/chatgpt_accounts_test.go create mode 100644 db/chatgpt_profiles_test.go create mode 100644 db/migrations/0020_chatgpt_accounts.sql create mode 100644 db/migrations/0021_chatgpt_profiles.sql create mode 100644 db/migrations/0022_openrouter_profiles.sql create mode 100644 server/chatgpt_callback_port_test.go create mode 100644 server/chatgpt_lifecycle.go create mode 100644 server/chatgpt_lifecycle_test.go create mode 100644 server/chatgpt_oauth.go create mode 100644 server/chatgpt_oauth_test.go create mode 100644 server/chatgpt_profile_pg_test.go create mode 100644 server/chatgpt_provider.go create mode 100644 server/chatgpt_provider_test.go create mode 100644 web/src/components/chatgpt-usage-error.tsx diff --git a/agent/chatgpt_guard.go b/agent/chatgpt_guard.go new file mode 100644 index 000000000..bf293b439 --- /dev/null +++ b/agent/chatgpt_guard.go @@ -0,0 +1,42 @@ +package agent + +import ( + "context" + "errors" + "iter" + "strings" + + "github.com/Autumn-27/norma/llm" +) + +// A ChatGPT-plan carrier is private Responses state, not Anthropic thinking. +// Other providers must fail rather than silently discard it or send it as a +// different provider's opaque data after a profile switch or failover. +var errForeignPlanState = errors.New("conversation contains ChatGPT plan state; use the same profile or start a new conversation") + +func hasPlanState(req llm.CompletionRequest) bool { + for _, msg := range req.Messages { + for _, block := range msg.Content { + if block.Type == llm.BlockRedactedThinking && strings.HasPrefix(block.Data, planCarrier) { + return true + } + } + } + return false +} + +type foreignPlanGuard struct{ inner llm.Provider } + +func (g foreignPlanGuard) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + if hasPlanState(req) { + return func(yield func(llm.StreamEvent, error) bool) { yield(llm.StreamEvent{}, errForeignPlanState) } + } + return g.inner.Stream(ctx, req) +} + +func (g foreignPlanGuard) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + if hasPlanState(req) { + return llm.Message{}, "", llm.Usage{}, errForeignPlanState + } + return g.inner.Complete(ctx, req) +} diff --git a/agent/chatgpt_guard_test.go b/agent/chatgpt_guard_test.go new file mode 100644 index 000000000..05e852cdd --- /dev/null +++ b/agent/chatgpt_guard_test.go @@ -0,0 +1,39 @@ +package agent + +import ( + "context" + "iter" + "testing" + + "github.com/Autumn-27/norma/llm" +) + +type guardProbe struct{ calls int } + +func (p *guardProbe) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + p.calls++ + return func(func(llm.StreamEvent, error) bool) {} +} +func (p *guardProbe) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.calls++ + return llm.Message{}, "", llm.Usage{}, nil +} + +func TestForeignPlanStateIsNotSentToOtherProviders(t *testing.T) { + inner := &guardProbe{} + p := foreignPlanGuard{inner: inner} + req := llm.CompletionRequest{Messages: []llm.Message{{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockRedactedThinking, Data: planCarrier + `{}`}}}}} + if _, _, _, err := p.Complete(context.Background(), req); err == nil { + t.Fatal("Complete accepted foreign plan state") + } + var gotErr error + for _, err := range p.Stream(context.Background(), req) { + gotErr = err + } + if gotErr == nil || inner.calls != 0 { + t.Fatalf("Stream error=%v, delegated calls=%d", gotErr, inner.calls) + } + if _, _, _, err := p.Complete(context.Background(), llm.CompletionRequest{}); err != nil || inner.calls != 1 { + t.Fatalf("ordinary request: error=%v, delegated calls=%d", err, inner.calls) + } +} diff --git a/agent/chatgpt_plan_provider.go b/agent/chatgpt_plan_provider.go new file mode 100644 index 000000000..9f7d58ab7 --- /dev/null +++ b/agent/chatgpt_plan_provider.go @@ -0,0 +1,307 @@ +package agent + +// This isolated bridge is not wired into ARTEX. Before enabling it, every other +// provider (including pool members) must reject the tagged blocks below, and +// compaction and all alternate context views must be audited for their handling. +// The carrier is provider-private state, not Anthropic redacted thinking. +// The host must reject explicitly configured output caps before constructing this +// provider. Norma supplies internal limits for ordinary requests and compaction; +// all nonnegative limits are omitted on the wire and therefore unenforced. +// Compaction's "disabled" thinking override is accepted but not sent: this +// protocol cannot guarantee reasoning is disabled. Other overrides are rejected. +// The host UI and profile must disclose that neither output caps nor a thinking +// switch can be enforced for this provider. +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "iter" + "strings" + + "github.com/Autumn-27/artex/chatgptplan" + "github.com/Autumn-27/norma/llm" +) + +const planCarrier = "artex.chatgptplan.item.v1:" +const planNamespace = "artex" + +type ChatGPTPlanProvider struct { + Client chatgptplan.Client + Model string + AccountID string // Stable account registration ID; binds opaque replay to its origin. + Token func(context.Context) (string, error) +} + +// planItemToBlock validates the subset that the neutral model can faithfully +// represent. The complete raw item is retained separately for exact replay. +func planItemToBlock(raw json.RawMessage) (*llm.ContentBlock, error) { + var x struct { + Type string `json:"type"` + Role string `json:"role"` + Namespace string `json:"namespace"` + Name string `json:"name"` + CallID string `json:"call_id"` + Arguments string `json:"arguments"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + Refusal string `json:"refusal"` + } `json:"content"` + } + if json.Unmarshal(raw, &x) != nil { + return nil, errors.New("chatgptplan bridge: invalid output item") + } + switch x.Type { + case "reasoning": + return nil, nil + case "message": + if x.Role != "assistant" || len(x.Content) != 1 || (x.Content[0].Type != "output_text" && x.Content[0].Type != "refusal") { + return nil, errors.New("chatgptplan bridge: unsupported output message") + } + text := x.Content[0].Text + if x.Content[0].Type == "refusal" { + text = x.Content[0].Refusal + } + b := llm.TextBlock(text) + if b.Text == "" { + return nil, errors.New("chatgptplan bridge: empty output text") + } + return &b, nil + case "function_call": + if x.Namespace != planNamespace || x.Name == "" || x.CallID == "" || !json.Valid([]byte(x.Arguments)) { + return nil, errors.New("chatgptplan bridge: invalid function call") + } + var obj map[string]json.RawMessage + if json.Unmarshal([]byte(x.Arguments), &obj) != nil || obj == nil { + return nil, errors.New("chatgptplan bridge: tool arguments must be an object") + } + return &llm.ContentBlock{Type: llm.BlockToolUse, ID: x.CallID, Name: x.Name, Input: json.RawMessage(strings.TrimSpace(x.Arguments))}, nil + default: + return nil, fmt.Errorf("chatgptplan bridge: unsupported output item %q", x.Type) + } +} +func planEqualBlock(a, b llm.ContentBlock) bool { + if a.Type != b.Type { + return false + } + switch a.Type { + case llm.BlockText: + return a.Text == b.Text + case llm.BlockToolUse: + return a.ID == b.ID && a.Name == b.Name && string(a.Input) == string(b.Input) && a.ThoughtSignature == "" + } + return false +} +func planAccountCarrier(accountID string) string { + return planCarrier + base64.RawURLEncoding.EncodeToString([]byte(accountID)) + ":" +} +func planInput(req llm.CompletionRequest, accountID string) ([]any, error) { + var out []any + if len(req.System) > 0 { + out = append(out, map[string]any{"role": "developer", "content": strings.Join(req.System, "\n\n")}) + } + calls := map[string]bool{} + results := map[string]bool{} + for _, m := range req.Messages { + if m.Role != llm.RoleAssistant && m.Role != llm.RoleUser { + return nil, errors.New("chatgptplan bridge: unsupported role") + } + for i := 0; i < len(m.Content); i++ { + b := m.Content[i] + if b.Type == llm.BlockRedactedThinking { + if m.Role != llm.RoleAssistant || !strings.HasPrefix(b.Data, planAccountCarrier(accountID)) { + return nil, errors.New("chatgptplan bridge: unsupported opaque block") + } + raw := json.RawMessage(strings.TrimPrefix(b.Data, planAccountCarrier(accountID))) + block, err := planItemToBlock(raw) + if err != nil { + return nil, err + } + if block != nil { + i++ + if i >= len(m.Content) || !planEqualBlock(*block, m.Content[i]) { + return nil, errors.New("chatgptplan bridge: carrier mismatch or missing block") + } + if block.Type == llm.BlockToolUse { + if calls[block.ID] { + return nil, errors.New("chatgptplan bridge: duplicate call") + } + calls[block.ID] = true + } + } + out = append(out, raw) + continue + } + switch b.Type { + case llm.BlockText: + out = append(out, map[string]any{"role": string(m.Role), "content": b.Text}) + case llm.BlockToolResult: + if m.Role != llm.RoleUser || b.ToolUseID == "" || !calls[b.ToolUseID] || results[b.ToolUseID] { + return nil, errors.New("chatgptplan bridge: invalid tool result") + } + var s strings.Builder + for _, c := range b.Content { + if c.Type != llm.BlockText { + return nil, errors.New("chatgptplan bridge: unsupported tool result") + } + s.WriteString(c.Text) + } + results[b.ToolUseID] = true + output := s.String() + if b.IsError { + output = "Tool execution error:\n" + output + } + out = append(out, map[string]any{"type": "function_call_output", "call_id": b.ToolUseID, "output": output}) + default: + return nil, errors.New("chatgptplan bridge: unsupported untagged block") + } + } + } + for id := range calls { + if !results[id] { + return nil, errors.New("chatgptplan bridge: unpaired call") + } + } + for id := range results { + if !calls[id] { + return nil, errors.New("chatgptplan bridge: unpaired result") + } + } + if out == nil { + out = []any{} + } + return out, nil +} +func (p *ChatGPTPlanProvider) completion(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + fail := func(e error) (llm.Message, string, llm.Usage, error) { return llm.Message{}, "", llm.Usage{}, e } + if p.Token == nil || p.Model == "" || p.AccountID == "" { + return fail(errors.New("chatgptplan bridge: missing token callback, model, or account ID")) + } + if req.Temperature != nil || len(req.Stop) > 0 || req.MaxTokens < 0 || (req.Thinking != "" && req.Thinking != "disabled") { + return fail(errors.New("chatgptplan bridge: unsupported request options")) + } + input, err := planInput(req, p.AccountID) + if err != nil { + return fail(err) + } + body := map[string]any{"model": p.Model, "input": input} + names := map[string]bool{} + if len(req.Tools) > 0 { + tools := make([]any, 0, len(req.Tools)) + for _, t := range req.Tools { + if t.Name == "" || names[t.Name] { + return fail(errors.New("chatgptplan bridge: invalid tool schema")) + } + names[t.Name] = true + tools = append(tools, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": t.InputSchema}) + } + body["tools"] = []any{map[string]any{"type": "namespace", "name": planNamespace, "description": "ARTEX tools", "tools": tools}} + } + raw, err := json.Marshal(body) + if err != nil { + return fail(err) + } + token, err := p.Token(ctx) + if err != nil { + return fail(err) + } + result, err := p.Client.Stream(ctx, token, raw, nil) + if err != nil { + return fail(err) + } + msg := llm.Message{Role: llm.RoleAssistant} + stop := "end_turn" + seen := map[string]bool{} + // Inspect the entire completed response before exposing any tool calls. + refusal := false + for _, item := range result.Output { + var x struct { + Type string `json:"type"` + Content []struct { + Type string `json:"type"` + } `json:"content"` + } + if json.Unmarshal(item, &x) != nil { + return fail(errors.New("chatgptplan bridge: invalid output item")) + } + if x.Type == "message" { + for _, c := range x.Content { + if c.Type == "refusal" { + refusal = true + } + } + } + } + for _, item := range result.Output { + block, e := planItemToBlock(item) + if e != nil { + return fail(e) + } + if block != nil && block.Type == llm.BlockToolUse { + if !names[block.Name] || seen[block.ID] { + return fail(errors.New("chatgptplan bridge: unknown or duplicate tool call")) + } + seen[block.ID] = true + if refusal { + continue + } + stop = "tool_use" + } + msg.Content = append(msg.Content, llm.ContentBlock{Type: llm.BlockRedactedThinking, Data: planAccountCarrier(p.AccountID) + string(item)}) + if block != nil { + msg.Content = append(msg.Content, *block) + } + } + if refusal { + stop = "refusal" + } + var response struct { + Usage struct { + Input int `json:"input_tokens"` + Output int `json:"output_tokens"` + InputDetails struct { + Cached int `json:"cached_tokens"` + } `json:"input_tokens_details"` + } `json:"usage"` + } + if json.Unmarshal(result.Response, &response) != nil { + return fail(errors.New("chatgptplan bridge: invalid response")) + } + usage := llm.Usage{InputTokens: response.Usage.Input, OutputTokens: response.Usage.Output, CacheReadTokens: response.Usage.InputDetails.Cached} + return msg, stop, usage, nil +} +func (p *ChatGPTPlanProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + return p.completion(ctx, req) +} +func (p *ChatGPTPlanProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + msg, stop, usage, err := p.completion(ctx, req) + if err != nil { + yield(llm.StreamEvent{}, err) + return + } + for _, b := range msg.Content { + var ev llm.StreamEvent + switch b.Type { + case llm.BlockRedactedThinking: + ev = llm.StreamEvent{Type: llm.SERedactedThinking, Text: b.Data} + case llm.BlockText: + ev = llm.StreamEvent{Type: llm.SETextDelta, Text: b.Text} + case llm.BlockToolUse: + if !yield(llm.StreamEvent{Type: llm.SEToolUseStart, ToolID: b.ID, ToolName: b.Name}, nil) { + return + } + ev = llm.StreamEvent{Type: llm.SEToolInputJSON, Text: string(b.Input)} + } + if !yield(ev, nil) { + return + } + } + if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: stop, Usage: usage}, nil) { + return + } + yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil) + } +} diff --git a/agent/chatgpt_plan_provider_test.go b/agent/chatgpt_plan_provider_test.go new file mode 100644 index 000000000..06ab6118b --- /dev/null +++ b/agent/chatgpt_plan_provider_test.go @@ -0,0 +1,252 @@ +package agent + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Autumn-27/artex/chatgptplan" + "github.com/Autumn-27/norma/agentcore" + "github.com/Autumn-27/norma/llm" + "github.com/Autumn-27/norma/permission" + "github.com/Autumn-27/norma/tool" +) + +func TestChatGPTPlanBridgeReplay(t *testing.T) { + n := 0 + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n++ + var body struct { + Input []json.RawMessage `json:"input"` + MaxOutputTokens json.RawMessage `json:"max_output_tokens"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if len(body.MaxOutputTokens) != 0 { + t.Error("unexpected output cap on wire") + } + if n == 2 { + raw, _ := json.Marshal(body.Input) + for _, v := range []string{`"encrypted_content":"opaque"`, `"namespace":"artex"`, `"call_id":"c1"`, `"call_id":"c2"`, `"function_call_output"`, `Tool execution error:\nfailed`} { + if !strings.Contains(string(raw), v) { + t.Errorf("replay missing %s: %s", v, raw) + } + } + } + events := []string{`{"type":"response.output_item.added","output_index":0,"item":{"id":"a"}}`, `{"type":"response.output_item.added","output_index":1,"item":{"id":"b"}}`, `{"type":"response.function_call_arguments.delta","output_index":0,"item_id":"a","delta":"{"}`, `{"type":"response.function_call_arguments.delta","output_index":1,"item_id":"b","delta":"{"}`} + if n == 1 { + events = append(events, `{"type":"response.completed","response":{"status":"completed","output":[{"type":"reasoning","id":"r","encrypted_content":"opaque"},{"type":"function_call","id":"a","namespace":"artex","name":"read","arguments":"{\"n\":1}","call_id":"c1"},{"type":"function_call","id":"b","namespace":"artex","name":"read","arguments":"{\"n\":2}","call_id":"c2"}]}}`) + } else { + events = append(events, `{"type":"response.completed","response":{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}}`) + } + for _, e := range events { + fmt.Fprintf(w, "data: %s\n\n", e) + } + })) + defer s.Close() + p := ChatGPTPlanProvider{Client: chatgptplan.Client{Endpoint: s.URL, HTTPClient: s.Client()}, Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { return "test", nil }} + req := llm.CompletionRequest{Messages: []llm.Message{llm.UserText("go")}, MaxTokens: 32768, Tools: []llm.ToolSchema{{Name: "read", InputSchema: map[string]any{"type": "object"}}}} + acc := llm.NewAccumulator() + for e, err := range p.Stream(context.Background(), req) { + if err != nil { + t.Fatal(err) + } + acc.Add(e) + } + msg := acc.Message() + uses := msg.ToolUses() + if len(uses) != 2 || string(uses[0].Input) != `{"n":1}` || string(uses[1].Input) != `{"n":2}` { + t.Fatalf("calls: %+v", uses) + } + // Exercise the same JSON persistence used by transcript records. + wire, err := json.Marshal(msg) + if err != nil { + t.Fatal(err) + } + var saved llm.Message + if err = json.Unmarshal(wire, &saved); err != nil { + t.Fatal(err) + } + req.Messages = append(req.Messages, saved, llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("c1", "one", false), llm.ToolResultText("c2", "failed", true)}}) + got, _, _, err := p.Complete(context.Background(), req) + if err != nil || got.Text() != "done" { + t.Fatalf("completion: %+v %v", got, err) + } + req.Messages = req.Messages[:2] + if _, _, _, err = p.Complete(context.Background(), req); err == nil { + t.Fatal("accepted orphaned calls") + } + if n != 2 { + t.Fatal("invalid replay reached server") + } +} +func TestChatGPTPlanBridgeIncompleteDoesNotEmitTools(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"a\"}}\n\ndata: {\"type\":\"response.incomplete\",\"response\":{}}\n\n") + })) + defer s.Close() + p := ChatGPTPlanProvider{Client: chatgptplan.Client{Endpoint: s.URL, HTTPClient: s.Client()}, Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { return "test", nil }} + count := 0 + gotErr := false + for e, err := range p.Stream(context.Background(), llm.CompletionRequest{}) { + if err != nil { + gotErr = true + } else { + count++ + if e.Type == llm.SEToolUseStart { + t.Fatal("partial tool emitted") + } + } + } + if !gotErr || count != 0 { + t.Fatalf("error=%v events=%d", gotErr, count) + } +} + +func TestChatGPTPlanBridgeRejectsCorruptAndUnsupported(t *testing.T) { + for _, tc := range []struct { + name string + msgs []llm.Message + }{ + {"orphan carrier", []llm.Message{{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockRedactedThinking, Data: planCarrier + `{"type":"function_call","namespace":"artex","name":"read","call_id":"c","arguments":"{}"}`}}}}}, + {"foreign opaque", []llm.Message{{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockRedactedThinking, Data: "other"}}}}}, + {"orphan result", []llm.Message{{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("c", "result", false)}}}}, + } { + t.Run(tc.name, func(t *testing.T) { + if _, err := planInput(llm.CompletionRequest{Messages: tc.msgs}, "account-a"); err == nil { + t.Fatal("expected rejection") + } + }) + } + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[{\"type\":\"computer_call\"}]}}\n\n") + })) + defer s.Close() + p := ChatGPTPlanProvider{Client: chatgptplan.Client{Endpoint: s.URL, HTTPClient: s.Client()}, Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { return "test", nil }} + for ev, err := range p.Stream(context.Background(), llm.CompletionRequest{}) { + if err == nil { + t.Fatalf("unexpected event: %+v", ev) + } + } +} + +func TestChatGPTPlanBridgeRejectsUnsupportedOverrides(t *testing.T) { + p := ChatGPTPlanProvider{Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { + t.Fatal("token callback reached for invalid request") + return "", nil + }} + for _, req := range []llm.CompletionRequest{{MaxTokens: -1}, {Thinking: "enabled"}} { + if _, _, _, err := p.Complete(context.Background(), req); err == nil { + t.Fatalf("accepted unsupported request: %+v", req) + } + } +} + +func TestChatGPTPlanBridgeCompactionThinkingOmitted(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if _, ok := body["max_output_tokens"]; ok { + t.Error("compaction cap sent") + } + if _, ok := body["thinking"]; ok { + t.Error("thinking override sent") + } + if _, ok := body["reasoning"]; ok { + t.Error("reasoning override sent") + } + fmt.Fprint(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n") + })) + defer server.Close() + p := ChatGPTPlanProvider{Client: chatgptplan.Client{Endpoint: server.URL, HTTPClient: server.Client()}, Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { return "test", nil }} + for _, req := range []llm.CompletionRequest{{Thinking: "disabled", MaxTokens: 8000}, {MaxTokens: 1500}, {MaxTokens: 1234, Tools: []llm.ToolSchema{{Name: "read", InputSchema: map[string]any{"type": "object"}}}}} { + if _, _, _, err := p.Complete(context.Background(), req); err != nil { + t.Fatal(err) + } + } +} + +func TestChatGPTPlanBridgeNormaSession(t *testing.T) { + for _, scenario := range []string{"replay", "interrupted", "refusal"} { + t.Run(scenario, func(t *testing.T) { + requests, executions := 0, 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + var body struct { + Input []json.RawMessage `json:"input"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + return + } + if requests == 2 { + raw, _ := json.Marshal(body.Input) + for _, want := range []string{`"encrypted_content":"opaque"`, `"namespace":"artex"`, `"call_id":"call-1"`, `"type":"function_call_output"`, `"output":"tool result"`} { + if !strings.Contains(string(raw), want) { + t.Errorf("replay missing %s: %s", want, raw) + } + } + fmt.Fprint(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"done\"}]}]}}\n\n") + return + } + if scenario == "interrupted" { + fmt.Fprint(w, "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"a\"}}\n\n") + return + } + output := `[{"type":"reasoning","id":"r","encrypted_content":"opaque"},{"type":"function_call","id":"a","namespace":"artex","name":"read","arguments":"{}","call_id":"call-1"}]` + if scenario == "refusal" { + output = `[{"type":"function_call","id":"a","namespace":"artex","name":"read","arguments":"{}","call_id":"call-1"},{"type":"message","role":"assistant","content":[{"type":"refusal","refusal":"Cannot help."}]}]` + } + fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":%s}}\n\n", output) + })) + defer server.Close() + p := &ChatGPTPlanProvider{Client: chatgptplan.Client{Endpoint: server.URL, HTTPClient: server.Client()}, Model: "test", AccountID: "account-a", Token: func(context.Context) (string, error) { return "test", nil }} + probe := tool.Build(tool.Spec{Name: "read", Schema: map[string]any{"type": "object"}, Run: func(context.Context, json.RawMessage, *tool.ToolContext) (tool.Result, error) { + executions++ + return tool.Text("tool result"), nil + }}) + opts := agentcore.Options{Provider: p, Tools: []tool.CoreTool{probe}, PermissionMode: permission.ModeBypass, WorkingDir: t.TempDir(), MaxTurns: 2} + if scenario == "refusal" { + msg, stop, _, err := p.Complete(context.Background(), llm.CompletionRequest{Tools: []llm.ToolSchema{{Name: "read", InputSchema: map[string]any{"type": "object"}}}}) + if err != nil || stop != "refusal" || msg.Text() != "Cannot help." || len(msg.ToolUses()) != 0 { + t.Fatalf("refusal: msg=%+v stop=%s err=%v", msg, stop, err) + } + requests = 0 + } + text, err := agentcore.Run(context.Background(), opts, "go") + switch scenario { + case "replay": + if err != nil || text != "done" || requests != 2 || executions != 1 { + t.Fatalf("text=%q err=%v requests=%d executions=%d", text, err, requests, executions) + } + case "interrupted": + if err == nil || executions != 0 || requests != 1 { + t.Fatalf("err=%v requests=%d executions=%d", err, requests, executions) + } + case "refusal": + if executions != 0 || requests != 1 { + t.Fatalf("text=%q err=%v requests=%d executions=%d", text, err, requests, executions) + } + } + }) + } +} + +func TestChatGPTPlanBridgeRejectsCrossAccountReplay(t *testing.T) { + called := false + p := ChatGPTPlanProvider{Model: "test", AccountID: "account-b", Token: func(context.Context) (string, error) { called = true; return "test", nil }} + msg := llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockRedactedThinking, Data: planAccountCarrier("account-a") + `{"type":"reasoning","encrypted_content":"private"}`}}} + if _, _, _, err := p.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{msg}}); err == nil { + t.Fatal("accepted another account's carrier") + } + if called { + t.Fatal("token callback reached for cross-account replay") + } +} diff --git a/agent/provider.go b/agent/provider.go index e5e3d4abd..c74daf9bd 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -39,6 +39,9 @@ type Config struct { BaseURL string APIKey string Model string + // ChatGPTAccountID identifies an independently authorized plan account. + // Its tokens are acquired by the server on each request, not stored here. + ChatGPTAccountID int64 // Proxy routes all LLM requests through the given proxy URL (http/https/socks5, // optionally with user:pass@ credentials). Empty means direct — it does NOT // fall back to the standard *_PROXY environment variables. @@ -145,7 +148,10 @@ const ( // forcing our base-URL/key defaults so an empty key never falls back to // OpenAI's public endpoint). const FormatOllama llm.Format = "ollama" +const FormatOpenRouter llm.Format = "openrouter" +const DefaultOpenRouterBaseURL = "https://openrouter.ai/api/v1" const FormatBedrockGateway llm.Format = "bedrock-gateway" +const FormatChatGPTPlan llm.Format = "chatgpt-plan" // DefaultOllamaBaseURL is the base of Ollama's OpenAI-compatible endpoint the // provider appends /chat/completions to. Must never end up empty: with an @@ -177,7 +183,7 @@ func normalizeOllamaBaseURL(raw string) string { // NeedsAPIKey reports whether this provider format requires an API key to be // usable. Ollama (local server) is keyless; every cloud format needs one. -func (c Config) NeedsAPIKey() bool { return c.Format != FormatOllama } +func (c Config) NeedsAPIKey() bool { return c.Format != FormatOllama && c.Format != FormatChatGPTPlan } // CompactionWindow returns the model context window in TOKENS for compaction // thresholds, resolved from the user-configured size (ContextWindowK). 0/unset → @@ -224,11 +230,11 @@ func compactionConfig(windowTokens int) *compaction.Config { // FromEnv resolves the LLM provider config: // -// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama (default: inferred from keys) +// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|openrouter|ollama (default: inferred from keys) // ARTEX_LLM_MODEL = model id (default: per provider) // ARTEX_LLM_BASE_URL = endpoint (optional; ollama defaults to localhost:11434/v1) // ARTEX_LLM_PROXY = proxy URL (optional; http/https/socks5) -// ANTHROPIC_API_KEY / OPENAI_API_KEY = credentials (unused for ollama) +// ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY = credentials (unused for ollama) func FromEnv() (Config, bool) { // Case- and space-insensitive: "Ollama" used to miss every case below and // fall through to anthropic, sending ANTHROPIC_API_KEY to the Ollama base URL. @@ -268,6 +274,12 @@ func FromEnv() (Config, bool) { if c.Model == "" { c.Model = "gpt-5" } + case "openrouter": + c = ConfigFrom("openrouter", c.Model, c.BaseURL, os.Getenv("OPENROUTER_API_KEY"), c.Proxy) + c.Stream = !isFalsy(os.Getenv("ARTEX_LLM_STREAM")) + case "chatgpt-plan": + // ChatGPT plan access requires a saved, authorized account, not env keys. + return Config{}, false case "ollama": c.Format = FormatOllama // Deliberately NOT inheriting OPENAI_API_KEY: a local Ollama ignores the @@ -312,6 +324,10 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config { Stream: true, // streaming by default; the caller overrides per profile } switch strings.TrimSpace(provider) { + case "chatgpt-plan": + c.Format = FormatChatGPTPlan + // Only the server's authorized account token source may supply credentials. + c.BaseURL, c.APIKey, c.Proxy = "", "", "" case "openai": c.Format = llm.FormatOpenAI // provider appends "/chat/completions"; tolerate a full endpoint URL. @@ -319,6 +335,15 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config { if c.Model == "" { c.Model = "gpt-4o" } + case "openrouter": + c.Format = FormatOpenRouter + c.BaseURL = strings.TrimRight(strings.TrimSuffix(c.BaseURL, "/chat/completions"), "/") + if c.BaseURL == "" { + c.BaseURL = DefaultOpenRouterBaseURL + } + if c.Model == "" { + c.Model = "openrouter/auto" + } case "openai-responses": c.Format = llm.FormatOpenAIResponses // provider appends "/responses"; tolerate a full endpoint URL. @@ -362,7 +387,7 @@ func isFalsy(s string) bool { } // Provider returns the short provider name -// ("anthropic"/"openai"/"openai-responses"/"ollama"). +// ("anthropic"/"openai"/"openai-responses"/"openrouter"/"ollama"). func (c Config) Provider() string { switch c.Format { case llm.FormatOpenAI: @@ -371,8 +396,12 @@ func (c Config) Provider() string { return "openai-responses" case FormatOllama: return "ollama" + case FormatOpenRouter: + return "openrouter" case FormatBedrockGateway: return "bedrock-gateway" + case FormatChatGPTPlan: + return "chatgpt-plan" } return "anthropic" } @@ -381,6 +410,9 @@ func (c Config) Provider() string { // limiter lives on the single provider instance — so planner + all workers + // main agent (which share this provider) are bounded by one shared rate limit. func (c Config) NewProvider() (llm.Provider, error) { + if c.Format == FormatChatGPTPlan { + return nil, errors.New("ChatGPT plan profiles require an authorized account managed by the server") + } client, err := quotaAwareHTTPClient(c.Proxy, c.SessionHeaderKey, c.UserAgent) if err != nil { return nil, err @@ -393,6 +425,15 @@ func (c Config) NewProvider() (llm.Provider, error) { // driven fallbacks: BaseURL to OpenAI's public endpoint, APIKey to // OPENAI_API_KEY. A local Ollama ignores the placeholder token; a gateway // that requires one carries a real key in the profile. + if wireFormat == FormatOpenRouter { + if strings.TrimSpace(apiKey) == "" { + return nil, errors.New("OpenRouter API key is required") + } + if strings.TrimSpace(baseURL) == "" { + baseURL = DefaultOpenRouterBaseURL + } + wireFormat = llm.FormatOpenAI + } if wireFormat == FormatOllama { wireFormat = llm.FormatOpenAI if strings.TrimSpace(baseURL) == "" { diff --git a/chatgptauth/README.md b/chatgptauth/README.md new file mode 100644 index 000000000..26cb64f4a --- /dev/null +++ b/chatgptauth/README.md @@ -0,0 +1,10 @@ +# Sign in with ChatGPT: Go primitives + +This module implements the public-client open-source sign-in flow described in the [registration guide](https://developers.openai.com/siwc/token-sharing-open-source/sign-in) and [accounts and sessions guide](https://developers.openai.com/siwc/token-sharing-open-source/profiles-and-sessions). It uses `go-oidc` to verify RS256 ID token signatures against the configured issuer's JWKS. Production defaults match OpenAI's discovery document. Configure overrides only with trusted endpoints and a trusted HTTP transport. + +1. Generate and persist a host ID in an OpenAI-supported format. Start a listener on `127.0.0.1` with path `/auth/callback` before calling `NewClient(Config{}).Start(Options{HostID: ..., AgentName: ..., RedirectURI: ...})`. Open the resulting URL in the system browser. Never log the URL: reauthorization URLs can contain an ID token hint. +2. Pass the full callback URL and the original attempt to `Complete`. The attempt is consumed on every call, including failures. `Result.ClientID` is available after a valid callback even if token exchange or validation fails, so an issued registration can be retained for a fresh sign-in after an invalid grant. Save credentials only after successful completion, keyed separately by issuer, issued client ID, and verified subject. +3. For a returning account, call `Start` with its issued `ClientID`, `ExpectedSubject`, and optionally the ID token and email from that same account as `IDTokenHint` and `LoginHint`. The newly verified subject must match. Never mix registrations, even when emails match. +4. Call `Refresh` near expiry with the issued client ID and most recent tokens. Serialize refreshes per account across processes and atomically store replacements. An `ErrInvalidGrant` requires fresh authorization. Refresh does not authenticate a new identity. If returned scope omits direct access, `ErrScope` requires fresh authorization; do not use the returned credentials. + +`Tokens` contains secrets. Protect them at rest, never print or log them, and do not send them to browser storage. Keep the attempt object private and do not copy it. The caller owns the listener, UI, account selection, secure persistence, token lifetime tracking, and sign-out/revocation. Attempts live only in this process; cross-process transaction storage and coordination are outside this package. Network errors and server response bodies are deliberately redacted. The token and JWKS clients refuse HTTP redirects. The package does not call discovery or implement revocation; the caller should follow the provider's session-ending guidance. diff --git a/chatgptauth/auth.go b/chatgptauth/auth.go new file mode 100644 index 000000000..d45ee66c4 --- /dev/null +++ b/chatgptauth/auth.go @@ -0,0 +1,382 @@ +// Package chatgptauth implements the public-client Sign in with ChatGPT OSS flow. +// It does not provide a listener, persistent storage, or refresh synchronization. +package chatgptauth + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/coreos/go-oidc/v3/oidc" +) + +const ( + Issuer = "https://auth.openai.com" + AuthorizationEndpoint = Issuer + "/api/accounts/authorize" + TokenEndpoint = Issuer + "/api/accounts/oauth/token" + JWKSURI = Issuer + "/.well-known/jwks.json" + Resource = "https://api.openai.com/v1" + DirectScope = "chatgpt.tokens.use.direct" + scopes = "openid profile email offline_access resource.invoke " + DirectScope + dynamicClient = "dynamic_agent_client" +) + +var ( + ErrAttempt = errors.New("invalid, expired, or consumed authorization attempt") + ErrCallback = errors.New("invalid authorization callback") + ErrAuthorization = errors.New("authorization failed") + ErrToken = errors.New("token request failed") + ErrInvalidGrant = errors.New("token grant is invalid; reauthorize") + ErrIdentity = errors.New("ID token validation failed") + ErrScope = errors.New("required ChatGPT plan scope was not granted") +) + +// Config endpoints must be trusted; overrides exist for tests and alternate issuers. +// HTTPClient must use a trusted transport. Redirects are refused for token and JWKS requests. +type Config struct { + Issuer, AuthorizationEndpoint, TokenEndpoint, JWKSURI, Resource string + HTTPClient *http.Client +} +type Client struct { + issuer, authorization, token, jwks, resource string + http *http.Client +} + +func NewClient(c Config) *Client { + if c.Issuer == "" { + c.Issuer = Issuer + } + if c.AuthorizationEndpoint == "" { + c.AuthorizationEndpoint = AuthorizationEndpoint + } + if c.TokenEndpoint == "" { + c.TokenEndpoint = TokenEndpoint + } + if c.JWKSURI == "" { + c.JWKSURI = JWKSURI + } + if c.Resource == "" { + c.Resource = Resource + } + h := http.Client{Timeout: 30 * time.Second} + if c.HTTPClient != nil { + h = *c.HTTPClient + } + h.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &Client{c.Issuer, c.AuthorizationEndpoint, c.TokenEndpoint, c.JWKSURI, c.Resource, &h} +} + +// Options select a new registration (empty ClientID) or an existing account. +// For reauthorization ExpectedSubject must be the selected account's verified subject. +// Hints must belong to that account; host ID must be stable for the host. +// RetryRegistration is only for a newly issued client whose first exchange failed; +// it cannot carry account hints or an expected subject. Do not use it to replace an account. +// RequestConsent requests consent again for an existing verified account. +type Options struct { + HostID, AgentName, RedirectURI, ClientID, ExpectedSubject, IDTokenHint, LoginHint string + RetryRegistration bool + RequestConsent bool +} +type Attempt struct { + mu sync.Mutex + used bool + state, nonce, verifier, redirect, clientID, subject string + expires time.Time +} + +func randomString() (string, error) { + b := make([]byte, 32) + if _, e := rand.Read(b); e != nil { + return "", e + } + return base64.RawURLEncoding.EncodeToString(b), nil +} +func validRedirect(s string) bool { + u, e := url.Parse(s) + if e != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.User != nil || u.Path != "/auth/callback" || u.RawPath != "" || u.RawQuery != "" || u.Fragment != "" || u.ForceQuery { + return false + } + p, e := strconv.Atoi(u.Port()) + return e == nil && p > 0 && p <= 65535 && u.Host == "127.0.0.1:"+strconv.Itoa(p) +} + +// Start creates a ten-minute, one-use attempt and its authorization URL. Start the +// caller-owned loopback listener before opening the URL. Do not log the URL. +func (c *Client) Start(o Options) (string, *Attempt, error) { + if o.RequestConsent && (o.ClientID == "" || o.ExpectedSubject == "" || o.RetryRegistration) { + return "", nil, ErrAttempt + } + if !validRedirect(o.RedirectURI) || strings.TrimSpace(o.HostID) == "" || (o.ClientID == "" && (strings.TrimSpace(o.AgentName) == "" || o.ExpectedSubject != "" || o.IDTokenHint != "" || o.LoginHint != "" || o.RetryRegistration)) || (o.ClientID != "" && (o.ClientID == dynamicClient || (o.ExpectedSubject == "" && !o.RetryRegistration) || (o.RetryRegistration && (o.ExpectedSubject != "" || o.IDTokenHint != "" || o.LoginHint != "")))) { + return "", nil, ErrAttempt + } + state, e := randomString() + if e != nil { + return "", nil, ErrAttempt + } + nonce, e := randomString() + if e != nil { + return "", nil, ErrAttempt + } + verifier, e := randomString() + if e != nil { + return "", nil, ErrAttempt + } + a := &Attempt{state: state, nonce: nonce, verifier: verifier, redirect: o.RedirectURI, clientID: o.ClientID, subject: o.ExpectedSubject, expires: time.Now().Add(10 * time.Minute)} + u, e := url.Parse(c.authorization) + if e != nil || u.Scheme == "" || u.Host == "" || u.RawQuery != "" || u.Fragment != "" { + return "", nil, ErrAttempt + } + id := o.ClientID + if id == "" { + id = dynamicClient + } + sum := sha256.Sum256([]byte(verifier)) + q := url.Values{"client_id": {id}, "ext_agent_host_id": {o.HostID}, "response_type": {"code"}, "redirect_uri": {o.RedirectURI}, "scope": {scopes}, "resource": {c.resource}, "state": {state}, "nonce": {nonce}, "code_challenge_method": {"S256"}, "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}} + if o.RequestConsent { + q.Set("prompt", "consent") + } + if o.ClientID == "" { + q.Set("agent_name_hint", o.AgentName) + } else { + if o.IDTokenHint != "" { + q.Set("id_token_hint", o.IDTokenHint) + } + if o.LoginHint != "" { + q.Set("login_hint", o.LoginHint) + } + } + u.RawQuery = q.Encode() + return u.String(), a, nil +} + +// Tokens contain secrets; store securely and do not log or format them. +type Tokens struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + TokenType string `json:"token_type"` + Scope string `json:"scope"` + ExpiresIn int64 `json:"expires_in"` +} + +// Identity contains only claims verified from the signed ID token. +type Identity struct { + Issuer, Subject, Email, Name, SessionID string + EmailVerified bool +} +type Result struct { + ClientID string + Tokens Tokens + Identity Identity +} + +func one(q url.Values, k string) string { + if len(q[k]) != 1 { + return "" + } + return q.Get(k) +} + +// Complete consumes a exactly once even on failure. The callback is the full URL. +// Result.ClientID is populated after a valid callback, including on exchange failure, +// so the caller can retain a newly issued ID and retry with a fresh attempt. +// ErrScope returns verified Identity and Tokens for a disabled account. The +// caller must not use these tokens for inference without the required scope. +func (c *Client) Complete(ctx context.Context, a *Attempt, callback string) (Result, error) { + var out Result + if a == nil { + return out, ErrAttempt + } + a.mu.Lock() + if a.used { + a.mu.Unlock() + return out, ErrAttempt + } + a.used = true + state, nonce, verifier, redirect, id, subject, expiry := a.state, a.nonce, a.verifier, a.redirect, a.clientID, a.subject, a.expires + a.state = "" + a.nonce = "" + a.verifier = "" + a.mu.Unlock() + if !time.Now().Before(expiry) { + return out, ErrAttempt + } + u, e := url.Parse(callback) + if e != nil || u.Fragment != "" { + return out, ErrCallback + } + u.RawQuery = "" + u.ForceQuery = false + if u.String() != redirect { + return out, ErrCallback + } + original, e := url.Parse(callback) + if e != nil { + return out, ErrCallback + } + q := original.Query() + if issuers, ok := q["iss"]; ok && (len(issuers) != 1 || issuers[0] != c.issuer) { + return out, ErrCallback + } + got := one(q, "state") + if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(state)) != 1 { + return out, ErrCallback + } + if _, ok := q["error"]; ok { + return out, ErrAuthorization + } + code := one(q, "code") + if code == "" { + return out, ErrCallback + } + returned := one(q, "client_id") + if id == "" { + if returned == "" || returned == dynamicClient { + return out, ErrCallback + } + id = returned + } else if len(q["client_id"]) > 0 && returned != id { + return out, ErrCallback + } + out.ClientID = id + t, e := c.tokenRequest(ctx, url.Values{"grant_type": {"authorization_code"}, "client_id": {id}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {redirect}, "resource": {c.resource}}) + if e != nil { + return out, e + } + if t.IDToken == "" { + return out, ErrToken + } + identity, e := c.verify(ctx, t.IDToken, id, nonce) + if e != nil { + return out, ErrIdentity + } + if subject != "" && identity.Subject != subject { + return out, ErrIdentity + } + out.Identity = identity + if !hasScope(t.Scope, DirectScope) { + out.Tokens = t + return out, ErrScope + } + if t.AccessToken == "" { + return out, ErrToken + } + out.Tokens = t + return out, nil +} +func hasScope(s, want string) bool { + for _, v := range strings.Fields(s) { + if v == want { + return true + } + } + return false +} +func (c *Client) tokenRequest(ctx context.Context, form url.Values) (Tokens, error) { + var t Tokens + req, e := http.NewRequestWithContext(ctx, http.MethodPost, c.token, strings.NewReader(form.Encode())) + if e != nil { + return t, ErrToken + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + resp, e := c.http.Do(req) + if e != nil { + return t, ErrToken + } + defer resp.Body.Close() + b, e := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if e != nil { + return t, ErrToken + } + if resp.StatusCode != http.StatusOK { + var x struct { + Error string `json:"error"` + } + if json.Unmarshal(b, &x) == nil && x.Error == "invalid_grant" { + return t, ErrInvalidGrant + } + return t, ErrToken + } + if json.Unmarshal(b, &t) != nil { + return Tokens{}, ErrToken + } + return t, nil +} + +// Refresh exchanges a refresh token for its replacement. Serialize refreshes per +// account and atomically persist rotated credentials. An omitted refresh token or +// scope means retain the previous value. Invalid grants require reauthorization. +func (c *Client) Refresh(ctx context.Context, clientID string, previous Tokens) (Tokens, error) { + if clientID == "" || clientID == dynamicClient || previous.RefreshToken == "" || !hasScope(previous.Scope, DirectScope) { + return Tokens{}, ErrToken + } + t, e := c.tokenRequest(ctx, url.Values{"grant_type": {"refresh_token"}, "client_id": {clientID}, "refresh_token": {previous.RefreshToken}, "resource": {c.resource}}) + if e != nil { + return Tokens{}, e + } + if t.AccessToken == "" { + return Tokens{}, ErrToken + } + if t.RefreshToken == "" { + t.RefreshToken = previous.RefreshToken + } + if t.Scope == "" { + t.Scope = previous.Scope + } + if t.TokenType == "" { + t.TokenType = previous.TokenType + } + if !hasScope(t.Scope, DirectScope) { + return Tokens{}, ErrScope + } + if t.IDToken == "" { + t.IDToken = previous.IDToken + } + return t, nil +} +func (c *Client) verify(ctx context.Context, raw, clientID, nonce string) (Identity, error) { + ctx = oidc.ClientContext(ctx, c.http) + keys := oidc.NewRemoteKeySet(ctx, c.jwks) + verifier := oidc.NewVerifier(c.issuer, keys, &oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}) + tok, e := verifier.Verify(ctx, raw) + if e != nil { + return Identity{}, ErrIdentity + } + var claims struct { + Nonce string `json:"nonce"` + Iat *int64 `json:"iat"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + Name string `json:"name"` + SID *string `json:"sid"` + Azp string `json:"azp"` + Audience json.RawMessage `json:"aud"` + } + if tok.Claims(&claims) != nil || claims.Iat == nil || tok.Subject == "" || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(nonce)) != 1 || claims.Nonce == "" || (claims.SID != nil && strings.TrimSpace(*claims.SID) == "") { + return Identity{}, ErrIdentity + } + var aud []string + if json.Unmarshal(claims.Audience, &aud) == nil && len(aud) > 1 && claims.Azp != clientID { + return Identity{}, ErrIdentity + } + if claims.Azp != "" && claims.Azp != clientID { + return Identity{}, ErrIdentity + } + sid := "" + if claims.SID != nil { + sid = *claims.SID + } + return Identity{tok.Issuer, tok.Subject, claims.Email, claims.Name, sid, claims.EmailVerified}, nil +} diff --git a/chatgptauth/auth_test.go b/chatgptauth/auth_test.go new file mode 100644 index 000000000..c9c95c0b1 --- /dev/null +++ b/chatgptauth/auth_test.go @@ -0,0 +1,211 @@ +package chatgptauth + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "math/big" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" +) + +func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } +func jwt(t *testing.T, k *rsa.PrivateKey, claims map[string]any) string { + t.Helper() + h, _ := json.Marshal(map[string]string{"alg": "RS256", "kid": "one"}) + p, _ := json.Marshal(claims) + s := b64(h) + "." + b64(p) + d := sha256.Sum256([]byte(s)) + sig, e := rsa.SignPKCS1v15(rand.Reader, k, 0, d[:]) + _ = sig + _ = e + // crypto.SHA256 must identify the digest in PKCS#1's DigestInfo. + sig, e = rsa.SignPKCS1v15(rand.Reader, k, crypto.SHA256, d[:]) + if e != nil { + t.Fatal(e) + } + return s + "." + b64(sig) +} + +func TestFlow(t *testing.T) { + key, e := rsa.GenerateKey(rand.Reader, 2048) + if e != nil { + t.Fatal(e) + } + var nonce, mode string + var calls int + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/keys": + json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]string{"kty": "RSA", "kid": "one", "use": "sig", "alg": "RS256", "n": b64(key.N.Bytes()), "e": b64(big.NewInt(int64(key.E)).Bytes())}}}) + case "/token": + calls++ + r.ParseForm() + if r.Form.Get("client_id") != "issued" || r.Form.Get("resource") != Resource { + t.Error("incorrect token form") + } + if r.Form.Get("grant_type") == "refresh_token" { + json.NewEncoder(w).Encode(map[string]any{"access_token": "rotated", "refresh_token": "new"}) + return + } + if r.Form.Get("code_verifier") == "" || r.Form.Get("redirect_uri") != "http://127.0.0.1:1455/auth/callback" { + t.Error("missing exchange binding") + } + claims := map[string]any{"iss": srv.URL, "aud": "issued", "sub": "subject", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), "nonce": nonce} + switch mode { + case "nonce", "invalid_and_scope": + claims["nonce"] = "wrong" + case "issuer": + claims["iss"] = "wrong" + case "aud": + claims["aud"] = "wrong" + case "expired": + claims["exp"] = time.Now().Add(-time.Hour).Unix() + } + id := jwt(t, key, claims) + if mode == "signature" { + id = id[:len(id)-8] + "AAAAAAAA" + } + scope := DirectScope + if mode == "scope" || mode == "invalid_and_scope" || mode == "scope_no_access" { + scope = "openid" + } + access := "access" + if mode == "scope_no_access" { + access = "" + } + json.NewEncoder(w).Encode(map[string]any{"id_token": id, "access_token": access, "refresh_token": "refresh", "scope": scope}) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + c := NewClient(Config{Issuer: srv.URL, AuthorizationEndpoint: srv.URL + "/authorize", TokenEndpoint: srv.URL + "/token", JWKSURI: srv.URL + "/keys", HTTPClient: srv.Client()}) + for _, m := range []string{"ok", "nonce", "issuer", "aud", "expired", "signature", "scope", "scope_no_access", "invalid_and_scope"} { + t.Run(m, func(t *testing.T) { + mode = m + aurl, a, e := c.Start(Options{HostID: "urn:uuid:host", AgentName: "My App", RedirectURI: "http://127.0.0.1:1455/auth/callback"}) + if e != nil { + t.Fatal(e) + } + u, _ := url.Parse(aurl) + q := u.Query() + nonce = q.Get("nonce") + if q.Get("client_id") != dynamicClient || q.Get("agent_name_hint") != "My App" || q.Get("code_challenge_method") != "S256" { + t.Fatal("bad authorization") + } + sum := sha256.Sum256([]byte(a.verifier)) + if q.Get("code_challenge") != b64(sum[:]) { + t.Fatal("bad PKCE") + } + cb := "http://127.0.0.1:1455/auth/callback?" + url.Values{"state": {q.Get("state")}, "client_id": {"issued"}, "code": {"code"}, "iss": {srv.URL}}.Encode() + result, e := c.Complete(context.Background(), a, cb) + if m == "ok" { + if e != nil || result.Identity.Subject != "subject" { + t.Fatalf("valid flow failed: %v", e) + } + refreshed, e := c.Refresh(context.Background(), "issued", result.Tokens) + if e != nil || refreshed.RefreshToken != "new" || refreshed.Scope != DirectScope { + t.Fatalf("refresh failed: %v", e) + } + } else if m == "scope" || m == "scope_no_access" { + if e != ErrScope || result.ClientID != "issued" || result.Identity.Subject != "subject" || result.Tokens.IDToken == "" || hasScope(result.Tokens.Scope, DirectScope) { + t.Fatalf("declined scope did not preserve verified identity safely: %v", e) + } + } else if e == nil || result.ClientID != "issued" || result.Tokens.AccessToken != "" || result.Identity.Subject != "" || (m == "invalid_and_scope" && e != ErrIdentity) { + t.Fatalf("accepted invalid %s: %v", m, e) + } + if _, e = c.Complete(context.Background(), a, cb); e != ErrAttempt { + t.Fatal("attempt reused") + } + }) + } + before := calls + for _, issuers := range [][]string{{"https://wrong.example"}, {srv.URL, srv.URL}} { + aurl, attempt, err := c.Start(Options{HostID: "host", AgentName: "app", RedirectURI: "http://127.0.0.1:1455/auth/callback"}) + if err != nil { + t.Fatal(err) + } + u, _ := url.Parse(aurl) + callback := "http://127.0.0.1:1455/auth/callback?" + url.Values{"state": {u.Query().Get("state")}, "client_id": {"issued"}, "code": {"code"}, "iss": issuers}.Encode() + if _, err := c.Complete(context.Background(), attempt, callback); err != ErrCallback || calls != before { + t.Fatal("invalid callback issuer was exchanged") + } + } + _, a, _ := c.Start(Options{HostID: "host", AgentName: "app", RedirectURI: "http://127.0.0.1:1455/auth/callback"}) + if _, e := c.Complete(context.Background(), a, "http://127.0.0.1:1455/auth/callback?state=wrong&code=x&client_id=issued"); e != ErrCallback || calls != before { + t.Fatal("bad state was exchanged") + } + _, a, _ = c.Start(Options{HostID: "host", AgentName: "app", RedirectURI: "http://127.0.0.1:1455/auth/callback"}) + a.expires = time.Now().Add(-time.Second) + if _, e := c.Complete(context.Background(), a, "http://127.0.0.1:1455/auth/callback"); e != ErrAttempt { + t.Fatal("expired attempt accepted") + } + for _, uri := range []string{"http://localhost:1455/auth/callback", "http://127.0.0.1:1455/callback", "http://127.0.0.1/auth/callback", "http://127.0.0.1:1455/auth/callback?x=1"} { + if _, _, e := c.Start(Options{HostID: "host", AgentName: "app", RedirectURI: uri}); e == nil { + t.Fatal("invalid redirect accepted") + } + } + _, aurlAttempt, e := c.Start(Options{HostID: "host", ClientID: "issued", ExpectedSubject: "subject", RedirectURI: "http://127.0.0.1:1455/auth/callback"}) + if e != nil || aurlAttempt == nil { + t.Fatal("reauthorization failed") + } + consentURL, _, e := c.Start(Options{HostID: "host", ClientID: "issued", ExpectedSubject: "subject", RedirectURI: "http://127.0.0.1:1455/auth/callback", RequestConsent: true}) + if e != nil { + t.Fatal("consent request rejected") + } + consentParsed, _ := url.Parse(consentURL) + if consentParsed.Query().Get("prompt") != "consent" { + t.Fatal("consent prompt missing") + } + if _, _, e := c.Start(Options{HostID: "host", AgentName: "app", RedirectURI: "http://127.0.0.1:1455/auth/callback", RequestConsent: true}); e == nil { + t.Fatal("new registration accepted consent option") + } + base := Options{HostID: "host", ClientID: "issued", RedirectURI: "http://127.0.0.1:1455/auth/callback"} + if _, _, e := c.Start(base); e == nil { + t.Fatal("unbound client accepted without retry") + } + base.RetryRegistration = true + base.RequestConsent = true + if _, _, e := c.Start(base); e == nil { + t.Fatal("retry accepted consent option") + } + base.RequestConsent = false + first, _, e := c.Start(base) + if e != nil { + t.Fatal("retry rejected") + } + second, _, e := c.Start(base) + if e != nil || first == second { + t.Fatal("retry did not use fresh values") + } + u, _ := url.Parse(first) + if u.Query().Get("client_id") != "issued" || u.Query().Has("agent_name_hint") { + t.Fatal("invalid retry request") + } + base.LoginHint = "other@example.com" + if _, _, e := c.Start(base); e == nil { + t.Fatal("retry accepted account hint") + } +} +func TestNoSecretInErrors(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(400) + w.Write([]byte(`{"error":"oops","error_description":"sensitive-refresh"}`)) + })) + defer srv.Close() + c := NewClient(Config{TokenEndpoint: srv.URL, HTTPClient: srv.Client()}) + _, e := c.Refresh(context.Background(), "issued", Tokens{RefreshToken: "sensitive-refresh", Scope: DirectScope}) + if e == nil || strings.Contains(e.Error(), "sensitive") { + t.Fatal("unsafe error") + } +} diff --git a/chatgptplan/README.md b/chatgptplan/README.md new file mode 100644 index 000000000..f0536461f --- /dev/null +++ b/chatgptplan/README.md @@ -0,0 +1,18 @@ +# ChatGPT-plan Responses stream client + +This package is a standalone protocol building block, not an ARTEX or norma provider. It performs no OAuth, token refresh, model selection, tool execution, transcript storage, compaction, or automatic retries. No inference has been run to validate account-specific behavior. + +Pass a complete Responses request as JSON with `input` as an array, full history, and function/custom tools grouped in namespaces. Use developer messages or `instructions`. The client forces `store: false` and `stream: true`, and rejects unsupported preview fields and tool types rather than silently discarding requested semantics. Only use a ChatGPT-account model available to the authenticated user. Web search remains subject to account/model policy. + +Supply the token to `Stream`, optionally an injected HTTP client and endpoint, and consume the result only after it returns successfully. A successful result contains the complete raw terminal response and output items, including reasoning and namespaced function calls. Save those items and replay them as part of complete input alongside tool outputs, in order, including any required encrypted reasoning state. Events passed to the callback are provisional and include their raw JSON and correlation identifiers; do not execute tool calls from partial events before successful completion. Missing terminal events, failures, incomplete responses, invalid correlation, and interrupted streams return errors. No credentials or response content are logged. + +A norma bridge must explicitly retain and replay full raw Responses items through transcript persistence and compaction, map namespaced tools and call IDs, and handle provider switching. Norma's opaque redacted-thinking block might serve as a tagged carrier, but preservation across every relevant path and rejection of cross-provider replay require separate verification; this package makes no such integration guarantee. It also does not provide norma's non-streaming interface. + +Preview rules: https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations.md ; streaming and terminal behavior: https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference.md . + +The client rejects empty tokens, does not follow redirects, and applies a ten-minute request timeout when the supplied HTTP client has no positive timeout. It copies the supplied client before applying these settings. Transport and response-body read errors are classified without exposing their underlying error strings or unwrap chains. + +`ListModels` fetches the current account's catalog from the public models endpoint, retaining entries whose visibility is `list` in server order. Use each returned slug for inference and refresh the list when the account changes. It uses the same no-redirect and error-redaction protections as streaming; `ModelsEndpoint` is intended for injected test servers. + + +For non-2xx responses, use errors.As to inspect *HTTPError. StatusCode distinguishes HTTP 403 and 429; Code distinguishes the two subscription-sharing usage errors from rate_limit_exceeded. Code, Type, and Param are allowlisted and may be empty for unknown values. RequestID is retained only in a restricted format. Raw error messages, bodies, and transport causes are never exposed. Handle unknown or empty codes by status rather than assuming their meaning. diff --git a/chatgptplan/client.go b/chatgptplan/client.go new file mode 100644 index 000000000..73823b066 --- /dev/null +++ b/chatgptplan/client.go @@ -0,0 +1,329 @@ +// Package chatgptplan provides the ChatGPT-plan Responses HTTP streaming wire +// protocol. It does not manage OAuth, model selection, conversation history, +// tool execution, or implement norma's provider interface. +package chatgptplan + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// Client uses HTTPClient for requests. Endpoint must be the public Responses +// URL in production; alternate URLs are useful for offline tests. +type Client struct { + HTTPClient *http.Client + Endpoint string + ModelsEndpoint string // defaults to https://api.openai.com/v1/models +} + +// StreamError classifies failures without embedding server bodies or tokens. +type StreamError struct { + Kind string + Code string + HTTPStatus int + Cause error +} + +func (e *StreamError) Error() string { + if e.HTTPStatus != 0 { + return fmt.Sprintf("chatgptplan: %s (HTTP %d)", e.Kind, e.HTTPStatus) + } + if e.Code != "" { + return fmt.Sprintf("chatgptplan: %s (%s)", e.Kind, e.Code) + } + return "chatgptplan: " + e.Kind +} +func (e *StreamError) Unwrap() error { return e.Cause } + +// Event carries the untouched event JSON and its correlation identifiers. +// The callback must copy Data if it needs to retain or modify it independently. +type Event struct { + Type string + OutputIndex *int + ItemID string + Data json.RawMessage +} + +// Result preserves the full terminal response and each complete output item. +// Preserve Output in order and replay it with tool outputs as appropriate. +type Result struct { + Response json.RawMessage + Output []json.RawMessage +} + +var forbidden = map[string]bool{"background": true, "conversation": true, "max_output_tokens": true, "max_tool_calls": true, "metadata": true, "moderation": true, "multi_agent": true, "prompt": true, "prompt_cache_retention": true, "safety_identifier": true, "temperature": true, "top_logprobs": true, "top_p": true, "truncation": true, "user": true, "previous_response_id": true} + +// Stream validates a complete stateless Responses request and consumes its SSE +// stream. token is used only as a Bearer header. The caller owns history and +// must retain returned reasoning items and function calls when continuing. +func (c Client) Stream(ctx context.Context, token string, request json.RawMessage, onEvent func(Event)) (*Result, error) { + if strings.TrimSpace(token) == "" { + return nil, &StreamError{Kind: "empty_token"} + } + body, err := prepare(request) + if err != nil { + return nil, err + } + endpoint := c.Endpoint + if endpoint == "" { + endpoint = "https://api.openai.com/v1/responses" + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, &StreamError{Kind: "request"} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Authorization", "Bearer "+token) + client := c.safeHTTPClient() + resp, err := client.Do(req) + if err != nil { + // Transport errors may contain request details or secrets. Do not expose + // their message or an unwrap path to the caller. + return nil, &StreamError{Kind: "transport"} + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, parseHTTPError(resp, token) + } + return consume(resp.Body, onEvent) +} + +func (c Client) safeHTTPClient() *http.Client { + base := c.HTTPClient + if base == nil { + base = http.DefaultClient + } + // Copy, rather than mutate, a caller-owned client. Never forward credentials + // on redirects, even if the supplied client permits them. + client := *base + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + if client.Timeout <= 0 { + client.Timeout = 10 * time.Minute + } + return &client +} +func prepare(raw []byte) ([]byte, error) { + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil || obj == nil { + return nil, errors.New("chatgptplan: request must be a JSON object") + } + for k := range obj { + if forbidden[k] { + return nil, fmt.Errorf("chatgptplan: unsupported request field %s", k) + } + } + var input []json.RawMessage + if err := json.Unmarshal(obj["input"], &input); err != nil || input == nil { + return nil, errors.New("chatgptplan: input must be an array") + } + for _, rawItem := range input { + if err := rejectUnsupportedInput(rawItem); err != nil { + return nil, err + } + var item struct { + Role string `json:"role"` + Type string `json:"type"` + } + if json.Unmarshal(rawItem, &item) != nil { + return nil, errors.New("chatgptplan: invalid input item") + } + if item.Role == "system" { + return nil, errors.New("chatgptplan: system input is unsupported; use developer or instructions") + } + if item.Type == "additional_tools" { + return nil, errors.New("chatgptplan: additional_tools input is not supported by this client") + } + } + if rawTools, ok := obj["tools"]; ok { + var tools []struct { + Type string `json:"type"` + Name string `json:"name"` + Description string `json:"description"` + Tools []struct { + Type string `json:"type"` + Name string `json:"name"` + } `json:"tools"` + } + if json.Unmarshal(rawTools, &tools) != nil || tools == nil { + return nil, errors.New("chatgptplan: tools must be an array") + } + for _, t := range tools { + switch t.Type { + case "namespace": + if t.Name == "" || t.Description == "" || len(t.Tools) == 0 { + return nil, errors.New("chatgptplan: invalid namespace") + } + for _, f := range t.Tools { + if (f.Type != "function" && f.Type != "custom") || f.Name == "" { + return nil, errors.New("chatgptplan: invalid namespace tool") + } + } + case "web_search", "web_search_preview": + default: + return nil, fmt.Errorf("chatgptplan: unsupported tool type %q", t.Type) + } + } + } + obj["store"] = json.RawMessage("false") + obj["stream"] = json.RawMessage("true") + return json.Marshal(obj) +} + +// Reject input variants the preview cannot process, including nested content. +func rejectUnsupportedInput(raw json.RawMessage) error { + var value any + if err := json.Unmarshal(raw, &value); err != nil { + return errors.New("chatgptplan: invalid input item") + } + var walk func(any) error + walk = func(v any) error { + switch x := v.(type) { + case map[string]any: + if typ, ok := x["type"].(string); ok { + if strings.Contains(typ, "audio") || strings.Contains(typ, "video") || typ == "tool_search_call" || typ == "tool_search_output" { + return fmt.Errorf("chatgptplan: unsupported input type %q", typ) + } + } + for _, child := range x { + if err := walk(child); err != nil { + return err + } + } + case []any: + for _, child := range x { + if err := walk(child); err != nil { + return err + } + } + } + return nil + } + return walk(value) +} + +func consume(r io.Reader, cb func(Event)) (*Result, error) { + scanner := bufio.NewScanner(r) + scanner.Buffer(make([]byte, 4096), 16<<20) + var name string + var lines []string + byIndex := map[int]string{} + dispatch := func() (*Result, error) { + if len(lines) == 0 { + name = "" + return nil, nil + } + data := []byte(strings.Join(lines, "\n")) + lines = nil + var v struct { + Type string `json:"type"` + OutputIndex *int `json:"output_index"` + ItemID string `json:"item_id"` + Item struct { + ID string `json:"id"` + } `json:"item"` + Response json.RawMessage `json:"response"` + Error struct { + Code string `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal(data, &v); err != nil { + return nil, &StreamError{Kind: "invalid_event", Cause: err} + } + kind := name + name = "" + if kind == "" { + kind = v.Type + } + if kind == "" { + return nil, &StreamError{Kind: "invalid_event"} + } + if kind == "response.output_item.added" { + if v.OutputIndex == nil || v.Item.ID == "" { + return nil, &StreamError{Kind: "invalid_event"} + } + if old, ok := byIndex[*v.OutputIndex]; ok && old != v.Item.ID { + return nil, &StreamError{Kind: "invalid_event"} + } + byIndex[*v.OutputIndex] = v.Item.ID + } + if strings.HasPrefix(kind, "response.function_call_arguments.") { + if v.OutputIndex == nil || v.ItemID == "" || byIndex[*v.OutputIndex] != v.ItemID { + return nil, &StreamError{Kind: "invalid_event"} + } + } + if cb != nil { + cb(Event{Type: kind, OutputIndex: v.OutputIndex, ItemID: v.ItemID, Data: append(json.RawMessage(nil), data...)}) + } + switch kind { + case "response.failed", "response.incomplete", "error": + var info struct { + Error struct { + Code string `json:"code"` + } `json:"error"` + IncompleteDetails struct { + Reason string `json:"reason"` + } `json:"incomplete_details"` + } + _ = json.Unmarshal(v.Response, &info) + code := info.Error.Code + if code == "" { + code = info.IncompleteDetails.Reason + } + if code == "" { + code = v.Error.Code + } + if !knownCodes[code] && code != "max_output_tokens" && code != "content_filter" { + code = "" + } + return nil, &StreamError{Kind: kind, Code: code} + case "response.completed": + var terminal struct { + Status string `json:"status"` + Output []json.RawMessage `json:"output"` + } + if json.Unmarshal(v.Response, &terminal) != nil || terminal.Status != "completed" || terminal.Output == nil { + return nil, &StreamError{Kind: "invalid_terminal"} + } + return &Result{Response: append(json.RawMessage(nil), v.Response...), Output: terminal.Output}, nil + } + return nil, nil + } + for scanner.Scan() { + line := scanner.Text() + if line == "" { + result, err := dispatch() + if err != nil || result != nil { + return result, err + } + continue + } + if strings.HasPrefix(line, ":") { + continue + } + field, value, ok := strings.Cut(line, ":") + if !ok { + value = "" + } + value = strings.TrimPrefix(value, " ") + switch field { + case "event": + name = value + case "data": + lines = append(lines, value) + } + } + if err := scanner.Err(); err != nil { + return nil, &StreamError{Kind: "interrupted"} + } + // SSE events require a blank-line terminator; an unterminated last event is interrupted. + return nil, &StreamError{Kind: "interrupted", Cause: io.ErrUnexpectedEOF} +} diff --git a/chatgptplan/client_test.go b/chatgptplan/client_test.go new file mode 100644 index 000000000..0477c80c8 --- /dev/null +++ b/chatgptplan/client_test.go @@ -0,0 +1,117 @@ +package chatgptplan + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestInterleavedCallsAndReplayItems(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if string(body["store"]) != "false" || string(body["stream"]) != "true" { + t.Errorf("flags: %s %s", body["store"], body["stream"]) + } + if r.Header.Get("Authorization") != "Bearer test-token" { + t.Error("missing authorization") + } + w.Header().Set("Content-Type", "text/event-stream") + for _, e := range []string{ + `{"type":"response.output_item.added","output_index":0,"item":{"id":"a","type":"function_call"}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"id":"b","type":"function_call"}}`, + `{"type":"response.function_call_arguments.delta","output_index":0,"item_id":"a","delta":"a"}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"item_id":"b","delta":"b"}`, + `{"type":"response.completed","response":{"status":"completed","output":[{"type":"reasoning","id":"r","encrypted_content":"opaque"},{"type":"function_call","id":"a","namespace":"local","name":"read","arguments":"{}","call_id":"c1"},{"type":"function_call","id":"b","namespace":"local","name":"read","arguments":"{}","call_id":"c2"}]}}`, + } { + fmt.Fprintf(w, "data: %s\n\n", e) + } + })) + defer srv.Close() + req := json.RawMessage(`{"model":"test","input":[{"role":"user","content":"hello"}],"stream":false,"store":true,"tools":[{"type":"namespace","name":"local","description":"Local tools","tools":[{"type":"function","name":"read","parameters":{"type":"object"}}]}]}`) + var got []string + result, err := (Client{HTTPClient: srv.Client(), Endpoint: srv.URL}).Stream(context.Background(), "test-token", req, func(e Event) { + if strings.Contains(e.Type, "arguments.delta") { + got = append(got, fmt.Sprintf("%d:%s", *e.OutputIndex, e.ItemID)) + } + }) + if err != nil { + t.Fatal(err) + } + if strings.Join(got, ",") != "0:a,1:b" { + t.Fatalf("correlation %v", got) + } + if len(result.Output) != 3 || !strings.Contains(string(result.Output[0]), `"encrypted_content":"opaque"`) || !strings.Contains(string(result.Output[1]), `"namespace":"local"`) { + t.Fatalf("output %s", result.Response) + } +} +func TestTerminalFailures(t *testing.T) { + for _, tc := range []struct{ name, wire, kind, code string }{ + {"eof", "data: {\"type\":\"response.created\"}\n\n", "interrupted", ""}, + {"truncated terminal", "data: {\"type\":\"response.completed\"}", "interrupted", ""}, + {"failed", "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"rate_limit_exceeded\"}}}\n\n", "response.failed", "rate_limit_exceeded"}, + {"incomplete", "data: {\"type\":\"response.incomplete\",\"response\":{\"incomplete_details\":{\"reason\":\"content_filter\"}}}\n\n", "response.incomplete", "content_filter"}, + {"wrong correlation", "data: {\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"item_id\":\"unknown\"}\n\n", "invalid_event", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := consume(strings.NewReader(tc.wire), nil) + var se *StreamError + if !errors.As(err, &se) || se.Kind != tc.kind || se.Code != tc.code { + t.Fatalf("error %#v", err) + } + }) + } +} +func TestRejectUnsupportedRequests(t *testing.T) { + for _, s := range []string{`{"input":[],"temperature":0}`, `{"input":[],"previous_response_id":"x"}`, `{"input":[{"role":"system","content":"x"}]}`, `{"input":[],"tools":[{"type":"function","name":"x"}]}`, `{"input":[],"tools":[{"type":"file_search"}]}`, `{"input":"hello"}`, `{"input":[],"tools":[{"type":"namespace","name":"n","description":"d","tools":[{"type":"tool_search","name":"x"}]}]}`} { + if _, err := prepare([]byte(s)); err == nil { + t.Errorf("accepted %s", s) + } + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestCredentialsAndTimeout(t *testing.T) { + var reached bool + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true })) + defer target.Close() + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect) + })) + defer source.Close() + original := source.Client() + c := Client{HTTPClient: original, Endpoint: source.URL} + _, err := c.Stream(context.Background(), "test-token", json.RawMessage(`{"input":[]}`), nil) + var se *StreamError + if !errors.As(err, &se) || se.Kind != "http" || se.HTTPStatus != 307 || reached { + t.Fatalf("redirect: %v reached=%v", err, reached) + } + if original.CheckRedirect != nil || original.Timeout != 0 { + t.Fatal("mutated supplied client") + } + _, err = c.Stream(context.Background(), " \t", json.RawMessage(`{"input":[]}`), nil) + if !errors.As(err, &se) || se.Kind != "empty_token" { + t.Fatalf("empty token: %v", err) + } + secret := "transport-secret" + transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { + if _, ok := r.Context().Deadline(); !ok { + t.Error("missing default timeout") + } + return nil, fmt.Errorf("request contained %s", secret) + }) + _, err = (Client{HTTPClient: &http.Client{Transport: transport}, Endpoint: "https://example.invalid"}).Stream(context.Background(), "token", json.RawMessage(`{"input":[]}`), nil) + if !errors.As(err, &se) || se.Kind != "transport" || errors.Unwrap(err) != nil || strings.Contains(fmt.Sprintf("%+v", err), secret) { + t.Fatalf("transport error leaked: %v", err) + } +} diff --git a/chatgptplan/errors.go b/chatgptplan/errors.go new file mode 100644 index 000000000..a0ee56c67 --- /dev/null +++ b/chatgptplan/errors.go @@ -0,0 +1,71 @@ +package chatgptplan + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" +) + +// HTTPError is an unsuccessful HTTP response. Its fields are restricted to +// recognized values; empty values mean absent or not recognized. RequestID is +// retained only in a conservative OpenAI request-ID format. +type HTTPError struct { + StatusCode int + Code, Type, Param, RequestID string +} + +func (e *HTTPError) Error() string { + if e.Code != "" { + return fmt.Sprintf("chatgptplan: HTTP %d (%s)", e.StatusCode, e.Code) + } + return fmt.Sprintf("chatgptplan: HTTP %d", e.StatusCode) +} + +// Unwrap retains compatibility with clients classifying HTTP errors by Kind. +func (e *HTTPError) Unwrap() error { return &StreamError{Kind: "http", HTTPStatus: e.StatusCode} } + +var knownCodes = map[string]bool{ + "subscription_sharing_usage_limit_exceeded": true, "subscription_sharing_usage_unavailable": true, + "rate_limit_exceeded": true, "insufficient_quota": true, "invalid_api_key": true, "invalid_request_error": true, + "authentication_error": true, "permission_denied": true, "access_denied": true, "model_not_found": true, + "server_error": true, "service_unavailable": true, "context_length_exceeded": true, +} +var knownTypes = map[string]bool{"invalid_request_error": true, "authentication_error": true, "permission_error": true, "rate_limit_error": true, "server_error": true, "api_error": true, "insufficient_quota": true} +var knownParams = map[string]bool{"model": true, "input": true, "tools": true, "stream": true, "store": true, "instructions": true, "reasoning": true, "tool_choice": true, "include": true} +var requestIDPattern = regexp.MustCompile(`^req_[A-Za-z0-9]{1,64}$`) + +func safeKnown(value, token string, known map[string]bool) string { + if value == "" || !known[value] || (token != "" && strings.Contains(value, token)) { + return "" + } + return value +} +func parseHTTPError(resp *http.Response, token string) error { + result := &HTTPError{StatusCode: resp.StatusCode} + id := resp.Header.Get("x-request-id") + if requestIDPattern.MatchString(id) && (token == "" || !strings.Contains(id, token)) { + result.RequestID = id + } + const maxErrorBody = 64 << 10 + raw, err := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody+1)) + if err != nil || len(raw) > maxErrorBody { + return result + } + var body struct { + Error struct { + Code string `json:"code"` + Type string `json:"type"` + Param string `json:"param"` + } `json:"error"` + } + if json.Unmarshal(raw, &body) != nil { + return result + } + result.Code = safeKnown(body.Error.Code, token, knownCodes) + result.Type = safeKnown(body.Error.Type, token, knownTypes) + result.Param = safeKnown(body.Error.Param, token, knownParams) + return result +} diff --git a/chatgptplan/errors_test.go b/chatgptplan/errors_test.go new file mode 100644 index 000000000..a7aaf4135 --- /dev/null +++ b/chatgptplan/errors_test.go @@ -0,0 +1,63 @@ +package chatgptplan + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestStructuredHTTPErrors(t *testing.T) { + for _, tc := range []struct { + status int + code, typ, param string + }{ + {429, "subscription_sharing_usage_limit_exceeded", "rate_limit_error", "model"}, + {429, "subscription_sharing_usage_unavailable", "rate_limit_error", ""}, + {429, "rate_limit_exceeded", "rate_limit_error", ""}, + {403, "permission_denied", "permission_error", ""}, + } { + t.Run(tc.code, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("x-request-id", "req_ABC123") + w.WriteHeader(tc.status) + fmt.Fprintf(w, `{"error":{"code":%q,"type":%q,"param":%q,"message":"do not expose secret"}}`, tc.code, tc.typ, tc.param) + })) + defer srv.Close() + c := Client{HTTPClient: srv.Client(), Endpoint: srv.URL, ModelsEndpoint: srv.URL} + for _, call := range []func() error{func() error { _, e := c.ListModels(context.Background(), "test-secret"); return e }, func() error { + _, e := c.Stream(context.Background(), "test-secret", json.RawMessage(`{"input":[]}`), nil) + return e + }} { + err := call() + var he *HTTPError + if !errors.As(err, &he) || he.StatusCode != tc.status || he.Code != tc.code || he.Type != tc.typ || he.Param != tc.param || he.RequestID != "req_ABC123" { + t.Fatalf("error %#v", err) + } + if strings.Contains(fmt.Sprintf("%+v", err), "secret") { + t.Fatal("leaked message") + } + } + }) + } +} +func TestUntrustedErrorFieldsAndLimit(t *testing.T) { + for _, payload := range []string{`{"error":{"code":"token-secret","type":"x\nInjected","param":"https://evil","message":"token-secret"}}`, strings.Repeat("x", (64<<10)+1)} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("x-request-id", "req_token-secret") + w.WriteHeader(429) + w.Write([]byte(payload)) + })) + c := Client{HTTPClient: srv.Client(), ModelsEndpoint: srv.URL} + _, err := c.ListModels(context.Background(), "token-secret") + srv.Close() + var he *HTTPError + if !errors.As(err, &he) || he.Code != "" || he.Type != "" || he.Param != "" || he.RequestID != "" || strings.Contains(fmt.Sprintf("%+v", err), "token-secret") { + t.Fatalf("unsafe error %#v", err) + } + } +} diff --git a/chatgptplan/models.go b/chatgptplan/models.go new file mode 100644 index 000000000..600a3d420 --- /dev/null +++ b/chatgptplan/models.go @@ -0,0 +1,71 @@ +package chatgptplan + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" +) + +// Model is a displayable model available to the authenticated ChatGPT account. +// Pass Slug as the model field in a Responses request. +type Model struct { + Slug string `json:"slug"` + DisplayName string `json:"display_name"` +} + +// ListModels obtains the account-specific model catalog in server order. Refresh +// it after switching accounts. ModelsEndpoint is an injection point for tests; +// production callers should leave it empty. +func (c Client) ListModels(ctx context.Context, token string) ([]Model, error) { + if strings.TrimSpace(token) == "" { + return nil, &StreamError{Kind: "empty_token"} + } + endpoint := c.ModelsEndpoint + if endpoint == "" { + endpoint = "https://api.openai.com/v1/models" + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, &StreamError{Kind: "request"} + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Accept", "application/json") + resp, err := c.safeHTTPClient().Do(req) + if err != nil { + return nil, &StreamError{Kind: "transport"} + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, parseHTTPError(resp, token) + } + const limit = 8 << 20 + raw, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil { + return nil, &StreamError{Kind: "interrupted"} + } + if len(raw) > limit { + return nil, &StreamError{Kind: "invalid_catalog"} + } + var catalog struct { + Models []struct { + Slug string `json:"slug"` + DisplayName string `json:"display_name"` + Visibility string `json:"visibility"` + } `json:"models"` + } + if json.Unmarshal(raw, &catalog) != nil || catalog.Models == nil { + return nil, &StreamError{Kind: "invalid_catalog"} + } + models := make([]Model, 0, len(catalog.Models)) + for _, m := range catalog.Models { + if m.Visibility == "list" { + if m.Slug == "" || m.DisplayName == "" { + return nil, &StreamError{Kind: "invalid_catalog"} + } + models = append(models, Model{Slug: m.Slug, DisplayName: m.DisplayName}) + } + } + return models, nil +} diff --git a/chatgptplan/models_test.go b/chatgptplan/models_test.go new file mode 100644 index 000000000..204d2838f --- /dev/null +++ b/chatgptplan/models_test.go @@ -0,0 +1,47 @@ +package chatgptplan + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +func TestListModels(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" || r.Header.Get("Authorization") != "Bearer test-token" { + t.Error("invalid request") + } + w.Write([]byte(`{"models":[{"slug":"z","display_name":"Z","visibility":"list"},{"slug":"hidden","display_name":"Hidden","visibility":"hide"},{"slug":"a","display_name":"A","visibility":"list"}]}`)) + })) + defer srv.Close() + got, err := (Client{HTTPClient: srv.Client(), ModelsEndpoint: srv.URL}).ListModels(context.Background(), "test-token") + if err != nil || len(got) != 2 || got[0].Slug != "z" || got[1].DisplayName != "A" { + t.Fatalf("catalog %v %v", got, err) + } +} +func TestListModelsErrors(t *testing.T) { + targetReached := false + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { targetReached = true })) + defer target.Close() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, 307) })) + defer srv.Close() + c := Client{HTTPClient: srv.Client(), ModelsEndpoint: srv.URL} + _, err := c.ListModels(context.Background(), "token") + var se *StreamError + if !errors.As(err, &se) || se.HTTPStatus != 307 || targetReached { + t.Fatalf("redirect %v %v", err, targetReached) + } + _, err = c.ListModels(context.Background(), "") + if !errors.As(err, &se) || se.Kind != "empty_token" { + t.Fatal(err) + } + bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"models":[{"visibility":"list"}]}`)) })) + defer bad.Close() + c.ModelsEndpoint = bad.URL + _, err = c.ListModels(context.Background(), "token") + if !errors.As(err, &se) || se.Kind != "invalid_catalog" { + t.Fatal(err) + } +} diff --git a/db/chatgpt_accounts.go b/db/chatgpt_accounts.go new file mode 100644 index 000000000..8ff93ac6c --- /dev/null +++ b/db/chatgpt_accounts.go @@ -0,0 +1,241 @@ +package db + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +// ChatGPTAccount identifies one issued client and its validated ID-token subject. +// Callers must validate the ID token before passing Subject to CreateChatGPTAccount. +type ChatGPTAccount struct { + ID int64 `json:"id"` + ClientID string `json:"client_id"` + Subject string `json:"subject"` + Label string `json:"label"` + Email string `json:"email"` + Version int64 `json:"version"` +} + +// ChatGPTTokens is intentionally excluded from JSON serialization. +type ChatGPTTokens struct { + AccessToken string `json:"-"` + RefreshToken string `json:"-"` + IDToken string `json:"-"` + ExpiresAt *time.Time `json:"-"` + Scope string `json:"-"` + TokenType string `json:"-"` +} + +// ChatGPTHostID returns a stable opaque identifier kept in the host's private +// application directory. It is not an authentication credential. +func ChatGPTHostID(dir string) (string, error) { + if err := os.MkdirAll(dir, 0700); err != nil { + return "", err + } + path := filepath.Join(dir, "chatgpt-host-id") + read := func() (string, error) { + b, err := os.ReadFile(path) + if err != nil { + return "", err + } + s := strings.TrimSpace(string(b)) + if len(s) != 45 || !strings.HasPrefix(s, "urn:uuid:") || s[17] != '-' || s[22] != '-' || s[27] != '-' || s[32] != '-' { + return "", errors.New("invalid ChatGPT host ID") + } + v, err := hex.DecodeString(strings.ReplaceAll(s[9:], "-", "")) + if err != nil || len(v) != 16 || v[6]>>4 != 4 || v[8]>>6 != 2 || s != strings.ToLower(s) { + return "", errors.New("invalid ChatGPT host ID") + } + return s, nil + } + if id, err := read(); err == nil { + return id, nil + } else if !os.IsNotExist(err) { + return "", err + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + uuid := fmt.Sprintf("urn:uuid:%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) + f, err := os.CreateTemp(dir, ".chatgpt-host-id-*") + if err != nil { + return "", err + } + temp := f.Name() + defer os.Remove(temp) + if err = f.Chmod(0600); err == nil { + _, err = f.WriteString(uuid) + } + if closeErr := f.Close(); err == nil { + err = closeErr + } + if err != nil { + return "", err + } + if err = os.Link(temp, path); err != nil && !os.IsExist(err) { + return "", err + } + return read() +} + +func (d *DB) CreateChatGPTAccount(ctx context.Context, clientID, validatedSubject, label, email string) (ChatGPTAccount, error) { + var a ChatGPTAccount + if strings.TrimSpace(clientID) == "" || strings.TrimSpace(validatedSubject) == "" || strings.TrimSpace(label) == "" { + return a, errors.New("client ID, validated subject and label are required") + } + err := d.QueryRowContext(ctx, `INSERT INTO chatgpt_accounts(client_id,subject,label,email) VALUES($1,$2,$3,$4) RETURNING id,client_id,subject,label,email,version`, clientID, validatedSubject, label, email).Scan(&a.ID, &a.ClientID, &a.Subject, &a.Label, &a.Email, &a.Version) + return a, err +} + +func (d *DB) ListChatGPTAccounts(ctx context.Context) ([]ChatGPTAccount, error) { + rows, err := d.QueryContext(ctx, `SELECT id,client_id,subject,label,email,version FROM chatgpt_accounts ORDER BY id`) + if err != nil { + return nil, err + } + defer rows.Close() + var result []ChatGPTAccount + for rows.Next() { + var a ChatGPTAccount + if err = rows.Scan(&a.ID, &a.ClientID, &a.Subject, &a.Label, &a.Email, &a.Version); err != nil { + return nil, err + } + result = append(result, a) + } + return result, rows.Err() +} + +func readChatGPTTokens(ctx context.Context, tx *sql.Tx, id int64) (ChatGPTAccount, ChatGPTTokens, error) { + var a ChatGPTAccount + var t ChatGPTTokens + var access, refresh, identity string + err := tx.QueryRowContext(ctx, `SELECT id,client_id,subject,label,email,version,access_token,refresh_token,id_token,expires_at,scope,token_type FROM chatgpt_accounts WHERE id=$1 FOR UPDATE`, id).Scan(&a.ID, &a.ClientID, &a.Subject, &a.Label, &a.Email, &a.Version, &access, &refresh, &identity, &t.ExpiresAt, &t.Scope, &t.TokenType) + if err != nil { + return a, t, err + } + for _, v := range []string{access, refresh, identity} { + if v != "" && !isEncrypted(v) { + return a, t, errors.New("unsealed ChatGPT token") + } + } + if t.AccessToken, err = openSecret(colChatGPTAccess, access); err != nil { + return a, t, err + } + if t.RefreshToken, err = openSecret(colChatGPTRefresh, refresh); err != nil { + return a, t, err + } + t.IDToken, err = openSecret(colChatGPTID, identity) + return a, t, err +} + +// WithChatGPTTokens locks the registration across processes for the entire callback, +// including any refresh request. Return replacement tokens to atomically rotate or +// clear credentials; return nil to leave them unchanged. Do not call this recursively. +// Before replacing tokens after reauthorization, callers must validate the new ID +// token and ensure its subject matches the account supplied to the callback. +func (d *DB) WithChatGPTTokens(ctx context.Context, id int64, fn func(ChatGPTAccount, ChatGPTTokens) (*ChatGPTTokens, error)) error { + tx, err := d.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + a, t, err := readChatGPTTokens(ctx, tx, id) + if err != nil { + return err + } + next, err := fn(a, t) + if err != nil { + return err + } + if next != nil { + access, err := sealSecret(colChatGPTAccess, next.AccessToken) + if err != nil { + return err + } + refresh, err := sealSecret(colChatGPTRefresh, next.RefreshToken) + if err != nil { + return err + } + identity, err := sealSecret(colChatGPTID, next.IDToken) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `UPDATE chatgpt_accounts SET access_token=$1,refresh_token=$2,id_token=$3,expires_at=$4,scope=$5,token_type=$6,version=version+1 WHERE id=$7`, access, refresh, identity, next.ExpiresAt, next.Scope, next.TokenType, id) + if err != nil { + return fmt.Errorf("save ChatGPT tokens: %w", err) + } + } + return tx.Commit() +} + +// ErrChatGPTRegistrationChanged indicates that the expected registration version +// or validated identity no longer matches the row being reauthorized. +var ErrChatGPTRegistrationChanged = errors.New("ChatGPT registration changed") + +// SaveChatGPTRegistration atomically creates a registration (ID zero) or +// reauthorizes an existing one. The caller must validate the ID token and +// supply its subject and the issued client ID. On update, ID, Version, ClientID +// and Subject must match the existing row. Token values are never returned in +// the account record or serialized to JSON. +func (d *DB) SaveChatGPTRegistration(ctx context.Context, a ChatGPTAccount, tokens ChatGPTTokens) (ChatGPTAccount, error) { + if strings.TrimSpace(a.ClientID) == "" || strings.TrimSpace(a.Subject) == "" || strings.TrimSpace(a.Label) == "" { + return ChatGPTAccount{}, errors.New("client ID, validated subject and label are required") + } + if tokens.IDToken == "" { + return ChatGPTAccount{}, errors.New("validated ID token is required") + } + if tokens.AccessToken == "" { + for _, scope := range strings.Fields(tokens.Scope) { + if scope == "chatgpt.tokens.use.direct" { + return ChatGPTAccount{}, errors.New("access token is required for direct plan scope") + } + } + } + access, err := sealSecret(colChatGPTAccess, tokens.AccessToken) + if err != nil { + return ChatGPTAccount{}, err + } + refresh, err := sealSecret(colChatGPTRefresh, tokens.RefreshToken) + if err != nil { + return ChatGPTAccount{}, err + } + identity, err := sealSecret(colChatGPTID, tokens.IDToken) + if err != nil { + return ChatGPTAccount{}, err + } + tx, err := d.BeginTx(ctx, nil) + if err != nil { + return ChatGPTAccount{}, err + } + defer tx.Rollback() + if a.ID == 0 { + err = tx.QueryRowContext(ctx, `INSERT INTO chatgpt_accounts(client_id,subject,label,email,access_token,refresh_token,id_token,expires_at,scope,token_type) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING id,version`, a.ClientID, a.Subject, a.Label, a.Email, access, refresh, identity, tokens.ExpiresAt, tokens.Scope, tokens.TokenType).Scan(&a.ID, &a.Version) + } else { + var client, subject string + var version int64 + err = tx.QueryRowContext(ctx, `SELECT client_id,subject,version FROM chatgpt_accounts WHERE id=$1 FOR UPDATE`, a.ID).Scan(&client, &subject, &version) + if err == nil && (client != a.ClientID || subject != a.Subject || version != a.Version) { + return ChatGPTAccount{}, ErrChatGPTRegistrationChanged + } + if err == nil { + err = tx.QueryRowContext(ctx, `UPDATE chatgpt_accounts SET label=$1,email=$2,access_token=$3,refresh_token=$4,id_token=$5,expires_at=$6,scope=$7,token_type=$8,version=version+1 WHERE id=$9 RETURNING version`, a.Label, a.Email, access, refresh, identity, tokens.ExpiresAt, tokens.Scope, tokens.TokenType, a.ID).Scan(&a.Version) + } + } + if err != nil { + return ChatGPTAccount{}, err + } + if err = tx.Commit(); err != nil { + return ChatGPTAccount{}, err + } + return a, nil +} diff --git a/db/chatgpt_accounts_test.go b/db/chatgpt_accounts_test.go new file mode 100644 index 000000000..dc0fef5c9 --- /dev/null +++ b/db/chatgpt_accounts_test.go @@ -0,0 +1,125 @@ +package db + +import ( + "context" + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "sync" + "testing" +) + +func TestChatGPTHostID(t *testing.T) { + dir := t.TempDir() + ids := make([]string, 8) + var wg sync.WaitGroup + for i := range ids { + wg.Add(1) + go func(i int) { + defer wg.Done() + var err error + ids[i], err = ChatGPTHostID(dir) + if err != nil { + t.Error(err) + } + }(i) + } + wg.Wait() + for _, id := range ids { + if !regexp.MustCompile(`^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`).MatchString(id) || id != ids[0] { + t.Fatal("host ID must be stable across concurrent calls") + } + } + path := filepath.Join(dir, "chatgpt-host-id") + if runtime.GOOS != "windows" { + info, err := os.Stat(path) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatalf("host ID permissions: %v %v", info, err) + } + } + if err := os.WriteFile(path, []byte("invalid"), 0600); err != nil { + t.Fatal(err) + } + if _, err := ChatGPTHostID(dir); err == nil { + t.Fatal("invalid saved host ID accepted") + } +} + +func TestChatGPTAccountsStorage(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + t.Setenv(secretKeyEnv, base64.StdEncoding.EncodeToString(testSecretKey)) + if err := d.InitSecrets(t.TempDir()); err != nil { + t.Fatal(err) + } + ctx := context.Background() + a, err := d.CreateChatGPTAccount(ctx, "fake-client-a", "fake-subject", "first", "same@example.test") + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, a.ID) + b, err := d.CreateChatGPTAccount(ctx, "fake-client-b", "fake-subject", "second", "same@example.test") + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, b.ID) + if _, err = d.CreateChatGPTAccount(ctx, "fake-client-a", "other-subject", "third", ""); err == nil { + t.Fatal("client must not be rebound") + } + tokens := ChatGPTTokens{AccessToken: "fake-access", RefreshToken: "fake-refresh", IDToken: "fake-id", Scope: "openid profile", TokenType: "Bearer"} + encoded, _ := json.Marshal(tokens) + if strings.Contains(string(encoded), "fake-") { + t.Fatal("tokens serialized") + } + err = d.WithChatGPTTokens(ctx, a.ID, func(_ ChatGPTAccount, _ ChatGPTTokens) (*ChatGPTTokens, error) { return &tokens, nil }) + if err != nil { + t.Fatal(err) + } + var raw string + if err = d.QueryRow(`SELECT access_token||refresh_token||id_token FROM chatgpt_accounts WHERE id=$1`, a.ID).Scan(&raw); err != nil || strings.Contains(raw, "fake-") || strings.Count(raw, secretPrefix) != 3 { + t.Fatal("tokens not encrypted", err) + } + err = d.WithChatGPTTokens(ctx, b.ID, func(_ ChatGPTAccount, tokens ChatGPTTokens) (*ChatGPTTokens, error) { + if tokens.AccessToken != "" { + t.Error("tokens crossed registrations") + } + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + err := d.WithChatGPTTokens(ctx, a.ID, func(_ ChatGPTAccount, tokens ChatGPTTokens) (*ChatGPTTokens, error) { + tokens.RefreshToken += "x" + return &tokens, nil + }) + if err != nil { + t.Error(err) + } + }() + } + wg.Wait() + err = d.WithChatGPTTokens(ctx, a.ID, func(_ ChatGPTAccount, tokens ChatGPTTokens) (*ChatGPTTokens, error) { + if tokens.Scope != "openid profile" || tokens.TokenType != "Bearer" { + t.Error("token metadata lost") + } + if tokens.RefreshToken != "fake-refreshxx" { + t.Error("lost concurrent update") + } + return &ChatGPTTokens{}, nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/db/chatgpt_profiles_test.go b/db/chatgpt_profiles_test.go new file mode 100644 index 000000000..1e6a5e0b1 --- /dev/null +++ b/db/chatgpt_profiles_test.go @@ -0,0 +1,158 @@ +package db + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestChatGPTProfileAssociation(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + t.Setenv(secretKeyEnv, base64.StdEncoding.EncodeToString(testSecretKey)) + if err := d.InitSecrets(t.TempDir()); err != nil { + t.Fatal(err) + } + ctx := context.Background() + a, err := d.CreateChatGPTAccount(ctx, "fake-profile-client", "fake-subject", "fixture", "") + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, a.ID) + p := &LLMProfile{Name: "fake-chatgpt-profile", Format: "chatgpt-plan", Model: "fake", ChatGPTAccountID: &a.ID} + id, err := d.SaveProfile(p) + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) + got, err := d.ProfileByID(id) + if err != nil || got.ChatGPTAccountID == nil || *got.ChatGPTAccountID != a.ID { + t.Fatalf("association: %+v %v", got, err) + } + listed, err := d.ListProfiles() + if err != nil { + t.Fatal(err) + } + found := false + for _, p := range listed { + if p.ID == id { + found = p.ChatGPTAccountID != nil && *p.ChatGPTAccountID == a.ID + } + } + if !found { + t.Fatal("association missing from list") + } + eligible := func() bool { + profiles, err := d.PoolProfiles() + if err != nil { + t.Fatal(err) + } + for _, p := range profiles { + if p.ID == id { + raw, _ := json.Marshal(p) + if strings.Contains(string(raw), "fake-access") { + t.Fatal("serialized token") + } + return true + } + } + return false + } + if eligible() { + t.Fatal("empty session eligible") + } + token := ChatGPTTokens{AccessToken: "fake-access", Scope: "openid chatgpt.tokens.use.direct.extra"} + set := func() { + t.Helper() + if err := d.WithChatGPTTokens(ctx, a.ID, func(ChatGPTAccount, ChatGPTTokens) (*ChatGPTTokens, error) { return &token, nil }); err != nil { + t.Fatal(err) + } + } + set() + if eligible() { + t.Fatal("partial scope match eligible") + } + token.Scope = "openid chatgpt.tokens.use.direct" + set() + if !eligible() { + t.Fatal("authorized session missing from pool") + } + got.Name = "fake-chatgpt-profile-renamed" + if _, err = d.SaveProfile(got); err != nil { + t.Fatal(err) + } + got, err = d.ProfileByID(id) + if err != nil || got.ChatGPTAccountID == nil || *got.ChatGPTAccountID != a.ID { + t.Fatal("update lost association", err) + } + if _, err = d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, a.ID); err != nil { + t.Fatal(err) + } + got, err = d.ProfileByID(id) + if err != nil || got.ChatGPTAccountID != nil || eligible() { + t.Fatal("deleted account remains associated or eligible", err) + } +} + +func TestChatGPTRegistrationAtomic(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + t.Setenv(secretKeyEnv, base64.StdEncoding.EncodeToString(testSecretKey)) + if err := d.InitSecrets(t.TempDir()); err != nil { + t.Fatal(err) + } + ctx := context.Background() + a := ChatGPTAccount{ClientID: "fake-atomic-client", Subject: "subject", Label: "atomic"} + tokens := ChatGPTTokens{AccessToken: "fake-access", IDToken: "fake-identity", RefreshToken: "fake-refresh", Scope: "chatgpt.tokens.use.direct"} + if _, err = d.SaveChatGPTRegistration(ctx, a, ChatGPTTokens{}); err == nil { + t.Fatal("missing credentials accepted") + } + var n int + if err = d.QueryRow(`SELECT count(*) FROM chatgpt_accounts WHERE client_id=$1`, a.ClientID).Scan(&n); err != nil || n != 0 { + t.Fatal("partial account created", err) + } + disabled := tokens + disabled.AccessToken = "" + disabled.Scope = "openid profile" + disabledAccount, err := d.SaveChatGPTRegistration(ctx, a, disabled) + if err != nil { + t.Fatal("disabled sign-in should be saved", err) + } + defer d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, disabledAccount.ID) + if _, err = d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, disabledAccount.ID); err != nil { + t.Fatal(err) + } + missingAccess := tokens + missingAccess.AccessToken = "" + if _, err = d.SaveChatGPTRegistration(ctx, a, missingAccess); err == nil { + t.Fatal("direct scope without access token accepted") + } + a, err = d.SaveChatGPTRegistration(ctx, a, tokens) + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, a.ID) + stale := a + a.Label = "renamed" + tokens.AccessToken = "new-access" + a, err = d.SaveChatGPTRegistration(ctx, a, tokens) + if err != nil { + t.Fatal(err) + } + if _, err = d.SaveChatGPTRegistration(ctx, stale, tokens); !errors.Is(err, ErrChatGPTRegistrationChanged) { + t.Fatal("stale update accepted", err) + } + a.Subject = "other" + if _, err = d.SaveChatGPTRegistration(ctx, a, tokens); !errors.Is(err, ErrChatGPTRegistrationChanged) { + t.Fatal("identity change accepted", err) + } +} diff --git a/db/config.go b/db/config.go index 1e7c9e9bb..9946008f8 100644 --- a/db/config.go +++ b/db/config.go @@ -16,6 +16,7 @@ type LLMProfile struct { ID int64 `json:"id"` Name string `json:"name"` Format string `json:"format"` + ChatGPTAccountID *int64 `json:"chatgpt_account_id,omitempty"` BaseURL string `json:"base_url,omitempty"` Proxy string `json:"proxy,omitempty"` // LLM outbound proxy (http/https/socks5); empty = use environment variables Model string `json:"model"` @@ -95,8 +96,8 @@ type RetryOverride struct { // profileCols is the read column list (hint variant, no api key) shared by the // list query; profileColsKey is the same with api_key for the single-row loads. const profileRetryCols = `COALESCE(retry_connect_attempts,0),COALESCE(retry_connect_interval_ms,0),COALESCE(retry_empty_attempts,0),COALESCE(retry_empty_interval_ms,0),COALESCE(retry_stream_attempts,0),COALESCE(retry_stream_interval_ms,0)` -const profileCols = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key_hint,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,'')` -const profileColsKey = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,'')` +const profileCols = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key_hint,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,''),chatgpt_account_id` +const profileColsKey = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,''),chatgpt_account_id` // scanProfile reads one row in the profileCols / profileColsKey column order. The // 7th column lands in APIKeyHint or APIKey depending on which list the caller used. @@ -108,7 +109,7 @@ func scanProfile(sc interface{ Scan(...any) error }, into *string, p *LLMProfile &p.Retry.Empty.Attempts, &p.Retry.Empty.IntervalMS, &p.Retry.Stream.Attempts, &p.Retry.Stream.IntervalMS, &p.PriceInputPerM, &p.PriceOutputPerM, &p.PriceCacheReadPerM, &p.PriceCacheWritePerM, - &p.UserAgent, &p.CustomHeaders) + &p.UserAgent, &p.CustomHeaders, &p.ChatGPTAccountID) if err != nil { return err } @@ -168,7 +169,9 @@ func (d *DB) ProfileByID(id int64) (*LLMProfile, error) { // slice front to back. func (d *DB) PoolProfiles() ([]*LLMProfile, error) { rows, err := d.Query(`SELECT ` + profileColsKey + ` FROM llm_profiles -WHERE (COALESCE(api_key,'') <> '' OR format='ollama') AND (is_default OR NOT pool_exclude) +WHERE ((format <> 'chatgpt-plan' AND (COALESCE(api_key,'') <> '' OR format='ollama')) OR + (format = 'chatgpt-plan' AND EXISTS (SELECT 1 FROM chatgpt_accounts a WHERE a.id=llm_profiles.chatgpt_account_id AND a.access_token LIKE 'enc:v1:%' AND length(a.access_token)>7 AND 'chatgpt.tokens.use.direct'=ANY(regexp_split_to_array(a.scope, E'\\s+'))))) + AND (is_default OR NOT pool_exclude) ORDER BY is_default DESC, priority DESC, id ASC`) if err != nil { return nil, err @@ -220,27 +223,27 @@ func (d *DB) SaveProfile(p *LLMProfile) (int64, error) { r := p.Retry.Clamped() if p.ID == 0 { var id int64 - err := d.QueryRow(`INSERT INTO llm_profiles(name,format,base_url,proxy,model,api_key,api_key_hint,rate_per_second,rate_per_minute,context_window_k,reasoning_effort,priority,pool_exclude,thinking_type,streaming,max_tokens,max_tokens_field,session_header_key,retry_connect_attempts,retry_connect_interval_ms,retry_empty_attempts,retry_empty_interval_ms,retry_stream_attempts,retry_stream_interval_ms,user_agent,custom_headers) -VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26) RETURNING id`, + err := d.QueryRow(`INSERT INTO llm_profiles(name,format,base_url,proxy,model,api_key,api_key_hint,rate_per_second,rate_per_minute,context_window_k,reasoning_effort,priority,pool_exclude,thinking_type,streaming,max_tokens,max_tokens_field,session_header_key,retry_connect_attempts,retry_connect_interval_ms,retry_empty_attempts,retry_empty_interval_ms,retry_stream_attempts,retry_stream_interval_ms,user_agent,custom_headers,chatgpt_account_id) +VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27) RETURNING id`, p.Name, p.Format, p.BaseURL, proxy, p.Model, key, hint, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, headerValue).Scan(&id) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, headerValue, p.ChatGPTAccountID).Scan(&id) if err == nil { _, err = d.saveProfilePrices(id, p) } return id, err } if p.APIKey == "" { - _, err := d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key END,api_key_hint=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key_hint END,rate_per_second=$6,rate_per_minute=$7,context_window_k=$8,reasoning_effort=$9,priority=$10,pool_exclude=$11,thinking_type=$12,streaming=$13,max_tokens=$14,max_tokens_field=$15,session_header_key=$16,retry_connect_attempts=$17,retry_connect_interval_ms=$18,retry_empty_attempts=$19,retry_empty_interval_ms=$20,retry_stream_attempts=$21,retry_stream_interval_ms=$22,user_agent=$23,custom_headers=CASE WHEN $25 THEN $26 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END WHERE id=$24`, + _, err := d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key END,api_key_hint=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key_hint END,rate_per_second=$6,rate_per_minute=$7,context_window_k=$8,reasoning_effort=$9,priority=$10,pool_exclude=$11,thinking_type=$12,streaming=$13,max_tokens=$14,max_tokens_field=$15,session_header_key=$16,retry_connect_attempts=$17,retry_connect_interval_ms=$18,retry_empty_attempts=$19,retry_empty_interval_ms=$20,retry_stream_attempts=$21,retry_stream_interval_ms=$22,user_agent=$23,custom_headers=CASE WHEN $25 THEN $26 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END,chatgpt_account_id=$27 WHERE id=$24`, p.Name, p.Format, p.BaseURL, proxy, p.Model, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue, p.ChatGPTAccountID) if err == nil { _, err = d.saveProfilePrices(p.ID, p) } return p.ID, err } - _, err = d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=$6,api_key_hint=$7,rate_per_second=$8,rate_per_minute=$9,context_window_k=$10,reasoning_effort=$11,priority=$12,pool_exclude=$13,thinking_type=$14,streaming=$15,max_tokens=$16,max_tokens_field=$17,session_header_key=$18,retry_connect_attempts=$19,retry_connect_interval_ms=$20,retry_empty_attempts=$21,retry_empty_interval_ms=$22,retry_stream_attempts=$23,retry_stream_interval_ms=$24,user_agent=$25,custom_headers=CASE WHEN $27 THEN $28 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END WHERE id=$26`, + _, err = d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=$6,api_key_hint=$7,rate_per_second=$8,rate_per_minute=$9,context_window_k=$10,reasoning_effort=$11,priority=$12,pool_exclude=$13,thinking_type=$14,streaming=$15,max_tokens=$16,max_tokens_field=$17,session_header_key=$18,retry_connect_attempts=$19,retry_connect_interval_ms=$20,retry_empty_attempts=$21,retry_empty_interval_ms=$22,retry_stream_attempts=$23,retry_stream_interval_ms=$24,user_agent=$25,custom_headers=CASE WHEN $27 THEN $28 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END,chatgpt_account_id=$29 WHERE id=$26`, p.Name, p.Format, p.BaseURL, proxy, p.Model, key, hint, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue, p.ChatGPTAccountID) if err == nil { _, err = d.saveProfilePrices(p.ID, p) } diff --git a/db/migrations/0020_chatgpt_accounts.sql b/db/migrations/0020_chatgpt_accounts.sql new file mode 100644 index 000000000..542684d36 --- /dev/null +++ b/db/migrations/0020_chatgpt_accounts.sql @@ -0,0 +1,19 @@ +-- Independent ChatGPT sign-in registrations. Token values are sealed by the +-- application; this table never uses a shared API-key field for OAuth state. +CREATE TABLE IF NOT EXISTS chatgpt_accounts ( + id BIGSERIAL PRIMARY KEY, + client_id TEXT NOT NULL UNIQUE CHECK (client_id <> ''), + subject TEXT NOT NULL CHECK (subject <> ''), + label TEXT NOT NULL CHECK (label <> ''), + email TEXT NOT NULL DEFAULT '', + access_token TEXT NOT NULL DEFAULT '', + refresh_token TEXT NOT NULL DEFAULT '', + id_token TEXT NOT NULL DEFAULT '', + expires_at TIMESTAMPTZ, + scope TEXT NOT NULL DEFAULT '', + token_type TEXT NOT NULL DEFAULT '', + version BIGINT NOT NULL DEFAULT 0, + UNIQUE (client_id, subject) +); +ALTER TABLE chatgpt_accounts ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT ''; +ALTER TABLE chatgpt_accounts ADD COLUMN IF NOT EXISTS token_type TEXT NOT NULL DEFAULT ''; diff --git a/db/migrations/0021_chatgpt_profiles.sql b/db/migrations/0021_chatgpt_profiles.sql new file mode 100644 index 000000000..302d76305 --- /dev/null +++ b/db/migrations/0021_chatgpt_profiles.sql @@ -0,0 +1,5 @@ +-- Associate a plan profile with its own ChatGPT registration. +ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS chatgpt_account_id BIGINT REFERENCES chatgpt_accounts(id) ON DELETE SET NULL; +ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; +ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','chatgpt-plan')); diff --git a/db/migrations/0022_openrouter_profiles.sql b/db/migrations/0022_openrouter_profiles.sql new file mode 100644 index 000000000..127fcda3c --- /dev/null +++ b/db/migrations/0022_openrouter_profiles.sql @@ -0,0 +1,3 @@ +ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; +ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','chatgpt-plan','openrouter')); diff --git a/db/schema.sql b/db/schema.sql index 62331a3e9..b4c5b691c 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -370,7 +370,7 @@ CREATE TABLE IF NOT EXISTS settings ( CREATE TABLE IF NOT EXISTS llm_profiles ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, - format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')), + format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','chatgpt-plan','openrouter')), base_url TEXT, proxy TEXT, model TEXT NOT NULL, @@ -431,7 +431,7 @@ ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS streaming BOOLEAN NOT NULL -- Runs at every startup, idempotent: drop the old CHECK first, then create the current format CHECK. ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check - CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')); + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','chatgpt-plan','openrouter')); -- Output cap and its field name; backfills old databases. Defaults 0 / '' = send no cap and keep the max_tokens field name; -- old configs behave exactly as before. @@ -1623,3 +1623,26 @@ CREATE INDEX IF NOT EXISTS idx_coverage_ledger_history_task ON coverage_ledger_h -- written with the guarded terminal status, cleared when the task moves back to a -- non-terminal state (revive), so an earlier run's reason never marks a later one. ALTER TABLE tasks ADD COLUMN IF NOT EXISTS end_reason TEXT NOT NULL DEFAULT ''; + +-- Independent ChatGPT OAuth registrations; no LLM profile binding. +CREATE TABLE IF NOT EXISTS chatgpt_accounts ( + id BIGSERIAL PRIMARY KEY, + client_id TEXT NOT NULL UNIQUE CHECK (client_id <> ''), + subject TEXT NOT NULL CHECK (subject <> ''), + label TEXT NOT NULL CHECK (label <> ''), + email TEXT NOT NULL DEFAULT '', + access_token TEXT NOT NULL DEFAULT '', + refresh_token TEXT NOT NULL DEFAULT '', + id_token TEXT NOT NULL DEFAULT '', + expires_at TIMESTAMPTZ, + scope TEXT NOT NULL DEFAULT '', + token_type TEXT NOT NULL DEFAULT '', + version BIGINT NOT NULL DEFAULT 0, + UNIQUE (client_id, subject) +); + +ALTER TABLE chatgpt_accounts ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT ''; +ALTER TABLE chatgpt_accounts ADD COLUMN IF NOT EXISTS token_type TEXT NOT NULL DEFAULT ''; + +-- Keep profiles if an account is removed; an unlinked plan profile is ineligible. +ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS chatgpt_account_id BIGINT REFERENCES chatgpt_accounts(id) ON DELETE SET NULL; diff --git a/db/secrets.go b/db/secrets.go index 770549380..c238b2cf0 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -98,7 +98,10 @@ var ( colHookSource = secretColumn{"traffic_tamper_hooks", "source", false, ""} colHookVerMatchers = secretColumn{"traffic_tamper_hook_versions", "matchers", true, ""} colHookVerSource = secretColumn{"traffic_tamper_hook_versions", "source", false, ""} - secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) + colChatGPTAccess = secretColumn{"chatgpt_accounts", "access_token", false, ""} + colChatGPTRefresh = secretColumn{"chatgpt_accounts", "refresh_token", false, ""} + colChatGPTID = secretColumn{"chatgpt_accounts", "id_token", false, ""} + secretColumns = append([]secretColumn{colChatGPTAccess, colChatGPTRefresh, colChatGPTID, colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) ) // secretSettingKeys are the settings stored encrypted, AAD "settings.". diff --git a/go.mod b/go.mod index 4d903e831..9db614411 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/aws/aws-sdk-go-v2/credentials v1.20.13 github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 + github.com/coreos/go-oidc/v3 v3.14.1 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 @@ -26,6 +27,11 @@ require ( mvdan.cc/sh/v3 v3.14.1 ) +require ( + github.com/go-jose/go-jose/v4 v4.0.5 // indirect + golang.org/x/oauth2 v0.28.0 // indirect +) + require ( github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect diff --git a/go.sum b/go.sum index 8c899e51c..47ea7f82e 100644 --- a/go.sum +++ b/go.sum @@ -44,6 +44,8 @@ github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE= github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= +github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= +github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -53,6 +55,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/gaissmai/bart v0.26.0 h1:xOZ57E9hJLBiQaSyeZa9wgWhGuzfGACgqp4BE77OkO0= github.com/gaissmai/bart v0.26.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c= +github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= +github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= @@ -151,6 +155,8 @@ golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/server/chatgpt_callback_port_test.go b/server/chatgpt_callback_port_test.go new file mode 100644 index 000000000..f35084150 --- /dev/null +++ b/server/chatgpt_callback_port_test.go @@ -0,0 +1,21 @@ +package server + +import "testing" + +func TestChatGPTCallbackPortConfiguration(t *testing.T) { + for _, tc := range []struct{ port, host string }{ + {"", "127.0.0.1:8787"}, + {"8797", "127.0.0.1:8797"}, + {"0", "127.0.0.1:8787"}, + {"99999", "127.0.0.1:8787"}, + {"01", "127.0.0.1:8787"}, + {"evil.test", "127.0.0.1:8787"}, + } { + t.Run(tc.port, func(t *testing.T) { + t.Setenv("ARTEX_CHATGPT_CALLBACK_PORT", tc.port) + if got := chatGPTCallbackHost(); got != tc.host { + t.Errorf("host = %q, want %q", got, tc.host) + } + }) + } +} diff --git a/server/chatgpt_lifecycle.go b/server/chatgpt_lifecycle.go new file mode 100644 index 000000000..dda03059a --- /dev/null +++ b/server/chatgpt_lifecycle.go @@ -0,0 +1,102 @@ +package server + +import ( + "context" + "errors" + "iter" + "sync" + + "github.com/Autumn-27/norma/llm" +) + +var errChatGPTSignedOut = errors.New("ChatGPT account is signed out") + +// chatGPTLifecycle is process-local. Deployments sharing OAuth sessions across +// multiple servers are unsupported: each server must stop its own requests. +type chatGPTLifecycle struct { + mu sync.Mutex + accounts map[int64]*chatGPTLifecycleAccount +} +type chatGPTLifecycleAccount struct { + closed bool + active map[*chatGPTOperation]struct{} +} +type chatGPTOperation struct { + cancel context.CancelFunc + done chan struct{} +} + +func (l *chatGPTLifecycle) account(id int64) *chatGPTLifecycleAccount { + if l.accounts == nil { + l.accounts = make(map[int64]*chatGPTLifecycleAccount) + } + a := l.accounts[id] + if a == nil { + a = &chatGPTLifecycleAccount{active: make(map[*chatGPTOperation]struct{})} + l.accounts[id] = a + } + return a +} +func (l *chatGPTLifecycle) begin(ctx context.Context, id int64) (context.Context, func(), error) { + l.mu.Lock() + defer l.mu.Unlock() + a := l.account(id) + if a.closed { + return nil, nil, errChatGPTSignedOut + } + ctx, cancel := context.WithCancel(ctx) + op := &chatGPTOperation{cancel: cancel, done: make(chan struct{})} + a.active[op] = struct{}{} + var once sync.Once + return ctx, func() { once.Do(func() { cancel(); l.mu.Lock(); delete(a.active, op); close(op.done); l.mu.Unlock() }) }, nil +} +func (l *chatGPTLifecycle) closeAndWait(ctx context.Context, id int64) error { + l.mu.Lock() + a := l.account(id) + a.closed = true + ops := make([]*chatGPTOperation, 0, len(a.active)) + for op := range a.active { + ops = append(ops, op) + op.cancel() + } + l.mu.Unlock() + for _, op := range ops { + select { + case <-op.done: + case <-ctx.Done(): + return ctx.Err() + } + } + return nil +} +func (l *chatGPTLifecycle) reopen(id int64) { + l.mu.Lock() + defer l.mu.Unlock() + l.account(id).closed = false +} + +type chatGPTLifecycleProvider struct { + lifecycle *chatGPTLifecycle + accountID int64 + provider llm.Provider +} + +func (p *chatGPTLifecycleProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + ctx, done, err := p.lifecycle.begin(ctx, p.accountID) + if err != nil { + return llm.Message{}, "", llm.Usage{}, err + } + defer done() + return p.provider.Complete(ctx, req) +} +func (p *chatGPTLifecycleProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + ctx, done, err := p.lifecycle.begin(ctx, p.accountID) + if err != nil { + yield(llm.StreamEvent{}, err) + return + } + defer done() + p.provider.Stream(ctx, req)(yield) + } +} diff --git a/server/chatgpt_lifecycle_test.go b/server/chatgpt_lifecycle_test.go new file mode 100644 index 000000000..d675e4ee8 --- /dev/null +++ b/server/chatgpt_lifecycle_test.go @@ -0,0 +1,124 @@ +package server + +import ( + "context" + "errors" + "iter" + "net/http/httptest" + "strings" + + "github.com/Autumn-27/artex/db" + "testing" + "time" + + "github.com/Autumn-27/norma/llm" +) + +type blockingLifecycleProvider struct { + started chan struct{} + release chan struct{} +} + +func (p *blockingLifecycleProvider) Complete(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + close(p.started) + <-ctx.Done() + <-p.release + return llm.Message{}, "", llm.Usage{}, ctx.Err() +} +func (p *blockingLifecycleProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + _, _, _, err := p.Complete(ctx, req) + yield(llm.StreamEvent{}, err) + } +} +func TestChatGPTLifecycleProviderAndModels(t *testing.T) { + var l chatGPTLifecycle + for _, stream := range []bool{false, true} { + p := &blockingLifecycleProvider{make(chan struct{}), make(chan struct{})} + wrapped := &chatGPTLifecycleProvider{&l, 1, p} + finished := make(chan struct{}) + go func() { + defer close(finished) + if stream { + for range wrapped.Stream(context.Background(), llm.CompletionRequest{}) { + } + } else { + _, _, _, _ = wrapped.Complete(context.Background(), llm.CompletionRequest{}) + } + }() + <-p.started + // A model request is admitted through the same gate, before token access. + modelCtx, modelDone, err := l.begin(context.Background(), 1) + if err != nil { + t.Fatal(err) + } + stopped := make(chan error, 1) + go func() { stopped <- l.closeAndWait(context.Background(), 1) }() + <-modelCtx.Done() + if _, _, err := l.begin(context.Background(), 1); !errors.Is(err, errChatGPTSignedOut) { + t.Fatalf("admission: %v", err) + } + select { + case <-stopped: + t.Fatal("signout returned while requests running") + default: + } + modelDone() + close(p.release) + <-finished + if err := <-stopped; err != nil { + t.Fatal(err) + } + l.reopen(1) + _, done, err := l.begin(context.Background(), 1) + if err != nil { + t.Fatal(err) + } + done() + } +} +func TestChatGPTLifecycleWaitBoundedAndAccountScoped(t *testing.T) { + var l chatGPTLifecycle + _, done, err := l.begin(context.Background(), 1) + if err != nil { + t.Fatal(err) + } + defer done() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + if err := l.closeAndWait(ctx, 1); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait: %v", err) + } + if _, _, err := l.begin(context.Background(), 1); !errors.Is(err, errChatGPTSignedOut) { + t.Fatalf("closed: %v", err) + } + _, otherDone, err := l.begin(context.Background(), 2) + if err != nil { + t.Fatal(err) + } + otherDone() +} + +func TestChatGPTLifecycleSignoutRevocationFailureClearsLocal(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + store := &fakeChatGPTStore{account: db.ChatGPTAccount{ID: 1}, tokens: db.ChatGPTTokens{AccessToken: "access", RefreshToken: "refresh"}} + manager := newChatGPTOAuthManager(&fakeChatGPTOAuth{}, 8, time.Minute) + manager.revoke = func(context.Context, string, string) bool { return false } + s := &Server{jwtKey: key, oauthStore: store, oauth: manager} + req := httptest.NewRequest("POST", "/api/chatgpt/signout", strings.NewReader(`{"account_id":"1"}`)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Origin", "http://127.0.0.1:8787") + req.Host = "127.0.0.1:8787" + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, req) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"remote_revocation_confirmed":false`) || store.tokens.AccessToken != "" || store.tokens.RefreshToken != "" { + t.Fatalf("signout response %d %s; credentials cleared: %v", w.Code, w.Body.String(), store.tokens.AccessToken == "" && store.tokens.RefreshToken == "") + } + if _, _, err := s.chatGPTRequests.begin(context.Background(), 1); !errors.Is(err, errChatGPTSignedOut) { + t.Fatalf("admission: %v", err) + } +} diff --git a/server/chatgpt_oauth.go b/server/chatgpt_oauth.go new file mode 100644 index 000000000..994961128 --- /dev/null +++ b/server/chatgpt_oauth.go @@ -0,0 +1,791 @@ +package server + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/Autumn-27/artex/chatgptauth" + "github.com/Autumn-27/artex/chatgptplan" + "github.com/Autumn-27/artex/db" +) + +// chatGPTAuthClient keeps the exchange replaceable in tests. Production uses chatgptauth.Client. +type chatGPTModelsClient interface { + ListModels(context.Context, string) ([]chatgptplan.Model, error) +} + +type chatGPTAuthClient interface { + Start(chatgptauth.Options) (string, *chatgptauth.Attempt, error) + Complete(context.Context, *chatgptauth.Attempt, string) (chatgptauth.Result, error) +} + +var errChatGPTOAuth = errors.New("authorization attempt unavailable") + +type chatGPTOAuthStatus string + +const ( + chatGPTOAuthPending chatGPTOAuthStatus = "pending" + chatGPTOAuthComplete chatGPTOAuthStatus = "complete" + chatGPTOAuthFailed chatGPTOAuthStatus = "failed" + chatGPTOAuthCallbackRejected chatGPTOAuthStatus = "callback_rejected" + chatGPTOAuthPlanDisabled chatGPTOAuthStatus = "plan_disabled" + chatGPTOAuthRetry chatGPTOAuthStatus = "retry_available" +) + +type chatGPTOAuthEntry struct { + session, redirect string + attempt *chatgptauth.Attempt + expires time.Time + status chatGPTOAuthStatus + running bool + saving bool + retrying bool + result chatgptauth.Result + handle string + account db.ChatGPTAccount + completedAt time.Time + cancel context.CancelFunc +} + +// chatGPTOAuthManager is process-local. The caller must authenticate sessions, +// expose the callback only on host loopback, and securely persist successful claims. +type chatGPTOAuthManager struct { + mu sync.Mutex + lifecycle sync.Mutex + client chatGPTAuthClient + models chatGPTModelsClient + revoke func(context.Context, string, string) bool + entries map[string]*chatGPTOAuthEntry + max int + ttl time.Duration + now func() time.Time +} + +func newChatGPTOAuthManager(client chatGPTAuthClient, max int, ttl time.Duration) *chatGPTOAuthManager { + if client == nil { + client = chatgptauth.NewClient(chatgptauth.Config{}) + } + if max <= 0 { + max = 128 + } + if ttl <= 0 || ttl > 10*time.Minute { + ttl = 10 * time.Minute + } + return &chatGPTOAuthManager{client: client, entries: make(map[string]*chatGPTOAuthEntry), max: max, ttl: ttl, now: time.Now} +} + +func validChatGPTRedirect(s string) bool { + u, err := url.Parse(s) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "/auth/callback" || u.RawPath != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return false + } + p, err := strconv.Atoi(u.Port()) + return err == nil && p > 0 && p <= 65535 && u.Host == "127.0.0.1:"+strconv.Itoa(p) +} +func (m *chatGPTOAuthManager) prune(now time.Time) { + for state, e := range m.entries { + if !e.saving && !e.retrying && !now.Before(e.expires) { + if e.cancel != nil { + e.cancel() + } + delete(m.entries, state) + } + } +} + +// start requires a verified, stable session fingerprint and trusted account data. +// The returned URL is secret-bearing; callers must not log it or persist it in browser storage. +func (m *chatGPTOAuthManager) start(session string, opts chatgptauth.Options) (authorizationURL, state string, err error) { + if strings.TrimSpace(session) == "" || !validChatGPTRedirect(opts.RedirectURI) || (opts.ClientID == "" && opts.ExpectedSubject != "") || (opts.ClientID != "" && opts.ExpectedSubject == "" && !opts.RetryRegistration) { + return "", "", errChatGPTOAuth + } + m.mu.Lock() + defer m.mu.Unlock() + m.prune(m.now()) + if len(m.entries) >= m.max { + reserved := false + if opts.RetryRegistration { + for _, entry := range m.entries { + if entry.retrying && entry.session == session { + reserved = true + break + } + } + } + if !reserved || len(m.entries) >= 2*m.max { + return "", "", errChatGPTOAuth + } + } + authorizationURL, attempt, e := m.client.Start(opts) + if e != nil || attempt == nil { + return "", "", errChatGPTOAuth + } + u, e := url.Parse(authorizationURL) + if e != nil { + return "", "", errChatGPTOAuth + } + q, e := url.ParseQuery(u.RawQuery) + if e != nil || len(q["state"]) != 1 || q.Get("state") == "" { + return "", "", errChatGPTOAuth + } + state = q.Get("state") + if _, exists := m.entries[state]; exists { + return "", "", errChatGPTOAuth + } + m.entries[state] = &chatGPTOAuthEntry{session: session, redirect: opts.RedirectURI, attempt: attempt, expires: m.now().Add(m.ttl), status: chatGPTOAuthPending} + return authorizationURL, state, nil +} + +// callback requires the caller to enforce loopback publication; Host validation +// alone does not establish it, including when ARTEX runs in a container. +// It returns no provider error, callback parameters, credentials, or secrets. +func (m *chatGPTOAuthManager) callback(ctx context.Context, r *http.Request) chatGPTOAuthStatus { + if r == nil || r.Method != http.MethodGet || r.TLS != nil || r.URL == nil || r.URL.IsAbs() || r.URL.Host != "" || r.URL.User != nil || r.URL.Path != "/auth/callback" || r.URL.RawPath != "" || r.URL.Fragment != "" { + return chatGPTOAuthFailed + } + q, err := url.ParseQuery(r.URL.RawQuery) + if err != nil { + return chatGPTOAuthFailed + } + // Only an unambiguous state at the expected redirect can identify an + // attempt. Never let malformed or replayed callbacks alter another attempt. + if len(q["state"]) != 1 || q.Get("state") == "" { + return chatGPTOAuthFailed + } + state := q.Get("state") + m.mu.Lock() + m.prune(m.now()) + e := m.entries[state] + if e == nil || e.running || e.status != chatGPTOAuthPending || "http://"+r.Host+"/auth/callback" != e.redirect { + m.mu.Unlock() + return chatGPTOAuthFailed + } + valid := (q.Get("code") == "") != (q.Get("error") == "") + for k, values := range q { + if len(values) != 1 || (k != "state" && k != "code" && k != "client_id" && k != "error" && k != "error_description" && k != "error_uri" && k != "scope" && k != "iss") { + valid = false + } + } + if !valid { + e.attempt = nil + e.status = chatGPTOAuthCallbackRejected + m.mu.Unlock() + return chatGPTOAuthCallbackRejected + } + e.running = true + exchangeCtx, cancel := context.WithCancel(ctx) + e.cancel = cancel + m.mu.Unlock() + result, completeErr := m.client.Complete(exchangeCtx, e.attempt, e.redirect+"?"+r.URL.RawQuery) + cancel() + m.mu.Lock() + defer m.mu.Unlock() + // Expiration or replacement while the exchange was in flight discards the result. + if m.entries[state] != e || !m.now().Before(e.expires) { + if m.entries[state] == e { + delete(m.entries, state) + } + return chatGPTOAuthFailed + } + e.attempt = nil + e.cancel = nil + e.running = false + if completeErr != nil { + if errors.Is(completeErr, chatgptauth.ErrScope) && result.Identity.Subject != "" && result.Tokens.IDToken != "" && !chatGPTScopeGranted(result.Tokens.Scope) { + e.result = result + e.completedAt = m.now() + e.status = chatGPTOAuthPlanDisabled + } else if e.account.ID == 0 && result.ClientID != "" { + e.result = chatgptauth.Result{ClientID: result.ClientID} + e.status = chatGPTOAuthRetry + } else { + e.status = chatGPTOAuthFailed + } + return e.status + } + e.result = result + e.completedAt = m.now() + e.status = chatGPTOAuthComplete + return e.status +} + +// claim consumes the result atomically only for the authenticated initiating session. +// Neither the result nor its tokens should be serialized into a browser response. +func (m *chatGPTOAuthManager) claim(session, state string) (chatgptauth.Result, chatGPTOAuthStatus, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.prune(m.now()) + e := m.entries[state] + if session == "" || e == nil || subtle.ConstantTimeCompare([]byte(session), []byte(e.session)) != 1 { + return chatgptauth.Result{}, chatGPTOAuthFailed, errChatGPTOAuth + } + if e.status == chatGPTOAuthPending { + return chatgptauth.Result{}, chatGPTOAuthPending, nil + } + delete(m.entries, state) + if e.status != chatGPTOAuthComplete { + return chatgptauth.Result{}, chatGPTOAuthFailed, errChatGPTOAuth + } + return e.result, chatGPTOAuthComplete, nil +} + +// The deployment must publish this port on the host's loopback interface only. +func chatGPTCallbackURI() string { + port := os.Getenv("ARTEX_CHATGPT_CALLBACK_PORT") + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port { + port = "8787" + } + return "http://127.0.0.1:" + port + "/auth/callback" +} + +func chatGPTCallbackHost() string { + return strings.TrimSuffix(strings.TrimPrefix(chatGPTCallbackURI(), "http://"), "/auth/callback") +} + +type chatGPTOAuthStore interface { + ListChatGPTAccounts(context.Context) ([]db.ChatGPTAccount, error) + WithChatGPTTokens(context.Context, int64, func(db.ChatGPTAccount, db.ChatGPTTokens) (*db.ChatGPTTokens, error)) error + SaveChatGPTRegistration(context.Context, db.ChatGPTAccount, db.ChatGPTTokens) (db.ChatGPTAccount, error) +} + +func (s *Server) chatGPTManager() *chatGPTOAuthManager { + s.oauthOnce.Do(func() { + if s.oauth == nil { + s.oauth = newChatGPTOAuthManager(nil, 128, 10*time.Minute) + } + }) + return s.oauth +} +func (s *Server) chatGPTStore() chatGPTOAuthStore { + if s.oauthStore != nil { + return s.oauthStore + } + if s.m == nil || s.m.pg == nil { + return nil + } + return s.m.pg +} +func chatGPTResponseHeaders(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'") + w.Header().Set("X-Content-Type-Options", "nosniff") +} + +// The API only accepts a local browser console and a verified session. The +// deployment is responsible for keeping the published port on host loopback. +func (s *Server) chatGPTSession(w http.ResponseWriter, r *http.Request) string { + chatGPTResponseHeaders(w) + if r.TLS != nil || r.Host != chatGPTCallbackHost() || !sameOrigin(r) || (!strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") && !cookieAuthenticated(r)) || !s.sessionOK(extractToken(r)) { + writeErr(w, http.StatusForbidden, "local authenticated session required") + return "" + } + token := extractToken(r) + sum := sha256.Sum256([]byte(token)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +type chatGPTPublicAccount struct { + ID string `json:"id"` + Label string `json:"label"` + Email string `json:"email,omitempty"` + Version int64 `json:"version"` + Connected bool `json:"connected"` +} + +func publicChatGPTAccount(a db.ChatGPTAccount, connected bool) chatGPTPublicAccount { + return chatGPTPublicAccount{strconv.FormatInt(a.ID, 10), a.Label, a.Email, a.Version, connected} +} +func chatGPTScopeGranted(value string) bool { + for _, scope := range strings.Fields(value) { + if scope == chatgptauth.DirectScope { + return true + } + } + return false +} +func chatGPTTokensConnected(t db.ChatGPTTokens, now time.Time) bool { + return chatGPTScopeGranted(t.Scope) && strings.EqualFold(t.TokenType, "Bearer") && t.AccessToken != "" && t.ExpiresAt != nil && (t.ExpiresAt.After(now) || t.RefreshToken != "") +} +func (s *Server) chatGPTAccounts(w http.ResponseWriter, r *http.Request) { + if s.chatGPTSession(w, r) == "" { + return + } + store := s.chatGPTStore() + if store == nil { + writeErr(w, 503, "account storage unavailable") + return + } + accounts, err := store.ListChatGPTAccounts(r.Context()) + if err != nil { + writeErr(w, 503, "account storage unavailable") + return + } + out := make([]chatGPTPublicAccount, 0, len(accounts)) + for _, a := range accounts { + connected := false + err = store.WithChatGPTTokens(r.Context(), a.ID, func(_ db.ChatGPTAccount, t db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + connected = chatGPTTokensConnected(t, time.Now()) + return nil, nil + }) + if err != nil { + writeErr(w, 503, "account storage unavailable") + return + } + out = append(out, publicChatGPTAccount(a, connected)) + } + writeJSON(w, 200, map[string]any{"accounts": out}) +} +func (s *Server) chatGPTModels(w http.ResponseWriter, r *http.Request) { + if s.chatGPTSession(w, r) == "" { + return + } + q, err := url.ParseQuery(r.URL.RawQuery) + if err != nil || len(q["account_id"]) != 1 { + writeErr(w, 400, "invalid account") + return + } + accountID, err := strconv.ParseInt(q.Get("account_id"), 10, 64) + if err != nil || accountID <= 0 { + writeErr(w, 400, "invalid account") + return + } + store := s.chatGPTStore() + if store == nil { + writeErr(w, 503, "account storage unavailable") + return + } + ctx, done, err := s.chatGPTRequests.begin(r.Context(), accountID) + if err != nil { + writeErr(w, 403, "account authorization unavailable; reconnect the account") + return + } + defer done() + token, err := chatGPTAccessToken(ctx, store, chatgptauth.NewClient(chatgptauth.Config{}), accountID, time.Now()) + if err != nil { + writeErr(w, 403, "account authorization unavailable; reconnect the account") + return + } + var client chatGPTModelsClient = chatgptplan.Client{} + if override := s.chatGPTManager().models; override != nil { + client = override + } + models, err := client.ListModels(ctx, token) + if err != nil { + var remote *chatgptplan.StreamError + if errors.As(err, &remote) && (remote.HTTPStatus == 401 || remote.HTTPStatus == 403) { + writeErr(w, 403, "account is not authorized to list models") + return + } + writeErr(w, 502, "model catalog unavailable") + return + } + if models == nil { + models = []chatgptplan.Model{} + } + writeJSON(w, 200, map[string]any{"models": models, "available": true}) +} + +func (s *Server) chatGPTConnect(w http.ResponseWriter, r *http.Request) { + session := s.chatGPTSession(w, r) + if session == "" { + return + } + store := s.chatGPTStore() + if store == nil { + writeErr(w, 503, "account storage unavailable") + return + } + var input struct { + AccountID string `json:"account_id"` + RetryAttemptID string `json:"retry_attempt_id"` + Label string `json:"label"` + } + if err := decode(w, r, &input); err != nil { + return + } + label := strings.TrimSpace(input.Label) + accountID := int64(0) + if input.AccountID != "" { + var parseErr error + accountID, parseErr = strconv.ParseInt(input.AccountID, 10, 64) + if parseErr != nil || accountID <= 0 { + writeErr(w, 400, "invalid account") + return + } + } + if len(label) > 120 { + writeErr(w, 400, "invalid account") + return + } + a := db.ChatGPTAccount{Label: label} + requestConsent := false + m := s.chatGPTManager() + var retryState string + var retryEntry *chatGPTOAuthEntry + if input.RetryAttemptID != "" { + if accountID != 0 || label != "" { + writeErr(w, 400, "invalid retry") + return + } + m.mu.Lock() + m.prune(m.now()) + retryState, retryEntry = m.findHandle(session, input.RetryAttemptID) + if retryEntry == nil || retryEntry.status != chatGPTOAuthRetry || retryEntry.retrying || retryEntry.saving { + m.mu.Unlock() + writeErr(w, 404, "authorization unavailable") + return + } + retryEntry.retrying = true + a = retryEntry.account + a.ClientID = retryEntry.result.ClientID + m.mu.Unlock() + defer func() { + m.mu.Lock() + if m.entries[retryState] == retryEntry { + retryEntry.retrying = false + } + m.mu.Unlock() + }() + } + if accountID != 0 { + accounts, err := store.ListChatGPTAccounts(r.Context()) + if err != nil { + writeErr(w, 503, "account storage unavailable") + return + } + found := false + for _, candidate := range accounts { + if candidate.ID == accountID { + a = candidate + found = true + break + } + } + if !found { + writeErr(w, 404, "account unavailable") + return + } + if err := store.WithChatGPTTokens(r.Context(), a.ID, func(_ db.ChatGPTAccount, t db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + requestConsent = !chatGPTScopeGranted(t.Scope) + return nil, nil + }); err != nil { + writeErr(w, 503, "account storage unavailable") + return + } + } else if label == "" && retryEntry == nil { + a.Label = "ChatGPT" + } + host, err := db.ChatGPTHostID(s.oauthKeyDir) + if err != nil { + writeErr(w, 503, "host identity unavailable") + return + } + var b [32]byte + if _, err = rand.Read(b[:]); err != nil { + writeErr(w, 503, "authorization unavailable") + return + } + handle := base64.RawURLEncoding.EncodeToString(b[:]) + authURL, state, err := m.start(session, chatgptauth.Options{HostID: host, AgentName: "ARTEX", RedirectURI: chatGPTCallbackURI(), ClientID: a.ClientID, ExpectedSubject: a.Subject, RetryRegistration: retryEntry != nil, RequestConsent: requestConsent}) + if err != nil { + writeErr(w, 503, "authorization unavailable") + return + } + m.mu.Lock() + if retryEntry != nil && (m.entries[retryState] != retryEntry || !m.now().Before(retryEntry.expires)) { + delete(m.entries, state) + if m.entries[retryState] == retryEntry { + delete(m.entries, retryState) + } + m.mu.Unlock() + writeErr(w, 404, "authorization unavailable") + return + } + if e := m.entries[state]; e != nil { + e.handle = handle + e.account = a + } + if retryEntry != nil { + delete(m.entries, retryState) + } + m.mu.Unlock() + writeJSON(w, 200, map[string]any{"authorization_url": authURL, "attempt_id": handle}) +} +func (s *Server) chatGPTCallback(w http.ResponseWriter, r *http.Request) { + chatGPTResponseHeaders(w) + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + // Always return the same body, including for invalid or failed attempts. + if r.Host == chatGPTCallbackHost() { + s.chatGPTManager().callback(r.Context(), r) + } + fmt.Fprint(w, "Return to ARTEX to check the sign-in status.") +} +func (m *chatGPTOAuthManager) findHandle(session, handle string) (string, *chatGPTOAuthEntry) { + for state, e := range m.entries { + if e.handle != "" && subtle.ConstantTimeCompare([]byte(handle), []byte(e.handle)) == 1 && subtle.ConstantTimeCompare([]byte(session), []byte(e.session)) == 1 { + return state, e + } + } + return "", nil +} +func (s *Server) chatGPTClaim(w http.ResponseWriter, r *http.Request) { + session := s.chatGPTSession(w, r) + if session == "" { + return + } + var input struct { + AttemptID string `json:"attempt_id"` + } + if err := decode(w, r, &input); err != nil { + return + } + m := s.chatGPTManager() + m.mu.Lock() + m.prune(m.now()) + state, e := m.findHandle(session, input.AttemptID) + if e == nil { + m.mu.Unlock() + writeErr(w, 404, "authorization unavailable") + return + } + if e.saving || e.retrying { + m.mu.Unlock() + writeJSON(w, 409, map[string]any{"status": "saving"}) + return + } + if e.status == chatGPTOAuthRetry { + m.mu.Unlock() + writeJSON(w, 200, map[string]any{"status": "retry_available"}) + return + } + if e.status == chatGPTOAuthPending { + m.mu.Unlock() + writeJSON(w, 200, map[string]any{"status": "pending"}) + return + } + result, account, status, completedAt := e.result, e.account, e.status, e.completedAt + if status != chatGPTOAuthComplete && status != chatGPTOAuthPlanDisabled { + delete(m.entries, state) + m.mu.Unlock() + writeJSON(w, 200, map[string]any{"status": status}) + return + } + e.saving = true + m.mu.Unlock() + defer func() { + m.mu.Lock() + if m.entries[state] == e { + delete(m.entries, state) + } + m.mu.Unlock() + }() + // The auth client verified signature, nonce, audience, scope and existing subject. + if result.ClientID == "" || result.Identity.Subject == "" || (status == chatGPTOAuthComplete && result.Tokens.AccessToken == "") || result.Tokens.IDToken == "" || (account.ID != 0 && (result.ClientID != account.ClientID || result.Identity.Subject != account.Subject)) { + writeErr(w, 400, "authorization failed") + return + } + account.ClientID = result.ClientID + account.Subject = result.Identity.Subject + account.Email = result.Identity.Email + tokens := db.ChatGPTTokens{AccessToken: result.Tokens.AccessToken, RefreshToken: result.Tokens.RefreshToken, IDToken: result.Tokens.IDToken, Scope: result.Tokens.Scope, TokenType: result.Tokens.TokenType} + if result.Tokens.ExpiresIn > 0 && result.Tokens.ExpiresIn <= int64((365*24*time.Hour)/time.Second) { + expiry := completedAt.Add(time.Duration(result.Tokens.ExpiresIn) * time.Second) + tokens.ExpiresAt = &expiry + } + store := s.chatGPTStore() + if store == nil { + writeErr(w, 503, "account storage unavailable") + return + } + m.lifecycle.Lock() + defer m.lifecycle.Unlock() + saved, err := store.SaveChatGPTRegistration(r.Context(), account, tokens) + if err != nil { + writeErr(w, 409, "account could not be saved; please reconnect") + return + } + if status == chatGPTOAuthComplete { + s.chatGPTRequests.reopen(saved.ID) + } + s.chatGPTAccountChanged(saved.ID, status == chatGPTOAuthComplete) + writeJSON(w, 200, map[string]any{"status": status, "account": publicChatGPTAccount(saved, chatGPTTokensConnected(tokens, time.Now()))}) +} +func (s *Server) chatGPTCancel(w http.ResponseWriter, r *http.Request) { + session := s.chatGPTSession(w, r) + if session == "" { + return + } + var input struct { + AttemptID string `json:"attempt_id"` + } + if err := decode(w, r, &input); err != nil { + return + } + m := s.chatGPTManager() + m.mu.Lock() + m.prune(m.now()) + state, e := m.findHandle(session, input.AttemptID) + if e != nil && (e.saving || e.retrying) { + m.mu.Unlock() + writeJSON(w, 409, map[string]any{"status": "saving"}) + return + } + if e != nil { + if e.cancel != nil { + e.cancel() + } + delete(m.entries, state) + } + m.mu.Unlock() + if e == nil { + writeErr(w, 404, "authorization unavailable") + return + } + writeJSON(w, 200, map[string]any{"status": "cancelled"}) +} + +// Signout removes credentials under the storage lock and invalidates in-flight +// reauthorization through the registration version increment. +func (s *Server) chatGPTSignout(w http.ResponseWriter, r *http.Request) { + if s.chatGPTSession(w, r) == "" { + return + } + var input struct { + AccountID string `json:"account_id"` + } + if err := decode(w, r, &input); err != nil { + return + } + accountID, parseErr := strconv.ParseInt(input.AccountID, 10, 64) + if parseErr != nil || accountID <= 0 { + writeErr(w, 400, "invalid account") + return + } + store := s.chatGPTStore() + if store == nil { + writeErr(w, 503, "account storage unavailable") + return + } + m := s.chatGPTManager() + m.lifecycle.Lock() + defer m.lifecycle.Unlock() + if err := s.chatGPTRequests.closeAndWait(r.Context(), accountID); err != nil { + writeErr(w, 503, "could not stop account requests") + return + } + remoteConfirmed := false + if err := store.WithChatGPTTokens(r.Context(), accountID, func(a db.ChatGPTAccount, tokens db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + revoke := revokeChatGPTSession + if m.revoke != nil { + revoke = m.revoke + } + remoteConfirmed = revoke(r.Context(), a.ClientID, tokens.RefreshToken) + return &db.ChatGPTTokens{}, nil + }); err != nil { + writeErr(w, 503, "account credential clearing failed") + return + } + s.chatGPTAccountChanged(accountID, false) + writeJSON(w, 200, map[string]any{"status": "signed_out", "remote_revocation_confirmed": remoteConfirmed}) +} + +// Revoke only against an HTTPS endpoint on the trusted issuer; redirects and +// response bodies are never logged. +func revokeChatGPTSession(parent context.Context, clientID, refresh string) bool { + if refresh == "" { + return true + } + ctx, cancel := context.WithTimeout(parent, 12*time.Second) + defer cancel() + client := &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, chatgptauth.Issuer+"/.well-known/openid-configuration", nil) + if err != nil { + return false + } + resp, err := client.Do(req) + if err != nil { + return false + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return false + } + var discovery struct { + Issuer string `json:"issuer"` + RevocationEndpoint string `json:"revocation_endpoint"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(&discovery) != nil || discovery.Issuer != chatgptauth.Issuer { + return false + } + u, err := url.Parse(discovery.RevocationEndpoint) + if err != nil || u.Scheme != "https" || u.Host != "auth.openai.com" || u.User != nil || u.Fragment != "" || u.RawQuery != "" { + return false + } + form := url.Values{"token": {refresh}, "token_type_hint": {"refresh_token"}, "client_id": {clientID}} + for i := 0; i < 3; i++ { + if i > 0 { + select { + case <-ctx.Done(): + return false + case <-time.After(time.Duration(i) * 200 * time.Millisecond): + } + } + req, err = http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(form.Encode())) + if err != nil { + return false + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + response, err := client.Do(req) + if err != nil { + continue + } + response.Body.Close() + if response.StatusCode == http.StatusOK { + return true + } + if response.StatusCode < 500 { + return false + } + } + return false +} + +// Drop cached agents/providers after a credential change. If the live global +// configuration uses this account, remove it before attempting a reconnect so +// readiness cannot continue reporting a signed-out profile as usable. +func (s *Server) chatGPTAccountChanged(accountID int64, connected bool) { + s.invalidateProfileAgents() + s.cfgMu.Lock() + if s.llmCfg.ChatGPTAccountID == accountID { + s.llmOn = false + s.llmProv = nil + s.llmDirect = nil + s.chatAgent = nil + s.llmHealthProfileID = 0 + } + s.cfgMu.Unlock() + if !connected || s.m == nil || s.m.pg == nil { + return + } + active, err := s.m.pg.ActiveProfile() + if err == nil && active != nil && active.ChatGPTAccountID != nil && *active.ChatGPTAccountID == accountID { + s.reapplyActiveProfile() + } +} diff --git a/server/chatgpt_oauth_test.go b/server/chatgpt_oauth_test.go new file mode 100644 index 000000000..08207b4af --- /dev/null +++ b/server/chatgpt_oauth_test.go @@ -0,0 +1,554 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/Autumn-27/artex/chatgptplan" + "github.com/Autumn-27/artex/db" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Autumn-27/artex/chatgptauth" +) + +type fakeChatGPTOAuth struct { + counter atomic.Int32 + calls atomic.Int32 + gate chan struct{} +} + +func (f *fakeChatGPTOAuth) Start(o chatgptauth.Options) (string, *chatgptauth.Attempt, error) { + return fmt.Sprintf("https://example.test/authorize?state=s%d", f.counter.Add(1)), &chatgptauth.Attempt{}, nil +} +func (f *fakeChatGPTOAuth) Complete(ctx context.Context, _ *chatgptauth.Attempt, _ string) (chatgptauth.Result, error) { + f.calls.Add(1) + if f.gate != nil { + <-f.gate + } + return chatgptauth.Result{ClientID: "issued", Tokens: chatgptauth.Tokens{AccessToken: "secret", IDToken: "identity-secret"}, Identity: chatgptauth.Identity{Subject: "subject"}}, nil +} +func oauthRequest(target string) *http.Request { + req := httptest.NewRequest("GET", target, nil) + req.URL.Scheme = "" + req.URL.Host = "" + return req +} +func TestChatGPTOAuthSessionAndCallback(t *testing.T) { + f := &fakeChatGPTOAuth{} + m := newChatGPTOAuthManager(f, 2, time.Minute) + opts := chatgptauth.Options{RedirectURI: "http://127.0.0.1:1234/auth/callback"} + _, state, err := m.start("session-a", opts) + if err != nil { + t.Fatal(err) + } + for _, raw := range []string{ + "http://127.0.0.1:1234/auth/callback?state=unknown&code=x", + "http://127.0.0.1:1235/auth/callback?state=" + state + "&code=x", + "http://127.0.0.1:1234/auth/callback?state=" + state + "&state=" + state + "&code=x", + } { + if got := m.callback(context.Background(), oauthRequest(raw)); got != chatGPTOAuthFailed { + t.Fatalf("bad callback: %s", got) + } + } + if f.calls.Load() != 0 { + t.Fatal("invalid callback consumed attempt") + } + if _, _, err = m.claim("session-b", state); err == nil { + t.Fatal("cross-session claim succeeded") + } + req := oauthRequest("http://127.0.0.1:1234/auth/callback?state=" + url.QueryEscape(state) + "&code=x&scope=openid&iss=https%3A%2F%2Fauth.openai.com") + if got := m.callback(context.Background(), req); got != chatGPTOAuthComplete { + t.Fatalf("callback: %s", got) + } + if got := m.callback(context.Background(), req); got != chatGPTOAuthFailed { + t.Fatal("callback replay accepted") + } + result, status, err := m.claim("session-a", state) + if err != nil || status != chatGPTOAuthComplete || result.Tokens.AccessToken != "secret" { + t.Fatal("claim failed") + } + if _, _, err = m.claim("session-a", state); err == nil { + t.Fatal("claim replay succeeded") + } +} +func TestChatGPTOAuthBoundsExpiryAndConcurrency(t *testing.T) { + now := time.Now() + f := &fakeChatGPTOAuth{gate: make(chan struct{})} + m := newChatGPTOAuthManager(f, 1, time.Minute) + m.now = func() time.Time { return now } + opts := chatgptauth.Options{RedirectURI: "http://127.0.0.1:1234/auth/callback"} + _, state, err := m.start("a", opts) + if err != nil { + t.Fatal(err) + } + if _, _, err = m.start("a", opts); err == nil { + t.Fatal("capacity exceeded") + } + req := oauthRequest("http://127.0.0.1:1234/auth/callback?state=" + state + "&code=x&scope=openid") + done := make(chan chatGPTOAuthStatus, 1) + go func() { done <- m.callback(context.Background(), req) }() + for f.calls.Load() == 0 { + time.Sleep(time.Millisecond) + } + if got := m.callback(context.Background(), req); got != chatGPTOAuthFailed { + t.Fatal("concurrent callback accepted") + } + close(f.gate) + if <-done != chatGPTOAuthComplete { + t.Fatal("callback failed") + } + var wins atomic.Int32 + var wg sync.WaitGroup + for i := 0; i < 20; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, _, err := m.claim("a", state); err == nil { + wins.Add(1) + } + }() + } + wg.Wait() + if wins.Load() != 1 { + t.Fatalf("claims: %d", wins.Load()) + } + _, state, err = m.start("a", opts) + if err != nil { + t.Fatal(err) + } + now = now.Add(time.Minute) + if _, _, err = m.claim("a", state); err == nil { + t.Fatal("expired claim accepted") + } + if _, _, err = m.start("a", opts); err != nil { + t.Fatal("expired entry retained") + } +} +func TestChatGPTOAuthRejectsBadStart(t *testing.T) { + m := newChatGPTOAuthManager(&fakeChatGPTOAuth{}, 1, time.Minute) + for _, redirect := range []string{"http://localhost:1234/auth/callback", "http://127.0.0.1:01234/auth/callback", "http://127.0.0.1:1234/auth/callback?x=y", "https://127.0.0.1:1234/auth/callback"} { + if _, _, err := m.start("a", chatgptauth.Options{RedirectURI: redirect}); err == nil { + t.Fatalf("accepted %s", redirect) + } + } + if _, _, err := m.start("a", chatgptauth.Options{RedirectURI: "http://127.0.0.1:1234/auth/callback", ClientID: "id"}); err == nil { + t.Fatal("accepted unbound reauthorization") + } +} + +type fakeChatGPTStore struct { + account db.ChatGPTAccount + tokens db.ChatGPTTokens + saves int +} + +func (f *fakeChatGPTStore) ListChatGPTAccounts(context.Context) ([]db.ChatGPTAccount, error) { + if f.account.ID == 0 { + return nil, nil + } + return []db.ChatGPTAccount{f.account}, nil +} +func (f *fakeChatGPTStore) SaveChatGPTRegistration(_ context.Context, a db.ChatGPTAccount, t db.ChatGPTTokens) (db.ChatGPTAccount, error) { + f.saves++ + a.ID = 1 + f.account = a + f.tokens = t + return a, nil +} +func (f *fakeChatGPTStore) WithChatGPTTokens(_ context.Context, _ int64, fn func(db.ChatGPTAccount, db.ChatGPTTokens) (*db.ChatGPTTokens, error)) error { + v, e := fn(f.account, f.tokens) + if e == nil && v != nil { + f.tokens = *v + } + return e +} +func TestChatGPTOAuthRoutes(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + store := &fakeChatGPTStore{} + fake := &fakeChatGPTOAuth{} + s := &Server{jwtKey: key, oauthKeyDir: t.TempDir(), oauthStore: store, oauth: newChatGPTOAuthManager(fake, 8, time.Minute)} + handler := s.Handler() + call := func(method, path, body, auth, origin string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, "http://127.0.0.1:8787"+path, strings.NewReader(body)) + req.URL.Scheme = "" + req.URL.Host = "" + if auth != "" { + req.Header.Set("Authorization", "Bearer "+auth) + } + if origin != "" { + req.Header.Set("Origin", origin) + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + return w + } + if w := call("POST", "/api/chatgpt/connect", `{}`, token, ""); w.Code != 403 { + t.Fatalf("missing origin: %d", w.Code) + } + if w := call("POST", "/api/chatgpt/connect", `{}`, "", "http://127.0.0.1:8787"); w.Code != 401 { + t.Fatalf("missing auth: %d", w.Code) + } + if fake.counter.Load() != 0 { + t.Fatal("unauthorized initiation") + } + w := call("POST", "/api/chatgpt/connect", `{"label":"Account"}`, token, "http://127.0.0.1:8787") + if w.Code != 200 { + t.Fatalf("connect: %d %s", w.Code, w.Body.String()) + } + var connect struct { + URL string `json:"authorization_url"` + Attempt string `json:"attempt_id"` + } + if json.Unmarshal(w.Body.Bytes(), &connect) != nil || connect.Attempt == "" { + t.Fatal("bad connect response") + } + parsed, _ := url.Parse(connect.URL) + state := parsed.Query().Get("state") + if connect.Attempt == state { + t.Fatal("state exposed as attempt handle") + } + w = call("GET", "/auth/callback?state="+state+"&code=private-code&scope=openid", "", "", "") + if w.Code != 200 || strings.Contains(w.Body.String(), "private-code") || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Referrer-Policy") != "no-referrer" || w.Header().Get("Content-Security-Policy") == "" { + t.Fatal("unsafe callback response") + } + claim := `{"attempt_id":"` + connect.Attempt + `"}` + w = call("POST", "/api/chatgpt/claim", claim, token, "http://127.0.0.1:8787") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"complete"`) || strings.Contains(w.Body.String(), "secret") || strings.Contains(w.Body.String(), "subject") { + t.Fatalf("claim: %d %s", w.Code, w.Body.String()) + } + if store.saves != 1 || store.tokens.AccessToken != "secret" { + t.Fatal("did not persist validated result") + } + if w = call("POST", "/api/chatgpt/claim", claim, token, "http://127.0.0.1:8787"); w.Code != 404 { + t.Fatal("claim replay accepted") + } + w = call("POST", "/api/chatgpt/connect", `{}`, token, "http://127.0.0.1:8787") + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &connect) != nil { + t.Fatal("second connect failed") + } + parsed, _ = url.Parse(connect.URL) + state = parsed.Query().Get("state") + cancelBody := `{"attempt_id":"` + connect.Attempt + `"}` + if w = call("POST", "/api/chatgpt/cancel", cancelBody, token, "http://127.0.0.1:8787"); w.Code != 200 { + t.Fatal("cancel failed") + } + calls := fake.calls.Load() + call("GET", "/auth/callback?state="+state+"&code=x", "", "", "") + if fake.calls.Load() != calls { + t.Fatal("cancelled callback exchanged") + } + s.llmCfg.ChatGPTAccountID = 1 + s.llmOn = true + w = call("POST", "/api/chatgpt/signout", `{"account_id":"1"}`, token, "http://127.0.0.1:8787") + if w.Code != 200 || store.tokens.AccessToken != "" || s.llmOn { + t.Fatal("local signout failed or readiness remained active") + } +} + +type fakeChatGPTModels struct { + token string + err error +} + +func (f *fakeChatGPTModels) ListModels(_ context.Context, token string) ([]chatgptplan.Model, error) { + f.token = token + if f.err != nil { + return nil, f.err + } + return []chatgptplan.Model{{Slug: "model-a", DisplayName: "Model A"}}, nil +} +func TestChatGPTOAuthModelsRoute(t *testing.T) { + key := []byte("01234567890123456789012345678901") + session, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + expires := time.Now().Add(time.Hour) + store := &fakeChatGPTStore{account: db.ChatGPTAccount{ID: 1}, tokens: db.ChatGPTTokens{AccessToken: "model-secret", Scope: chatgptauth.DirectScope, TokenType: "Bearer", ExpiresAt: &expires}} + catalog := &fakeChatGPTModels{} + manager := newChatGPTOAuthManager(nil, 8, time.Minute) + manager.models = catalog + server := &Server{jwtKey: key, oauthStore: store, oauth: manager} + handler := server.Handler() + get := func(query string) *httptest.ResponseRecorder { + req := httptest.NewRequest("GET", "http://127.0.0.1:8787/api/chatgpt/models"+query, nil) + req.Header.Set("Authorization", "Bearer "+session) + req.Header.Set("Origin", "http://127.0.0.1:8787") + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + return w + } + for _, q := range []string{"", "?account_id=-1", "?account_id=1&account_id=2"} { + if w := get(q); w.Code != 400 { + t.Fatalf("invalid account accepted: %d", w.Code) + } + } + req := httptest.NewRequest("GET", "http://127.0.0.1:8787/api/chatgpt/accounts", nil) + req.Header.Set("Authorization", "Bearer "+session) + req.Header.Set("Origin", "http://127.0.0.1:8787") + accounts := httptest.NewRecorder() + handler.ServeHTTP(accounts, req) + if accounts.Code != 200 || !strings.Contains(accounts.Body.String(), `"connected":true`) || strings.Contains(accounts.Body.String(), "model-secret") { + t.Fatal("incorrect account status") + } + w := get("?account_id=1") + if w.Code != 200 || !strings.Contains(w.Body.String(), "model-a") || strings.Contains(w.Body.String(), "model-secret") || catalog.token != "model-secret" { + t.Fatalf("catalog response: %d %s", w.Code, w.Body.String()) + } + catalog.err = errors.New("model-secret") + w = get("?account_id=1") + if w.Code != 502 || strings.Contains(w.Body.String(), "model-secret") { + t.Fatal("catalog error leaked") + } + catalog.err = &chatgptplan.StreamError{HTTPStatus: 403} + if w = get("?account_id=1"); w.Code != 403 { + t.Fatalf("provider denial: %d", w.Code) + } + store.tokens.AccessToken = "" + catalog.token = "" + if w = get("?account_id=1"); w.Code != 403 || catalog.token != "" { + t.Fatal("unauthorized account reached provider") + } +} + +type scriptedChatGPTAuth struct { + opts chan chatgptauth.Options + result chatgptauth.Result + err error + seq atomic.Int32 +} + +func (f *scriptedChatGPTAuth) Start(o chatgptauth.Options) (string, *chatgptauth.Attempt, error) { + f.opts <- o + return fmt.Sprintf("https://example.test/?state=script%d", f.seq.Add(1)), &chatgptauth.Attempt{}, nil +} +func (f *scriptedChatGPTAuth) Complete(context.Context, *chatgptauth.Attempt, string) (chatgptauth.Result, error) { + return f.result, f.err +} + +type blockingChatGPTStore struct { + fakeChatGPTStore + entered chan struct{} + release chan struct{} +} + +func (f *blockingChatGPTStore) SaveChatGPTRegistration(ctx context.Context, a db.ChatGPTAccount, t db.ChatGPTTokens) (db.ChatGPTAccount, error) { + close(f.entered) + <-f.release + return f.fakeChatGPTStore.SaveChatGPTRegistration(ctx, a, t) +} +func TestChatGPTOAuthDisabledAndCancelDuringSave(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, _ := signJWT(key) + f := &scriptedChatGPTAuth{opts: make(chan chatgptauth.Options, 2), result: chatgptauth.Result{ClientID: "issued", Identity: chatgptauth.Identity{Subject: "validated"}, Tokens: chatgptauth.Tokens{IDToken: "private-id", Scope: "openid"}}, err: chatgptauth.ErrScope} + store := &blockingChatGPTStore{entered: make(chan struct{}), release: make(chan struct{})} + srv := &Server{jwtKey: key, oauthKeyDir: t.TempDir(), oauthStore: store, oauth: newChatGPTOAuthManager(f, 4, time.Minute)} + handler := srv.Handler() + call := func(method, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, "http://127.0.0.1:8787"+path, strings.NewReader(body)) + req.URL.Scheme = "" + req.URL.Host = "" + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Origin", "http://127.0.0.1:8787") + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + return w + } + w := call("POST", "/api/chatgpt/connect", `{}`) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + var info struct { + URL string `json:"authorization_url"` + Attempt string `json:"attempt_id"` + } + json.Unmarshal(w.Body.Bytes(), &info) + <-f.opts + u, _ := url.Parse(info.URL) + call("GET", "/auth/callback?state="+u.Query().Get("state")+"&code=x", "") + body := `{"attempt_id":"` + info.Attempt + `"}` + done := make(chan *httptest.ResponseRecorder, 1) + go func() { done <- call("POST", "/api/chatgpt/claim", body) }() + <-store.entered + w = call("POST", "/api/chatgpt/cancel", body) + if w.Code != 409 || !strings.Contains(w.Body.String(), "saving") { + t.Fatal("cancel did not report in-progress claim") + } + close(store.release) + w = <-done + if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"plan_disabled"`) || !strings.Contains(w.Body.String(), `"connected":false`) || strings.Contains(w.Body.String(), "private-id") || store.account.Subject != "validated" { + t.Fatalf("disabled claim: %d %s", w.Code, w.Body.String()) + } +} +func TestChatGPTOAuthRetryIssuedRegistration(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, _ := signJWT(key) + f := &scriptedChatGPTAuth{opts: make(chan chatgptauth.Options, 2), result: chatgptauth.Result{ClientID: "issued"}, err: chatgptauth.ErrToken} + store := &fakeChatGPTStore{} + srv := &Server{jwtKey: key, oauthKeyDir: t.TempDir(), oauthStore: store, oauth: newChatGPTOAuthManager(f, 1, time.Minute)} + handler := srv.Handler() + call := func(method, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, "http://127.0.0.1:8787"+path, strings.NewReader(body)) + req.URL.Scheme = "" + req.URL.Host = "" + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Origin", "http://127.0.0.1:8787") + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + return w + } + w := call("POST", "/api/chatgpt/connect", `{"label":"Test"}`) + var info struct { + URL string `json:"authorization_url"` + Attempt string `json:"attempt_id"` + } + json.Unmarshal(w.Body.Bytes(), &info) + <-f.opts + u, _ := url.Parse(info.URL) + call("GET", "/auth/callback?state="+u.Query().Get("state")+"&code=x", "") + body := `{"attempt_id":"` + info.Attempt + `"}` + w = call("POST", "/api/chatgpt/claim", body) + if !strings.Contains(w.Body.String(), "retry_available") || store.saves != 0 { + t.Fatal("issued registration not retained for retry") + } + retry := `{"retry_attempt_id":"` + info.Attempt + `"}` + w = call("POST", "/api/chatgpt/connect", retry) + if w.Code != 200 { + t.Fatalf("retry: %d %s", w.Code, w.Body.String()) + } + opts := <-f.opts + if opts.ClientID != "issued" || !opts.RetryRegistration || opts.ExpectedSubject != "" { + t.Fatal("retry not bound to issued registration") + } + if w = call("POST", "/api/chatgpt/claim", body); w.Code != 404 { + t.Fatal("old retry handle still valid") + } +} + +func TestChatGPTOAuthConsentOnlyWhenNeeded(t *testing.T) { + for _, tc := range []struct { + name, body, scope string + want bool + }{ + {"new", `{}`, "", false}, + {"existing disabled", `{"account_id":"1"}`, "openid profile", true}, + {"existing direct", `{"account_id":"1"}`, "openid " + chatgptauth.DirectScope, false}, + } { + t.Run(tc.name, func(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, _ := signJWT(key) + auth := &scriptedChatGPTAuth{opts: make(chan chatgptauth.Options, 1)} + store := &fakeChatGPTStore{account: db.ChatGPTAccount{ID: 1, ClientID: "issued", Subject: "validated", Label: "test"}, tokens: db.ChatGPTTokens{Scope: tc.scope}} + srv := &Server{jwtKey: key, oauthKeyDir: t.TempDir(), oauthStore: store, oauth: newChatGPTOAuthManager(auth, 4, time.Minute)} + req := httptest.NewRequest("POST", "http://127.0.0.1:8787/api/chatgpt/connect", strings.NewReader(tc.body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Origin", "http://127.0.0.1:8787") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != 200 { + t.Fatalf("connect: %d", w.Code) + } + opts := <-auth.opts + if opts.RequestConsent != tc.want { + t.Fatalf("RequestConsent=%v, want %v", opts.RequestConsent, tc.want) + } + }) + } +} +func TestChatGPTOAuthRejectedCallback(t *testing.T) { + for _, query := range []string{"&code=x&code=y", "&code=x&unexpected=x", "&code=x&iss=one&iss=two", "", "&code=x&error=denied"} { + t.Run(query, func(t *testing.T) { + f := &fakeChatGPTOAuth{} + m := newChatGPTOAuthManager(f, 2, time.Minute) + _, state, err := m.start("session", chatgptauth.Options{RedirectURI: "http://127.0.0.1:1234/auth/callback"}) + if err != nil { + t.Fatal(err) + } + r := oauthRequest("http://127.0.0.1:1234/auth/callback?state=" + state + query) + if got := m.callback(context.Background(), r); got != chatGPTOAuthCallbackRejected { + t.Fatalf("status %s", got) + } + if f.calls.Load() != 0 { + t.Fatal("rejected callback exchanged") + } + if got := m.callback(context.Background(), oauthRequest("http://127.0.0.1:1234/auth/callback?state="+state+"&code=x")); got != chatGPTOAuthFailed { + t.Fatal("rejected attempt replayed") + } + m.mu.Lock() + status := m.entries[state].status + m.mu.Unlock() + if status != chatGPTOAuthCallbackRejected { + t.Fatal("replay altered status") + } + }) + } +} + +func TestChatGPTOAuthRejectedCallbackClaimRoute(t *testing.T) { + key := []byte("01234567890123456789012345678901") + token, err := signJWT(key) + if err != nil { + t.Fatal(err) + } + m := newChatGPTOAuthManager(&fakeChatGPTOAuth{}, 2, time.Minute) + s := &Server{jwtKey: key, oauthKeyDir: t.TempDir(), oauthStore: &fakeChatGPTStore{}, oauth: m} + h := s.Handler() + call := func(method, path, body string, auth bool) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, "http://127.0.0.1:8787"+path, strings.NewReader(body)) + r.URL.Scheme, r.URL.Host = "", "" + if auth { + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("Origin", "http://127.0.0.1:8787") + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + w := call("POST", "/api/chatgpt/connect", "{}", true) + var start struct { + URL string `json:"authorization_url"` + Attempt string `json:"attempt_id"` + } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &start) != nil { + t.Fatal("connect failed") + } + u, _ := url.Parse(start.URL) + w = call("GET", "/auth/callback?state="+url.QueryEscape(u.Query().Get("state"))+"&code=x&unexpected=y", "", false) + if strings.Contains(w.Body.String(), "unexpected") || !strings.Contains(w.Body.String(), "check the sign-in status") { + t.Fatal("unsafe callback response") + } + w = call("POST", "/api/chatgpt/claim", `{"attempt_id":"`+start.Attempt+`"}`, true) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"callback_rejected"`) { + t.Fatalf("claim status: %d %s", w.Code, w.Body.String()) + } +} +func TestChatGPTOAuthRejectedCallbackAfterExpiry(t *testing.T) { + now := time.Now() + f := &fakeChatGPTOAuth{} + m := newChatGPTOAuthManager(f, 2, time.Minute) + m.now = func() time.Time { return now } + _, state, err := m.start("session", chatgptauth.Options{RedirectURI: "http://127.0.0.1:1234/auth/callback"}) + if err != nil { + t.Fatal(err) + } + now = now.Add(time.Minute) + r := oauthRequest("http://127.0.0.1:1234/auth/callback?state=" + state + "&code=x&unexpected=y") + if got := m.callback(context.Background(), r); got != chatGPTOAuthFailed { + t.Fatal("expired callback accepted") + } + if len(m.entries) != 0 || f.calls.Load() != 0 { + t.Fatal("expired attempt retained or exchanged") + } +} diff --git a/server/chatgpt_profile_pg_test.go b/server/chatgpt_profile_pg_test.go new file mode 100644 index 000000000..d15dd7f24 --- /dev/null +++ b/server/chatgpt_profile_pg_test.go @@ -0,0 +1,79 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/artex/chatgptauth" + "github.com/Autumn-27/artex/db" +) + +func TestChatGPTProfileConversionKeepsExistingKey(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + if m.pg == nil { + db.SkipNoPG(t) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + const key = "synthetic-key" + id, err := m.pg.SaveProfile(&db.LLMProfile{Name: "conversion-test", Format: "openai", Model: "test", APIKey: key, Streaming: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) }) + body, _ := json.Marshal(map[string]any{"id": id, "name": "conversion-test", "format": "chatgpt-plan", "model": "test"}) + rec := httptest.NewRecorder() + s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body))) + if rec.Code != http.StatusBadRequest { + t.Fatalf("conversion status = %d", rec.Code) + } + stored, err := m.pg.ProfileByID(id) + if err != nil || stored == nil || stored.Format != "openai" || stored.APIKey != key { + t.Fatal("rejected conversion changed the saved profile or key") + } +} + +func TestChatGPTSavedProfileLoadsProvider(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + if m.pg == nil { + db.SkipNoPG(t) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + expires := time.Now().Add(time.Hour) + a, err := m.pg.SaveChatGPTRegistration(ctx, db.ChatGPTAccount{ClientID: "fake-client", Subject: "fake-subject", Label: "fixture"}, db.ChatGPTTokens{AccessToken: "fake-access", RefreshToken: "fake-refresh", IDToken: "fake-id", Scope: chatgptauth.DirectScope, TokenType: "Bearer", ExpiresAt: &expires}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM chatgpt_accounts WHERE id=$1`, a.ID) }) + id, err := m.pg.SaveProfile(&db.LLMProfile{Name: "chatgpt-profile-test", Format: "chatgpt-plan", Model: "fake-model", ChatGPTAccountID: &a.ID, Streaming: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) }) + cfg, ok := s.loadProfileConfig(id) + if !ok || cfg.Format != agent.FormatChatGPTPlan || cfg.ChatGPTAccountID != a.ID { + t.Fatal("saved ChatGPT profile did not resolve to the authorized account") + } + if prov, _, ok := s.providerForProfile(id); !ok || prov == nil { + t.Fatal("saved ChatGPT profile did not build a provider") + } +} diff --git a/server/chatgpt_provider.go b/server/chatgpt_provider.go new file mode 100644 index 000000000..c4d769c94 --- /dev/null +++ b/server/chatgpt_provider.go @@ -0,0 +1,78 @@ +package server + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/Autumn-27/artex/chatgptauth" + "github.com/Autumn-27/artex/chatgptplan" + "github.com/Autumn-27/artex/db" +) + +func chatGPTFailure(err error) (string, string) { + var httpErr *chatgptplan.HTTPError + var streamErr *chatgptplan.StreamError + code := "" + if errors.As(err, &httpErr) { + code = httpErr.Code + } else if errors.As(err, &streamErr) { + code = streamErr.Code + } + switch code { + case "subscription_sharing_usage_limit_exceeded", "subscription_sharing_usage_unavailable": + return "ChatGPT plan usage is unavailable or has reached its limit; review usage in ChatGPT settings", code + default: + return "ChatGPT plan request did not complete", code + } +} + +type chatGPTTokenStore interface { + WithChatGPTTokens(context.Context, int64, func(db.ChatGPTAccount, db.ChatGPTTokens) (*db.ChatGPTTokens, error)) error +} + +type chatGPTRefresher interface { + Refresh(context.Context, string, chatgptauth.Tokens) (chatgptauth.Tokens, error) +} + +// chatGPTAccessToken holds the database row lock across refresh, so concurrent +// workers and server processes cannot race a rotating refresh token. +func chatGPTAccessToken(ctx context.Context, store chatGPTTokenStore, auth chatGPTRefresher, accountID int64, now time.Time) (string, error) { + if store == nil || auth == nil || accountID <= 0 { + return "", errors.New("ChatGPT account is unavailable") + } + var access string + err := store.WithChatGPTTokens(ctx, accountID, func(account db.ChatGPTAccount, tokens db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + allowed := false + for _, scope := range strings.Fields(tokens.Scope) { + allowed = allowed || scope == chatgptauth.DirectScope + } + if !allowed || !strings.EqualFold(tokens.TokenType, "Bearer") || tokens.AccessToken == "" || tokens.ExpiresAt == nil { + return nil, errors.New("ChatGPT account needs authorization") + } + if tokens.ExpiresAt.After(now.Add(time.Minute)) { + access = tokens.AccessToken + return nil, nil + } + fresh, err := auth.Refresh(ctx, account.ClientID, chatgptauth.Tokens{ + AccessToken: tokens.AccessToken, RefreshToken: tokens.RefreshToken, + IDToken: tokens.IDToken, Scope: tokens.Scope, TokenType: tokens.TokenType, + }) + freshAllowed := false + for _, scope := range strings.Fields(fresh.Scope) { + freshAllowed = freshAllowed || scope == chatgptauth.DirectScope + } + if err != nil || fresh.AccessToken == "" || fresh.ExpiresIn <= 0 || fresh.ExpiresIn > 365*24*60*60 || !strings.EqualFold(fresh.TokenType, "Bearer") || !freshAllowed { + return nil, errors.New("ChatGPT account refresh failed; reconnect the account") + } + expires := now.Add(time.Duration(fresh.ExpiresIn) * time.Second) + access = fresh.AccessToken + return &db.ChatGPTTokens{AccessToken: fresh.AccessToken, RefreshToken: fresh.RefreshToken, + IDToken: fresh.IDToken, Scope: fresh.Scope, TokenType: fresh.TokenType, ExpiresAt: &expires}, nil + }) + if err != nil { + return "", err + } + return access, nil +} diff --git a/server/chatgpt_provider_test.go b/server/chatgpt_provider_test.go new file mode 100644 index 000000000..db1b83f9d --- /dev/null +++ b/server/chatgpt_provider_test.go @@ -0,0 +1,67 @@ +package server + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Autumn-27/artex/chatgptauth" + "github.com/Autumn-27/artex/db" +) + +type tokenStoreProbe struct { + account db.ChatGPTAccount + tokens db.ChatGPTTokens + err error +} + +func (s *tokenStoreProbe) WithChatGPTTokens(_ context.Context, _ int64, fn func(db.ChatGPTAccount, db.ChatGPTTokens) (*db.ChatGPTTokens, error)) error { + if s.err != nil { + return s.err + } + next, err := fn(s.account, s.tokens) + if err == nil && next != nil { + s.tokens = *next + } + return err +} + +type refreshProbe struct { + result chatgptauth.Tokens + err error + calls int +} + +func (r *refreshProbe) Refresh(context.Context, string, chatgptauth.Tokens) (chatgptauth.Tokens, error) { + r.calls++ + return r.result, r.err +} + +func TestChatGPTAccessTokenRefreshAndFailures(t *testing.T) { + now := time.Now() + expires := now.Add(time.Hour) + s := &tokenStoreProbe{account: db.ChatGPTAccount{ClientID: "client"}, tokens: db.ChatGPTTokens{ + AccessToken: "old", RefreshToken: "refresh", IDToken: "id", Scope: chatgptauth.DirectScope, + TokenType: "Bearer", ExpiresAt: &expires, + }} + r := &refreshProbe{result: chatgptauth.Tokens{AccessToken: "new", RefreshToken: "rotated", IDToken: "id", Scope: chatgptauth.DirectScope, TokenType: "Bearer", ExpiresIn: 3600}} + got, err := chatGPTAccessToken(context.Background(), s, r, 1, now) + if err != nil || got != "old" || r.calls != 0 { + t.Fatalf("unexpired token: got=%q calls=%d err=%v", got, r.calls, err) + } + expires = now.Add(-time.Second) + got, err = chatGPTAccessToken(context.Background(), s, r, 1, now) + if err != nil || got != "new" || s.tokens.RefreshToken != "rotated" || r.calls != 1 { + t.Fatalf("refresh: got=%q calls=%d err=%v", got, r.calls, err) + } + s.tokens.ExpiresAt = &expires + r.err = errors.New("sensitive provider details") + if got, err = chatGPTAccessToken(context.Background(), s, r, 1, now); err == nil || got != "" || err.Error() == r.err.Error() { + t.Fatal("failed refresh must not return a token or provider error") + } + s.tokens.Scope = "openid" + if got, err = chatGPTAccessToken(context.Background(), s, r, 1, now); err == nil || got != "" { + t.Fatal("ungranted plan scope must fail") + } +} diff --git a/server/dto.go b/server/dto.go index 80efde658..d39e1e455 100644 --- a/server/dto.go +++ b/server/dto.go @@ -614,20 +614,21 @@ func agentDTOs(in []*db.Agent) []AgentDTO { // ---- LLMProfile (frontend "LLMProfile") — string id ---- type LLMProfileDTO struct { - ID string `json:"id"` - Name string `json:"name"` - Format string `json:"format"` - BaseURL string `json:"base_url,omitempty"` - Proxy string `json:"proxy,omitempty"` // masked: the placeholder when set - ProxySet bool `json:"proxy_set"` - Model string `json:"model"` - APIKeyHint string `json:"api_key_hint,omitempty"` - RatePerSecond float64 `json:"rate_per_second"` - RatePerMinute float64 `json:"rate_per_minute"` - ContextWindowK int `json:"context_window_k"` - ThinkingType string `json:"thinking_type"` - ReasoningEffort string `json:"reasoning_effort"` - IsDefault bool `json:"is_default"` + ID string `json:"id"` + Name string `json:"name"` + Format string `json:"format"` + BaseURL string `json:"base_url,omitempty"` + Proxy string `json:"proxy,omitempty"` // masked: the placeholder when set + ProxySet bool `json:"proxy_set"` + Model string `json:"model"` + ChatGPTAccountID string `json:"chatgpt_account_id,omitempty"` + APIKeyHint string `json:"api_key_hint,omitempty"` + RatePerSecond float64 `json:"rate_per_second"` + RatePerMinute float64 `json:"rate_per_minute"` + ContextWindowK int `json:"context_window_k"` + ThinkingType string `json:"thinking_type"` + ReasoningEffort string `json:"reasoning_effort"` + IsDefault bool `json:"is_default"` // Pooling (failover) parameters: higher priority is picked first (the active // profile is always the chain head); pool_exclude=true excludes it as a failover target, though agents/tasks can still bind it explicitly. Priority int `json:"priority"` @@ -658,7 +659,7 @@ type LLMProfileDTO struct { } func llmProfileDTO(p *db.LLMProfile) LLMProfileDTO { - return LLMProfileDTO{ + dto := LLMProfileDTO{ ID: i64s(p.ID), Name: p.Name, Format: p.Format, @@ -688,6 +689,10 @@ func llmProfileDTO(p *db.LLMProfile) LLMProfileDTO { PriceCacheReadPerM: p.PriceCacheReadPerM, PriceCacheWritePerM: p.PriceCacheWritePerM, } + if p.ChatGPTAccountID != nil { + dto.ChatGPTAccountID = i64s(*p.ChatGPTAccountID) + } + return dto } func llmProfileDTOs(in []*db.LLMProfile) []LLMProfileDTO { diff --git a/server/server.go b/server/server.go index e4b721034..4c8ce6800 100644 --- a/server/server.go +++ b/server/server.go @@ -27,6 +27,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/archivestore" + "github.com/Autumn-27/artex/chatgptauth" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/egress" "github.com/Autumn-27/artex/intercept" @@ -59,6 +60,12 @@ type Server struct { execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own isolation IsolationStatus // result of the startup isolation self-test (isolation.go); zero when not run + chatGPTRequests chatGPTLifecycle + oauthOnce sync.Once + oauth *chatGPTOAuthManager + oauthStore chatGPTOAuthStore + oauthKeyDir string + chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL // browser is the shared Chromium the operator can watch and take over @@ -204,7 +211,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi if err != nil { log.Fatalf("[auth] JWT key: %v", err) } - s := &Server{m: m, engine: NewEngine(m), ctx: ctx, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{}, + s := &Server{oauthKeyDir: keyDir, m: m, engine: NewEngine(m), ctx: ctx, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{}, chatCancel: map[string]context.CancelCauseFunc{}, triggerQ: map[string][]triggeredRun{}, triggerActive: map[string]int{}, triggerCfg: map[string]triggerBehavior{}, profChatAgents: map[int64]*agent.ChatAgent{}, @@ -644,6 +651,23 @@ func (s *Server) loadProfileConfig(id int64) (agent.Config, bool) { cfg.UserAgent = p.UserAgent cfg.CustomHeaders = p.CustomHeaders s.applyProfileRetry(&cfg, p) + if cfg.Format == agent.FormatChatGPTPlan { + if p.ChatGPTAccountID == nil || *p.ChatGPTAccountID <= 0 || !p.Streaming || p.MaxTokens != 0 || p.RatePerSecond != 0 || p.RatePerMinute != 0 || p.ThinkingType != "" || p.ReasoningEffort != "" || strings.TrimSpace(p.Model) == "" { + return cfg, false + } + cfg.ChatGPTAccountID = *p.ChatGPTAccountID + connected := false + if err := s.m.pg.WithChatGPTTokens(s.ctx, cfg.ChatGPTAccountID, func(_ db.ChatGPTAccount, tokens db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + for _, scope := range strings.Fields(tokens.Scope) { + if scope == chatgptauth.DirectScope && tokens.AccessToken != "" && tokens.ExpiresAt != nil && strings.EqualFold(tokens.TokenType, "Bearer") { + connected = true + } + } + return nil, nil + }); err != nil || !connected { + return cfg, false + } + } if cfg.APIKey == "" && cfg.NeedsAPIKey() { return cfg, false } @@ -710,7 +734,16 @@ func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool) if !ok { return nil, agent.Config{}, false } - prov, err := cfg.NewProvider() + var prov llm.Provider + var err error + if cfg.Format == agent.FormatChatGPTPlan { + accountID := cfg.ChatGPTAccountID + prov = &chatGPTLifecycleProvider{lifecycle: &s.chatGPTRequests, accountID: accountID, provider: &agent.ChatGPTPlanProvider{Model: cfg.Model, AccountID: strconv.FormatInt(accountID, 10), Token: func(ctx context.Context) (string, error) { + return chatGPTAccessToken(ctx, s.m.pg, chatgptauth.NewClient(chatgptauth.Config{}), accountID, time.Now()) + }}} + } else { + prov, err = cfg.NewProvider() + } if err != nil { log.Printf("[engine] build provider for LLM profile %d failed: %v", id, err) return nil, agent.Config{}, false @@ -797,6 +830,12 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/auth/login", s.authLogin) mux.HandleFunc("POST /api/auth/change-password", s.authChangePassword) + mux.HandleFunc("GET /api/chatgpt/accounts", s.chatGPTAccounts) + mux.HandleFunc("GET /api/chatgpt/models", s.chatGPTModels) + mux.HandleFunc("POST /api/chatgpt/connect", s.chatGPTConnect) + mux.HandleFunc("POST /api/chatgpt/claim", s.chatGPTClaim) + mux.HandleFunc("POST /api/chatgpt/cancel", s.chatGPTCancel) + mux.HandleFunc("POST /api/chatgpt/signout", s.chatGPTSignout) mux.HandleFunc("GET /api/health", s.health) mux.HandleFunc("GET /api/ready", s.ready) mux.HandleFunc("GET /api/stats", s.stats) @@ -1120,6 +1159,7 @@ func (s *Server) Handler() http.Handler { api := cors(s.requireAuth(mux)) root := http.NewServeMux() root.Handle("/api/", api) + root.HandleFunc("/auth/callback", s.chatGPTCallback) webui := s.webuiHandler() root.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Document-only headers; the shared ones come from securityHeaders. @@ -1632,6 +1672,32 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { stored = p } } + if stored != nil && stored.Format == "chatgpt-plan" { + if (req.Provider != "" && req.Provider != stored.Format) || (req.Model != "" && req.Model != stored.Model) || req.BaseURL != "" || req.Proxy != "" || req.APIKey != "" { + writeErr(w, 400, "test the saved ChatGPT plan profile without endpoint or model overrides") + return + } + provider, _, ok := s.providerForProfile(stored.ID) + if !ok { + writeJSON(w, 200, map[string]any{"ok": false, "error": "ChatGPT account or profile is unavailable"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + start := time.Now() + msg, stop, _, err := provider.Complete(ctx, llm.CompletionRequest{Messages: []llm.Message{llm.UserText("Reply with OK.")}}) + if err != nil { + message, code := chatGPTFailure(err) + writeJSON(w, 200, map[string]any{"ok": false, "error": message, "error_code": code}) + return + } + if agent.IsRefusalStop(stop) || strings.TrimSpace(msg.Text()) == "" { + writeJSON(w, 200, map[string]any{"ok": false, "error": "ChatGPT plan test did not return a completed text response"}) + return + } + writeJSON(w, 200, map[string]any{"ok": true, "latency_ms": time.Since(start).Milliseconds(), "reply": msg.Text()}) + return + } if isMaskedSecret(req.Proxy) { // the form echoes the masked proxy: test with the stored one req.Proxy = "" if stored == nil { @@ -1683,7 +1749,7 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { } else if stored != nil { cfg.MaxTokensField = stored.MaxTokensField } - if cfg.Format != llm.FormatOpenAI || cfg.MaxTokensField != llm.MaxTokensFieldCompletion { + if (cfg.Format != llm.FormatOpenAI && cfg.Format != agent.FormatOpenRouter) || cfg.MaxTokensField != llm.MaxTokensFieldCompletion { cfg.MaxTokensField = "" } // The custom session header name follows that profile too: when non-empty, the test request also sends it (value is a one-off random session id, diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 28f109f48..e0827f17f 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -30,6 +30,7 @@ import ( "unicode/utf8" "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/artex/chatgptauth" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/notify" @@ -2198,6 +2199,53 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { p.ClearCustomHeaders = true } p.Streaming = body.Streaming == nil || *body.Streaming + if p.ID != 0 { + previous, err := pg.ProfileByID(p.ID) + if err != nil { + writeErr(w, 500, "profile lookup failed") + return + } + if previous != nil && ((previous.Format == "chatgpt-plan") != (p.Format == "chatgpt-plan")) { + writeErr(w, 400, "create a separate profile when switching to or from ChatGPT plan") + return + } + } + if p.Format == "chatgpt-plan" { + if p.ChatGPTAccountID == nil || *p.ChatGPTAccountID <= 0 || strings.TrimSpace(p.Model) == "" { + writeErr(w, 400, "select a connected ChatGPT account and model") + return + } + if !p.Streaming || p.MaxTokens != 0 || p.RatePerSecond != 0 || p.RatePerMinute != 0 || p.ThinkingType != "" || p.ReasoningEffort != "" || p.APIKey != "" || p.BaseURL != "" || p.Proxy != "" || p.SessionHeaderKey != "" || p.UserAgent != "" { + writeErr(w, 400, "ChatGPT plan profiles require streaming and do not support API keys, custom endpoints, proxies, headers, output caps, request-rate limits, or reasoning controls") + return + } + connected := false + err := pg.WithChatGPTTokens(r.Context(), *p.ChatGPTAccountID, func(_ db.ChatGPTAccount, tokens db.ChatGPTTokens) (*db.ChatGPTTokens, error) { + for _, scope := range strings.Fields(tokens.Scope) { + if scope == chatgptauth.DirectScope && tokens.AccessToken != "" && strings.EqualFold(tokens.TokenType, "Bearer") { + connected = true + } + } + return nil, nil + }) + if err != nil || !connected { + writeErr(w, 400, "the selected ChatGPT account is not connected for plan usage") + return + } + } else if p.ChatGPTAccountID != nil { + writeErr(w, 400, "a ChatGPT account can only be used with a ChatGPT plan profile") + return + } + // The list returns the proxy masked: the placeholder sent back keeps the + // stored proxy and is never stored itself. + if isMaskedSecret(p.Proxy) { + stored, err := pg.ProfileByID(p.ID) + if p.ID == 0 || err != nil || stored == nil { + writeErr(w, 400, "proxy is a masked placeholder but no stored proxy to keep; enter the proxy or clear it") + return + } + p.Proxy = stored.Proxy + } // Output cap: negative values are meaningless, clamp to zero (= do not send the // field). The field-name switch only matters for Chat Completions — anthropic and // openai-responses hard-code their field names; storing it would only mislead later readers, so it is cleared for any non-openai format. Unknown values are cleared too, to avoid throwing DB CHECK errors at the user. @@ -2230,7 +2278,7 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { price(body.PriceOutputPerM, &p.PriceOutputPerM, old.PriceOutputPerM) price(body.PriceCacheReadPerM, &p.PriceCacheReadPerM, old.PriceCacheReadPerM) price(body.PriceCacheWritePerM, &p.PriceCacheWritePerM, old.PriceCacheWritePerM) - if p.Format != "openai" || p.MaxTokensField != llm.MaxTokensFieldCompletion { + if (p.Format != "openai" && p.Format != "openrouter") || p.MaxTokensField != llm.MaxTokensFieldCompletion { p.MaxTokensField = "" } // Custom User-Agent: trim and reject control characters / over-long values so a @@ -2758,11 +2806,15 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { var candidates []candidate switch provider { - case "openai", "openai-responses": + case "openai", "openai-responses", "openrouter": // Responses API shares the OpenAI model list at /v1/models; tolerate a full // endpoint URL of either format. if baseURL == "" { - baseURL = "https://api.openai.com/v1" + if provider == "openrouter" { + baseURL = agent.DefaultOpenRouterBaseURL + } else { + baseURL = "https://api.openai.com/v1" + } } b := strings.TrimRight(strings.TrimSuffix(strings.TrimSuffix(baseURL, "/chat/completions"), "/responses"), "/") candidates = append(candidates, candidate{b + "/models", bearerHdr()}) diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index 760084f8f..5a30f7ba5 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -8,7 +8,7 @@ import { Loader2Icon, PlugZapIcon, PlusIcon, - RefreshCwIcon, + ChevronDownIcon, RotateCcwIcon, SaveIcon, StarIcon, @@ -17,6 +17,7 @@ import { } from "lucide-react"; import { toast } from "sonner"; +import { ChatGPTUsageError, chatGPTUsageError } from "@/components/chatgpt-usage-error"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; @@ -29,13 +30,13 @@ import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from " import { Switch } from "@/components/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { t } from "@/i18n"; -import { api } from "@/lib/api"; +import { api, ApiError } from "@/lib/api"; import { OPENAI_COMPATIBLE_BASE_PLACEHOLDER, OPENAI_COMPATIBLE_PRESET, openAICompatiblePresetSelected, } from "@/lib/openai-compatible"; -import type { LLMPoolMember, LLMPoolStatus, LLMProfile, LLMRetryOverride } from "@/lib/types"; +import type { ChatGPTAccount, LLMPoolMember, LLMPoolStatus, LLMProfile, LLMRetryOverride } from "@/lib/types"; import { cn } from "@/lib/utils"; import { ProfileRetryFields, RetryPolicyPanel, ZERO_OVERRIDE } from "./_components/retry"; @@ -74,7 +75,7 @@ const MAX_TOKENS_FIELD_HINTS: Record = { }; // LLM profile formats. The default in the create form is "anthropic"; "ollama" is the // keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1). -type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway"; +type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway" | "chatgpt-plan" | "openrouter"; const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1"; const EFFORT_LEVELS: { value: string; label: string }[] = [ { value: NONE, label: t("Not sent (default)") }, @@ -96,7 +97,7 @@ function cooldownText(secs: number) { // records (with polling off no new records appear, so "healthy" = no known failure). type Health = { label: string; cls: string; hint?: string }; function healthOf(p: LLMProfile, m?: LLMPoolMember): Health { - if (!p.api_key_hint && p.format !== "ollama") { + if (!p.api_key_hint && p.format !== "ollama" && p.format !== "chatgpt-plan") { return { label: t("No Key configured"), cls: "border-muted-foreground/40 text-muted-foreground", @@ -343,6 +344,95 @@ function ProfileSheet({ }) { const isNew = !profile; const [name, setName] = React.useState(""); + const [accounts, setAccounts] = React.useState([]); + const accountCount = React.useRef(0); + accountCount.current = accounts.length; + const [accountId, setAccountId] = React.useState(""); + const [attempt, setAttempt] = React.useState(""); + const [retryAvailable, setRetryAvailable] = React.useState(false); + const [signInMessage, setSignInMessage] = React.useState(""); + const cancelRequested = React.useRef(false); + const [connecting, setConnecting] = React.useState(false); + const [localConsole, setLocalConsole] = React.useState(false); + const [welcome, setWelcome] = React.useState(false); + const loadAccounts = React.useCallback(async () => { + const result = await api.chatGPTAccounts(); + setAccounts(result.accounts ?? []); + }, []); + React.useEffect(() => { + if (!open) return; + setLocalConsole(window.location.protocol === "http:" && window.location.hostname === "127.0.0.1"); + void loadAccounts().catch(() => setAccounts([])); + }, [open, loadAccounts]); + React.useEffect(() => { + if (!open || !attempt) return; + let cancelled = false; + let completed = false; + let timer: ReturnType; + const slowTimer = setTimeout(() => { + if (!cancelled) setSignInMessage(t("Sign-in is taking longer than expected. Finish in the browser, then return here. You can cancel and start again.")); + }, 60000); + const expiryTimer = setTimeout(() => { + if (!cancelled) { + cancelled = true; + clearTimeout(timer); + setSignInMessage(t("The sign-in attempt timed out. Cancel it and start again.")); + } + }, 10 * 60 * 1000); + const poll = async () => { + try { + const result = await api.chatGPTClaim(attempt); + if (cancelled) return; + if (cancelRequested.current) { timer = setTimeout(poll, 1500); return; } + if (result.status === "retry_available") { setRetryAvailable(true); return; } + if (result.status === "pending") { timer = setTimeout(poll, 1500); return; } + completed = true; + if (result.status === "complete" && result.account) { + setAccountId(String(result.account.id)); + if (accountCount.current === 0) setWelcome(true); + toast.success(t("ChatGPT account connected")); + void loadAccounts(); + } else if (result.status === "plan_disabled" && result.account) { + setAccountId(String(result.account.id)); + void loadAccounts(); + toast.warning(t("Signed in, but ChatGPT plan usage is not enabled. Reconnect to grant permission.")); + } else if (result.status === "callback_rejected") { + setSignInMessage(t("Sign-in could not be verified. Start again and complete sign-in in the browser.")); + } else setSignInMessage(t("ChatGPT sign-in failed. Please try again.")); + setAttempt(""); + } catch (e) { + if (cancelled) return; + if (e instanceof ApiError && e.status === 409) { timer = setTimeout(poll, 1500); return; } + setSignInMessage(e instanceof ApiError && e.status === 404 + ? t("The sign-in attempt expired. Start again.") + : t("Could not check sign-in status. Start again and try connecting.") ); + setAttempt(""); + } + }; + void poll(); + return () => { cancelled = true; clearTimeout(timer); clearTimeout(slowTimer); clearTimeout(expiryTimer); if (!completed && !cancelRequested.current) void api.chatGPTCancel(attempt).catch(() => {}); }; + }, [attempt, open, loadAccounts]); + async function cancelSignIn() { + if (!attempt) return; + cancelRequested.current = true; + try { await api.chatGPTCancel(attempt); setRetryAvailable(false); setSignInMessage(""); setAttempt(""); } + catch (e) { cancelRequested.current = false; if (e instanceof ApiError && e.status === 404) { setRetryAvailable(false); setAttempt(""); toast.error(t("The sign-in attempt expired. Start again.")); } else toast.error(e instanceof ApiError && e.status === 409 ? t("Sign-in is being saved. Please wait and try again.") : (e as Error).message); } + } + async function connect(account?: string, retryAttempt?: string) { + if (!localConsole || connecting) return; + const popup = window.open("", "_blank"); + if (!popup) { toast.error(t("Allow pop-ups to continue with ChatGPT.")); return; } + setConnecting(true); + try { + const result = await api.chatGPTConnect(account, retryAttempt); + popup.location.href = result.authorization_url; + cancelRequested.current = false; + setRetryAvailable(false); + setSignInMessage(""); + setAttempt(result.attempt_id); + } catch (e) { popup.close(); if (retryAttempt && e instanceof ApiError && e.status === 404) { setRetryAvailable(false); setAttempt(""); toast.error(t("The sign-in attempt expired. Start again.")); } else toast.error((e as Error).message); } + finally { setConnecting(false); } + } const [format, setFormat] = React.useState("anthropic"); // The "Custom OpenAI-compatible" preset. UI-only: it selects the openai // format and the expected base-URL shape, and is never stored, so it is @@ -370,10 +460,13 @@ function ProfileSheet({ const [clearCustomHeaders, setClearCustomHeaders] = React.useState(false); const [retry, setRetry] = React.useState(ZERO_OVERRIDE); // retry override for this profile; all 0 = follow the global const [testing, setTesting] = React.useState(false); + const [testUsageError, setTestUsageError] = React.useState(""); const [saving, setSaving] = React.useState(false); const [models, setModels] = React.useState([]); const [loadingModels, setLoadingModels] = React.useState(false); const [modelsOpen, setModelsOpen] = React.useState(false); + const [modelsError, setModelsError] = React.useState(""); + const modelsRequest = React.useRef(0); const [modelQuery, setModelQuery] = React.useState(""); // filter text for the loaded model list; reset on open/close // Every time it opens, the form is re-filled from the passed-in profile (reset to defaults when creating). Closing and reopening @@ -382,12 +475,13 @@ function ProfileSheet({ if (!open) return; setName(profile?.name ?? ""); setFormat( - profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "ollama" || profile?.format === "bedrock-gateway" + profile?.format === "openrouter" || profile?.format === "chatgpt-plan" || profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "ollama" || profile?.format === "bedrock-gateway" ? profile.format : "anthropic", ); setCompatPreset(openAICompatiblePresetSelected(profile?.format, profile?.base_url)); setModel(profile?.model ?? ""); + setAccountId(profile?.chatgpt_account_id ? String(profile.chatgpt_account_id) : ""); setBaseUrl(profile?.base_url ?? ""); setProxy(profile?.proxy ?? ""); setRps(String(profile?.rate_per_second ?? 0)); @@ -413,12 +507,26 @@ function ProfileSheet({ setRetry(profile?.retry ?? ZERO_OVERRIDE); setApiKey(""); setKeyHint(profile?.api_key_hint ?? ""); + modelsRequest.current += 1; + setLoadingModels(false); setModels([]); + setModelsError(""); + setTestUsageError(""); setModelsOpen(false); setModelQuery(""); }, [open, profile]); + // Invalidate results when the credentials or endpoint change while a request is in flight. + React.useEffect(() => { + modelsRequest.current += 1; + setLoadingModels(false); + setModels([]); + setModelsError(""); + setModelsOpen(false); + }, [open, format, baseUrl, apiKey, proxy, accountId]); + const profileId = profile ? Number(profile.id) : undefined; + const selectedAccount = accounts.find((account) => String(account.id) === accountId); // Case-insensitive substring filter, so a provider prefix ("deepseek/") or a // fragment ("flash") is enough to narrow a 400-entry list. @@ -430,32 +538,39 @@ function ProfileSheet({ async function loadModels() { if (loadingModels) return; + const request = ++modelsRequest.current; setLoadingModels(true); + setModelsError(""); setModels([]); setModelQuery(""); try { - const r = await api.fetchLLMModels(format, baseUrl, apiKey, proxy, profileId); + const r = format === "chatgpt-plan" + ? { ok: true, models: (await api.chatGPTModels(accountId)).models.map((m) => m.slug), error: undefined } + : await api.fetchLLMModels(format, baseUrl, apiKey, proxy, profile?.format === format ? profileId : undefined); + if (request !== modelsRequest.current) return; if (r.ok && r.models && r.models.length > 0) { setModels(r.models); - setModelsOpen(true); - toast.success(t("Loaded {count} models", { count: r.models.length })); + } else { - toast.error(t("Failed to load models: {error}", { error: r.error ?? t("no models returned") })); + setModelsError(t("Failed to load models: {error}", { error: r.error ?? t("no models returned") })); } } catch (e) { - toast.error(t("Error loading models: {error}", { error: (e as Error).message })); + if (request === modelsRequest.current) setModelsError(t("Error loading models: {error}", { error: (e as Error).message })); } finally { - setLoadingModels(false); + if (request === modelsRequest.current) setLoadingModels(false); } } async function testConnection() { if (testing) return; setTesting(true); + setTestUsageError(""); try { // Test with the thinking parameters the profile would actually run, so a model that does not support the field fails here, // not when a task is already running. Pass the profile id: with the Key input left empty, the stored Key is used. - const r = await api.testLLM( + const r = format === "chatgpt-plan" && profileId + ? await api.testStoredLLM(profileId) + : await api.testLLM( format, model, baseUrl, @@ -476,6 +591,7 @@ function ProfileSheet({ toast.success(t("Connected · {latency}ms · {model}", { latency: r.latency_ms ?? "?", model: r.model ?? model }), { description: r.reply ? t("Reply: {reply}", { reply: r.reply }) : undefined, }); + else if ("error_code" in r && typeof r.error_code === "string" && chatGPTUsageError(r.error_code)) setTestUsageError(r.error_code); else toast.error(t("Connection failed: {error}", { error: r.error ?? t("unknown") })); } catch (e) { toast.error(t("Test error: {error}", { error: (e as Error).message })); @@ -489,6 +605,7 @@ function ProfileSheet({ toast.error(t("Please fill in a name and a model")); return; } + if (format === "chatgpt-plan" && !selectedAccount?.connected) { toast.error(t("Select a connected ChatGPT account")); return; } if (saving) return; setSaving(true); try { @@ -496,30 +613,31 @@ function ProfileSheet({ ...(profile ? { id: Number(profile.id) } : {}), name: name.trim(), format, + chatgpt_account_id: format === "chatgpt-plan" ? Number(accountId) : undefined, model: model.trim(), - base_url: baseUrl.trim(), - proxy: proxy.trim(), - api_key: apiKey, - rate_per_second: Number(rps) || 0, - rate_per_minute: Number(rpm) || 0, + base_url: format === "chatgpt-plan" ? "" : baseUrl.trim(), + proxy: format === "chatgpt-plan" ? "" : proxy.trim(), + api_key: format === "chatgpt-plan" ? "" : apiKey, + rate_per_second: format === "chatgpt-plan" ? 0 : Number(rps) || 0, + rate_per_minute: format === "chatgpt-plan" ? 0 : Number(rpm) || 0, context_window_k: Number(cw) || 0, price_input_per_m: Math.max(0, Number(prices.input) || 0), price_output_per_m: Math.max(0, Number(prices.output) || 0), price_cache_read_per_m: Math.max(0, Number(prices.cacheRead) || 0), price_cache_write_per_m: Math.max(0, Number(prices.cacheWrite) || 0), - thinking_type: toStore(thinkingType), - reasoning_effort: toStore(effort), + thinking_type: format === "chatgpt-plan" ? "" : toStore(thinkingType), + reasoning_effort: format === "chatgpt-plan" ? "" : toStore(effort), priority: Number(priority) || 0, pool_exclude: poolExclude, - streaming, - max_tokens: Math.max(0, Number(maxTokens) || 0), + streaming: format === "chatgpt-plan" ? true : streaming, + max_tokens: format === "chatgpt-plan" ? 0 : Math.max(0, Number(maxTokens) || 0), // The field-name switch only matters for openai (Chat Completions); every other format falls back to the default, // and the backend re-applies the same normalization; this just keeps the UI from sending contradictory values. max_tokens_field: format === "openai" ? toStore(maxTokensField) : "", - session_header_key: sessionHeaderKey.trim(), - user_agent: userAgent.trim(), + session_header_key: format === "chatgpt-plan" ? "" : sessionHeaderKey.trim(), + user_agent: format === "chatgpt-plan" ? "" : userAgent.trim(), custom_headers: format === "bedrock-gateway" ? customHeaders : "", - clear_custom_headers: clearCustomHeaders, + clear_custom_headers: format === "chatgpt-plan" ? false : clearCustomHeaders, retry, }); if (isNew) toast.success(t('Created: {name} (use "Set as active" on its card to enable it)', { name: name.trim() })); @@ -543,6 +661,9 @@ function ProfileSheet({ keyPlaceholder = t("optional — a local Ollama server runs keyless"); keyLabel = t("API Key (optional for Ollama)"); basePlaceholder = OLLAMA_DEFAULT_BASE_URL; + } else if (format === "openrouter") { + basePlaceholder = "https://openrouter.ai/api/v1"; + if (keyHint) keyPlaceholder = t("Set ({hint}); leave empty to keep it", { hint: keyHint }); } else if (format === "bedrock-gateway") { keyLabel = "Bearer token"; basePlaceholder = "https://gateway.example.com/bedrock"; @@ -596,6 +717,11 @@ function ProfileSheet({ onValueChange={(v) => { // The preset is not a wire format: it selects openai and is // remembered only for the placeholder and the hint below. + modelsRequest.current += 1; + setLoadingModels(false); + setModels([]); + setModelsError(""); + if (v === "openrouter" && !model.trim()) setModel("openrouter/auto"); const preset = v === OPENAI_COMPATIBLE_PRESET; setCompatPreset(preset); setFormat(preset ? "openai" : (v as ProfileFormat)); @@ -607,22 +733,45 @@ function ProfileSheet({ Anthropic OpenAI (Chat Completions) + OpenRouter OpenAI (Responses API) Custom OpenAI-compatible {t("Ollama (local, no key needed)")} Bedrock gateway + {t("ChatGPT plan")} + {format === "chatgpt-plan" && ( +
+

{t("Use your ChatGPT plan")}

+

{t("Eligible AI requests use your ChatGPT plan or credits balance. This is separate from any app charges.")}

+ {!localConsole &&

{t("Open the console at {url} to connect an account.").split("{url}").map((part, i) => {i > 0 && http://127.0.0.1:8787}{part})}

} + {accounts.length > 0 && } + {selectedAccount &&

{selectedAccount.connected ? t("Connected (local credentials available)") : t("Signed out — reconnect to use this account.")}

} +
+ + {accountId && } + {selectedAccount?.connected && } + {attempt && } +
+ {signInMessage &&

{signInMessage}

} + {attempt && (retryAvailable ?

{t("Sign-in could not finish. Retry with the existing registration or cancel.")}

:

{t("Finish signing in in the browser window, then return to ARTEX. This page will update automatically.")}

)} + {welcome &&
{t("You’re using your ChatGPT plan. Eligible usage in this app uses your ChatGPT plan. Manage usage in your ChatGPT settings.")}
} +

{t("Using ChatGPT plan")} · {t("Manage usage")}

+

{t("Streaming is required. Per-profile rate limits, output caps, and reasoning controls are not supported.")}

+
+ )} +
-
+
setModel(e.target.value)} /> @@ -640,18 +789,18 @@ function ProfileSheet({ - {models.length > 0 && ( -
+ {loadingModels ?

{t("Loading models…")}

: modelsError ?

{modelsError}

:
-
-
+
} + {!loadingModels && !modelsError &&
{filteredModels.length === 0 ? (

{t("No model matches “{query}”", { query: modelQuery.trim() })} @@ -682,14 +831,14 @@ function ProfileSheet({ )) )} -

+
} +

{t("You can also enter a model ID manually.")}

- )}
-
+ {format !== "chatgpt-plan" &&
+ } + {format === "bedrock-gateway" && (
@@ -768,7 +919,7 @@ function ProfileSheet({

-
+ {format !== "chatgpt-plan" &&
@@ -788,14 +939,16 @@ function ProfileSheet({ />
+ } +
- setRps(e.target.value)} /> + setRps(e.target.value)} />
- setRpm(e.target.value)} /> + setRpm(e.target.value)} />
@@ -882,7 +1035,7 @@ function ProfileSheet({ )}

- +
@@ -903,7 +1056,8 @@ function ProfileSheet({ type="number" min={0} className="w-28 shrink-0" - value={maxTokens} + disabled={format === "chatgpt-plan"} + value={format === "chatgpt-plan" ? "0" : maxTokens} onChange={(e) => setMaxTokens(e.target.value)} placeholder="0" /> @@ -942,7 +1096,7 @@ function ProfileSheet({ )}

- @@ -964,7 +1118,7 @@ function ProfileSheet({ )}

- @@ -979,11 +1133,13 @@ function ProfileSheet({
+ {format === "chatgpt-plan" &&

{t("Save a ChatGPT plan profile before testing. The test uses the saved profile, including its account and model.")}

} +
- diff --git a/web/src/components/chatgpt-usage-error.tsx b/web/src/components/chatgpt-usage-error.tsx new file mode 100644 index 000000000..893194973 --- /dev/null +++ b/web/src/components/chatgpt-usage-error.tsx @@ -0,0 +1,18 @@ +import { t } from "@/i18n"; + +export const CHATGPT_USAGE_URL = "https://chatgpt.com/#settings/usage"; +export function chatGPTUsageError(value?: string | null): "limit" | "unavailable" | null { + if (value?.includes("subscription_sharing_usage_limit_exceeded")) return "limit"; + if (value?.includes("subscription_sharing_usage_unavailable")) return "unavailable"; + return null; +} + +export function ChatGPTUsageError({ value }: { value?: string | null }) { + const kind = chatGPTUsageError(value); + if (!kind) return null; + return
+

{kind === "limit" ? t("ChatGPT usage limit reached") : t("ChatGPT usage is temporarily unavailable")}

+

{kind === "limit" ? t("Review your ChatGPT plan or this app’s limit in ChatGPT settings.") : t("ChatGPT could not check usage. Try again later; your connection is preserved.")}

+ {t("Manage usage")} +
; +} diff --git a/web/src/components/transcript.tsx b/web/src/components/transcript.tsx index 360546697..9d05bf78f 100644 --- a/web/src/components/transcript.tsx +++ b/web/src/components/transcript.tsx @@ -19,6 +19,7 @@ import { toast } from "sonner"; import { api } from "@/lib/api"; import { intlLocale, t } from "@/i18n"; import { Markdown } from "@/components/markdown"; +import { ChatGPTUsageError } from "@/components/chatgpt-usage-error"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; @@ -557,6 +558,7 @@ function MessageBlock({ {hasThinking && · {t("includes thinking")}} + {isError && } {open && (
           {detail ?? t("Loading…")}
@@ -688,6 +690,7 @@ function AnswerBlock({ step, getDetail }: { step: Activity; getDetail: (seq: num
           
         )}
       
+ {step.is_error && } ); diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json index 45e446118..cc3559536 100644 --- a/web/src/i18n/locales/tr.json +++ b/web/src/i18n/locales/tr.json @@ -2787,5 +2787,47 @@ "The shared browser starts when an agent first uses a browser tool. Start it now to sign in to the target before a task runs.": "Paylaşılan tarayıcı, bir ajan ilk kez bir tarayıcı aracı kullandığında başlar. Bir görev çalışmadan önce hedefte oturum açmak için şimdi başlatın.", "Start browser": "Tarayıcıyı başlat", "Click and type in the view. Agent browser tools are paused until you press Hand back.": "Görünümde tıklayın ve yazın. Geri ver'e basana kadar ajanın tarayıcı araçları duraklatılır.", - "Clicking or typing in the view takes control from the agent.": "Görünümde tıklamak veya yazmak kontrolü ajandan alır." + "Clicking or typing in the view takes control from the agent.": "Görünümde tıklamak veya yazmak kontrolü ajandan alır.", + "ChatGPT account connected": "ChatGPT hesabı bağlandı", + "ChatGPT sign-in failed. Please try again.": "ChatGPT ile oturum açılamadı. Lütfen tekrar deneyin.", + "Allow pop-ups to continue with ChatGPT.": "ChatGPT ile devam etmek için açılır pencerelere izin verin.", + "Select a connected ChatGPT account": "Bağlı bir ChatGPT hesabı seçin", + "Signed out locally. Remote revocation was not confirmed; disconnect the app in ChatGPT settings.": "Yerel oturum kapatıldı. Uzaktan yetki iptali doğrulanamadı; ChatGPT ayarlarından uygulamanın bağlantısını kesin.", + "Signed out of ChatGPT": "ChatGPT oturumu kapatıldı", + "ChatGPT plan": "ChatGPT planı", + "Use your ChatGPT plan": "ChatGPT planınızı kullanın", + "Eligible AI requests use your ChatGPT plan or credits balance. This is separate from any app charges.": "Uygun yapay zekâ istekleri ChatGPT planınızı veya kredi bakiyenizi kullanır. Bu, uygulamanın ücretlerinden ayrıdır.", + "Open the console at {url} to connect an account.": "Bir hesap bağlamak için konsolu {url} adresinden açın.", + "Select a ChatGPT account": "Bir ChatGPT hesabı seçin", + "Account {id}": "Hesap {id}", + "Signed out": "Oturum kapatıldı", + "Connected (local credentials available)": "Bağlı (yerel kimlik bilgileri kullanılabilir)", + "Signed out — reconnect to use this account.": "Oturum kapatıldı; bu hesabı kullanmak için yeniden bağlanın.", + "Continue with ChatGPT": "ChatGPT ile devam et", + "Reconnect": "Yeniden bağlan", + "Cancel sign-in": "Oturum açmayı iptal et", + "Waiting for sign-in in your browser…": "Tarayıcınızda oturum açmanız bekleniyor…", + "You’re using your ChatGPT plan. Eligible usage in this app uses your ChatGPT plan. Manage usage in your ChatGPT settings.": "ChatGPT planınızı kullanıyorsunuz. Bu uygulamadaki uygun kullanım ChatGPT planınızdan karşılanır. Kullanımı ChatGPT ayarlarından yönetin.", + "Got it": "Anladım", + "Using ChatGPT plan": "ChatGPT planı kullanılıyor", + "Manage usage": "Kullanımı yönet", + "Streaming is required. Per-profile rate limits, output caps, and reasoning controls are not supported.": "Akış gereklidir. Profile özel hız sınırları, çıktı sınırları ve akıl yürütme kontrolleri desteklenmez.", + "Signed in, but ChatGPT plan usage is not enabled. Reconnect to grant permission.": "Oturum açıldı ancak ChatGPT planı kullanımı etkin değil. İzin vermek için yeniden bağlanın.", + "Sign-in is being saved. Please wait and try again.": "Oturum açma bilgileri kaydediliyor. Lütfen bekleyip tekrar deneyin.", + "Sign-in could not finish. Retry with the existing registration or cancel.": "Oturum açma tamamlanamadı. Mevcut kayıtla tekrar deneyin veya iptal edin.", + "Retry sign-in": "Oturum açmayı tekrar dene", + "The sign-in attempt expired. Start again.": "Oturum açma girişiminin süresi doldu. Yeniden başlayın.", + "ChatGPT usage limit reached": "ChatGPT kullanım sınırına ulaşıldı", + "ChatGPT usage is temporarily unavailable": "ChatGPT kullanımı geçici olarak kullanılamıyor", + "Review your ChatGPT plan or this app’s limit in ChatGPT settings.": "ChatGPT ayarlarında planınızın veya bu uygulamanın sınırını gözden geçirin.", + "ChatGPT could not check usage. Try again later; your connection is preserved.": "ChatGPT kullanımı kontrol edemedi. Daha sonra tekrar deneyin; bağlantınız korunuyor.", + "Save a ChatGPT plan profile before testing. The test uses the saved profile, including its account and model.": "Test etmeden önce ChatGPT planı profilini kaydedin. Test, kayıtlı profilin hesabını ve modelini kullanır.", + "Loading models…": "Modeller yükleniyor…", + "You can also enter a model ID manually.": "Bir model kimliğini elle de girebilirsiniz.", + "Sign-in is taking longer than expected. Finish in the browser, then return here. You can cancel and start again.": "Giriş beklenenden uzun sürüyor. Tarayıcıda işlemi tamamlayıp buraya dönün. İptal edip yeniden başlayabilirsiniz.", + "The sign-in attempt timed out. Cancel it and start again.": "Giriş denemesi zaman aşımına uğradı. İptal edip yeniden başlayın.", + "Sign-in could not be verified. Start again and complete sign-in in the browser.": "Giriş doğrulanamadı. Yeniden başlayın ve tarayıcıda girişi tamamlayın.", + "Could not check sign-in status. Start again and try connecting.": "Giriş durumu kontrol edilemedi. Yeniden başlayıp bağlanmayı deneyin.", + "Finish signing in in the browser window, then return to ARTEX. This page will update automatically.": "Tarayıcı penceresinde girişi tamamlayıp ARTEX’e dönün. Bu sayfa otomatik olarak güncellenecek.", + "Browse models": "Modellere göz at" } diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.json index b91d890b6..8945db8fe 100644 --- a/web/src/i18n/locales/zh-CN.json +++ b/web/src/i18n/locales/zh-CN.json @@ -2787,5 +2787,47 @@ "The shared browser starts when an agent first uses a browser tool. Start it now to sign in to the target before a task runs.": "共享浏览器会在智能体首次使用浏览器工具时启动。现在启动它,可在任务运行前先登录目标。", "Start browser": "启动浏览器", "Click and type in the view. Agent browser tools are paused until you press Hand back.": "在视图中点击和输入。在您点击“交还”之前,智能体的浏览器工具会暂停。", - "Clicking or typing in the view takes control from the agent.": "在视图中点击或输入会从智能体手中接管控制。" + "Clicking or typing in the view takes control from the agent.": "在视图中点击或输入会从智能体手中接管控制。", + "ChatGPT account connected": "ChatGPT 账号已连接", + "ChatGPT sign-in failed. Please try again.": "ChatGPT 登录失败,请重试。", + "Allow pop-ups to continue with ChatGPT.": "请允许弹出窗口,以便继续使用 ChatGPT。", + "Select a connected ChatGPT account": "请选择已连接的 ChatGPT 账号", + "Signed out locally. Remote revocation was not confirmed; disconnect the app in ChatGPT settings.": "已在本地退出登录。无法确认远程授权已撤销;请在 ChatGPT 设置中断开此应用。", + "Signed out of ChatGPT": "已退出 ChatGPT", + "ChatGPT plan": "ChatGPT 套餐", + "Use your ChatGPT plan": "使用你的 ChatGPT 套餐", + "Eligible AI requests use your ChatGPT plan or credits balance. This is separate from any app charges.": "符合条件的 AI 请求会使用你的 ChatGPT 套餐或点数余额,与应用自身的收费分开计算。", + "Open the console at {url} to connect an account.": "请通过 {url} 打开控制台以连接账号。", + "Select a ChatGPT account": "选择 ChatGPT 账号", + "Account {id}": "账号 {id}", + "Signed out": "已退出登录", + "Connected (local credentials available)": "已连接(本地凭据可用)", + "Signed out — reconnect to use this account.": "已退出登录,请重新连接以使用此账号。", + "Continue with ChatGPT": "使用 ChatGPT 继续", + "Reconnect": "重新连接", + "Cancel sign-in": "取消登录", + "Waiting for sign-in in your browser…": "等待在浏览器中完成登录…", + "You’re using your ChatGPT plan. Eligible usage in this app uses your ChatGPT plan. Manage usage in your ChatGPT settings.": "你正在使用 ChatGPT 套餐。此应用中符合条件的用量会计入你的 ChatGPT 套餐。你可以在 ChatGPT 设置中管理用量。", + "Got it": "知道了", + "Using ChatGPT plan": "正在使用 ChatGPT 套餐", + "Manage usage": "管理用量", + "Streaming is required. Per-profile rate limits, output caps, and reasoning controls are not supported.": "必须使用流式输出。不支持按配置设置速率限制、输出上限或推理控制。", + "Signed in, but ChatGPT plan usage is not enabled. Reconnect to grant permission.": "已登录,但未启用 ChatGPT 套餐用量。请重新连接以授予权限。", + "Sign-in is being saved. Please wait and try again.": "正在保存登录信息,请稍后重试。", + "Sign-in could not finish. Retry with the existing registration or cancel.": "无法完成登录。请使用现有注册信息重试,或取消登录。", + "Retry sign-in": "重试登录", + "The sign-in attempt expired. Start again.": "登录尝试已过期,请重新开始。", + "ChatGPT usage limit reached": "已达到 ChatGPT 用量限制", + "ChatGPT usage is temporarily unavailable": "暂时无法查询 ChatGPT 用量", + "Review your ChatGPT plan or this app’s limit in ChatGPT settings.": "请在 ChatGPT 设置中查看套餐或此应用的用量限制。", + "ChatGPT could not check usage. Try again later; your connection is preserved.": "ChatGPT 无法检查用量,请稍后重试;连接信息已保留。", + "Save a ChatGPT plan profile before testing. The test uses the saved profile, including its account and model.": "请先保存 ChatGPT 套餐配置再测试。测试使用已保存配置中的账号和模型。", + "Loading models…": "正在加载模型…", + "You can also enter a model ID manually.": "您也可以手动输入模型 ID。", + "Sign-in is taking longer than expected. Finish in the browser, then return here. You can cancel and start again.": "登录时间比预期更长。请在浏览器中完成登录,然后返回此处。您也可以取消并重新开始。", + "The sign-in attempt timed out. Cancel it and start again.": "登录尝试已超时。请取消并重新开始。", + "Sign-in could not be verified. Start again and complete sign-in in the browser.": "无法验证登录。请重新开始并在浏览器中完成登录。", + "Could not check sign-in status. Start again and try connecting.": "无法检查登录状态。请重新开始并尝试连接。", + "Finish signing in in the browser window, then return to ARTEX. This page will update automatically.": "请在浏览器窗口中完成登录,然后返回 ARTEX。此页面会自动更新。", + "Browse models": "浏览模型" } diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 527da63fc..a20b66d30 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1209,6 +1209,13 @@ export const api = { custom_headers, max_tokens_field, }), + testStoredLLM: (profile_id: number) => post<{ ok: boolean; error?: string; error_code?: string; latency_ms?: number; model?: string; reply?: string }>("/llm/test", { profile_id }), + chatGPTAccounts: () => get<{ accounts: import("./types").ChatGPTAccount[] }>("/chatgpt/accounts"), + chatGPTConnect: (account_id?: string, retry_attempt_id?: string) => post<{ authorization_url: string; attempt_id: string }>("/chatgpt/connect", { account_id, retry_attempt_id }), + chatGPTClaim: (attempt_id: string) => post<{ status: "pending" | "failed" | "complete" | "plan_disabled" | "retry_available" | "callback_rejected"; account?: import("./types").ChatGPTAccount }>("/chatgpt/claim", { attempt_id }), + chatGPTCancel: (attempt_id: string) => post("/chatgpt/cancel", { attempt_id }), + chatGPTSignOut: (account_id: string) => post<{ status: string; remote_revocation_confirmed: boolean }>("/chatgpt/signout", { account_id }), + chatGPTModels: (account_id: string) => get<{ models: { slug: string; display_name: string }[] }>(`/chatgpt/models?account_id=${encodeURIComponent(account_id)}`), llmProfiles: () => get<{ profiles: LLMProfile[] }>("/llm/profiles").then((r) => arr(r.profiles)), saveLLMProfile: (p: { id?: number; // omit/0 = create; set = update that profile @@ -1217,6 +1224,7 @@ export const api = { model: string; base_url?: string; proxy?: string; + chatgpt_account_id?: number; api_key?: string; // blank on update keeps the existing key rate_per_second?: number; rate_per_minute?: number; diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 10f717694..09f261bb7 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -1162,14 +1162,17 @@ export interface NotificationDelivery { } // ---- LLM config ---- +export interface ChatGPTAccount { id: string; label: string; email?: string; version: number; connected: boolean } + export interface LLMProfile { id: string; name: string; - format: "openai" | "anthropic" | "openai-responses" | "ollama" | "bedrock-gateway"; + format: "openai" | "anthropic" | "openai-responses" | "ollama" | "bedrock-gateway" | "chatgpt-plan" | "openrouter"; base_url?: string; proxy?: string; model: string; api_key_hint?: string; + chatgpt_account_id?: string; rate_per_second: number; rate_per_minute: number; context_window_k?: number;