-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathchannel_instances.go
More file actions
292 lines (254 loc) · 10.3 KB
/
Copy pathchannel_instances.go
File metadata and controls
292 lines (254 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package methods
import (
"context"
"encoding/json"
"log/slog"
"github.com/google/uuid"
"github.com/nextlevelbuilder/goclaw/internal/bus"
"github.com/nextlevelbuilder/goclaw/internal/gateway"
"github.com/nextlevelbuilder/goclaw/internal/i18n"
"github.com/nextlevelbuilder/goclaw/internal/store"
"github.com/nextlevelbuilder/goclaw/pkg/protocol"
)
// channelInstanceAllowed mirrors the HTTP allowlist in internal/http/validate.go.
var channelInstanceAllowed = map[string]bool{
"channel_type": true, "credentials": true, "agent_id": true,
"enabled": true, "group_policy": true, "allow_from": true,
"metadata": true, "webhook_secret": true, "config": true,
"display_name": true,
}
// ChannelInstancesMethods handles channel instance CRUD via WebSocket RPC.
// agentStore is held so the create/update handlers can resolve agent_key or
// UUID input via resolveAgentUUIDCached.
type ChannelInstancesMethods struct {
store store.ChannelInstanceStore
agentStore store.AgentStore
msgBus *bus.MessageBus
eventBus bus.EventPublisher
}
// NewChannelInstancesMethods creates a new handler for channel instance management.
func NewChannelInstancesMethods(s store.ChannelInstanceStore, as store.AgentStore, msgBus *bus.MessageBus, eventBus bus.EventPublisher) *ChannelInstancesMethods {
return &ChannelInstancesMethods{store: s, agentStore: as, msgBus: msgBus, eventBus: eventBus}
}
// Register registers all channel instance RPC methods.
func (m *ChannelInstancesMethods) Register(router *gateway.MethodRouter) {
router.Register(protocol.MethodChannelInstancesList, m.handleList)
router.Register(protocol.MethodChannelInstancesGet, m.handleGet)
router.Register(protocol.MethodChannelInstancesCreate, m.handleCreate)
router.Register(protocol.MethodChannelInstancesUpdate, m.handleUpdate)
router.Register(protocol.MethodChannelInstancesDelete, m.handleDelete)
}
func (m *ChannelInstancesMethods) emitCacheInvalidate() {
if m.msgBus == nil {
return
}
m.msgBus.Broadcast(bus.Event{
Name: protocol.EventCacheInvalidate,
Payload: bus.CacheInvalidatePayload{Kind: bus.CacheKindChannelInstances},
})
}
func (m *ChannelInstancesMethods) handleList(ctx context.Context, client *gateway.Client, req *protocol.RequestFrame) {
locale := store.LocaleFromContext(ctx)
instances, err := m.store.ListAll(ctx)
if err != nil {
slog.Error("channels.instances.list", "error", err)
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInternal, i18n.T(locale, i18n.MsgFailedToList, "channel instances")))
return
}
// Mask credentials in response — never expose secrets via WS.
result := make([]map[string]any, 0, len(instances))
for _, inst := range instances {
result = append(result, maskInstance(inst))
}
client.SendResponse(protocol.NewOKResponse(req.ID, map[string]any{
"instances": result,
}))
}
func (m *ChannelInstancesMethods) handleGet(ctx context.Context, client *gateway.Client, req *protocol.RequestFrame) {
locale := store.LocaleFromContext(ctx)
var params struct {
ID string `json:"id"`
}
if req.Params != nil {
json.Unmarshal(req.Params, ¶ms)
}
id, err := uuid.Parse(params.ID)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidID, "instance")))
return
}
inst, err := m.store.Get(ctx, id)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrNotFound, i18n.T(locale, i18n.MsgInstanceNotFound)))
return
}
client.SendResponse(protocol.NewOKResponse(req.ID, maskInstance(*inst)))
}
func (m *ChannelInstancesMethods) handleCreate(ctx context.Context, client *gateway.Client, req *protocol.RequestFrame) {
locale := store.LocaleFromContext(ctx)
var params struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
ChannelType string `json:"channel_type"`
AgentID string `json:"agent_id"`
Credentials json.RawMessage `json:"credentials"`
Config json.RawMessage `json:"config"`
Enabled *bool `json:"enabled"`
}
if req.Params != nil {
json.Unmarshal(req.Params, ¶ms)
}
if params.Name == "" || params.ChannelType == "" || params.AgentID == "" {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgRequired, "name, channel_type, and agent_id")))
return
}
if !isValidChannelType(params.ChannelType) {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidChannelType)))
return
}
// Accept both agent_key and UUID via resolveAgentUUIDCached. Router is nil
// here because channel_instances methods are not wired to the router —
// falls back to a pure DB lookup, acceptable given create is a rare op.
agentID, err := resolveAgentUUIDCached(ctx, nil, m.agentStore, params.AgentID)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidID, "agent_id")))
return
}
enabled := true
if params.Enabled != nil {
enabled = *params.Enabled
}
inst := &store.ChannelInstanceData{
Name: params.Name,
DisplayName: params.DisplayName,
ChannelType: params.ChannelType,
AgentID: agentID,
Credentials: params.Credentials,
Config: params.Config,
Enabled: enabled,
}
if err := m.store.Create(ctx, inst); err != nil {
slog.Error("channels.instances.create", "error", err)
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInternal, i18n.T(locale, i18n.MsgFailedToCreate, "instance", err.Error())))
return
}
m.emitCacheInvalidate()
emitAudit(m.eventBus, client, "channel_instance.created", "channel_instance", inst.ID.String())
client.SendResponse(protocol.NewOKResponse(req.ID, maskInstance(*inst)))
}
func (m *ChannelInstancesMethods) handleUpdate(ctx context.Context, client *gateway.Client, req *protocol.RequestFrame) {
locale := store.LocaleFromContext(ctx)
var params struct {
ID string `json:"id"`
Updates json.RawMessage `json:"updates"`
}
if req.Params != nil {
json.Unmarshal(req.Params, ¶ms)
}
id, err := uuid.Parse(params.ID)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidID, "instance")))
return
}
var raw map[string]any
if err := json.Unmarshal(params.Updates, &raw); err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidUpdates)))
return
}
// Allowlist: only permit known channel instance columns (matches HTTP handler).
updates := make(map[string]any, len(raw))
for k, v := range raw {
if channelInstanceAllowed[k] {
updates[k] = v
} else {
slog.Warn("security.filtered_unknown_field", "field", k, "handler", "channels.instances.update")
}
}
if err := m.store.Update(ctx, id, updates); err != nil {
slog.Error("channels.instances.update", "error", err)
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInternal, i18n.T(locale, i18n.MsgFailedToUpdate, "instance", err.Error())))
return
}
m.emitCacheInvalidate()
emitAudit(m.eventBus, client, "channel_instance.updated", "channel_instance", id.String())
client.SendResponse(protocol.NewOKResponse(req.ID, map[string]any{"status": "updated"}))
}
func (m *ChannelInstancesMethods) handleDelete(ctx context.Context, client *gateway.Client, req *protocol.RequestFrame) {
locale := store.LocaleFromContext(ctx)
var params struct {
ID string `json:"id"`
}
if req.Params != nil {
json.Unmarshal(req.Params, ¶ms)
}
id, err := uuid.Parse(params.ID)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInvalidID, "instance")))
return
}
// Look up instance to check if it's a default (seeded) instance.
inst, err := m.store.Get(ctx, id)
if err != nil {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgInstanceNotFound)))
return
}
if store.IsDefaultChannelInstance(inst.Name) {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInvalidRequest, i18n.T(locale, i18n.MsgCannotDeleteDefaultInst)))
return
}
if err := m.store.Delete(ctx, id); err != nil {
slog.Error("channels.instances.delete", "error", err)
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrInternal, i18n.T(locale, i18n.MsgFailedToDelete, "instance", err.Error())))
return
}
m.emitCacheInvalidate()
emitAudit(m.eventBus, client, "channel_instance.deleted", "channel_instance", id.String())
client.SendResponse(protocol.NewOKResponse(req.ID, map[string]any{"status": "deleted"}))
}
// maskInstance returns a map representation with credentials masked.
func maskInstance(inst store.ChannelInstanceData) map[string]any {
result := map[string]any{
"id": inst.ID,
"name": inst.Name,
"display_name": inst.DisplayName,
"channel_type": inst.ChannelType,
"agent_id": inst.AgentID,
"config": inst.Config,
"enabled": inst.Enabled,
"is_default": store.IsDefaultChannelInstance(inst.Name),
"has_credentials": len(inst.Credentials) > 0,
"created_by": inst.CreatedBy,
"created_at": inst.CreatedAt,
"updated_at": inst.UpdatedAt,
}
// Mask credentials: show keys with "***" values
if len(inst.Credentials) > 0 {
var raw map[string]any
if json.Unmarshal(inst.Credentials, &raw) == nil {
masked := make(map[string]any, len(raw))
for k := range raw {
masked[k] = "***"
}
result["credentials"] = masked
} else {
result["credentials"] = map[string]string{}
}
} else {
result["credentials"] = map[string]string{}
}
return result
}
// isValidChannelType checks if the channel type is supported.
//
// Keep this list in sync with the HTTP twin in internal/http/channel_instances.go
// and with CHANNEL_TYPES in ui/web/src/constants/channels.ts. When the two
// backend switches drift (as happened with facebook/pancake/bitrix24), the
// WS-driven UI rejects channels the HTTP API accepts, and the dropdown offers
// channels neither API accepts.
func isValidChannelType(ct string) bool {
switch ct {
case "telegram", "discord", "slack", "whatsapp", "zalo_oa", "zalo_personal", "feishu", "facebook", "pancake", "bitrix24":
return true
}
return false
}