Files
ai/controllers/zap_chat-graph-crud.go
zeekay e71dfbc4f3 SuperAdmin is the host boundary's verdict, never the org a token names
util.IsSuperAdmin compared the resolved user's owner to "admin", a
second predicate beside the one the host boundary decides, and the two
disagreed. An admin-org application (no orgs, owner claim admin), an
admin-org person's sk- key, and an org spelled "admin " (the parse
trimmed orgs[0]) were each SuperAdmin here and refused by the boundary.

The host now states the verdict: object.SetSuper, which hanzo-inc/cloud
fills with principal.Super, the X-User-IsAdmin its boundary deletes from
every request and re-mints from authz.Claims.Sudo. Every HTTP seam that
turns a token into a principal goes through object.Verify, which stamps
it on iam.User.Sudo (never decoded); IsSuperAdmin and ScopeOwner read
that and compare no org. util.AdminOrg is gone; the rows that are the
platform's own are named by authz.AdminOrg.

With no host there is no SuperAdmin, and a ZAP door is not the host:
target deletes X-User-IsAdmin from a ZAP-built request, and zapPrincipal
carries a verdict only when the HTTP bridge vouched for the request it
was handed. A key is never the SuperAdmin, as at the host.
2026-10-18 22:21:43 -07:00

1042 lines
35 KiB
Go

// Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Native ZAP handlers for the chat/message/graph CRUD route group (strangler
// migration of chat.go / message.go / graph.go / graph_chat.go). These
// re-implement the controller logic against object/ + iam directly — never
// wrapping the controller — mirroring controllers/zap_native.go:zapChatHandler
// and the first-migrated provider group (zap_providers-admin.go).
//
// Scope: this group is the CRUD surface only. The streaming answer-generation
// routes /v1/get-message-answer and /v1/get-answer live in message_answer.go
// (SSE over an http.ResponseWriter + session/store-scoped policy) and are a
// SEPARATE group; they are deliberately NOT migrated here.
//
// Auth parity: the native ZAP path never runs routers/authz_filter.go, so this
// file re-enforces that filter's decision verbatim in zapChatGraphAuthz for each
// route (preview-mode read bypass, the benign-read exempt list, and the org-admin
// gate for the non-exempt write routes), then each handler re-runs its OWN
// in-controller check (ownership via zapIsCurrentUser, store isolation via
// zapEnforceStoreIsolation, admin-only reads). The principal is resolved from the
// Bearer credential through the ONE shared seam (zapPrincipalUser: verified JWT
// via object.ParseAndValidateJWT / sk- IAM key via getUserByAccessKey) — identity
// is never taken from the body; org scope is always the resolved user's Owner.
//
// Tenancy parity: a chat-plane row's Owner and Organization are the ledger the
// answer's debit lands in and the org the usage plane books it to, so this plane
// stamps them from the server side exactly as chat.go / message.go do — Owner from
// the chatOwner constant, Organization from the resolved principal — and re-derives
// the owner half of any caller-supplied id. A write that names a STORED row is
// authorized against THAT row's user, never against the user the request carries.
//
// Envelope parity: success/error use the SAME {status,data,data2,msg} Response the
// ResponseOk/ResponseError emit (the console frontend contract), via the
// shared zapProviderOk / zapProviderError builders.
//
// Registration: this file OWNS its wiring. init() self-registers each route into
// the package-level registries (registerCloud / registerGatewayPath) defined in
// zap_registry.go; it never edits a shared registration file. handleCloudService
// and the gateway dispatch consult those registries; the same routes stay live on
// routers.App, which also backs the gateway fallback.
package controllers
import (
"context"
"encoding/json"
"slices"
iam "github.com/hanzoai/ai/internal/iam"
"github.com/luxfi/zap"
"github.com/hanzoai/ai/conf"
"github.com/hanzoai/ai/object"
"github.com/hanzoai/ai/util"
)
func init() {
registerZapChatGraphCrud()
}
// registerZapChatGraphCrud wires the group's native cloud methods (MsgType 100)
// and gateway path prefixes (MsgType 200) into the shared registries. Called by
// name so InitZapHandlers stays the single Node.Handle bootstrap without a
// per-group switch arm.
func registerZapChatGraphCrud() {
// Cloud (MsgType 100) — native method names.
registerCloud("chats.global.list", zapGetGlobalChatsHandler)
registerCloud("chats.list", zapGetChatsHandler)
registerCloud("chats.get", zapGetChatHandler)
registerCloud("chats.update", zapUpdateChatHandler)
registerCloud("chats.add", zapAddChatHandler)
registerCloud("chats.delete", zapDeleteChatHandler)
registerCloud("messages.list", zapGetMessagesHandler)
registerCloud("messages.get", zapGetMessageHandler)
registerCloud("messages.update", zapUpdateMessageHandler)
registerCloud("messages.add", zapAddMessageHandler)
registerCloud("messages.delete", zapDeleteMessageHandler)
registerCloud("messages.welcome.delete", zapDeleteWelcomeMessageHandler)
registerCloud("graphs.global.list", zapGetGlobalGraphsHandler)
registerCloud("graphs.list", zapGetGraphsHandler)
registerCloud("graphs.get", zapGetGraphHandler)
registerCloud("graphs.update", zapUpdateGraphHandler)
registerCloud("graphs.add", zapAddGraphHandler)
registerCloud("graphs.delete", zapDeleteGraphHandler)
// Gateway (MsgType 200) — /v1 path prefixes routing to the SAME handlers.
// dispatchGateway resolves by LONGEST matching prefix, so the pairs that share
// a prefix (/v1/get-chat ⊂ /v1/get-chats, /v1/get-graph ⊂ /v1/get-graphs,
// /v1/get-message ⊂ /v1/get-messages) route correctly. /v1/get-message-answer
// (the streaming answer group's route) is longer than /v1/get-message and is
// registered by THAT group, so once it migrates its longer prefix wins here.
}
// ── Shared gates (parity with routers/authz_filter.go + base controller) ─────
// zapChatGraphAuthz re-enforces the the router authz filter's decision for this
// group's routes (none of which are super-admin or present-credential endpoints):
// a preview-mode read is open, a benign-read exempt route is open, and every other
// write route requires an ORG admin (util.IsAdmin) — a non-admin is denied 403,
// exactly like permissionFilter's denyForbidden tail. name is the controllerName
// (the router path minus "/v1/"). Returns a denial message to return as-is, or nil
// to proceed to the handler's own in-controller check.
func zapChatGraphAuthz(name string, user *iam.User) *zap.Message {
isGet := len(name) >= 4 && name[:4] == "get-"
isWrite := hasAnyPrefix(name, "update-", "add-", "delete-")
// Preview-mode default-open for reads (matches !disablePreviewMode && isGet).
if !conf.DisablePreviewMode() && isGet {
return nil
}
// A name that is neither a read nor a write is untouched by the filter.
if !isGet && !isWrite {
return nil
}
if _, ok := zapChatGraphExempt[name]; ok {
return nil
}
if !util.IsAdmin(user) {
msg, _ := zapError(403, "this operation requires admin privilege")
return msg
}
return nil
}
// zapChatGraphExempt mirrors the benign-read/self-scoped exempt set in
// permissionFilter for this group's routes: these skip the coarse org-admin gate
// because each handler performs its own ownership / signed-in check.
var zapChatGraphExempt = map[string]struct{}{
"get-chats": {}, "get-chat": {},
"update-chat": {}, "add-chat": {}, "delete-chat": {},
"get-messages": {}, "get-message": {},
"update-message": {}, "add-message": {}, "delete-welcome-message": {},
}
func hasAnyPrefix(s string, prefixes ...string) bool {
for _, p := range prefixes {
if len(s) >= len(p) && s[:len(p)] == p {
return true
}
}
return false
}
// zapIsCurrentUser mirrors ApiController.IsCurrentUser: it answers for NAMES on both
// sides, then lets an org admin act on any user's row and a non-admin only on its own
// (username == input). Returns a 403 denial to return as-is, or nil to proceed. The
// anonymous (u-<hash>) fallback of the router path is unavailable natively (no client
// IP / user-agent), so a native caller is always its verified Bearer principal.
//
// The name test is the load-bearing half here. This plane's writes are on the the controller layer
// filter's benign-read exempt list, so an UNAUTHENTICATED caller reaches them:
// zapPrincipal("") is nil, which left username "" — and "" != "" is false, so the
// guard returned "allowed" and the caller acted as the empty user. A chat-plane row
// with no user bills `admin/`, the admin ORG's own pool wallet.
func zapIsCurrentUser(user *iam.User, input string) *zap.Message {
username := ""
if user != nil {
username = user.Name
}
if !isName(username) || !isName(input) {
msg, _ := zapError(403, "Unauthorized operation")
return msg
}
if !util.IsAdmin(user) && username != input {
msg, _ := zapError(403, "Unauthorized operation")
return msg
}
return nil
}
// zapEnforceStoreIsolation mirrors ApiController.EnforceStoreIsolation: a user
// bound to a store via Homepage is forced to that store for an unscoped/"All"
// request and denied for a different one. Returns the enforced store name and nil,
// or ("", denial).
// zapEnforceStoreIsolation applies the same rule and refuses on the ZAP surface.
func zapEnforceStoreIsolation(user *iam.User, requested string) (string, *zap.Message) {
store, ok := bound(user, requested)
if !ok {
msg, _ := zapError(200, notYourStore)
return "", msg
}
return store, nil
}
// paginationOffset computes the DB offset the pagination.SetPaginator would,
// from the 1-based page and page size carried on the native body (the native
// contract has no URL query or response headers). Guards a non-positive page.
func paginationOffset(page, limit int) int {
offset := (page - 1) * limit
if offset < 0 {
return 0
}
return offset
}
// ── chat.go parity ───────────────────────────────────────────────────────────
// zapListChatsRequest carries the list/pagination + filter params the GET
// handlers read from the URL query.
type zapListChatsRequest struct {
PageSize string `json:"pageSize"`
Page string `json:"p"`
Field string `json:"field"`
Value string `json:"value"`
SortField string `json:"sortField"`
SortOrder string `json:"sortOrder"`
Store string `json:"store"`
User string `json:"user"`
SelectedUser string `json:"selectedUser"`
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
}
// zapGetGlobalChatsHandler mirrors ApiController.GetGlobalChats.
func zapGetGlobalChatsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-global-chats", user); deny != nil {
return deny, nil
}
var req zapListChatsRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
// Same answer as the HTTP twin: the tenant is the Organization, and the
// reserved org reads every one of them. Which organization is a question about
// a caller, so there has to be one — the filter above lets an unnamed reader
// through while preview is on.
if user == nil {
return zapError(401, "auth:Please sign in first")
}
org := reach(user)
if req.PageSize == "" || req.Page == "" {
chats, err := object.GetPaginationChats("", org, -1, -1, req.Field, req.Value, req.SortField, req.SortOrder, req.Store)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(chats)
}
limit := util.ParseInt(req.PageSize)
count, err := object.GetChatCount("", org, req.Field, req.Value, req.Store)
if err != nil {
return zapError(200, err.Error())
}
offset := paginationOffset(util.ParseInt(req.Page), limit)
chats, err := object.GetPaginationChats("", org, offset, limit, req.Field, req.Value, req.SortField, req.SortOrder, req.Store)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(chats, count)
}
// zapGetChatsHandler mirrors ApiController.GetChats (admin sees all users; a
// non-admin is scoped to its own user, store isolation enforced from Homepage,
// optional time-range filter).
func zapGetChatsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-chats", user); deny != nil {
return deny, nil
}
var req zapListChatsRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
who := whose(user, req.User, req.SelectedUser, req.Field, req.Value)
storeName, deny := zapEnforceStoreIsolation(user, req.Store)
if deny != nil {
return deny, nil
}
chats, err := object.GetChats(chatOwner, reach(user), storeName, who)
if err != nil {
return zapError(200, err.Error())
}
if req.StartTime != "" || req.EndTime != "" {
chats = object.FilterChatsByTimeRange(chats, req.StartTime, req.EndTime)
}
return zapOk(chats)
}
// zapIDRequest carries a single id (URL query in the GET handlers).
type zapIDRequest struct {
ID string `json:"id"`
}
// zapGetChatHandler mirrors ApiController.GetChat (ownership check for a non-admin
// outside preview mode).
func zapGetChatHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-chat", user); deny != nil {
return deny, nil
}
var req zapIDRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
chat, err := object.GetChat(req.ID)
if err != nil {
return zapError(200, err.Error())
}
// Which organization the chat belongs to. zapIsCurrentUser is not asked of an
// admin, so this is what keeps an admin inside their own.
if chat == nil || !reaches(user, chat.Organization) {
return zapError(200, "Chat not found")
}
if !util.IsAdmin(user) && !conf.IsPreviewMode() {
username := ""
if user != nil {
username = user.Name
}
if username != chat.User {
return zapError(403, "Unauthorized operation")
}
}
return zapOk(chat)
}
// zapUpdateChatRequest carries the id (URL query in HTTP) plus the chat payload.
type zapUpdateChatRequest struct {
ID string `json:"id"`
Chat object.Chat `json:"chat"`
}
// zapUpdateChatHandler mirrors ApiController.UpdateChat (self-or-admin; in demo
// mode only ModelProvider is mutable).
func zapUpdateChatHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("update-chat", user); deny != nil {
return deny, nil
}
var req zapUpdateChatRequest
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
chat := req.Chat
if deny := zapIsCurrentUser(user, chat.User); deny != nil {
return deny, nil
}
_, name, err := util.GetOwnerAndNameFromIdWithError(req.ID)
if err != nil {
return zapError(200, err.Error())
}
id := util.GetIdFromOwnerAndName(chatOwner, name)
originalChat, err := object.GetChat(id)
if err != nil {
return zapError(200, err.Error())
}
// Which organization the chat belongs to. zapIsCurrentUser is not asked of an
// admin, so this is what keeps an admin inside their own.
if originalChat == nil || !reaches(user, originalChat.Organization) {
return zapError(200, "The chat: "+id+" is not found")
}
if deny := zapIsCurrentUser(user, originalChat.User); deny != nil {
return deny, nil
}
chat.Organization = originalChat.Organization
if conf.IsDemoMode() {
originalChat.ModelProvider = chat.ModelProvider
chat = *originalChat
}
success, err := object.UpdateChat(id, &chat)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapAddChatHandler mirrors ApiController.AddChat: self-or-admin, timestamps + IP/
// user-agent descriptors stamped from the (optional) body-supplied ClientIp/
// UserAgent, default store filled when absent.
func zapAddChatHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("add-chat", user); deny != nil {
return deny, nil
}
var chat object.Chat
if err := json.Unmarshal(body, &chat); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
if deny := zapIsCurrentUser(user, chat.User); deny != nil {
return deny, nil
}
chat.Owner = chatOwner
chat.Organization = user.Owner
currentTime := util.GetCurrentTime()
chat.CreatedTime = currentTime
chat.UpdatedTime = currentTime
chat.ClientIpDesc = util.GetDescFromIP(chat.ClientIp)
chat.UserAgentDesc = util.GetDescFromUserAgent(chat.UserAgent)
if chat.Store == "" {
store, err := object.GetDefaultStore("admin")
if err != nil {
return zapError(200, err.Error())
}
if store == nil {
return zapError(200, "The default store is not found")
}
chat.Store = store.Name
}
success, err := object.AddChat(&chat)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapDeleteChatHandler mirrors ApiController.DeleteChat (deletes the chat and its
// messages).
func zapDeleteChatHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("delete-chat", user); deny != nil {
return deny, nil
}
var chat object.Chat
if err := json.Unmarshal(body, &chat); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
if deny := zapIsCurrentUser(user, chat.User); deny != nil {
return deny, nil
}
chat.Owner = chatOwner
storedChat, err := object.GetChat(chat.GetId())
if err != nil {
return zapError(200, err.Error())
}
// Which organization the chat belongs to. zapIsCurrentUser is not asked of an
// admin, so this is what keeps an admin inside their own.
if storedChat == nil || !reaches(user, storedChat.Organization) {
return zapError(200, "The chat: "+chat.GetId()+" is not found")
}
if deny := zapIsCurrentUser(user, storedChat.User); deny != nil {
return deny, nil
}
success, err := object.DeleteChat(&chat)
if err != nil {
return zapError(200, err.Error())
}
message := object.Message{Owner: chat.Owner, Chat: chat.Name}
success, err = object.DeleteMessagesByChat(&message)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// ── message.go parity ────────────────────────────────────────────────────────
// zapListMessagesRequest carries the message list/pagination + filter params.
type zapListMessagesRequest struct {
PageSize string `json:"pageSize"`
Page string `json:"p"`
Field string `json:"field"`
Value string `json:"value"`
SortField string `json:"sortField"`
SortOrder string `json:"sortOrder"`
Store string `json:"store"`
User string `json:"user"`
Chat string `json:"chat"`
SelectedUser string `json:"selectedUser"`
}
// zapGetMessagesHandler mirrors ApiController.GetMessages (signed-in; admin sees
// all users, non-admin scoped to itself; a chat filter returns that chat's turns).
func zapGetMessagesHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if user == nil {
return zapError(401, "Please sign in first")
}
if deny := zapChatGraphAuthz("get-messages", user); deny != nil {
return deny, nil
}
var req zapListMessagesRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
who := whose(user, req.User, req.SelectedUser, "", "")
if req.Chat == "" {
messages, err := object.GetMessages(chatOwner, reach(user), who, "")
if err != nil {
return zapError(200, err.Error())
}
return zapOk(messages)
}
messages, err := object.GetChatMessages(req.Chat, reach(user))
if err != nil {
return zapError(200, err.Error())
}
return zapOk(messages)
}
// zapGetMessageHandler mirrors ApiController.GetMessage (ownership check for a
// non-admin outside preview mode).
func zapGetMessageHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-message", user); deny != nil {
return deny, nil
}
var req zapIDRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
message, err := object.GetMessage(req.ID)
if err != nil {
return zapError(200, err.Error())
}
if message == nil {
return zapError(200, "Message not found")
}
if !util.IsAdmin(user) && !conf.IsPreviewMode() {
username := ""
if user != nil {
username = user.Name
}
if username != message.User {
return zapError(403, "Unauthorized operation")
}
}
return zapOk(message)
}
// zapUpdateMessageRequest carries the id + isHitOnly (URL query in HTTP) plus the
// message payload.
type zapUpdateMessageRequest struct {
ID string `json:"id"`
IsHitOnly bool `json:"isHitOnly"`
Message object.Message `json:"message"`
}
// zapUpdateMessageHandler mirrors ApiController.UpdateMessage (self-or-admin;
// sends the notify email when requested, then persists).
func zapUpdateMessageHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("update-message", user); deny != nil {
return deny, nil
}
var req zapUpdateMessageRequest
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
message := req.Message
if deny := zapIsCurrentUser(user, message.User); deny != nil {
return deny, nil
}
_, name, err := util.GetOwnerAndNameFromIdWithError(req.ID)
if err != nil {
return zapError(200, err.Error())
}
id := util.GetIdFromOwnerAndName(chatOwner, name)
message.Owner = chatOwner
storedMessage, err := object.GetMessage(id)
if err != nil {
return zapError(200, err.Error())
}
if storedMessage == nil {
return zapError(200, "The message: "+id+" is not found")
}
if deny := zapIsCurrentUser(user, storedMessage.User); deny != nil {
return deny, nil
}
message.Organization = storedMessage.Organization
if message.NeedNotify {
if err := message.SendEmail("en", user.Owner); err != nil {
return zapError(200, err.Error())
}
message.NeedNotify = false
}
success, err := object.UpdateMessage(id, &message, req.IsHitOnly)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapAddMessageHandler mirrors ApiController.AddMessage: it edits-in-place (drops
// later turns), handles regeneration (drops the trailing AI+user turns), resolves
// or creates the parent chat, refines embedded files, enforces the store's
// forbidden-word list, persists the message, and — for an AI chat — seeds the
// empty AI answer placeholder the streaming answer route later fills. Returns the
// parent chat, exactly like the controller handler. lang is "en" and origin is empty
// natively (no http host) — file-URL refinement only rewrites base64-embedded
// images, which the native CRUD path does not carry.
func zapAddMessageHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("add-message", user); deny != nil {
return deny, nil
}
var message object.Message
if err := json.Unmarshal(body, &message); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
if deny := zapIsCurrentUser(user, message.User); deny != nil {
return deny, nil
}
message.Owner = chatOwner
id := util.GetIdFromOwnerAndName(message.Owner, message.Name)
originMessage, err := object.GetMessage(id)
if err != nil {
return zapError(200, err.Error())
}
// If originMessage is non-nil this is an edit — drop all later messages. It
// rewrites a STORED turn, so that row's own user authorizes it.
if originMessage != nil {
if deny := zapIsCurrentUser(user, originMessage.User); deny != nil {
return deny, nil
}
if err = object.DeleteAllLaterMessages(id); err != nil {
return zapError(200, err.Error())
}
}
addMessageAfterSuccess := true
if message.IsRegenerated {
messages, err := object.GetChatMessages(message.Chat, message.Organization)
if err != nil {
return zapError(200, err.Error())
}
var lastAIMessage *object.Message
var lastUserMessage *object.Message
for _, message := range slices.Backward(messages) {
if message.Author == "AI" && message.ErrorText != "" {
lastAIMessage = message
break
}
}
if lastAIMessage == nil {
for _, message := range slices.Backward(messages) {
if message.Author == "AI" {
lastAIMessage = message
break
}
}
}
for _, message := range slices.Backward(messages) {
if message.Author != "AI" {
lastUserMessage = message
break
}
}
if lastAIMessage != nil {
if lastAIMessage.ReplyTo == "Welcome" {
message.Author = "AI"
message.ReplyTo = "Welcome"
addMessageAfterSuccess = false
}
if _, err = object.DeleteMessage(lastAIMessage); err != nil {
return zapError(200, err.Error())
}
}
if lastUserMessage != nil {
if _, err = object.DeleteMessage(lastUserMessage); err != nil {
return zapError(200, err.Error())
}
}
}
var chat *object.Chat
if message.Chat == "" {
chat, err = zapAddInitialChat(user.Owner, message.User, message.Store)
if err != nil {
return zapError(200, err.Error())
}
message.Chat = chat.Name
} else {
chatId := util.GetId(message.Owner, message.Chat)
chat, err = object.GetChat(chatId)
if err != nil {
return zapError(200, err.Error())
}
if chat == nil {
return zapError(200, "chat:The chat: "+chatId+" is not found")
}
}
// A turn's org is its CHAT's org — the row the usage plane reads.
message.Organization = chat.Organization
if err = object.RefineMessageFiles(&message, "", "en"); err != nil {
return zapError(200, err.Error())
}
message.CreatedTime = util.GetCurrentTimeWithMilli()
if message.Text == "" {
return zapError(200, "The question should not be empty")
}
storeId := util.GetId(message.Owner, message.Store)
store, err := object.GetStore(storeId)
if err != nil {
return zapError(200, err.Error())
}
if store != nil {
contains, forbiddenWord := store.ContainsForbiddenWords(message.Text)
if contains {
return zapError(200, "Your message contains a forbidden word: \""+forbiddenWord+"\"")
}
}
success, err := object.AddMessage(&message)
if err != nil {
return zapError(200, err.Error())
}
if success && addMessageAfterSuccess {
chatId := util.GetId(message.Owner, message.Chat)
chat, err = object.GetChat(chatId)
if err != nil {
return zapError(200, err.Error())
}
if chat != nil && chat.Type == "AI" {
modelProvider := chat.ModelProvider
if modelProvider == "" {
storeId := util.GetId(chat.Owner, chat.Store)
store, storeErr := object.GetStore(storeId)
if storeErr == nil && store != nil {
modelProvider = store.ModelProvider
}
}
answerMessage := &object.Message{
Owner: message.Owner,
Name: "message_" + util.GetRandomName(),
CreatedTime: util.GetCurrentTimeEx(message.CreatedTime),
Organization: message.Organization,
Store: chat.Store,
User: message.User,
Chat: message.Chat,
ReplyTo: message.Name,
Author: "AI",
Text: "",
FileName: message.FileName,
VectorScores: []object.VectorScore{},
ModelProvider: modelProvider,
}
if _, err = object.AddMessage(answerMessage); err != nil {
return zapError(200, err.Error())
}
}
}
return zapOk(chat)
}
// zapAddMessageHandler reuses the shared zapAddInitialChat twin defined in
// zap_account-auth.go (identical store-resolve + AI-chat seed) — the ONE native
// initial-chat seeder, not a second copy.
// zapDeleteMessageHandler mirrors ApiController.DeleteMessage. This route is NOT
// on the filter's exempt list, so the outer gate requires an org admin.
func zapDeleteMessageHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("delete-message", user); deny != nil {
return deny, nil
}
var message object.Message
if err := json.Unmarshal(body, &message); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
if deny := zapIsCurrentUser(user, message.User); deny != nil {
return deny, nil
}
message.Owner = chatOwner
// Owner is the namespace every message shares, so it says nothing about whose
// message this is — Organization does, and only the STORED row carries it. The
// body carries whatever it likes, including the user checked above.
stored, err := object.GetMessage(message.GetId())
if err != nil {
return zapError(200, err.Error())
}
if stored == nil || !reaches(user, stored.Organization) {
return zapError(200, "The message does not exist")
}
success, err := object.DeleteMessage(&message)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapDeleteWelcomeMessageHandler mirrors ApiController.DeleteWelcomeMessage: only
// the message's own (signed-in) user may delete it, and only if it is the AI
// "Welcome" turn. The the router anonymous (u-<hash>) branch is unavailable natively
// (no client IP / user-agent) — a native caller is its verified Bearer principal.
func zapDeleteWelcomeMessageHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("delete-welcome-message", user); deny != nil {
return deny, nil
}
var reqMessage object.Message
if err := json.Unmarshal(body, &reqMessage); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
id := util.GetIdFromOwnerAndName(chatOwner, reqMessage.Name)
message, err := object.GetMessage(id)
if err != nil {
return zapError(200, err.Error())
}
if message == nil {
return zapError(200, "Message not found")
}
username := ""
if user != nil {
username = user.Name
}
if username == "" || username != message.User {
return zapError(200, "No permission")
}
if message.Author != "AI" || message.ReplyTo != "Welcome" {
return zapError(200, "No permission")
}
success, err := object.DeleteMessage(message)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// ── graph.go / graph_chat.go parity ──────────────────────────────────────────
// zapListGraphsRequest carries the graph list/pagination + filter params.
type zapListGraphsRequest struct {
PageSize string `json:"pageSize"`
Page string `json:"p"`
Field string `json:"field"`
Value string `json:"value"`
SortField string `json:"sortField"`
SortOrder string `json:"sortOrder"`
Owner string `json:"owner"`
}
// zapGetGlobalGraphsHandler mirrors ApiController.GetGlobalGraphs.
func zapGetGlobalGraphsHandler(ctx context.Context, auth string, _ []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-global-graphs", user); deny != nil {
return deny, nil
}
graphs, err := object.GetGlobalGraphs()
if err != nil {
return zapError(200, err.Error())
}
return zapOk(object.GetMaskedGraphs(graphs, true))
}
// zapGetGraphsHandler mirrors ApiController.GetGraphs: signed-in, owner resolved
// from the principal (a member of the admin org may target a specific ?owner).
func zapGetGraphsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-graphs", user); deny != nil {
return deny, nil
}
if user == nil {
return zapError(401, "Please sign in first")
}
var req zapListGraphsRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
owner := util.ScopeOwner(user, req.Owner)
if req.PageSize == "" || req.Page == "" {
graphs, err := object.GetGraphs(owner)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(object.GetMaskedGraphs(graphs, true))
}
limit := util.ParseInt(req.PageSize)
count, err := object.GetGraphCount(owner, req.Field, req.Value)
if err != nil {
return zapError(200, err.Error())
}
offset := paginationOffset(util.ParseInt(req.Page), limit)
graphs, err := object.GetPaginationGraphs(owner, offset, limit, req.Field, req.Value, req.SortField, req.SortOrder)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(graphs, count)
}
// zapGetGraphHandler mirrors ApiController.GetGraph, including the lazy word-cloud
// generation for an empty "Chats"-category graph (generateChatGraphData, which
// touches only object/ — invoked on a zero controller since it ignores its
// receiver, reusing the ONE implementation rather than duplicating it).
func zapGetGraphHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("get-graph", user); deny != nil {
return deny, nil
}
var req zapIDRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
}
if deny := zapReachable(ctx, auth, req.ID, theirOrg); deny != nil {
return deny, nil
}
graph, err := object.GetGraph(req.ID)
if err != nil {
return zapError(200, err.Error())
}
if graph != nil && graph.Category == "Chats" && graph.Text == "" {
if err = new(ApiController).generateChatGraphData(req.ID, graph); err != nil {
return zapError(200, err.Error())
}
}
return zapOk(object.GetMaskedGraph(graph, true))
}
// zapUpdateGraphRequest carries the id (URL query in HTTP) plus the graph payload.
type zapUpdateGraphRequest struct {
ID string `json:"id"`
Graph object.Graph `json:"graph"`
}
// zapUpdateGraphHandler mirrors ApiController.UpdateGraph (org-admin gated).
func zapUpdateGraphHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("update-graph", user); deny != nil {
return deny, nil
}
var req zapUpdateGraphRequest
if err := json.Unmarshal(body, &req); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
// The id names which graph, and it names one of the caller's own.
if deny := zapReachable(ctx, auth, req.ID, theirOrg); deny != nil {
return deny, nil
}
req.Graph.Owner = theirOrg(user)
success, err := object.UpdateGraph(req.ID, &req.Graph)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapAddGraphHandler mirrors ApiController.AddGraph (org-admin gated).
func zapAddGraphHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("add-graph", user); deny != nil {
return deny, nil
}
var graph object.Graph
if err := json.Unmarshal(body, &graph); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
graph.Owner = theirOrg(zapPrincipal(ctx, auth))
success, err := object.AddGraph(&graph)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}
// zapDeleteGraphHandler mirrors ApiController.DeleteGraph (org-admin gated).
func zapDeleteGraphHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user := zapPrincipal(ctx, auth)
if deny := zapChatGraphAuthz("delete-graph", user); deny != nil {
return deny, nil
}
var graph object.Graph
if err := json.Unmarshal(body, &graph); err != nil {
return zapError(400, "invalid request: "+err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
graph.Owner = theirOrg(zapPrincipal(ctx, auth))
success, err := object.DeleteGraph(&graph)
if err != nil {
return zapError(200, err.Error())
}
return zapOk(success)
}