Merge remote-tracking branch 'origin/pg/foundation' into worktree-agent-a62864fcfbdb43f5a

# Conflicts:
#	internal/app/archied/state_store.go
#	internal/contracts/state/v1/state.pb.go
#	internal/daemon/daemon.go
#	internal/infrastructure/captureintake/receiver.go
#	internal/infrastructure/captureintake/receiver_test.go
#	internal/infrastructure/legacyimport/load.go
#	internal/infrastructure/postgres/edastore_test.go
#	internal/infrastructure/postgres/postgresdb/edastore.sql.go
#	internal/infrastructure/postgres/queries/edastore.sql
#	internal/infrastructure/staterpc/client.go
#	internal/infrastructure/staterpc/values.go
#	internal/webui/api_binding.go
#	internal/webui/api_binding_test.go
#	ui/dist/assets/index.js
#	ui/src/bindings/BindingEditor.vue
#	ui/src/bindings/BindingRow.vue
This commit is contained in:
sam committed 2026-09-24 19:34:31 +10:00
commit 30834223dc
63 files changed
+3871 -1760

No files matched your search

+1 -2
View File
@@ -589,7 +589,7 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) {
}
bindingID, err := cl.InsertBinding(ctx, binding.Binding{
Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
Workflow: "implement",
})
if err != nil || bindingID == "" {
t.Fatalf("InsertBinding = (%q, %v)", bindingID, err)
@@ -600,7 +600,6 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) {
if err := cl.UpdateBinding(ctx, binding.Binding{
ID: bindingID, Name: "b1", Matcher: binding.Matcher{Source: "sentry"},
MappingID: mappingID, Workflow: "implement", Owner: "acme", Repo: "widget",
Secret: "0123456789abcdef0123456789abcdef",
}); err != nil {
t.Fatalf("UpdateBinding: %v", err)
}
+3 -7
View File
@@ -254,13 +254,9 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
deps.Bindings = b.eda
deps.BindingDispatcher = b.eda
deps.PlaybookDispatcher = b.eda
// Only the Postgres EDA store holds event types.
if eventTypes, ok := any(b.eda).(storecontract.EventTypeStore); ok {
deps.EventTypes = eventTypes
}
if matches, ok := any(b.eda).(storecontract.MappingMatchRecorder); ok {
deps.MappingMatches = matches
}
deps.EventTypes = b.eda
deps.Sources = b.eda
deps.MappingMatches = b.eda
}
// tool_call events project into the tool_calls collection on the same
// event-capture store: this process legitimately owns both, so the
+4 -1
View File
@@ -8,12 +8,15 @@ import (
// eventCaptureStore is every surface the State Store serves from the
// event-capture tables, plus the tool_call projection it writes through.
type eventCaptureStore interface {
type eventCaptureStore interface { //nolint:interfacebloat // composite of the store contracts the event-capture tables serve
storecontract.CaptureStore
storecontract.MappingStore
storecontract.BindingStore
storecontract.BindingDispatcher
storecontract.MappingMatchRecorder
storecontract.PlaybookDispatcher
storecontract.EventTypeStore
storecontract.SourceStore
toolCallWriter
}
+16 -5
View File
@@ -12,7 +12,7 @@ import (
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/logging"
@@ -147,16 +147,27 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
b := newBootstrap()
b.st = st
// The playbook ledger moved to the event-capture store with the rest of
// the dispatch tables; the task store no longer serves it.
eda := edastore.OpenTest(t)
// The playbook ledger, sources and event types are served by the
// event-capture store; the task store no longer serves them.
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatalf("open postgres: %v", err)
}
defer pool.Close()
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
t.Fatalf("migrate: %v", err)
}
eda := postgres.NewEDA(pool, nil)
b.eda = eda
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
if deps.PlaybookDispatcher == nil {
t.Fatal("stateStoreDeps leaves PlaybookDispatcher nil; the standalone State Store is the only production server for the playbook dispatch ledger")
}
if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) {
t.Fatalf("PlaybookDispatcher = %T, want the opened *edastore.Store", deps.PlaybookDispatcher)
t.Fatalf("PlaybookDispatcher = %T, want the opened event-capture store", deps.PlaybookDispatcher)
}
if deps.Sources == nil || deps.EventTypes == nil {
t.Fatalf("stateStoreDeps Sources = %v, EventTypes = %v; want both served, or intake verifies nothing and nothing dispatches", deps.Sources, deps.EventTypes)
}
// A boot without a store must not fabricate one: nil keeps the RPCs honest
// as unavailable rather than depending on a nil receiver.
@@ -11,6 +11,8 @@ import (
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -173,11 +175,15 @@ func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
// around a nil writer.
func TestStateStoreDepsProjectToolCalls(t *testing.T) {
st := store.OpenTest(t)
eda := edastore.OpenTest(t)
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatalf("open postgres: %v", err)
}
defer pool.Close()
b := newBootstrap()
b.st = st
b.eda = eda
b.eda = postgres.NewEDA(pool, nil)
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
if _, ok := deps.Tasks.(*toolCallProjectingTaskStore); !ok {
t.Fatalf("deps.Tasks = %T, want the tool_call projecting decorator", deps.Tasks)
+14 -10
View File
@@ -134,21 +134,25 @@ func wireTaskLogs(d deps, srv *webui.Server) {
srv.TaskLogs = logs
}
// wireCaptureSurfaces attaches the capture read and the intake receiver.
// Both resolve from d.Store's contracts: CaptureStore backs the inspector's
// list and the mapping preview's scan window, BindingDispatcher resolves the
// armed binding whose secret HMAC-verifies a source. A store that does not
// implement one degrades that half with a warning rather than aborting the
// process, mirroring the daemon's own adapter selection.
// wireCaptureSurfaces attaches the capture read, the source editor and the
// intake receiver. All resolve from d.Store's contracts: CaptureStore backs
// the inspector's list and the mapping preview's scan window, SourceStore
// resolves the source whose signing setting verifies an event. A store that
// does not implement one degrades that half with a warning rather than
// aborting the process, mirroring the daemon's own adapter selection.
func wireCaptureSurfaces(d deps, srv *webui.Server) {
captures, hasCaptures := d.Store.(storecontract.CaptureStore)
bindings, hasBindings := d.Store.(storecontract.BindingDispatcher)
sources, hasSources := d.Store.(storecontract.SourceStore)
if !hasCaptures {
d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore")
return
}
if !hasBindings {
d.Log.Warn("binding dispatcher unavailable: state store does not implement BindingDispatcher")
var resolver captureintake.SourceResolver
if hasSources {
srv.Sources = sources
resolver = sources
} else {
d.Log.Warn("source store unavailable: state store does not implement SourceStore; no capture will dispatch")
}
capture := d.Options.Capture.withDefaults()
@@ -157,7 +161,7 @@ func wireCaptureSurfaces(d deps, srv *webui.Server) {
srv.CaptureIntake = &captureintake.Receiver{
Captures: captures,
Limiter: webhookguard.NewRateLimiter(capture.RatePerSecond, capture.RateBurst, time.Now),
Bindings: bindings,
Sources: resolver,
Retention: capture.Retention,
MaxEvents: capture.MaxEvents,
MaxBodyBytes: int64(capture.MaxBodyBytes),
File diff suppressed because it is too large. Load diff
@@ -84,6 +84,11 @@ const (
StateStoreService_UpdateBinding_FullMethodName = "/state.v1.StateStoreService/UpdateBinding"
StateStoreService_DeleteBinding_FullMethodName = "/state.v1.StateStoreService/DeleteBinding"
StateStoreService_ApproveBinding_FullMethodName = "/state.v1.StateStoreService/ApproveBinding"
StateStoreService_InsertSource_FullMethodName = "/state.v1.StateStoreService/InsertSource"
StateStoreService_GetSource_FullMethodName = "/state.v1.StateStoreService/GetSource"
StateStoreService_ListSources_FullMethodName = "/state.v1.StateStoreService/ListSources"
StateStoreService_SetSourceSigning_FullMethodName = "/state.v1.StateStoreService/SetSourceSigning"
StateStoreService_SetSourceSecret_FullMethodName = "/state.v1.StateStoreService/SetSourceSecret"
StateStoreService_ArmedBindingsForSource_FullMethodName = "/state.v1.StateStoreService/ArmedBindingsForSource"
StateStoreService_RecordDispatch_FullMethodName = "/state.v1.StateStoreService/RecordDispatch"
StateStoreService_RecordPlaybookDispatch_FullMethodName = "/state.v1.StateStoreService/RecordPlaybookDispatch"
@@ -218,6 +223,13 @@ type StateStoreServiceClient interface {
UpdateBinding(ctx context.Context, in *UpdateBindingRequest, opts ...grpc.CallOption) (*UpdateBindingResponse, error)
DeleteBinding(ctx context.Context, in *DeleteBindingRequest, opts ...grpc.CallOption) (*DeleteBindingResponse, error)
ApproveBinding(ctx context.Context, in *ApproveBindingRequest, opts ...grpc.CallOption) (*ApproveBindingResponse, error)
// Source (event-automation.md "Sources"): the capture endpoint and its
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error)
GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error)
ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error)
SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error)
SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error)
// Dispatch
ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error)
RecordDispatch(ctx context.Context, in *RecordDispatchRequest, opts ...grpc.CallOption) (*RecordDispatchResponse, error)
@@ -913,6 +925,56 @@ func (c *stateStoreServiceClient) ApproveBinding(ctx context.Context, in *Approv
return out, nil
}
func (c *stateStoreServiceClient) InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(InsertSourceResponse)
err := c.cc.Invoke(ctx, StateStoreService_InsertSource_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetSourceResponse)
err := c.cc.Invoke(ctx, StateStoreService_GetSource_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListSourcesResponse)
err := c.cc.Invoke(ctx, StateStoreService_ListSources_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetSourceSigningResponse)
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSigning_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetSourceSecretResponse)
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSecret_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ArmedBindingsForSourceResponse)
@@ -1118,6 +1180,13 @@ type StateStoreServiceServer interface {
UpdateBinding(context.Context, *UpdateBindingRequest) (*UpdateBindingResponse, error)
DeleteBinding(context.Context, *DeleteBindingRequest) (*DeleteBindingResponse, error)
ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error)
// Source (event-automation.md "Sources"): the capture endpoint and its
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error)
GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error)
ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error)
SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error)
SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error)
// Dispatch
ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error)
RecordDispatch(context.Context, *RecordDispatchRequest) (*RecordDispatchResponse, error)
@@ -1339,6 +1408,21 @@ func (UnimplementedStateStoreServiceServer) DeleteBinding(context.Context, *Dele
func (UnimplementedStateStoreServiceServer) ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ApproveBinding not implemented")
}
func (UnimplementedStateStoreServiceServer) InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error) {
return nil, status.Error(codes.Unimplemented, "method InsertSource not implemented")
}
func (UnimplementedStateStoreServiceServer) GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetSource not implemented")
}
func (UnimplementedStateStoreServiceServer) ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListSources not implemented")
}
func (UnimplementedStateStoreServiceServer) SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetSourceSigning not implemented")
}
func (UnimplementedStateStoreServiceServer) SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetSourceSecret not implemented")
}
func (UnimplementedStateStoreServiceServer) ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ArmedBindingsForSource not implemented")
}
@@ -2537,6 +2621,96 @@ func _StateStoreService_ApproveBinding_Handler(srv interface{}, ctx context.Cont
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_InsertSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(InsertSourceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).InsertSource(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_InsertSource_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).InsertSource(ctx, req.(*InsertSourceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_GetSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSourceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).GetSource(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_GetSource_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).GetSource(ctx, req.(*GetSourceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ListSources_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListSourcesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ListSources(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ListSources_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ListSources(ctx, req.(*ListSourcesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SetSourceSigning_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetSourceSigningRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SetSourceSigning_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, req.(*SetSourceSigningRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SetSourceSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetSourceSecretRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SetSourceSecret_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, req.(*SetSourceSecretRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ArmedBindingsForSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ArmedBindingsForSourceRequest)
if err := dec(in); err != nil {
@@ -2915,6 +3089,26 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "ApproveBinding",
Handler: _StateStoreService_ApproveBinding_Handler,
},
{
MethodName: "InsertSource",
Handler: _StateStoreService_InsertSource_Handler,
},
{
MethodName: "GetSource",
Handler: _StateStoreService_GetSource_Handler,
},
{
MethodName: "ListSources",
Handler: _StateStoreService_ListSources_Handler,
},
{
MethodName: "SetSourceSigning",
Handler: _StateStoreService_SetSourceSigning_Handler,
},
{
MethodName: "SetSourceSecret",
Handler: _StateStoreService_SetSourceSecret_Handler,
},
{
MethodName: "ArmedBindingsForSource",
Handler: _StateStoreService_ArmedBindingsForSource_Handler,
+34 -16
View File
@@ -654,7 +654,7 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
continue
}
for _, b := range armed {
if !b.Matcher.Matches(c.Source, c.Authenticated) {
if !b.Matcher.Matches(c.Source, c.Dispatchable()) {
continue
}
d.dispatchOneBinding(ctx, b, c)
@@ -662,6 +662,24 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
}
}
// bindingMapping returns b's mapping, or nil after logging why it is
// unavailable.
func (d *Daemon) bindingMapping(ctx context.Context, b binding.Binding) *mapping.Mapping {
if d.Mappings == nil {
d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID)
return nil
}
m, err := d.Mappings.GetMapping(ctx, b.MappingID)
if err != nil {
d.Log.Warn("binding dispatch: get mapping", "binding", b.ID, "mapping", b.MappingID, "error", err)
return nil
}
if m == nil {
d.Log.Warn("binding dispatch: mapping missing", "binding", b.ID, "mapping", b.MappingID)
}
return m
}
// dispatchOneBinding offers one capture to one binding. The binding applies
// when its mapping belongs to the capture's event type. The mapping resolves
// the payload (a required-field failure records binding_dispatch_failure and
@@ -672,20 +690,8 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
// already fired from firing again on a later cycle. A failed enqueue after the
// claim loses that dispatch, which is the at-most-once side of the trade.
func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) {
if d.Mappings == nil {
d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID)
return
}
m, err := d.Mappings.GetMapping(ctx, b.MappingID)
if err != nil {
d.Log.Warn("binding dispatch: get mapping", "binding", b.ID, "mapping", b.MappingID, "error", err)
return
}
if m == nil {
d.Log.Warn("binding dispatch: mapping missing", "binding", b.ID, "mapping", b.MappingID)
return
}
if m.EventTypeID != c.EventType {
m := d.bindingMapping(ctx, b)
if m == nil || m.EventTypeID != c.EventType {
return
}
values, failures := mapping.Resolve(m.Fields, []byte(c.Body))
@@ -719,8 +725,20 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
}
title := fmt.Sprintf("binding %s/%d from %s", b.Name, b.Version, c.Source)
body := renderBindingBody(values, c)
if _, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, owner, repo, title, body, b.Workflow, "", b.ID, b.Version); err != nil {
task, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, owner, repo, title, body, b.Workflow, "", b.ID, b.Version)
if err != nil {
d.Log.Warn("binding dispatch: enqueue", "binding", b.ID, "capture", c.ID, "error", err)
return
}
if c.Unsigned {
if _, err := d.Store.InsertEvent(ctx, events.Event{
TaskID: task.ID,
Kind: events.KindUnsignedEvent,
Detail: fmt.Sprintf("started by an unsigned event from source %q", c.Source),
Data: map[string]any{"source": c.Source, "capture_id": c.ID, "binding_id": b.ID},
}); err != nil {
d.Log.Warn("binding dispatch: unsigned marker", "task", task.ID, "error", err)
}
}
}
+45 -1
View File
@@ -1,6 +1,7 @@
package daemon
import (
"context"
"log/slog"
"os"
"path/filepath"
@@ -10,7 +11,9 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -150,6 +153,48 @@ func TestDispatchBindingsSkipsUnauthenticatedCaptures(t *testing.T) {
}
}
// markUnsigned reports every undispatched capture as taken on an approved
// unsigned source, which the legacy capture store cannot persist.
type markUnsigned struct {
storecontract.BindingDispatcher
}
func (m markUnsigned) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]store.CapturedEvent, error) {
cs, err := m.BindingDispatcher.ListUndispatchedCaptures(ctx, sources, limit)
for i := range cs {
cs[i].Unsigned = true
}
return cs, err
}
// An event on an approved unsigned source dispatches without a signature,
// and the task it starts carries an unsigned_event on its timeline.
func TestDispatchBindingsDispatchesUnsignedCaptureAndMarksTimeline(t *testing.T) {
s := openDispatchTestStore(t)
mappingID := seedMapping(t, s, "fw", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
seedArmedBinding(t, s, "fw", mappingID)
seedCapture(t, s, "fw", false, `{"title":"blocked"}`)
d := newDispatchDaemon(t, s)
d.BindingDispatcher = markUnsigned{d.BindingDispatcher}
d.dispatchBindings(t.Context())
tasks, err := s.Tasks(t.Context(), 10)
if err != nil || len(tasks) != 1 {
t.Fatalf("Tasks = %d (err %v), want 1", len(tasks), err)
}
evs, err := s.TaskEvents(t.Context(), tasks[0].ID)
if err != nil {
t.Fatalf("TaskEvents: %v", err)
}
for _, e := range evs {
if e.Kind == events.KindUnsignedEvent {
return
}
}
t.Fatalf("task timeline has no %s event: %+v", events.KindUnsignedEvent, evs)
}
// Test 33: a required field whose path is missing in the capture body
// blocks the dispatch -- the failure path emits a
// binding_dispatch_failure event and creates no task.
@@ -305,7 +350,6 @@ func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID
Workflow: "implement",
Owner: owner,
Repo: repo,
Secret: "0123456789abcdef0123456789abcdef",
})
if err != nil {
t.Fatalf("InsertBinding: %v", err)
+12 -58
View File
@@ -39,9 +39,8 @@ type Matcher struct {
//
// Version is bumped on every UpdateBinding so a later edit cannot
// silently rewrite the historical provenance of a task that already
// fired. Secret is the HMAC-SHA256 shared secret a sender must sign with
// for an event to be marked authenticated; it is never returned by
// GET handlers.
// fired. Signing belongs to the source the matcher names, not to the
// binding (internal/domain/source).
type Binding struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -61,52 +60,15 @@ type Binding struct {
Repo string `json:"repo,omitempty"`
Version int `json:"version"`
Status Status `json:"status"`
Secret string `json:"secret,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// minSecretLen is the floor for an acceptable shared secret. A trivially
// short secret makes accidental binding to a known HMAC trivial; the
// floor is chosen so a one-character typo cannot arm.
const minSecretLen = 16
// Validate checks a binding is well-formed before it is newly persisted.
// A non-empty Name, a non-empty Matcher.Source, a positive MappingID, a
// non-empty Workflow, and a sufficiently long Secret are all required.
// Workflow existence is checked at the API/store layer because the domain
// package does not import the workflow registry. Use ValidateForUpdate
// instead when editing an existing binding, where an empty Secret is a
// meaningful "keep the current one," not a missing value.
// Validate checks a binding is well-formed before it is persisted: a
// non-empty Name, Matcher.Source, MappingID and Workflow, and a complete
// owner/repo pin or none. Workflow existence is checked at the API/store
// layer because the domain package does not import the workflow registry.
func (b Binding) Validate() error {
if err := b.validateCommon(); err != nil {
return err
}
if len(b.Secret) < minSecretLen {
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
}
return nil
}
// ValidateForUpdate is Validate for the edit path: every other field is
// checked identically, but Secret is only length-checked when the caller
// actually supplied one. UpdateBinding's own store-layer contract already
// treats an empty Secret as "preserve the existing one" (COALESCE against
// NULLIF) -- rejecting that here at the validation gate before the store
// ever sees it would make the store's own documented behavior
// unreachable. A non-empty Secret (a genuine change) is still held to the
// same floor Validate enforces.
func (b Binding) ValidateForUpdate() error {
if err := b.validateCommon(); err != nil {
return err
}
if b.Secret != "" && len(b.Secret) < minSecretLen {
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
}
return nil
}
func (b Binding) validateCommon() error {
if strings.TrimSpace(b.Name) == "" {
return fmt.Errorf("binding: name is required")
}
@@ -125,18 +87,10 @@ func (b Binding) validateCommon() error {
return nil
}
// Matches reports whether the given captured event would match this
// binding's matcher. The Authenticated clause encodes t2db.5 point 1 --
// an unauthenticated event can never trigger a binding, no matter how
// well it would otherwise match.
//
// Note: the caller is expected to be the dispatch loop or the capture
// intake receiver, both of which receive a CapturedEvent with the
// Authenticated flag already set by HMAC verification. Matches is pure
// and has no I/O.
func (m Matcher) Matches(source string, authenticated bool) bool {
if !authenticated {
return false
}
return m.Source == source
// Matches reports whether a captured event would trigger this binding. An
// event that is not dispatchable (no valid signature, and not from an
// approved unsigned source) never matches, however well it would otherwise.
// Matches is pure and has no I/O.
func (m Matcher) Matches(source string, dispatchable bool) bool {
return dispatchable && m.Source == source
}
+18 -42
View File
@@ -8,7 +8,6 @@ func validBinding() Binding {
Matcher: Matcher{Source: "sentry"},
MappingID: "m1",
Workflow: "implement",
Secret: "0123456789abcdef0123456789abcdef",
}
}
@@ -33,47 +32,6 @@ func TestValidateAcceptsBothOwnerAndRepo(t *testing.T) {
}
}
// TestValidateRejectsPartialRepoPin: Owner and Repo are a pair. A
// binding naming only one of them is ambiguous -- it isn't "no pin"
// (that's both empty) and it isn't a complete pin, so it must be
// rejected at validation time rather than silently guessing which
// half was meant.
// TestValidateForUpdateAcceptsEmptySecret is the fix for a real bug found
// via browser testing (t2db.8): UpdateBinding's own documented contract
// treats an empty Secret as "preserve the existing one" (COALESCE against
// NULLIF), but the API handler validated with the create-time Validate,
// which rejected any edit that didn't retype the full secret -- making
// the store's own documented behavior unreachable.
func TestValidateForUpdateAcceptsEmptySecret(t *testing.T) {
b := validBinding()
b.Secret = ""
if err := b.ValidateForUpdate(); err != nil {
t.Fatalf("ValidateForUpdate() = %v, want nil for an empty (preserve-existing) secret", err)
}
}
// TestValidateForUpdateStillEnforcesLengthOnANewSecret confirms the fix
// isn't a blanket bypass: a genuinely-supplied short secret on update is
// still rejected, same floor as create.
func TestValidateForUpdateStillEnforcesLengthOnANewSecret(t *testing.T) {
b := validBinding()
b.Secret = "short"
if err := b.ValidateForUpdate(); err == nil {
t.Fatal("ValidateForUpdate() = nil, want error for a too-short (but non-empty) secret")
}
}
// TestValidateRejectsEmptySecretOnCreate pins that the fix is scoped to
// update only -- Validate (used at create time, where there is no
// existing secret to fall back to) still requires a real one.
func TestValidateRejectsEmptySecretOnCreate(t *testing.T) {
b := validBinding()
b.Secret = ""
if err := b.Validate(); err == nil {
t.Fatal("Validate() = nil, want error for an empty secret at create time")
}
}
func TestValidateRejectsPartialRepoPin(t *testing.T) {
tests := []struct {
name string
@@ -92,3 +50,21 @@ func TestValidateRejectsPartialRepoPin(t *testing.T) {
})
}
}
func TestMatcherMatchesOnlyDispatchableEventsFromItsSource(t *testing.T) {
m := Matcher{Source: "sentry"}
tests := []struct {
source string
dispatchable bool
want bool
}{
{"sentry", true, true},
{"sentry", false, false},
{"other", true, false},
}
for _, tt := range tests {
if got := m.Matches(tt.source, tt.dispatchable); got != tt.want {
t.Errorf("Matches(%q, %v) = %v, want %v", tt.source, tt.dispatchable, got, tt.want)
}
}
}
+50
View File
@@ -0,0 +1,50 @@
package source
import (
"crypto/rand"
"encoding/hex"
"fmt"
"github.com/google/uuid"
)
// NewPath returns a fresh UUIDv7 path: time-ordered, unguessable, and never
// colliding with another source.
func NewPath() (string, error) {
id, err := uuid.NewV7()
if err != nil {
return "", fmt.Errorf("source: generate path: %w", err)
}
return id.String(), nil
}
// NewSecret returns a fresh 32-byte HMAC secret, hex encoded.
func NewSecret() (string, error) {
var b [MinSecretLen / 2]byte
if _, err := rand.Read(b[:]); err != nil {
return "", fmt.Errorf("source: generate secret: %w", err)
}
return hex.EncodeToString(b[:]), nil
}
// ValidatePath checks a custom path is URL-safe: RFC 3986 unreserved
// characters only, so it needs no escaping, and never a dot segment.
func ValidatePath(path string) error {
if path == "" || len(path) > MaxPathLen || path == "." || path == ".." {
return ErrInvalidPath
}
for i := range len(path) {
if !unreserved(path[i]) {
return ErrInvalidPath
}
}
return nil
}
func unreserved(c byte) bool {
switch {
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9':
return true
}
return c == '-' || c == '.' || c == '_' || c == '~'
}
+93
View File
@@ -0,0 +1,93 @@
// Package source owns the capture source: the endpoint one sender posts to,
// and its signing setting. See docs/prds/event-automation.md "Sources".
package source
import (
"errors"
"time"
)
// Signing is a source's signing state. A source is signed by default; turning
// signing off is requested and then approved, the same two-step gate as
// arming a binding, and only the approved state accepts unsigned events.
type Signing string
const (
SigningSigned Signing = "signed"
SigningUnsignedPending Signing = "unsigned_pending_approval"
SigningUnsigned Signing = "unsigned"
)
// MaxPathLen bounds a custom path.
const MaxPathLen = 128
// MinSecretLen is the length of a generated secret: 32 random bytes, hex.
const MinSecretLen = 64
var (
// ErrInvalidPath refuses a custom path that is not URL-safe.
ErrInvalidPath = errors.New("source: path must be 1-128 URL-safe characters (A-Z a-z 0-9 - . _ ~), not a dot segment")
// ErrSigningTransition refuses an approval with no pending request.
ErrSigningTransition = errors.New("source: signing transition rejected")
)
// Source is one capture endpoint. Path is its URL segment and its identity:
// captures and binding matchers reference it, so it does not change after
// creation. Secret is the HMAC key a signed sender signs with.
type Source struct {
Path string `json:"path"`
Signing Signing `json:"signing"`
Secret string `json:"secret,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// New builds a signed source with a generated secret. An empty customPath
// gets a UUIDv7 path; a non-empty one must be URL-safe. Uniqueness is the
// store's to enforce.
func New(customPath string) (Source, error) {
path := customPath
if path == "" {
generated, err := NewPath()
if err != nil {
return Source{}, err
}
path = generated
} else if err := ValidatePath(path); err != nil {
return Source{}, err
}
secret, err := NewSecret()
if err != nil {
return Source{}, err
}
return Source{Path: path, Signing: SigningSigned, Secret: secret}, nil
}
// Unsigned reports whether events on this source dispatch without a
// signature. Only an approved request counts.
func (s *Source) Unsigned() bool { return s.Signing == SigningUnsigned }
// RequestUnsigned asks to turn signing off. The source stays signed until
// ApproveUnsigned.
func (s *Source) RequestUnsigned() error {
if s.Signing == SigningSigned {
s.Signing = SigningUnsignedPending
}
return nil
}
// ApproveUnsigned is the only transition that turns signing off.
func (s *Source) ApproveUnsigned() error {
if s.Signing != SigningUnsignedPending {
return ErrSigningTransition
}
s.Signing = SigningUnsigned
return nil
}
// RequireSigning turns signing back on. It needs no approval: it only
// narrows what dispatches.
func (s *Source) RequireSigning() error {
s.Signing = SigningSigned
return nil
}
+108
View File
@@ -0,0 +1,108 @@
package source
import (
"errors"
"strings"
"testing"
"github.com/google/uuid"
)
func TestNewDefaultsToSignedUUIDv7Path(t *testing.T) {
s, err := New("")
if err != nil {
t.Fatalf("New() error = %v", err)
}
id, err := uuid.Parse(s.Path)
if err != nil {
t.Fatalf("path %q is not a UUID: %v", s.Path, err)
}
if id.Version() != 7 {
t.Fatalf("path version = %d, want 7", id.Version())
}
if s.Signing != SigningSigned {
t.Fatalf("signing = %q, want %q", s.Signing, SigningSigned)
}
if len(s.Secret) < MinSecretLen {
t.Fatalf("secret length = %d, want >= %d", len(s.Secret), MinSecretLen)
}
other, err := New("")
if err != nil {
t.Fatalf("New() error = %v", err)
}
if other.Path == s.Path || other.Secret == s.Secret {
t.Fatal("two new sources share a path or a secret")
}
}
func TestNewAcceptsOrRefusesCustomPath(t *testing.T) {
tests := []struct {
path string
ok bool
}{
{"sentry", true},
{"fire-wall_01.v2~x", true},
{"a/b", false},
{"with space", false},
{"percent%20", false},
{"..", false},
{".", false},
{strings.Repeat("a", MaxPathLen+1), false},
{"ünicode", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
s, err := New(tt.path)
if tt.ok {
if err != nil || s.Path != tt.path {
t.Fatalf("New(%q) = %q, %v; want path kept", tt.path, s.Path, err)
}
return
}
if !errors.Is(err, ErrInvalidPath) {
t.Fatalf("New(%q) error = %v, want ErrInvalidPath", tt.path, err)
}
})
}
}
func TestSigningTransitions(t *testing.T) {
tests := []struct {
name string
from Signing
action func(*Source) error
want Signing
wantErr bool
}{
{"request unsigned waits for approval", SigningSigned, (*Source).RequestUnsigned, SigningUnsignedPending, false},
{"approve pending", SigningUnsignedPending, (*Source).ApproveUnsigned, SigningUnsigned, false},
{"approve without request", SigningSigned, (*Source).ApproveUnsigned, SigningSigned, true},
{"approve twice", SigningUnsigned, (*Source).ApproveUnsigned, SigningUnsigned, true},
{"resign from unsigned", SigningUnsigned, (*Source).RequireSigning, SigningSigned, false},
{"resign from pending", SigningUnsignedPending, (*Source).RequireSigning, SigningSigned, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := Source{Path: "p", Signing: tt.from}
err := tt.action(&s)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if s.Signing != tt.want {
t.Fatalf("signing = %q, want %q", s.Signing, tt.want)
}
})
}
}
func TestUnsignedOnlyOnceApproved(t *testing.T) {
for signing, want := range map[Signing]bool{
SigningSigned: false,
SigningUnsignedPending: false,
SigningUnsigned: true,
} {
if got := (&Source{Signing: signing}).Unsigned(); got != want {
t.Errorf("Unsigned() for %q = %v, want %v", signing, got, want)
}
}
}
@@ -24,6 +24,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
@@ -212,6 +213,20 @@ type BindingStore interface {
ApproveBinding(ctx context.Context, id string) error
}
// SourceStore persists capture sources and their signing setting
// (docs/prds/event-automation.md "Sources"). The path is the key and never
// changes. Secrets cross this surface in plaintext; the store encrypts them
// at rest. Signing transitions are decided by the source domain and written
// with an expected-from guard, so two operators cannot race an approval.
type SourceStore interface {
InsertSource(ctx context.Context, s source.Source) error
// GetSource returns (nil, nil) for an unknown path.
GetSource(ctx context.Context, path string) (*source.Source, error)
ListSources(ctx context.Context) ([]source.Source, error)
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
SetSourceSecret(ctx context.Context, path, secret string) error
}
// BindingDispatcher is the dispatch-loop surface over the bindings store:
// look up armed bindings for HMAC verification, list captures that still
// need dispatching, and record the at-most-once ledger row. The
@@ -296,8 +311,15 @@ type CapturedEvent struct {
// when it arrived, or empty when it matched none. An unidentified capture
// is never dispatched.
EventType string `json:"event_type"`
// Unsigned marks an event that arrived on an approved unsigned source.
// It dispatches without Authenticated and is flagged wherever it shows.
Unsigned bool `json:"unsigned"`
}
// Dispatchable reports whether a binding may start a task from this event:
// a valid signature, or a source approved to take unsigned events.
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
// ConfigSnapshot is the running configuration as the dashboard renders it,
// published by whoever owns configuration for whoever displays it.
//
@@ -397,6 +419,13 @@ var (
ErrMappingNotFound = errors.New("store: mapping not found")
// ErrEventTypeNotFound is returned when an event type ID does not exist.
ErrEventTypeNotFound = errors.New("store: event type not found")
// ErrSourceNotFound is returned when a source path does not exist.
ErrSourceNotFound = errors.New("store: source not found")
// ErrSourcePathTaken is returned when a new source's path is in use.
ErrSourcePathTaken = errors.New("store: source path already taken")
// ErrSourceSigningStale is returned when a signing write's expected
// from state does not match the stored one.
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
// ErrResourceNotFound is returned when a control-plane resource kind has
// no stored document. It is in-process only (not on the gRPC wire): the
+5
View File
@@ -114,6 +114,11 @@ const (
KindBindingChanged = "binding_changed"
KindMappingChanged = "mapping_changed"
// KindUnsignedEvent marks a task started by an event from an approved
// unsigned source, so its timeline shows that nothing authenticated
// the sender. data: source, capture_id, binding_id.
KindUnsignedEvent = "unsigned_event"
// KindUpdateReport carries the phase-2 outcome of a dashboard-initiated
// update -- whether the restarted daemon came back up healthy and on
// the version it claimed, relayed once on the boot that finds the
@@ -21,7 +21,7 @@ import (
"net/http"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/webhookguard"
@@ -41,10 +41,10 @@ type Receiver struct {
// is read. Nil disables rate limiting, which composition never does in
// production.
Limiter *webhookguard.RateLimiter
// Bindings resolves the armed binding whose secret authenticates a
// source. Nil disables per-source HMAC verification and every event
// records as authenticated=false.
Bindings storecontract.BindingDispatcher
// Sources resolves the source a path names and its signing setting.
// Nil disables verification: every event records as neither
// authenticated nor unsigned, so none dispatches.
Sources SourceResolver
// Retention and MaxEvents are passed straight to InsertCapture's
// prune-on-write bounds. See config.CaptureConfig.
Retention time.Duration
@@ -60,23 +60,28 @@ type Receiver struct {
Log *slog.Logger
}
// SourceResolver is the one SourceStore read intake needs.
type SourceResolver interface {
GetSource(ctx context.Context, path string) (*source.Source, error)
}
// Register mounts the receiver on mux.
func (rc *Receiver) Register(mux *http.ServeMux) {
mux.HandleFunc(Path, rc.ServeHTTP)
}
// ServeHTTP accepts an inbound webhook POST and persists it. If a binding is
// armed for this source the body must also carry a valid HMAC signature; only
// correctly-signed events are recorded as authenticated (t2db.5 point 1). An
// unauthenticated event is still captured, visible in the inspector, and
// marked unauthenticated -- the dispatch loop's auth check
// (binding.Matcher.Matches) is the actual gate against false task creation.
// ServeHTTP accepts an inbound webhook POST and persists it. On a signed
// source only a valid HMAC under the source's secret marks the event
// authenticated; on an approved unsigned source every event is marked
// unsigned. Anything else is still captured and visible in the inspector,
// but is neither, so the dispatch loop's check (binding.Matcher.Matches over
// CapturedEvent.Dispatchable) never starts a task from it.
func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rc.Captures == nil {
http.Error(w, "capture not configured", http.StatusServiceUnavailable)
return
}
source := r.PathValue("source")
path := r.PathValue("source")
// webhookguard.RateLimiter's bucket map assumes a bounded, operator-
// registered key space (see its doc comment) -- it is never evicted, and
@@ -91,7 +96,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
armed := rc.armedBindings(r, source)
src := rc.resolveSource(r, path)
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytesOrFallback(rc.MaxBodyBytes))
body, err := io.ReadAll(r.Body)
@@ -102,23 +107,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// HMAC verification against each binding armed for this source: a
// signature valid for any of their secrets authenticates the event. Mirrors channels/webhook/webhook.go's header precedence:
// GitHub-style X-Hub-Signature-256 first, X-Signature-256 fallback.
// Empty header + non-empty secret is never valid (VerifyHMAC's own
// guard), so an absent signature with an armed binding lands here as
// authenticated=false rather than authenticated=true.
sig := r.Header.Get("X-Hub-Signature-256")
if sig == "" {
sig = r.Header.Get("X-Signature-256")
}
authenticated := false
for _, b := range armed {
if webhookguard.VerifyHMAC(body, sig, b.Secret) {
authenticated = true
break
}
}
// Verified on the raw bytes, before redaction parses them.
authenticated, unsigned := verify(src, r.Header, body)
headers, _ := json.Marshal(r.Header)
redactedHeaders, err := webhookguard.RedactPayload(headers)
@@ -136,16 +126,17 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := storecontract.CapturedEvent{
ReceivedAt: time.Now().UTC(),
Source: source,
Source: path,
RemoteAddr: r.RemoteAddr,
ContentType: r.Header.Get("Content-Type"),
Headers: string(redactedHeaders),
Body: string(redactedBody),
Authenticated: authenticated,
Unsigned: unsigned,
}
id, err := rc.Captures.InsertCapture(r.Context(), c, rc.Retention, rc.MaxEvents)
if err != nil {
rc.logger().Error("capture insert", "err", err, "source", source)
rc.logger().Error("capture insert", "err", err, "source", path)
http.Error(w, "capture failed", http.StatusInternalServerError)
return
}
@@ -160,29 +151,49 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rc.Publish != nil {
rc.Publish(r.Context(), events.Event{
Kind: "capture",
Detail: "capture from " + source,
Data: map[string]any{"id": id, "source": source},
Detail: "capture from " + path,
Data: map[string]any{"id": id, "source": path, "unsigned": unsigned},
})
}
w.WriteHeader(http.StatusAccepted)
}
// armedBindings resolves the bindings armed for source before the body is
// read. A lookup error is logged and treated as "no armed binding" -- the
// dispatch loop's auth check is the actual gate, so failing closed here would
// amplify a transient store hiccup into a capture outage for every
// sender-not-yet-bound flow.
func (rc *Receiver) armedBindings(r *http.Request, source string) []binding.Binding {
if rc.Bindings == nil {
// resolveSource looks up the source a path names. A lookup error is logged
// and treated as an unknown source: the event is still captured but cannot
// dispatch, so failing open here costs no safety, while failing closed would
// turn a transient store hiccup into a capture outage.
func (rc *Receiver) resolveSource(r *http.Request, path string) *source.Source {
if rc.Sources == nil {
return nil
}
armed, err := rc.Bindings.ArmedBindingsForSource(r.Context(), source)
src, err := rc.Sources.GetSource(r.Context(), path)
if err != nil {
rc.logger().Warn("armed bindings lookup", "source", source, "err", err)
rc.logger().Warn("source lookup", "source", path, "err", err)
return nil
}
return armed
return src
}
// verify decides how an event on src may dispatch. An approved unsigned
// source marks it unsigned. Otherwise a valid HMAC under the source's secret
// authenticates it: X-Hub-Signature-256 first, X-Signature-256 as fallback.
// A source with no secret yet authenticates nothing, since an empty key is
// one anybody can sign with.
func verify(src *source.Source, h http.Header, body []byte) (authenticated, unsigned bool) {
switch {
case src == nil:
return false, false
case src.Unsigned():
return false, true
case src.Secret == "":
return false, false
}
sig := h.Get("X-Hub-Signature-256")
if sig == "" {
sig = h.Get("X-Signature-256")
}
return webhookguard.VerifyHMAC(body, sig, src.Secret), false
}
func (rc *Receiver) logger() *slog.Logger {
@@ -13,7 +13,7 @@ import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/store"
@@ -74,87 +74,6 @@ func captureTestServer(t *testing.T) testReceiver {
}
}
// stubBindingStore injects a configurable armed-binding lookup result so
// handleCapture tests can exercise the HMAC path without seeding the real
// store through the draft -> pending_approval -> armed lifecycle.
type stubBindingStore struct {
armedBySource map[string][]binding.Binding
lookupErr error
}
func (s *stubBindingStore) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
if s.lookupErr != nil {
return nil, s.lookupErr
}
return s.armedBySource[source], nil
}
// handleCapture only touches ArmedBindingsForSource on the binding
// surface. The rest of BindingStore is stubbed so the type satisfies the
// interface and Phase C's other handlers can be exercised elsewhere.
func (s *stubBindingStore) InsertBinding(_ context.Context, _ binding.Binding) (int64, error) {
return 0, nil
}
func (s *stubBindingStore) GetBinding(_ context.Context, _ int64) (*binding.Binding, error) {
return nil, nil
}
func (s *stubBindingStore) ListBindings(_ context.Context) ([]binding.Binding, error) {
return nil, nil
}
func (s *stubBindingStore) UpdateBinding(_ context.Context, _ binding.Binding) error {
return nil
}
func (s *stubBindingStore) DeleteBinding(_ context.Context, _ int64) error {
return nil
}
func (s *stubBindingStore) ApproveBinding(_ context.Context, _ int64) error {
return nil
}
func (s *stubBindingStore) RecordDispatch(
_ context.Context,
_ string,
_ int64,
_ string,
_ int64,
) error {
return nil
}
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]store.CapturedEvent, error) {
return nil, nil
}
// captureBindingServer builds a Server with both a real CaptureStore (so
// ListCaptures can read back what handleCapture persisted) and a stub
// BindingDispatcher configured with one armed binding for the given
// source. The mapping/workflow fields are placeholders -- handleCapture
// never reads them, only the Secret.
func captureBindingServer(t *testing.T, secret, source string) testReceiver {
t.Helper()
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{
armedBySource: map[string][]binding.Binding{
source: {{
ID: "rbind0000000001",
Name: "test",
Matcher: binding.Matcher{Source: source},
MappingID: "rmap00000000001",
Workflow: "implement",
Version: 1,
Status: binding.StatusArmed,
Secret: secret,
}},
},
}
return srv
}
// hmacSHA256 returns the GitHub-style "sha256=<hex>" signature for body
// under secret, the same form webhookguard.VerifyHMAC accepts.
func hmacSHA256(secret, body string) string {
@@ -435,240 +354,99 @@ func TestHandleCaptureStorageFailureIs500(t *testing.T) {
}
}
// TestHandleCaptureMarksAuthenticatedWhenHMACMatches is the green half of
// the t2db.5 point 1 wiring: a capture POST signed with the armed
// binding's secret must be recorded with Authenticated=true so the
// dispatch loop's binding.Matcher.Matches check (which gates on
// authenticated) can fire.
func TestHandleCaptureMarksAuthenticatedWhenHMACMatches(t *testing.T) {
const secret = "abcdefghijklmnop" // exactly 16 bytes (binding.Validate floor)
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Hub-Signature-256", hmacSHA256(secret, body))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusAccepted, w.Body.String())
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 {
t.Fatalf("captured rows = %d, want 1", len(got))
}
if !got[0].Authenticated {
t.Errorf("Authenticated = false, want true (signature matched armed binding's secret)")
}
// stubSources resolves a fixed set of sources, or fails every lookup.
type stubSources struct {
byPath map[string]source.Source
err error
}
// TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches covers the
// negative side of the HMAC verification: a body signed with the WRONG
// secret is still captured (per t2db.5 point 1 -- captures must remain
// inspectable even when auth fails) but flagged as unauthenticated so
// the dispatch loop's auth gate can drop it.
func TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches(t *testing.T) {
func (s stubSources) GetSource(_ context.Context, path string) (*source.Source, error) {
if s.err != nil {
return nil, s.err
}
src, ok := s.byPath[path]
if !ok {
return nil, nil
}
return &src, nil
}
// memCaptures records inserted captures, including the Unsigned flag the
// legacy store does not persist.
type memCaptures struct{ rows []store.CapturedEvent }
func (m *memCaptures) InsertCapture(_ context.Context, c store.CapturedEvent, _ time.Duration, _ int) (string, error) {
m.rows = append(m.rows, c)
return "c", nil
}
func (m *memCaptures) ListCaptures(context.Context, int) ([]store.CapturedEvent, error) {
return m.rows, nil
}
// TestHandleCaptureSigning pins the source signing rule: a signed source
// authenticates only a valid X-Hub-Signature-256 or X-Signature-256 HMAC
// under its secret; an approved unsigned source marks every event unsigned;
// anything else is captured and neither authenticated nor unsigned, so it
// never dispatches.
func TestHandleCaptureSigning(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
wrong := hmacSHA256("not-the-real-secret-aaaaaaaaa", body)
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
req.Header.Set("X-Hub-Signature-256", wrong)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d (a mismatched signature must still produce a capture, not reject the request)", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 {
t.Fatalf("captured rows = %d, want 1", len(got))
}
if got[0].Authenticated {
t.Errorf("Authenticated = true, want false (signature did not match armed binding's secret)")
}
}
// TestHandleCaptureWithNoSignatureMarksUnauthenticated covers the
// "sender forgot the header" case: the binding is armed, the secret is
// registered, but the request carries no signature at all. The handler
// must fall through to authenticated=false (the empty-signature guard
// in webhookguard.VerifyHMAC). Captures are still recorded -- the
// operator can see the unsigned attempt in the inspector.
func TestHandleCaptureWithNoSignatureMarksUnauthenticated(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
// Deliberately no X-Hub-Signature-256 / X-Signature-256 header.
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureWithSeveralArmedBindings: several bindings may share a
// source, and an event signed with any one of their secrets is authenticated.
func TestHandleCaptureWithSeveralArmedBindings(t *testing.T) {
const body = `{"action":"opened"}`
signed := source.Source{Path: "github", Signing: source.SigningSigned, Secret: secret}
pending := source.Source{Path: "github", Signing: source.SigningUnsignedPending, Secret: secret}
unsigned := source.Source{Path: "github", Signing: source.SigningUnsigned, Secret: secret}
noSecret := source.Source{Path: "github", Signing: source.SigningSigned}
tests := []struct {
name string
secret string
want bool
name string
sources SourceResolver
header, sig string
authenticated bool
unsigned bool
}{
{"first binding's secret", "abcdefghijklmnop", true},
{"second binding's secret", "qrstuvwxyz123456", true},
{"no binding's secret", "not-the-real-secret-aaaaaaaaa", false},
{"signed, valid hub signature", sources(signed), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
{"signed, valid fallback signature", sources(signed), "X-Signature-256", hmacSHA256(secret, body), true, false},
{"signed, wrong signature", sources(signed), "X-Hub-Signature-256", hmacSHA256("not-the-real-secret", body), false, false},
{"signed, no signature", sources(signed), "", "", false, false},
{"signed, no secret yet", sources(noSecret), "X-Hub-Signature-256", hmacSHA256("", body), false, false},
{"unsigned request not yet approved", sources(pending), "", "", false, false},
{"unsigned request not yet approved, signed event", sources(pending), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
{"approved unsigned", sources(unsigned), "", "", false, true},
{"unknown source", sources(), "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
{"lookup error fails open at capture", stubSources{err: errors.New("db locked")}, "", "", false, false},
{"no source store", nil, "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{
armedBySource: map[string][]binding.Binding{
"github": {
{ID: "rbind0000000001", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "abcdefghijklmnop"},
{ID: "rbind0000000002", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "qrstuvwxyz123456"},
},
},
}
body := `{}`
captures := &memCaptures{}
rc := &Receiver{Log: slog.New(slog.DiscardHandler), Captures: captures, Sources: tt.sources}
mux := http.NewServeMux()
rc.Register(mux)
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
req.Header.Set("X-Hub-Signature-256", hmacSHA256(tt.secret, body))
if tt.header != "" {
req.Header.Set(tt.header, tt.sig)
}
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
mux.ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
if len(captures.rows) != 1 {
t.Fatalf("captured rows = %d, want 1", len(captures.rows))
}
if len(got) != 1 || got[0].Authenticated != tt.want {
t.Fatalf("captured = %+v, want 1 row with Authenticated=%v", got, tt.want)
got := captures.rows[0]
if got.Authenticated != tt.authenticated || got.Unsigned != tt.unsigned {
t.Fatalf("authenticated, unsigned = %v, %v; want %v, %v", got.Authenticated, got.Unsigned, tt.authenticated, tt.unsigned)
}
})
}
}
// TestHandleCaptureAcceptsWhenNoArmedBindingExists documents the
// "source has never been bound" path: Bindings is wired but
// ArmedBindingsForSource returns an empty slice. The handler must
// still capture, with authenticated=false -- there is no armed binding
// to check against, so HMAC is meaningless, but the event itself is
// still worth recording for the inspector.
func TestHandleCaptureAcceptsWhenNoArmedBindingExists(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{armedBySource: map[string][]binding.Binding{}}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureAcceptsWithBindingsNil pins the legacy backwards-
// compatibility behaviour: Bindings is nil (composition never wired the
// binding surface, or the dashboard is running without the feature).
// handleCapture must behave as it did before this phase landed -- still
// capture, still record authenticated=false.
func TestHandleCaptureAcceptsWithBindingsNil(t *testing.T) {
srv := captureTestServer(t)
if srv.Bindings != nil {
t.Fatalf("captureTestServer must not wire Bindings by default for this test")
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture pins the
// documented fail-open posture: if ArmedBindingsForSource errors, the
// capture still goes through (the dispatch loop's auth check is the
// actual gate). A transient store hiccup must not amplify into a
// capture outage for sends-that-haven't-been-bound-yet.
func TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{lookupErr: errors.New("db locked")}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d (a transient lookup error must not fail closed at capture)", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureAcceptsXSignature256FallbackHeader pins the second
// header in the precedence list: when X-Hub-Signature-256 is absent but
// X-Signature-256 is present, the fallback is honoured. Mirrors
// channels/webhook/webhook.go's header precedence.
func TestHandleCaptureAcceptsXSignature256FallbackHeader(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
// No X-Hub-Signature-256; signature is in X-Signature-256 only.
req.Header.Set("X-Signature-256", hmacSHA256(secret, body))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || !got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=true (X-Signature-256 fallback must work)", got)
func sources(list ...source.Source) stubSources {
byPath := map[string]source.Source{}
for _, s := range list {
byPath[s.Path] = s
}
return stubSources{byPath: byPath}
}
@@ -2,7 +2,6 @@ package edastore
import (
"encoding/base64"
"path/filepath"
"strings"
"testing"
)
@@ -122,111 +121,6 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
}
// openWithCipher builds a store whose binding secrets are encrypted at rest.
func openWithCipher(t *testing.T, cipher BindingCipher) *Store {
t.Helper()
dir := t.TempDir()
s, err := Open(Config{
DBPath: filepath.Join(dir, "eda.sqlite"),
DataDir: filepath.Join(dir, "pb_data"),
Cipher: cipher,
})
if err != nil {
t.Fatalf("Open() error = %v", err)
}
t.Cleanup(func() { _ = s.Close() })
return s
}
func sampleBinding() bindingInput {
return bindingInput{Name: "n", Source: "sentry", Workflow: "implement", Secret: "supersecretvalue0123"}
}
// TestBindingSecretIsEncryptedAtRest pins that the plaintext secret never
// reaches the database file. Reading the column directly is the point: a
// round-trip through the store would decrypt and prove nothing.
func TestBindingSecretIsEncryptedAtRest(t *testing.T) {
cipher, err := NewBindingCipher(testBindingKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
s := openWithCipher(t, cipher)
in := sampleBinding()
id := insertBinding(t, s, in)
var stored string
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
if stored == in.Secret {
t.Fatal("secret is stored as plaintext; it must be encrypted at rest")
}
if !strings.Contains(stored, ":") {
t.Errorf("stored secret %q does not look like a cipher envelope", stored)
}
}
// TestBindingSecretDecryptsOnRead pins the other half: what was encrypted
// comes back as the original plaintext.
func TestBindingSecretDecryptsOnRead(t *testing.T) {
cipher, _ := NewBindingCipher(testBindingKey, nil)
s := openWithCipher(t, cipher)
in := sampleBinding()
id := insertBinding(t, s, in)
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if got.Secret != in.Secret {
t.Errorf("Secret = %q, want %q", got.Secret, in.Secret)
}
}
// TestNoCipherKeepsPlaintext pins the behaviour that predates encryption: a
// deployment with no configured key still works, storing plaintext.
func TestNoCipherKeepsPlaintext(t *testing.T) {
s := openWithCipher(t, nil)
in := sampleBinding()
id := insertBinding(t, s, in)
var stored string
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
if stored != in.Secret {
t.Errorf("stored secret = %q, want the plaintext %q with no cipher configured", stored, in.Secret)
}
}
// TestRotatedKeyStillReadsOldRows pins key rotation: a secret written under
// the previous key must stay readable once a new active key is installed,
// otherwise a rotation silently bricks every armed binding.
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
oldCipher, _ := NewBindingCipher(oldKey, nil)
s := openWithCipher(t, oldCipher)
in := sampleBinding()
id := insertBinding(t, s, in)
rotated, err := NewBindingCipher(testBindingKey, []string{oldKey})
if err != nil {
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
}
s.cipher = rotated
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() after rotation error = %v", err)
}
if got.Secret != in.Secret {
t.Errorf("Secret after rotation = %q, want %q: the previous key must still decrypt", got.Secret, in.Secret)
}
}
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
// fail authentication rather than return altered plaintext.
func tamperEnvelope(t *testing.T, envelope string) string {
t.Helper()
parts := strings.SplitN(envelope, ":", 4)
@@ -133,17 +133,9 @@ func (s *Store) bindingValue(r *core.Record) (binding.Binding, error) {
Repo: r.GetString("repo"),
Version: r.GetInt("version"),
Status: binding.Status(r.GetString("status")),
Secret: r.GetString("secret"),
CreatedAt: r.GetDateTime("created_at").Time(),
UpdatedAt: r.GetDateTime("updated_at").Time(),
}
if s.cipher != nil && b.Secret != "" {
plain, err := s.cipher.Decrypt(b.Secret)
if err != nil {
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
}
b.Secret = plain
}
return b, nil
}
@@ -154,20 +146,6 @@ func (s *Store) applyBinding(r *core.Record, b binding.Binding) error {
r.Set("workflow", b.Workflow)
r.Set("owner", b.Owner)
r.Set("repo", b.Repo)
// An empty secret means "keep the stored one". An edit form that does not
// echo the secret back must not silently disarm the binding by erasing it.
if b.Secret == "" {
return nil
}
secret := b.Secret
if s.cipher != nil {
encrypted, err := s.cipher.Encrypt(secret)
if err != nil {
return fmt.Errorf("edastore: encrypt binding secret: %w", err)
}
secret = encrypted
}
r.Set("secret", secret)
return nil
}
@@ -12,7 +12,6 @@ type bindingInput struct {
Name string
Source string
Workflow string
Secret string
}
func insertBinding(t *testing.T, s *Store, in bindingInput) string {
@@ -21,7 +20,6 @@ func insertBinding(t *testing.T, s *Store, in bindingInput) string {
Name: in.Name,
Matcher: binding.Matcher{Source: in.Source},
Workflow: in.Workflow,
Secret: in.Secret,
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
@@ -284,6 +284,13 @@ func importInto(ctx context.Context, tx pgx.Tx, present []domain, sources map[st
return Report{}, err
}
}
// Sources are derived, not imported: the migration derived them from an
// empty target, so derive again from what was just loaded.
if sources["eda"] != nil {
if err := postgresdb.New(tx).DeriveSources(ctx); err != nil {
return Report{}, fmt.Errorf("legacy import: derive sources: %w", err)
}
}
if gw := sources["gateway"]; gw != nil {
var err error
if report.UnindexedMessages, err = unindexedMessages(ctx, gw, loaded); err != nil {
@@ -281,7 +281,7 @@ func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
}{
{"SELECT review_cursor FROM tasks WHERE id = 1", &reviewCursor},
{"SELECT value FROM resource_history WHERE id = 1", &value},
{"SELECT secret FROM bindings WHERE id = 'rbind1'", &gotSecret},
{"SELECT secret FROM sources WHERE path = 'gh'", &gotSecret},
{"SELECT headers FROM captures WHERE id = 'rcap2'", &headers},
{"SELECT result FROM tool_calls WHERE id = 'rtool1'", &result},
{"SELECT configured FROM channel_status WHERE id = 'tg'", &configured},
+6 -4
View File
@@ -24,14 +24,16 @@ var droppedColumns = map[string]bool{
}
// newColumns are target columns added after the legacy stores, with no
// legacy value to carry. Imported rows take the column default: an imported
// capture has no event type, so it stays unidentified and never dispatches;
// an imported mapping has no event type, so no binding using it dispatches
// until it is given one; an imported binding has no filter.
// legacy value to carry; an imported row takes the column default. An
// imported capture has no event type, so it stays unidentified and never
// dispatches, and no legacy source could take unsigned events. An imported
// mapping has no event type, so no binding using it dispatches until it is
// given one, and an imported binding has no filter.
var newColumns = map[string]bool{
"captures.event_type": true,
"mappings.event_type": true,
"bindings.filter": true,
"captures.unsigned": true,
}
// targetKeys override a table's legacy key where the target has no column
+11 -58
View File
@@ -45,7 +45,7 @@ type EDA struct {
notify func(events.Event)
}
// NewEDA builds an EDA store over pool. A nil cipher keeps binding secrets in
// NewEDA builds an EDA store over pool. A nil cipher keeps source secrets in
// plaintext (the behaviour that predates the option); the caller resolves the
// keyring through edastore.NewBindingCipher, exactly as the PocketBase store
// does. The pool is owned by the caller, not this store.
@@ -99,6 +99,7 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent,
Headers: c.Headers,
Body: c.Body,
Authenticated: c.Authenticated,
Unsigned: c.Unsigned,
ReceivedAt: received.UTC(),
EventType: eventType,
}); err != nil {
@@ -135,6 +136,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
Body: r.Body,
Authenticated: r.Authenticated,
EventType: r.EventType,
Unsigned: r.Unsigned,
}
}
@@ -304,19 +306,10 @@ func (s *EDA) RecordMappingMatch(ctx context.Context, mappingID, captureID strin
// --- bindings ---
func (s *EDA) encryptSecret(secret string) (string, error) {
if s.cipher == nil {
return secret, nil
}
encrypted, err := s.cipher.Encrypt(secret)
if err != nil {
return "", fmt.Errorf("edastore: encrypt binding secret: %w", err)
}
return encrypted, nil
}
func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
b := binding.Binding{
// bindingValue takes GetBindingRow; the list queries' rows share its fields
// and convert to it.
func bindingValue(r postgresdb.GetBindingRow) binding.Binding {
return binding.Binding{
ID: r.ID,
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
@@ -327,31 +320,14 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
Repo: r.Repo,
Version: int(r.Version),
Status: binding.Status(r.Status),
Secret: r.Secret,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}
if s.cipher != nil && b.Secret != "" {
plain, err := s.cipher.Decrypt(b.Secret)
if err != nil {
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
}
b.Secret = plain
}
return b, nil
}
// InsertBinding stores a new binding as pending_approval. Any number of
// bindings may share a source.
func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
secret := b.Secret
if secret != "" {
var err error
secret, err = s.encryptSecret(secret)
if err != nil {
return "", err
}
}
id := newRecordID()
err := s.q.InsertBinding(ctx, postgresdb.InsertBindingParams{
ID: id,
@@ -363,7 +339,6 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if err != nil {
return "", fmt.Errorf("edastore: insert binding: %w", err)
@@ -382,10 +357,7 @@ func (s *EDA) GetBinding(ctx context.Context, id string) (*binding.Binding, erro
if err != nil {
return nil, err
}
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
b := bindingValue(r)
return &b, nil
}
@@ -396,11 +368,7 @@ func (s *EDA) ListBindings(ctx context.Context) ([]binding.Binding, error) {
}
out := make([]binding.Binding, 0, len(rows))
for _, r := range rows {
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
out = append(out, b)
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
}
return out, nil
}
@@ -413,28 +381,14 @@ func (s *EDA) ArmedBindingsForSource(ctx context.Context, source string) ([]bind
}
out := make([]binding.Binding, 0, len(rows))
for _, r := range rows {
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
out = append(out, b)
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
}
return out, nil
}
// UpdateBinding rewrites a binding's editable fields, bumps its version and
// drops it back to pending_approval. An empty secret means "keep the stored
// one" (the CASE in the query), so an edit form that does not echo the secret
// cannot blank an armed binding's HMAC key.
// drops it back to pending_approval.
func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
secret := b.Secret
if secret != "" {
var err error
secret, err = s.encryptSecret(secret)
if err != nil {
return err
}
}
n, err := s.q.UpdateBinding(ctx, postgresdb.UpdateBindingParams{
ID: b.ID,
Name: b.Name,
@@ -445,7 +399,6 @@ func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if err != nil {
return err
@@ -91,79 +91,6 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) {
}
}
// Hazard 1: UpdateBinding with an empty secret must leave the stored envelope
// untouched, so an edit form that does not echo the secret cannot blank an
// armed binding's HMAC key.
func TestUpdateBindingEmptySecretPreservesStored(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
secretID, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "implement",
Secret: "supersecretvalue0123",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
before := readRawSecret(t, pool, secretID)
// Edit with an empty secret: the stored envelope must not change.
if err := s.UpdateBinding(t.Context(), binding.Binding{
ID: secretID, Name: "renamed", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "escalate",
}); err != nil {
t.Fatalf("UpdateBinding() error = %v", err)
}
after := readRawSecret(t, pool, secretID)
if after != before {
t.Fatalf("stored secret changed on empty-secret edit: %q -> %q", before, after)
}
if after == "" {
t.Fatal("stored secret is empty after an empty-secret edit; the binding was silently disarmed")
}
}
func readRawSecret(t *testing.T, pool *pgxpool.Pool, id string) string {
t.Helper()
var stored string
if err := pool.QueryRow(t.Context(), "SELECT secret FROM bindings WHERE id = $1", id).Scan(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
return stored
}
// The cipher path must keep decrypt-in-store: what is stored is an envelope,
// what reads back is the plaintext HMAC key the intake verifies with.
func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
id, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "src-cipher"}, Workflow: "implement",
Secret: "supersecretvalue0123",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
stored := readRawSecret(t, pool, id)
if stored == "supersecretvalue0123" {
t.Fatal("secret is stored plaintext; it must be encrypted at rest")
}
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if got.Secret != "supersecretvalue0123" {
t.Errorf("Secret = %q, want the plaintext on read: the wire carries plaintext, so decrypt must happen in the store", got.Secret)
}
}
// The lifecycle gate survives the port: pending_approval -> armed, and only
// from pending_approval.
func TestBindingLifecycle(t *testing.T) {
@@ -0,0 +1,50 @@
-- Capture sources own signing (docs/prds/event-automation.md "Sources").
--
-- * path is the key. It is the URL segment a sender posts to and the string
-- captures.source and bindings.source already carry, so existing rows keep
-- resolving without a rewrite. It never changes after creation.
-- * signing is signed by default. Turning it off is a request
-- (unsigned_pending_approval) that only an approval makes effective.
-- * secret holds the cipher envelope when a bindings encryption key is
-- configured, plaintext otherwise, exactly as bindings.secret did.
-- * captures.unsigned marks an event taken on an approved unsigned source.
-- * bindings.secret is no longer read. It stays so the one-time legacy
-- import can load it and derive_sources can move it onto the source.
--
-- derive_sources creates a source for every source string bindings and
-- captures already use. A bound source takes its binding's secret (one binding
-- per source is schema-enforced), so a signed sender keeps authenticating. A
-- capture-only source gets no secret and dispatches nothing until the
-- operator generates one. The legacy import calls it again after loading.
-- +goose Up
CREATE TABLE sources (
path text PRIMARY KEY,
signing text NOT NULL DEFAULT 'signed'
CHECK (signing IN ('signed', 'unsigned_pending_approval', 'unsigned')),
secret text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE captures ADD COLUMN unsigned boolean NOT NULL DEFAULT false;
-- +goose StatementBegin
CREATE FUNCTION derive_sources() RETURNS void LANGUAGE sql AS $$
INSERT INTO sources (path, secret)
SELECT source, secret FROM bindings WHERE source <> ''
ON CONFLICT (path) DO NOTHING;
INSERT INTO sources (path)
SELECT DISTINCT source FROM captures WHERE source <> ''
ON CONFLICT (path) DO NOTHING;
$$;
-- +goose StatementEnd
SELECT derive_sources();
-- +goose Down
DROP FUNCTION derive_sources();
ALTER TABLE captures DROP COLUMN unsigned;
DROP TABLE sources;
@@ -11,19 +11,34 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
`
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]Binding, error) {
type ArmedBindingsForSourceRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) {
rows, err := q.db.Query(ctx, armedBindingsForSource, source)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Binding
var items []ArmedBindingsForSourceRow
for rows.Next() {
var i Binding
var i ArmedBindingsForSourceRow
if err := rows.Scan(
&i.ID,
&i.Name,
@@ -34,7 +49,6 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
@@ -114,6 +128,15 @@ func (q *Queries) DeletePlaybookDispatches(ctx context.Context, playbookID strin
return err
}
const deriveSources = `-- name: DeriveSources :exec
SELECT derive_sources()
`
func (q *Queries) DeriveSources(ctx context.Context) error {
_, err := q.db.Exec(ctx, deriveSources)
return err
}
const eventTypesForSource = `-- name: EventTypesForSource :many
SELECT id, source, name, rule, schema, created_at, updated_at
FROM event_types WHERE source = $1 ORDER BY name
@@ -148,13 +171,28 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE id = $1
`
func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
type GetBindingRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) {
row := q.db.QueryRow(ctx, getBinding, id)
var i Binding
var i GetBindingRow
err := row.Scan(
&i.ID,
&i.Name,
@@ -165,7 +203,6 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
@@ -223,9 +260,26 @@ func (q *Queries) GetMapping(ctx context.Context, id string) (GetMappingRow, err
return i, err
}
const getSource = `-- name: GetSource :one
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1
`
func (q *Queries) GetSource(ctx context.Context, path string) (Source, error) {
row := q.db.QueryRow(ctx, getSource, path)
var i Source
err := row.Scan(
&i.Path,
&i.Signing,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertBinding = `-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10)
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)
`
type InsertBindingParams struct {
@@ -238,7 +292,6 @@ type InsertBindingParams struct {
Owner string
Repo string
Status string
Secret string
}
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
@@ -252,7 +305,6 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
arg.Owner,
arg.Repo,
arg.Status,
arg.Secret,
)
return err
}
@@ -281,8 +333,8 @@ func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDi
const insertCapture = `-- name: InsertCapture :exec
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
`
type InsertCaptureParams struct {
@@ -294,6 +346,7 @@ type InsertCaptureParams struct {
Body string
Authenticated bool
ReceivedAt time.Time
Unsigned bool
EventType string
}
@@ -308,6 +361,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
arg.Body,
arg.Authenticated,
arg.ReceivedAt,
arg.Unsigned,
arg.EventType,
)
return err
@@ -398,6 +452,21 @@ func (q *Queries) InsertPlaybookDispatch(ctx context.Context, arg InsertPlaybook
return err
}
const insertSource = `-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3)
`
type InsertSourceParams struct {
Path string
Signing string
Secret string
}
func (q *Queries) InsertSource(ctx context.Context, arg InsertSourceParams) error {
_, err := q.db.Exec(ctx, insertSource, arg.Path, arg.Signing, arg.Secret)
return err
}
const insertToolCall = `-- name: InsertToolCall :exec
INSERT INTO tool_calls (id, task_id, attempt, tool, result, error, called_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -427,19 +496,34 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC
`
func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
type ListBindingsRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
rows, err := q.db.Query(ctx, listBindings)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Binding
var items []ListBindingsRow
for rows.Next() {
var i Binding
var i ListBindingsRow
if err := rows.Scan(
&i.ID,
&i.Name,
@@ -450,7 +534,6 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
@@ -466,7 +549,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
}
const listCaptures = `-- name: ListCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
ORDER BY received_at DESC
LIMIT $1
@@ -490,6 +573,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
&i.EventType,
); err != nil {
return nil, err
@@ -578,8 +662,38 @@ func (q *Queries) ListMappings(ctx context.Context) ([]ListMappingsRow, error) {
return items, nil
}
const listSources = `-- name: ListSources :many
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path
`
func (q *Queries) ListSources(ctx context.Context) ([]Source, error) {
rows, err := q.db.Query(ctx, listSources)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Source
for rows.Next() {
var i Source
if err := rows.Scan(
&i.Path,
&i.Signing,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.event_type
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
FROM captures c
WHERE c.source = ANY($1::text[])
AND c.event_type <> ''
@@ -618,6 +732,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
&i.EventType,
); err != nil {
return nil, err
@@ -653,6 +768,53 @@ func (q *Queries) SetBindingArmed(ctx context.Context, id string) (int64, error)
return result.RowsAffected(), nil
}
const setSourceSecret = `-- name: SetSourceSecret :execrows
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1
`
type SetSourceSecretParams struct {
Path string
Secret string
}
func (q *Queries) SetSourceSecret(ctx context.Context, arg SetSourceSecretParams) (int64, error) {
result, err := q.db.Exec(ctx, setSourceSecret, arg.Path, arg.Secret)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setSourceSigning = `-- name: SetSourceSigning :execrows
UPDATE sources SET signing = $1, updated_at = now()
WHERE path = $2 AND signing = $3
`
type SetSourceSigningParams struct {
ToSigning string
Path string
FromSigning string
}
func (q *Queries) SetSourceSigning(ctx context.Context, arg SetSourceSigningParams) (int64, error) {
result, err := q.db.Exec(ctx, setSourceSigning, arg.ToSigning, arg.Path, arg.FromSigning)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const sourceExists = `-- name: SourceExists :one
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1)
`
func (q *Queries) SourceExists(ctx context.Context, path string) (bool, error) {
row := q.db.QueryRow(ctx, sourceExists, path)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const taskToolCalls = `-- name: TaskToolCalls :many
SELECT id, task_id, attempt, tool, result, error, called_at
FROM tool_calls WHERE task_id = $1 ORDER BY called_at ASC
@@ -699,9 +861,7 @@ func (q *Queries) TaskToolCalls(ctx context.Context, taskID int64) ([]TaskToolCa
const updateBinding = `-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9,
secret = CASE WHEN $10::text = '' THEN secret ELSE $10 END,
updated_at = now()
version = version + 1, status = $9, updated_at = now()
WHERE id = $1
`
@@ -715,12 +875,8 @@ type UpdateBindingParams struct {
Owner string
Repo string
Status string
Secret string
}
// An empty secret means "keep the stored one": the CASE leaves the column
// untouched so an edit form that does not echo the secret cannot blank an
// armed binding's HMAC key.
func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (int64, error) {
result, err := q.db.Exec(ctx, updateBinding,
arg.ID,
@@ -732,7 +888,6 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
arg.Owner,
arg.Repo,
arg.Status,
arg.Secret,
)
if err != nil {
return 0, err
@@ -49,6 +49,7 @@ type Capture struct {
Body string
Authenticated bool
ReceivedAt time.Time
Unsigned bool
EventType string
}
@@ -208,6 +209,14 @@ type Session struct {
LastActiveAt int64
}
type Source struct {
Path string
Signing string
Secret string
CreatedAt time.Time
UpdatedAt time.Time
}
type Task struct {
ID int64
Owner string
@@ -1,11 +1,11 @@
-- EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
-- name: InsertCapture :exec
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
-- name: ListCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
ORDER BY received_at DESC
LIMIT $1;
@@ -14,7 +14,7 @@ LIMIT $1;
-- A capture is undispatched while some armed binding on its source, whose
-- mapping belongs to the capture's event type, has not dispatched it. An
-- unidentified capture has no event type, so it is never listed.
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.event_type
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
FROM captures c
WHERE c.source = ANY(@sources::text[])
AND c.event_type <> ''
@@ -63,30 +63,25 @@ ON CONFLICT DO NOTHING;
DELETE FROM mappings WHERE id = $1;
-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10);
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9);
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE id = $1;
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
-- An empty secret means "keep the stored one": the CASE leaves the column
-- untouched so an edit form that does not echo the secret cannot blank an
-- armed binding's HMAC key.
UPDATE bindings
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9,
secret = CASE WHEN sqlc.arg(secret)::text = '' THEN secret ELSE sqlc.arg(secret) END,
updated_at = now()
version = version + 1, status = $9, updated_at = now()
WHERE id = $1;
-- name: SetBindingArmed :execrows
@@ -140,3 +135,24 @@ DELETE FROM event_types WHERE id = $1;
-- Serialises saves per source so two concurrent saves cannot each pass the
-- overlap check against a set that excludes the other.
SELECT pg_advisory_xact_lock(hashtext('event_types:' || sqlc.arg(source)::text));
-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3);
-- name: GetSource :one
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1;
-- name: ListSources :many
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path;
-- name: SetSourceSigning :execrows
UPDATE sources SET signing = sqlc.arg(to_signing), updated_at = now()
WHERE path = sqlc.arg(path) AND signing = sqlc.arg(from_signing);
-- name: SetSourceSecret :execrows
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1;
-- name: SourceExists :one
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1);
-- name: DeriveSources :exec
SELECT derive_sources();
+130
View File
@@ -0,0 +1,130 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.SourceStore = (*EDA)(nil)
// InsertSource stores a new source. The path is the primary key, so a taken
// path is refused by the database and surfaced as ErrSourcePathTaken.
func (s *EDA) InsertSource(ctx context.Context, src source.Source) error {
secret, err := s.sealSecret(src.Secret)
if err != nil {
return err
}
err = s.q.InsertSource(ctx, postgresdb.InsertSourceParams{
Path: src.Path, Signing: string(src.Signing), Secret: secret,
})
if isUniqueViolation(err) {
return storecontract.ErrSourcePathTaken
}
if err != nil {
return fmt.Errorf("edastore: insert source: %w", err)
}
return nil
}
// GetSource returns (nil, nil) for an unknown path.
func (s *EDA) GetSource(ctx context.Context, path string) (*source.Source, error) {
r, err := s.q.GetSource(ctx, path)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("edastore: get source: %w", err)
}
src, err := s.sourceValue(r)
if err != nil {
return nil, err
}
return &src, nil
}
func (s *EDA) ListSources(ctx context.Context) ([]source.Source, error) {
rows, err := s.q.ListSources(ctx)
if err != nil {
return nil, fmt.Errorf("edastore: list sources: %w", err)
}
out := make([]source.Source, 0, len(rows))
for _, r := range rows {
src, err := s.sourceValue(r)
if err != nil {
return nil, err
}
out = append(out, src)
}
return out, nil
}
// SetSourceSigning moves a source from one signing state to another, and
// refuses when the stored state is no longer from.
func (s *EDA) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
n, err := s.q.SetSourceSigning(ctx, postgresdb.SetSourceSigningParams{
Path: path, FromSigning: string(from), ToSigning: string(to),
})
if err != nil {
return fmt.Errorf("edastore: set source signing: %w", err)
}
if n == 1 {
return nil
}
exists, err := s.q.SourceExists(ctx, path)
if err != nil {
return fmt.Errorf("edastore: set source signing: %w", err)
}
if !exists {
return storecontract.ErrSourceNotFound
}
return storecontract.ErrSourceSigningStale
}
func (s *EDA) SetSourceSecret(ctx context.Context, path, secret string) error {
sealed, err := s.sealSecret(secret)
if err != nil {
return err
}
n, err := s.q.SetSourceSecret(ctx, postgresdb.SetSourceSecretParams{Path: path, Secret: sealed})
if err != nil {
return fmt.Errorf("edastore: set source secret: %w", err)
}
if n == 0 {
return storecontract.ErrSourceNotFound
}
return nil
}
// sealSecret encrypts a non-empty secret when a cipher is configured.
func (s *EDA) sealSecret(secret string) (string, error) {
if s.cipher == nil || secret == "" {
return secret, nil
}
sealed, err := s.cipher.Encrypt(secret)
if err != nil {
return "", fmt.Errorf("edastore: encrypt source secret: %w", err)
}
return sealed, nil
}
func (s *EDA) sourceValue(r postgresdb.Source) (source.Source, error) {
secret := r.Secret
if s.cipher != nil && secret != "" {
plain, err := s.cipher.Decrypt(secret)
if err != nil {
return source.Source{}, fmt.Errorf("edastore: decrypt source secret: %w", err)
}
secret = plain
}
return source.Source{
Path: r.Path, Signing: source.Signing(r.Signing), Secret: secret,
CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -0,0 +1,169 @@
package postgres
import (
"errors"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
)
func readRawSourceSecret(t *testing.T, pool *pgxpool.Pool, path string) string {
t.Helper()
var stored string
if err := pool.QueryRow(t.Context(), "SELECT secret FROM sources WHERE path = $1", path).Scan(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
return stored
}
// A new source keeps its generated path, is signed, stores its secret as a
// cipher envelope and reads it back as plaintext.
func TestSourceRoundTripEncryptsSecret(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
in, err := source.New("")
if err != nil {
t.Fatalf("source.New() error = %v", err)
}
if err := s.InsertSource(t.Context(), in); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
if raw := readRawSourceSecret(t, pool, in.Path); raw == in.Secret || raw == "" {
t.Fatalf("stored secret = %q, want a cipher envelope", raw)
}
got, err := s.GetSource(t.Context(), in.Path)
if err != nil || got == nil {
t.Fatalf("GetSource() = %v, %v", got, err)
}
if got.Path != in.Path || got.Signing != source.SigningSigned || got.Secret != in.Secret {
t.Fatalf("GetSource() = %+v, want path %q signed with the plaintext secret", got, in.Path)
}
list, err := s.ListSources(t.Context())
if err != nil || len(list) != 1 || list[0].Secret != in.Secret {
t.Fatalf("ListSources() = %+v, %v", list, err)
}
}
func TestSourceWritesRefuseBadState(t *testing.T) {
s := edaFor(t)
taken := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k"}
if err := s.InsertSource(t.Context(), taken); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
tests := []struct {
name string
write func() error
want error
}{
{"taken custom path", func() error { return s.InsertSource(t.Context(), taken) }, storecontract.ErrSourcePathTaken},
{"stale signing", func() error {
return s.SetSourceSigning(t.Context(), "sentry", source.SigningUnsignedPending, source.SigningUnsigned)
}, storecontract.ErrSourceSigningStale},
{"signing on unknown path", func() error {
return s.SetSourceSigning(t.Context(), "nope", source.SigningSigned, source.SigningUnsignedPending)
}, storecontract.ErrSourceNotFound},
{"secret on unknown path", func() error { return s.SetSourceSecret(t.Context(), "nope", "k") }, storecontract.ErrSourceNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.write(); !errors.Is(err, tt.want) {
t.Fatalf("error = %v, want %v", err, tt.want)
}
})
}
got, err := s.GetSource(t.Context(), "nope")
if err != nil || got != nil {
t.Fatalf("GetSource(unknown) = %v, %v; want nil, nil", got, err)
}
}
func TestSourceSigningAndSecretWrites(t *testing.T) {
s := edaFor(t)
if err := s.InsertSource(t.Context(), source.Source{Path: "fw", Signing: source.SigningSigned}); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
if err := s.SetSourceSigning(t.Context(), "fw", source.SigningSigned, source.SigningUnsignedPending); err != nil {
t.Fatalf("SetSourceSigning() error = %v", err)
}
if err := s.SetSourceSecret(t.Context(), "fw", "newsecret"); err != nil {
t.Fatalf("SetSourceSecret() error = %v", err)
}
got, err := s.GetSource(t.Context(), "fw")
if err != nil || got.Signing != source.SigningUnsignedPending || got.Secret != "newsecret" {
t.Fatalf("GetSource() = %+v, %v", got, err)
}
}
func TestCaptureUnsignedRoundTrip(t *testing.T) {
s := edaFor(t)
// Only an identified capture with an armed binding for its type is listed
// for dispatch; a catch-all type identifies every event on the source.
etID, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"})
if err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: etID})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
armedBinding(t, s, "fw", mid)
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
for name, list := range map[string]func() ([]storecontract.CapturedEvent, error){
"ListCaptures": func() ([]storecontract.CapturedEvent, error) { return s.ListCaptures(t.Context(), 10) },
"ListUndispatchedCaptures": func() ([]storecontract.CapturedEvent, error) {
return s.ListUndispatchedCaptures(t.Context(), []string{"fw"}, 10)
},
} {
got, err := list()
if err != nil || len(got) != 1 || !got[0].Unsigned {
t.Errorf("%s() = %+v, %v; want one unsigned capture", name, got, err)
}
}
}
// Existing source strings become sources: a bound source takes its binding's
// secret, a capture-only source gets none, and an existing source is kept.
func TestDeriveSourcesFromExistingRows(t *testing.T) {
pool, q := migrated(t)
ctx := t.Context()
for _, stmt := range []string{
`INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'n', 'sentry', 'envelope')`,
`INSERT INTO captures (id, source, received_at) VALUES ('c1', 'sentry', now()), ('c2', 'firewall', now()), ('c3', 'kept', now())`,
`INSERT INTO sources (path, signing, secret) VALUES ('kept', 'unsigned', 'x')`,
} {
if _, err := pool.Exec(ctx, stmt); err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
if err := q.DeriveSources(ctx); err != nil {
t.Fatalf("DeriveSources() error = %v", err)
}
want := map[string][2]string{
"sentry": {"signed", "envelope"},
"firewall": {"signed", ""},
"kept": {"unsigned", "x"},
}
rows, err := q.ListSources(ctx)
if err != nil {
t.Fatalf("ListSources() error = %v", err)
}
if len(rows) != len(want) {
t.Fatalf("derived %d sources, want %d: %+v", len(rows), len(want), rows)
}
for _, r := range rows {
if w := want[r.Path]; w != [2]string{r.Signing, r.Secret} {
t.Errorf("source %q = (%s, %q), want %v", r.Path, r.Signing, r.Secret, w)
}
}
}
@@ -33,14 +33,14 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
// public draft -> pending_approval -> armed lifecycle.
id, err := eda.InsertBinding(t.Context(), binding.Binding{
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatal(err)
}
if err := eda.UpdateBinding(t.Context(), binding.Binding{
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
}); err != nil {
t.Fatal(err)
}
@@ -13,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
@@ -47,6 +48,7 @@ var (
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
_ storecontract.SourceStore = (*Client)(nil)
_ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.MappingMatchRecorder = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil)
@@ -466,6 +468,43 @@ func (c *Client) ApproveBinding(ctx context.Context, id string) error {
return unmapError(err)
}
// Source
func (c *Client) InsertSource(ctx context.Context, s source.Source) error {
_, err := c.client.InsertSource(ctx, &pb.InsertSourceRequest{Source: sourceProto(s)})
return unmapError(err)
}
func (c *Client) GetSource(ctx context.Context, path string) (*source.Source, error) {
r, err := c.client.GetSource(ctx, &pb.GetSourceRequest{Path: path})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
v := sourceValue(r.Source)
return &v, nil
}
func (c *Client) ListSources(ctx context.Context) ([]source.Source, error) {
r, err := c.client.ListSources(ctx, &pb.ListSourcesRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Sources, sourceValue), nil
}
func (c *Client) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
_, err := c.client.SetSourceSigning(ctx, &pb.SetSourceSigningRequest{Path: path, From: string(from), To: string(to)})
return unmapError(err)
}
func (c *Client) SetSourceSecret(ctx context.Context, path, secret string) error {
_, err := c.client.SetSourceSecret(ctx, &pb.SetSourceSecretRequest{Path: path, Secret: secret})
return unmapError(err)
}
// Dispatch
func (c *Client) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) {
@@ -384,14 +384,14 @@ func TestStateStoreConformance(t *testing.T) {
// ErrAlreadyDispatched.
bindingID, err := ec.InsertBinding(ctx, binding.Binding{
Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
Workflow: "implement",
})
if err != nil || bindingID == "" {
t.Fatalf("InsertBinding: %v %v", bindingID, err)
}
_, err = ec.InsertBinding(ctx, binding.Binding{
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
Workflow: "implement",
})
if !errors.Is(err, store.ErrBindingOverlap) {
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
@@ -9,6 +9,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -81,6 +82,9 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
{name: "binding overlap", store: store.ErrBindingOverlap, rehyd: store.ErrBindingOverlap},
{name: "binding transition", store: store.ErrBindingTransition, rehyd: store.ErrBindingTransition},
{name: "already dispatched", store: store.ErrAlreadyDispatched, rehyd: store.ErrAlreadyDispatched},
{name: "source not found", store: storecontract.ErrSourceNotFound, rehyd: storecontract.ErrSourceNotFound},
{name: "source path taken", store: storecontract.ErrSourcePathTaken, rehyd: storecontract.ErrSourcePathTaken},
{name: "source signing stale", store: storecontract.ErrSourceSigningStale, rehyd: storecontract.ErrSourceSigningStale},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/logging"
)
@@ -35,6 +36,7 @@ var (
errApplyStatusUnavailable = status.Error(codes.Unavailable, "apply status store unavailable")
errMappingUnavailable = status.Error(codes.Unavailable, "mapping store unavailable")
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
errSourceUnavailable = status.Error(codes.Unavailable, "source store unavailable")
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
errPlaybookDispatcherUnavailable = status.Error(codes.Unavailable, "playbook dispatcher unavailable")
@@ -81,6 +83,7 @@ type Deps struct {
// answers RecordMappingMatch with codes.Unavailable.
MappingMatches storecontract.MappingMatchRecorder
Bindings storecontract.BindingStore
Sources storecontract.SourceStore
BindingDispatcher storecontract.BindingDispatcher
BindingTaskCreator storecontract.BindingTaskCreator
// PlaybookDispatcher is the side-effecting-action idempotency ledger
@@ -660,6 +663,75 @@ func (s *server) ApproveBinding(ctx context.Context, r *pb.ApproveBindingRequest
return &pb.ApproveBindingResponse{}, nil
}
// Source
func (s *server) sources() (storecontract.SourceStore, error) {
if s.deps.Sources == nil {
return nil, errSourceUnavailable
}
return s.deps.Sources, nil
}
func (s *server) InsertSource(ctx context.Context, r *pb.InsertSourceRequest) (*pb.InsertSourceResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.InsertSource(ctx, sourceValue(r.Source)); err != nil {
return nil, s.logErr("InsertSource", err)
}
return &pb.InsertSourceResponse{}, nil
}
func (s *server) GetSource(ctx context.Context, r *pb.GetSourceRequest) (*pb.GetSourceResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
src, err := ss.GetSource(ctx, r.Path)
if err != nil {
return nil, s.logErr("GetSource", err)
}
if src == nil {
return &pb.GetSourceResponse{}, nil
}
return &pb.GetSourceResponse{Source: sourceProto(*src), Found: true}, nil
}
func (s *server) ListSources(ctx context.Context, _ *pb.ListSourcesRequest) (*pb.ListSourcesResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
list, err := ss.ListSources(ctx)
if err != nil {
return nil, s.logErr("ListSources", err)
}
return &pb.ListSourcesResponse{Sources: mapValues(list, sourceProto)}, nil
}
func (s *server) SetSourceSigning(ctx context.Context, r *pb.SetSourceSigningRequest) (*pb.SetSourceSigningResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.SetSourceSigning(ctx, r.Path, source.Signing(r.From), source.Signing(r.To)); err != nil {
return nil, s.logErr("SetSourceSigning", err)
}
return &pb.SetSourceSigningResponse{}, nil
}
func (s *server) SetSourceSecret(ctx context.Context, r *pb.SetSourceSecretRequest) (*pb.SetSourceSecretResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.SetSourceSecret(ctx, r.Path, r.Secret); err != nil {
return nil, s.logErr("SetSourceSecret", err)
}
return &pb.SetSourceSecretResponse{}, nil
}
// Dispatch
func (s *server) ArmedBindingsForSource(ctx context.Context, r *pb.ArmedBindingsForSourceRequest) (*pb.ArmedBindingsForSourceResponse, error) {
@@ -0,0 +1,147 @@
package staterpc
import (
"context"
"errors"
"net"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// memSources is an in-memory SourceStore with the Postgres store's error
// contract, so the wire test checks the adapter rather than a database.
type memSources map[string]source.Source
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
if _, ok := m[s.Path]; ok {
return storecontract.ErrSourcePathTaken
}
m[s.Path] = s
return nil
}
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
s, ok := m[path]
if !ok {
return nil, nil
}
return &s, nil
}
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
out := make([]source.Source, 0, len(m))
for _, s := range m {
out = append(out, s)
}
return out, nil
}
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
s, ok := m[path]
switch {
case !ok:
return storecontract.ErrSourceNotFound
case s.Signing != from:
return storecontract.ErrSourceSigningStale
}
s.Signing = to
m[path] = s
return nil
}
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
s, ok := m[path]
if !ok {
return storecontract.ErrSourceNotFound
}
s.Secret = secret
m[path] = s
return nil
}
func remoteSources(t *testing.T, sources storecontract.SourceStore) *Client {
t.Helper()
listener := bufconn.Listen(1 << 20)
server := grpc.NewServer()
RegisterServer(server, Deps{Sources: sources})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
conn, err := grpc.NewClient("passthrough:///state",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return NewClient(conn)
}
func TestSourceStoreOverTheWire(t *testing.T) {
ctx := t.Context()
c := remoteSources(t, memSources{})
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
in := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k", CreatedAt: stamp, UpdatedAt: stamp}
if err := c.InsertSource(ctx, in); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
got, err := c.GetSource(ctx, "sentry")
if err != nil || got == nil || *got != in {
t.Fatalf("GetSource() = %+v, %v; want %+v", got, err, in)
}
if missing, err := c.GetSource(ctx, "nope"); err != nil || missing != nil {
t.Fatalf("GetSource(unknown) = %+v, %v; want nil, nil", missing, err)
}
if err := c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsignedPending); err != nil {
t.Fatalf("SetSourceSigning() error = %v", err)
}
if err := c.SetSourceSecret(ctx, "sentry", "k2"); err != nil {
t.Fatalf("SetSourceSecret() error = %v", err)
}
list, err := c.ListSources(ctx)
if err != nil || len(list) != 1 || list[0].Signing != source.SigningUnsignedPending || list[0].Secret != "k2" {
t.Fatalf("ListSources() = %+v, %v", list, err)
}
errs := []struct {
name string
call func() error
want error
}{
{"taken path", func() error { return c.InsertSource(ctx, in) }, storecontract.ErrSourcePathTaken},
{"stale signing", func() error {
return c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsigned)
}, storecontract.ErrSourceSigningStale},
{"unknown path", func() error { return c.SetSourceSecret(ctx, "nope", "k") }, storecontract.ErrSourceNotFound},
}
for _, tt := range errs {
t.Run(tt.name, func(t *testing.T) {
if err := tt.call(); !errors.Is(err, tt.want) {
t.Fatalf("error = %v, want %v", err, tt.want)
}
})
}
}
func TestSourceStoreUnavailableWithoutBackend(t *testing.T) {
c := remoteSources(t, nil)
_, err := c.ListSources(t.Context())
if status.Code(err) != codes.Unavailable {
t.Fatalf("ListSources() with no backend = %v, want Unavailable", err)
}
}
func TestCapturedEventUnsignedSurvivesTheWire(t *testing.T) {
in := storecontract.CapturedEvent{ID: "c", Source: "fw", Unsigned: true}
if got := capturedEventValue(capturedEventProto(in)); got != in {
t.Fatalf("round trip = %+v, want %+v", got, in)
}
}
@@ -97,14 +97,14 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
// public draft -> pending_approval -> armed lifecycle.
id, err := admin.InsertBinding(ctx, binding.Binding{
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatal(err)
}
if err := admin.UpdateBinding(ctx, binding.Binding{
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
}); err != nil {
t.Fatal(err)
}
+60 -36
View File
@@ -15,6 +15,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
@@ -151,6 +152,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source,
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
Unsigned: c.Unsigned,
}
}
@@ -162,6 +164,24 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source,
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
Unsigned: c.Unsigned,
}
}
func sourceProto(s source.Source) *pb.Source {
return &pb.Source{
Path: s.Path, Signing: string(s.Signing), Secret: s.Secret,
CreatedAt: timestamp(s.CreatedAt), UpdatedAt: timestamp(s.UpdatedAt),
}
}
func sourceValue(s *pb.Source) source.Source {
if s == nil {
return source.Source{}
}
return source.Source{
Path: s.Path, Signing: source.Signing(s.Signing), Secret: s.Secret,
CreatedAt: timeValue(s.CreatedAt), UpdatedAt: timeValue(s.UpdatedAt),
}
}
@@ -201,7 +221,7 @@ func bindingProto(b binding.Binding) *pb.Binding {
return &pb.Binding{
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int64(b.Version), Status: string(b.Status), Secret: b.Secret,
Version: int64(b.Version), Status: string(b.Status),
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
}
}
@@ -217,7 +237,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
return binding.Binding{
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int(b.Version), Status: binding.Status(b.Status), Secret: b.Secret,
Version: int(b.Version), Status: binding.Status(b.Status),
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
}
}
@@ -276,6 +296,9 @@ const (
msgBindingOverlap = "binding overlap"
msgBindingTransition = "binding transition rejected"
msgAlreadyDispatched = "already dispatched"
msgSourceNotFound = "source not found"
msgSourcePathTaken = "source path taken"
msgSourceSigning = "source signing stale"
msgInternal = "state store: internal error"
// msgTaskLogsUnavailable is the public phrase for "this service has no
// task-log reader". It is a wire contract like the sentinels above: the
@@ -308,28 +331,12 @@ func mapError(err error) error {
if errors.Is(err, context.DeadlineExceeded) {
return status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error())
}
switch {
case errors.Is(err, storecontract.ErrStaleTransition):
return status.Error(codes.FailedPrecondition, msgStaleTransition)
case errors.Is(err, storecontract.ErrBindingNotFound):
return status.Error(codes.NotFound, msgBindingNotFound)
case errors.Is(err, storecontract.ErrMappingNotFound):
return status.Error(codes.NotFound, msgMappingNotFound)
case errors.Is(err, storecontract.ErrEventTypeNotFound):
return status.Error(codes.NotFound, msgEventTypeNotFound)
case errors.Is(err, eventtype.ErrOverlap):
return status.Error(codes.FailedPrecondition, msgEventTypeOverlap)
case errors.Is(err, eventtype.ErrInvalid):
return status.Error(codes.InvalidArgument, msgEventTypeInvalid)
case errors.Is(err, storecontract.ErrBindingOverlap):
return status.Error(codes.FailedPrecondition, msgBindingOverlap)
case errors.Is(err, storecontract.ErrBindingTransition):
return status.Error(codes.FailedPrecondition, msgBindingTransition)
case errors.Is(err, storecontract.ErrAlreadyDispatched):
return status.Error(codes.AlreadyExists, msgAlreadyDispatched)
default:
return status.Error(codes.Internal, msgInternal)
for _, w := range wireErrors {
if errors.Is(err, w.sentinel) {
return status.Error(w.code, w.message)
}
}
return status.Error(codes.Internal, msgInternal)
}
// unmapError rehydrates a gRPC status error back to the store sentinel it
@@ -384,21 +391,38 @@ type wireStatus struct {
message string
}
// wireSentinels is the (code, canonical message) to sentinel table
// sentinelForStatus reads.
var wireSentinels = map[wireStatus]error{
{codes.FailedPrecondition, msgStaleTransition}: storecontract.ErrStaleTransition,
{codes.FailedPrecondition, msgBindingOverlap}: storecontract.ErrBindingOverlap,
{codes.FailedPrecondition, msgBindingTransition}: storecontract.ErrBindingTransition,
{codes.FailedPrecondition, msgEventTypeOverlap}: eventtype.ErrOverlap,
{codes.InvalidArgument, msgEventTypeInvalid}: eventtype.ErrInvalid,
{codes.NotFound, msgBindingNotFound}: storecontract.ErrBindingNotFound,
{codes.NotFound, msgMappingNotFound}: storecontract.ErrMappingNotFound,
{codes.NotFound, msgEventTypeNotFound}: storecontract.ErrEventTypeNotFound,
{codes.AlreadyExists, msgAlreadyDispatched}: storecontract.ErrAlreadyDispatched,
{codes.Unavailable, msgTaskLogsUnavailable}: logging.ErrTaskLogsUnavailable,
// wireErrors pairs each sentinel with its canonical (code, message). mapError
// reads it forward and sentinelForStatus backward, so the two directions
// cannot drift.
var wireErrors = []struct {
sentinel error
code codes.Code
message string
}{
{storecontract.ErrStaleTransition, codes.FailedPrecondition, msgStaleTransition},
{storecontract.ErrBindingOverlap, codes.FailedPrecondition, msgBindingOverlap},
{storecontract.ErrBindingTransition, codes.FailedPrecondition, msgBindingTransition},
{storecontract.ErrSourceSigningStale, codes.FailedPrecondition, msgSourceSigning},
{eventtype.ErrOverlap, codes.FailedPrecondition, msgEventTypeOverlap},
{eventtype.ErrInvalid, codes.InvalidArgument, msgEventTypeInvalid},
{storecontract.ErrBindingNotFound, codes.NotFound, msgBindingNotFound},
{storecontract.ErrMappingNotFound, codes.NotFound, msgMappingNotFound},
{storecontract.ErrEventTypeNotFound, codes.NotFound, msgEventTypeNotFound},
{storecontract.ErrSourceNotFound, codes.NotFound, msgSourceNotFound},
{storecontract.ErrAlreadyDispatched, codes.AlreadyExists, msgAlreadyDispatched},
{storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken},
{logging.ErrTaskLogsUnavailable, codes.Unavailable, msgTaskLogsUnavailable},
}
// wireSentinels indexes wireErrors by (code, canonical message).
var wireSentinels = func() map[wireStatus]error {
m := make(map[wireStatus]error, len(wireErrors))
for _, w := range wireErrors {
m[wireStatus{w.code, w.message}] = w.sentinel
}
return m
}()
// configSnapshotProto and configSnapshotValue carry the dashboard's
// configuration projection. document crosses as bytes, unread by either side
// of this hop: the store holds it and the page renders it.
+21 -21
View File
@@ -22,9 +22,15 @@ type bindingRequest struct {
// for multi-repo deployments. Both empty is valid (falls back to the
// daemon's single-configured-repo behaviour); binding.Validate
// rejects setting only one.
Owner string `json:"owner"`
Repo string `json:"repo"`
Secret string `json:"secret"`
Owner string `json:"owner"`
Repo string `json:"repo"`
}
// bindingView is a listed binding with its source's signing state, so the
// list can flag a binding that dispatches unsigned events.
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
}
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
@@ -38,8 +44,17 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
stripBindingSecrets(bindings)
writeJSON(w, map[string]any{"bindings": bindings})
unsigned, err := s.unsignedSources(r.Context())
if err != nil {
s.Log.Error("list sources", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source]})
}
writeJSON(w, map[string]any{"bindings": views})
}
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
@@ -72,7 +87,6 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
Secret: req.Secret,
Status: binding.StatusPendingApproval,
}
if err := b.Validate(); err != nil {
@@ -94,7 +108,6 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
created.Secret = ""
w.WriteHeader(http.StatusCreated)
writeJSON(w, created)
}
@@ -119,7 +132,6 @@ func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
b.Secret = ""
writeJSON(w, b)
}
@@ -159,9 +171,8 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
Secret: req.Secret,
}
if err := b.ValidateForUpdate(); err != nil {
if err := b.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
@@ -184,7 +195,6 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
http.Error(w, "update binding failed", http.StatusInternalServerError)
return
}
updated.Secret = ""
writeJSON(w, updated)
}
@@ -244,7 +254,6 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
http.Error(w, "approve binding failed", http.StatusInternalServerError)
return
}
updated.Secret = ""
writeJSON(w, updated)
}
@@ -271,12 +280,3 @@ func (s *Server) checkBindingFilter(w http.ResponseWriter, r *http.Request, b bi
}
return true
}
// stripBindingSecrets zeroes the Secret field on every binding in the slice
// so the list handler never leaks a shared HMAC secret through /api/bindings.
// Single-binding reads do the same inline; this covers the list path.
func stripBindingSecrets(bs []binding.Binding) {
for i := range bs {
bs[i].Secret = ""
}
}
+3 -72
View File
@@ -5,7 +5,6 @@ import (
"log/slog"
"net/http"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/binding"
@@ -52,16 +51,13 @@ func seedMapping(t *testing.T, srv *Server, name string) string {
}
// validBindingRequest returns a populated bindingRequest that passes
// binding.Validate and server-side workflow validation. The Secret is 32
// bytes (above the 16-byte floor) so length never accidentally trips
// validation in a test that isn't about secret length.
// binding.Validate and server-side workflow validation.
func validBindingRequest(suffix, source, mappingID string) map[string]any {
return map[string]any{
"name": "binding " + suffix,
"matcher": map[string]any{"source": source},
"mapping_id": mappingID,
"workflow": "implement",
"secret": "0123456789abcdef0123456789abcdef",
}
}
@@ -83,9 +79,6 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
if created.Status != binding.StatusPendingApproval {
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusPendingApproval)
}
if created.Secret != "" {
t.Fatalf("created.Secret = %q, want \"\" (response must strip secret)", created.Secret)
}
w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil)
if w.Code != http.StatusOK {
@@ -98,15 +91,12 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
if got.ID != created.ID {
t.Fatalf("got.ID = %q, want %q", got.ID, created.ID)
}
if got.Secret != "" {
t.Fatalf("get.Secret = %q, want \"\"", got.Secret)
}
}
// TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo covers the
// multi-repo fix at the API layer: a create/update request carrying
// owner/repo persists them, and they're visible in the response
// (they're not secret, unlike Secret).
// (they're not secret).
func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
@@ -159,34 +149,6 @@ func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) {
}
}
func TestHandleBindingsListStripsSecrets(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
if w.Code != http.StatusOK {
t.Fatalf("list status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
}
var body struct {
Bindings []binding.Binding `json:"bindings"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(body.Bindings) != 1 {
t.Fatalf("bindings = %d, want 1", len(body.Bindings))
}
if body.Bindings[0].Secret != "" {
t.Fatalf("listed Secret = %q, want \"\"", body.Bindings[0].Secret)
}
// Defence against accidental echo in the raw JSON: the "secret" key
// must not appear at all (the binding.Binding tag is omitempty).
if strings.Contains(w.Body.String(), `"secret"`) {
t.Fatalf("list response leaked secret key: %s", w.Body.String())
}
}
func TestHandleBindingCreateRejectsMissingWorkflow(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
@@ -203,10 +165,8 @@ func TestHandleBindingCreateRejectsValidationFailure(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
// Short secret trips binding.Validate's length floor regardless of
// any store-side check.
req := validBindingRequest("a", "sentry", mappingID)
req["secret"] = "short"
req["name"] = " "
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
@@ -260,35 +220,6 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) {
}
}
// TestHandleBindingUpdateWithEmptySecretPreservesExisting is the API-layer
// half of UpdateBinding's own documented contract ("Secret is preserved
// when the caller passes an empty string ... so a partial update cannot
// erase the HMAC secret"): an edit that never touches the secret field
// must not be rejected by Validate's create-time secret-length floor,
// since nothing about the existing secret is changing.
func TestHandleBindingUpdateWithEmptySecretPreservesExisting(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
var created binding.Binding
_ = json.Unmarshal(w.Body.Bytes(), &created)
update := validBindingRequest("renamed", "sentry", mappingID)
update["secret"] = ""
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update)
if w.Code != http.StatusOK {
t.Fatalf("patch status = %d, want %d (empty secret must mean 'keep existing', not fail validation); body = %s", w.Code, http.StatusOK, w.Body.String())
}
stored, err := srv.Bindings.GetBinding(t.Context(), created.ID)
if err != nil || stored == nil {
t.Fatalf("GetBinding: %+v, %v", stored, err)
}
if stored.Secret != "0123456789abcdef0123456789abcdef" {
t.Fatalf("stored secret = %q, want the original secret preserved", stored.Secret)
}
}
func TestHandleBindingApproveArmedRejected(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
+182
View File
@@ -0,0 +1,182 @@
package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// Capture sources and their signing setting (docs/prds/event-automation.md
// "Sources"). A secret is returned only by the two writes that generate it,
// so the operator can copy it into the sender; every other read withholds it.
// Turning signing off is a request plus an approval, both behind the same
// mutation gate that arms a binding.
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := s.Sources.ListSources(r.Context())
if err != nil {
s.Log.Error("list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list})
}
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
err = s.Sources.InsertSource(r.Context(), src)
}
if err != nil {
s.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !s.authorizeTaskMutation(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
s.transitionSource(w, r, transition)
}
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := s.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
s.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
s.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
s.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
default:
s.Log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}
// unsignedSources is the set of source paths approved to take unsigned
// events. With no source store nothing is unsigned.
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
out := map[string]bool{}
if s.Sources == nil {
return out, nil
}
list, err := s.Sources.ListSources(ctx)
if err != nil {
return nil, err
}
for _, src := range list {
if src.Unsigned() {
out[src.Path] = true
}
}
return out, nil
}
+201
View File
@@ -0,0 +1,201 @@
package webui
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// memSources is an in-memory SourceStore with the store's error contract.
type memSources map[string]source.Source
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
if _, ok := m[s.Path]; ok {
return storecontract.ErrSourcePathTaken
}
m[s.Path] = s
return nil
}
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
s, ok := m[path]
if !ok {
return nil, nil
}
return &s, nil
}
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
out := make([]source.Source, 0, len(m))
for _, s := range m {
out = append(out, s)
}
return out, nil
}
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
s, ok := m[path]
switch {
case !ok:
return storecontract.ErrSourceNotFound
case s.Signing != from:
return storecontract.ErrSourceSigningStale
}
s.Signing = to
m[path] = s
return nil
}
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
s, ok := m[path]
if !ok {
return storecontract.ErrSourceNotFound
}
s.Secret = secret
m[path] = s
return nil
}
func sourceTestServer(t *testing.T) (*Server, memSources) {
t.Helper()
srv := bindingTestServer(t)
sources := memSources{}
srv.Sources = sources
return srv, sources
}
func decodeSource(t *testing.T, body []byte) source.Source {
t.Helper()
var s source.Source
if err := json.Unmarshal(body, &s); err != nil {
t.Fatalf("unmarshal source: %v; body = %s", err, body)
}
return s
}
func TestSourceCreateDefaultsToSignedUUIDv7AndShowsSecretOnce(t *testing.T) {
srv, _ := sourceTestServer(t)
w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{})
if w.Code != http.StatusCreated {
t.Fatalf("create status = %d; body = %s", w.Code, w.Body.String())
}
created := decodeSource(t, w.Body.Bytes())
if id, err := uuid.Parse(created.Path); err != nil || id.Version() != 7 {
t.Fatalf("path %q is not a UUIDv7 (%v)", created.Path, err)
}
if created.Signing != source.SigningSigned || len(created.Secret) != source.MinSecretLen {
t.Fatalf("created = %+v, want signed with a generated secret shown once", created)
}
w = doJSON(t, srv, http.MethodGet, "/api/sources", nil)
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), created.Secret) || strings.Contains(w.Body.String(), `"secret"`) {
t.Fatalf("list = %d %s; want the secret withheld", w.Code, w.Body.String())
}
}
func TestSourceCreateRefusesTakenOrUnsafePath(t *testing.T) {
srv, _ := sourceTestServer(t)
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": "sentry"}); w.Code != http.StatusCreated {
t.Fatalf("first create = %d; body = %s", w.Code, w.Body.String())
}
tests := []struct {
path string
want int
}{
{"sentry", http.StatusConflict},
{"a/b", http.StatusBadRequest},
{"has space", http.StatusBadRequest},
}
for _, tt := range tests {
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": tt.path}); w.Code != tt.want {
t.Errorf("create %q = %d, want %d; body = %s", tt.path, w.Code, tt.want, w.Body.String())
}
}
}
func TestSourceUnsignedNeedsApproval(t *testing.T) {
srv, sources := sourceTestServer(t)
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned, Secret: "k"}
steps := []struct {
name, path string
body any
code int
want source.Signing
}{
{"approve with no request", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningSigned},
{"request unsigned", "/api/sources/fw/signing", map[string]any{"signed": false}, http.StatusOK, source.SigningUnsignedPending},
{"approve", "/api/sources/fw/approve-unsigned", nil, http.StatusOK, source.SigningUnsigned},
{"approve twice", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningUnsigned},
{"sign again", "/api/sources/fw/signing", map[string]any{"signed": true}, http.StatusOK, source.SigningSigned},
{"unknown source", "/api/sources/nope/signing", map[string]any{"signed": false}, http.StatusNotFound, source.SigningSigned},
}
for _, st := range steps {
w := doJSON(t, srv, http.MethodPost, st.path, st.body)
if w.Code != st.code {
t.Fatalf("%s: status = %d, want %d; body = %s", st.name, w.Code, st.code, w.Body.String())
}
if got := sources["fw"].Signing; got != st.want {
t.Fatalf("%s: signing = %q, want %q", st.name, got, st.want)
}
if strings.Contains(w.Body.String(), `"secret"`) {
t.Fatalf("%s: response leaked the secret: %s", st.name, w.Body.String())
}
}
}
func TestSourceRegenerateSecret(t *testing.T) {
srv, sources := sourceTestServer(t)
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned}
w := doJSON(t, srv, http.MethodPost, "/api/sources/fw/secret", nil)
if w.Code != http.StatusOK {
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
}
got := decodeSource(t, w.Body.Bytes())
if len(got.Secret) != source.MinSecretLen || sources["fw"].Secret != got.Secret {
t.Fatalf("secret = %q (stored %q), want a new stored secret shown once", got.Secret, sources["fw"].Secret)
}
}
func TestSourceMutationsRequireCSRFHeader(t *testing.T) {
srv, sources := sourceTestServer(t)
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsignedPending}
for _, path := range []string{"/api/sources", "/api/sources/fw/signing", "/api/sources/fw/approve-unsigned", "/api/sources/fw/secret"} {
if w := doJSONNoCSRF(t, srv, http.MethodPost, path, map[string]any{}); w.Code != http.StatusForbidden {
t.Errorf("%s without CSRF = %d, want %d", path, w.Code, http.StatusForbidden)
}
}
}
func TestBindingListMarksUnsignedSources(t *testing.T) {
srv, sources := sourceTestServer(t)
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsigned}
sources["sentry"] = source.Source{Path: "sentry", Signing: source.SigningSigned}
mappingID := seedMapping(t, srv, "m")
for _, src := range []string{"fw", "sentry"} {
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(src, src, mappingID)); w.Code != http.StatusCreated {
t.Fatalf("create binding = %d; body = %s", w.Code, w.Body.String())
}
}
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
var body struct {
Bindings []struct {
Matcher struct{ Source string } `json:"matcher"`
Unsigned bool `json:"unsigned"`
} `json:"bindings"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 2 {
t.Fatalf("list = %s (%v)", w.Body.String(), err)
}
for _, b := range body.Bindings {
if want := b.Matcher.Source == "fw"; b.Unsigned != want {
t.Errorf("binding on %q unsigned = %v, want %v", b.Matcher.Source, b.Unsigned, want)
}
}
}
+10
View File
@@ -156,6 +156,11 @@ type Server struct {
// /api/bindings route answer 503 rather than the dashboard failing to start.
Bindings storecontract.BindingStore
// Sources persists capture sources and their signing setting
// (docs/prds/event-automation.md "Sources"). Optional: nil makes every
// /api/sources route answer 503 and marks no binding unsigned.
Sources storecontract.SourceStore
// TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard-
// initiated update use the same post-restart notification route as a
// Telegram-initiated update. The web UI has no durable chat identity, so
@@ -274,6 +279,11 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingApprove)
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
}
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
+46 -1
View File
@@ -138,6 +138,14 @@ service StateStoreService {
rpc DeleteBinding(DeleteBindingRequest) returns (DeleteBindingResponse);
rpc ApproveBinding(ApproveBindingRequest) returns (ApproveBindingResponse);
// Source (event-automation.md "Sources"): the capture endpoint and its
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
rpc InsertSource(InsertSourceRequest) returns (InsertSourceResponse);
rpc GetSource(GetSourceRequest) returns (GetSourceResponse);
rpc ListSources(ListSourcesRequest) returns (ListSourcesResponse);
rpc SetSourceSigning(SetSourceSigningRequest) returns (SetSourceSigningResponse);
rpc SetSourceSecret(SetSourceSecretRequest) returns (SetSourceSecretResponse);
// Dispatch
rpc ArmedBindingsForSource(ArmedBindingsForSourceRequest) returns (ArmedBindingsForSourceResponse);
rpc RecordDispatch(RecordDispatchRequest) returns (RecordDispatchResponse);
@@ -321,6 +329,8 @@ message CapturedEvent {
// event_type is the ID of the event type the capture was identified as on
// arrival; empty is unidentified.
string event_type = 9;
// unsigned marks an event taken on an approved unsigned source.
bool unsigned = 10;
}
// EventTypeHeaderCondition mirrors internal/domain/eventtype.HeaderCondition.
@@ -387,12 +397,22 @@ message Binding {
string repo = 7;
int64 version = 8;
string status = 9;
string secret = 10;
// Unused: signing moved to Source. Kept so the field number is never reused.
string secret = 10 [deprecated = true];
google.protobuf.Timestamp created_at = 11;
google.protobuf.Timestamp updated_at = 12;
string filter = 13;
}
// Source mirrors internal/domain/source.Source.
message Source {
string path = 1;
string signing = 2;
string secret = 3;
google.protobuf.Timestamp created_at = 4;
google.protobuf.Timestamp updated_at = 5;
}
// WorkflowStat mirrors internal/store.WorkflowStat.
message WorkflowStat {
string workflow = 1;
@@ -771,6 +791,31 @@ message DeleteBindingResponse {}
message ApproveBindingRequest { string id = 1; }
message ApproveBindingResponse {}
message InsertSourceRequest { Source source = 1; }
message InsertSourceResponse {}
message GetSourceRequest { string path = 1; }
message GetSourceResponse {
Source source = 1;
bool found = 2;
}
message ListSourcesRequest {}
message ListSourcesResponse { repeated Source sources = 1; }
message SetSourceSigningRequest {
string path = 1;
string from = 2;
string to = 3;
}
message SetSourceSigningResponse {}
message SetSourceSecretRequest {
string path = 1;
string secret = 2;
}
message SetSourceSecretResponse {}
message ArmedBindingsForSourceRequest { string source = 1; }
message ArmedBindingsForSourceResponse { repeated Binding bindings = 1; }
+11 -11
View File
@@ -1,20 +1,20 @@
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>ee(e)===`[object Map]`,g=e=>ee(e)===`[object Set]`,_=e=>ee(e)===`[object Date]`,v=e=>ee(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,ee=e=>w.call(e),te=e=>ee(e).slice(8,-1),ne=e=>ee(e)===`[object Object]`,re=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ie=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ae=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},oe=/-\w/g,se=ae(e=>e.replace(oe,e=>e.slice(1).toUpperCase())),ce=/\B([A-Z])/g,le=ae(e=>e.replace(ce,`-$1`).toLowerCase()),ue=ae(e=>e.charAt(0).toUpperCase()+e.slice(1)),T=ae(e=>e?`on${ue(e)}`:``),de=(e,t)=>!Object.is(e,t),fe=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},pe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},me=e=>{let t=parseFloat(e);return isNaN(t)?e:t},he=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},ge,_e=()=>ge||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ve=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ye(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Ce(r):ye(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var be=/;(?![^(]*\))/g,xe=/:([^]+)/,Se=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Ce(e){let t={};return e.replace(Se,e=>e.startsWith(`/*`)?``:e).split(be).forEach(e=>{if(e){let n=e.split(xe);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function E(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=E(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function we(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=E(t)),n&&(e.style=ye(n)),e}var Te=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Ee=r(Te);Te+``;function De(e){return!!e||e===``}function Oe(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Me(e[i],t[i],n);return r}function ke(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Me(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Ae(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?ke(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!Me(e[r],t[r],n))return!1}return String(e)===String(t)}function je(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Me(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?je(e,t,n,Oe):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:je(e,t,n,Ae):String(e)===String(t))))}function Ne(e,t){return e.findIndex(e=>Me(e,t))}var Pe=e=>!!(e&&e.__v_isRef===!0),D=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Pe(e)?D(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}Line truncated
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=js(d[t]),g=h.type===ps;e?(g&&!u&&t+1<p&&js(d[t+1]).type===ps&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,Ai(r,1)||bi()),n(null,h,r,null,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Ci(d),c),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Ri(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return M({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Rs;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Zn(t,e,13,!r)};if(s&&e.suspense||Gs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?B(r,{error:e}):null));let a=O(!1),c=O(),d=O(!!i),f,m;return ca(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return B(r,{error:c.value});if(n&& Line truncated
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(m(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Ne(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||m(e))return Me(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=u({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=(( Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Mp;function Np(e){Mp=e}var Pp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Fp(e){let t=e instanceof Pp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ip(e,t){let n=await fetch(e,t);if(Mp?.(n.status===401),!n.ok)throw new Pp(await jp(n),n.status);return n}async function Lp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=kp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Ip(e,s);return a?await c.json():void 0}var J={health:()=>Lp(`/health/detailed`),summary:()=>Lp(`/api/summary`),tasks:()=>Lp(`/api/tasks`),taskMeta:()=>Lp(`/api/task-meta`),task:e=>Lp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Lp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/changes`+Ap(t)),taskDebug:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/debug`+Ap(t)),taskAction:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Lp(`/api/setup`),capabilities:()=>Lp(`/api/capabilities`),workflows:()=>Lp(`/api/workflows`),workRequest:e=>Lp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Lp(`/api/skills`),channels:()=>Lp(`/api/channels`),curators:()=>Lp(`/api/curators`),channelReload:e=>Lp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Lp(`/api/config`),logs:e=>Lp(`/api/logs`+Ap(e)),taskLogs:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/logs`+Ap(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Lp(`/api/version`),updateSnapshot:()=>Lp(`/api/chat/update`),updateInstall:e=>Lp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Lp(`/api/captures`+Ap({limit:e})),eventTypes:()=>Lp(`/api/event-types`),eventTypeCreate:e=>Lp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Lp(`/api/mappings`),mappingCreate:e=>Lp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Lp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Lp(`/api/bindings`),bindingCreate:e=>Lp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Lp(`/api/chat/sessions`),chatMessages:e=>Lp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Lp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Lp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Lp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Op(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Lp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Lp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Lp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Lp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Ip(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Rp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function zp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Dp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Bp=`archie.web.chat.channel`;function Vp(){let e=localStorage.getItem(Bp);return e||(e=Op(),localStorage.setItem(Bp,e)),e}var Hp=/(?:^|\s)\/([^\s]*)$/,Up=/(?:^|\s)\/[^\s]*$/,Wp=8;function Gp(e,t,n){let r=t.slice(0,n).match(Hp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Wp)}function Kp(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(Up),o=a<0?r.length:a+ +(r[a]===` `);return{text:`$Line truncated
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(m(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Ne(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||m(e))return Me(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=u({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=(( Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Fp;function Ip(e){Fp=e}var Lp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Rp(e){let t=e instanceof Lp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function zp(e,t){let n=await fetch(e,t);if(Fp?.(n.status===401),!n.ok)throw new Lp(await Pp(n),n.status);return n}async function Bp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Mp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await zp(e,s);return a?await c.json():void 0}var J={health:()=>Bp(`/health/detailed`),summary:()=>Bp(`/api/summary`),tasks:()=>Bp(`/api/tasks`),taskMeta:()=>Bp(`/api/task-meta`),task:e=>Bp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Bp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/changes`+Np(t)),taskDebug:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/debug`+Np(t)),taskAction:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Bp(`/api/setup`),capabilities:()=>Bp(`/api/capabilities`),workflows:()=>Bp(`/api/workflows`),workRequest:e=>Bp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Bp(`/api/skills`),channels:()=>Bp(`/api/channels`),curators:()=>Bp(`/api/curators`),channelReload:e=>Bp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Bp(`/api/config`),logs:e=>Bp(`/api/logs`+Np(e)),taskLogs:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/logs`+Np(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Bp(`/api/version`),updateSnapshot:()=>Bp(`/api/chat/update`),updateInstall:e=>Bp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Bp(`/api/captures`+Np({limit:e})),eventTypes:()=>Bp(`/api/event-types`),eventTypeCreate:e=>Bp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Bp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Bp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Bp(`/api/mappings`),mappingCreate:e=>Bp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Bp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Bp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Bp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Bp(`/api/bindings`),bindingCreate:e=>Bp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Bp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Bp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Bp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>Bp(`/api/sources`),sourceCreate:e=>Bp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Bp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Bp(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>Bp(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>Bp(`/api/chat/sessions`),chatMessages:e=>Bp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Bp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Bp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Bp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:jp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Bp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Bp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Bp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Bp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>zp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Vp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Hp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Ap(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Up=`archie.web.chat.channel`;function Wp(){let e=localStorage.getItem(Up);return e||(e= Line truncated
`);u=r.pop()||``;for(let e of r){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(em.value=n.session_id),n.type===`delta`&&(o+=n.text,am.value=am.value?{...am.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],am.value=am.value?{...am.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);tm.value=[...tm.value,{from:`assistant`,text:o,tool_calls:a}],am.value=null,rm.value=`Ready`,await bm()}catch(e){let t=e;t.name===`AbortError`&&!c?(am.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},rm.value=`Stopped`):(am.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Yp(r):void 0,isRetry:i},rm.value=`Error — retry available`)}finally{clearTimeout(l),vm=null,im.value=!1}}function Nm(){rm.value=`Stopping…`,em.value&&J.chatCancel(em.value).catch(()=>{}),ym()}function Pm(){ia(()=>{bm().catch(e=>{rm.value=e.message||`Chat unavailable`})}),ca(()=>{ym()})}var Fm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Im=M({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return q(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(I(),L(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":k(Zp),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Pd),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(Zd),{size:22})],2)],8,Fm))}});function Lm(e){return typeof e==`string`?`'${e}'`:new Vm().serialize(e)}var Rm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,zm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Rm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Bm(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&zm[n]?zm[n]:n+128,s=a<128&&zm[a]?zm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Vm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Bm(e,t):n===`number`&&r===`number`?e-t:Bm(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Bm),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(rm.value=n.session_id),n.type===`delta`&&(o+=n.text,cm.value=cm.value?{...cm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],cm.value=cm.value?{...cm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);im.value=[...im.value,{from:`assistant`,text:o,tool_calls:a}],cm.value=null,om.value=`Ready`,await Cm()}catch(e){let t=e;t.name===`AbortError`&&!c?(cm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},om.value=`Stopped`):(cm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Qp(r):void 0,isRetry:i},om.value=`Error — retry available`)}finally{clearTimeout(l),xm=null,sm.value=!1}}function Im(){om.value=`Stopping…`,rm.value&&J.chatCancel(rm.value).catch(()=>{}),Sm()}function Lm(){ia(()=>{Cm().catch(e=>{om.value=e.message||`Chat unavailable`})}),ca(()=>{Sm()})}var Rm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],zm=M({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return q(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(I(),L(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":k(em),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Ld),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(ef),{size:22})],2)],8,Rm))}});function Bm(e){return typeof e==`string`?`'${e}'`:new Wm().serialize(e)}var Vm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Hm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Vm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Um(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Hm[n]?Hm[n]:n+128,s=a<128&&Hm[a]?Hm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Wm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Um(e,t):n===`number`&&r===`number`?e-t:Um(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Um),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
`)].join(`
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=hh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),xg=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=wh(n.default()),r=e.findIndex(e=>e.type!==ms);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?U(t,i.props):t,o=ks({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),Sg=[`area`,`img`,`input`],X=M({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&Sg.includes(r)?()=>ac(r,t):r===`template`?()=>ac(xg,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function Cg(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:hh(e))}}function wg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Tg({type:e,defaultValue:t,modelValue:n}){return e||wg({type:e,defaultValue:t,modelValue:n})}function Eg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Dg(e,t){let n=W(()=>Tg(e)),r=Ch(e,`modelValue`,t,{defaultValue:Eg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Hm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Jm(t,e)){let n=t.findIndex(t=>Hm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[Og,kg]=Wm(`DialogRoot`),Ag=M({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=Ch(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return kg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>P(e.$slots,`default`,{open:k(r),close:()=>r.value=!1})}}),jg=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=Og();return(e,r)=>(I(),R(k(X),U(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>k(n).onOpenChange(!1)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`type`]))}}),Mg=`dismissableLayer.pointerDownOutside`,Ng=`dismissableLayer.focusOutside`;function Pg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Fg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!Qm||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(Pg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Km(Mg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{Sn(n)&&(i.value=!0)}}}function Ig(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!Qm||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!Pg(t.value,r)&&n.target&&!i.value&&Km(Ng,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{Sn(n)&&(i.value=!0)},onBlurCapture:()=>{Sn(n)&&(i.value=!1)}}}var Lg=M({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=Y(),o=W(()=>a.value?.ownerDocument??globalThis.document),s=W(()=>Ah.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>Ah.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...Ah.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Fg Line truncated
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=vh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),wg=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=Dh(n.default()),r=e.findIndex(e=>e.type!==ms);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?U(t,i.props):t,o=ks({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),Tg=[`area`,`img`,`input`],X=M({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&Tg.includes(r)?()=>ac(r,t):r===`template`?()=>ac(wg,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function Eg(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:vh(e))}}function Dg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Og({type:e,defaultValue:t,modelValue:n}){return e||Dg({type:e,defaultValue:t,modelValue:n})}function kg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Ag(e,t){let n=W(()=>Og(e)),r=Eh(e,`modelValue`,t,{defaultValue:kg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Gm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Zm(t,e)){let n=t.findIndex(t=>Gm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[jg,Mg]=qm(`DialogRoot`),Ng=M({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=Eh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return Mg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>P(e.$slots,`default`,{open:k(r),close:()=>r.value=!1})}}),Pg=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=jg();return(e,r)=>(I(),R(k(X),U(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>k(n).onOpenChange(!1)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`type`]))}}),Fg=`dismissableLayer.pointerDownOutside`,Ig=`dismissableLayer.focusOutside`;function Lg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Rg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!th||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(Lg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Ym(Fg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{Sn(n)&&(i.value=!0)}}}function zg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!th||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!Lg(t.value,r)&&n.target&&!i.value&&Ym(Ig,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{Sn(n)&&(i.value=!0)},onBlurCapture:()=>{Sn(n)&&(i.value=!1)}}}var Bg=M({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=Y(),o=W(()=>a.value?.ownerDocument??globalThis.document),s=W(()=>Nh.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>Nh.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...Nh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Rg Line truncated
- a positive number
- less than the value passed to \`max\` (or ${wx} if no \`max\` prop is set)
- less than the value passed to \`max\` (or ${Dx} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`),null)}function kx(e){return Dx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wx}\`.`),wx)}var Ax=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:wx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Dx(e)?`${Math.round(e/t*wx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Ch(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Ch(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=Ox(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=kx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>qm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ex({modelValue:i,max:a,progressState:o}),(e,t)=>(I(),R(k(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":k(a),"aria-valuemin":0,"aria-valuenow":Dx(k(i))?k(i):void 0,"aria-valuetext":e.getValueText?.(k(i),k(a)),"aria-label":e.getValueLabel(k(i),k(a)),role:`progressbar`,"data-state":o.value,"data-value":k(i)??void 0,"data-max":k(a)},{default:A(()=>[P(e.$slots,`default`,{modelValue:k(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),jx=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Tx();return Y(),(e,r)=>(I(),R(k(X),U(t,{"data-state":k(n).progressState.value,"data-value":k(n).modelValue?.value??void 0,"data-max":k(n).max.value}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Mx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Nx=[` `,`Enter`];function Px(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Fx(e,t,n)):Fx(e,t,n)}function Fx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Hm(e,t)}function Ix(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Lx=[`value`],[Rx,zx]=Wm(`SelectRoot`),Bx=M({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Ch(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Ch(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=O(),d=O(),f=O({x:0,y:0}),p=W(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:qm(c.value));j_({isProvider:!0});let m=zh(s),h=Wh(u),g=O(new Set),_=W(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Fx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Px(e,t.value,n.by))}return zx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(I(),R(k(W_),null,{default:A(()=>[P(e.$slots,`default`,{modelValue:k(c),open:k(l)}),k(h)&&e.name?(I(),R(Vx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:k(o),required:k(i),name:e.name,autocomplete:e.autocomplete,disabled:k(a),value:k(c)},{default:A(()=>[k(qm)(k(c))?(I(),L(`option`,{key:0,value:e.nullableValue},null,8,Lx)):H(`v-if`,!0),(I(!0),L(F,null,N(Array.from(g.value),e=>(I(),L(`option`,U({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):H(`v-if`,!0)]),_:3}))}}),Vx=M({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=O(),r=Rx();j(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:oT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>oT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=cT(c),u=e+1<n.length?cT(n[e+1]):null;if(l&&u&&lT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=cT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>oT(e)),rows:r.map(e=>e.map(e=>oT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:oT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:oT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function cT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function lT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var uT={class:`[overflow-wrap:anywhere]`},dT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},fT={class:`font-mono text-[0.85em]`},pT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},mT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},hT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},gT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},_T={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},vT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},yT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},bT={key:8,class:`mb-2.5 last:mb-0`},xT=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>sT(t.text));return(e,t)=>(I(),L(`div`,uT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,dT,[z(`code`,fT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,pT,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(iT,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(iT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,mT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,hT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,gT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,_T,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,vT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(iT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,yT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(iT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,bT,[B(iT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),ST={class:`truncate`},CT=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,ST,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),wT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},TT={class:`font-semibold text-foreground`},ET={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},DT=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(CT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,wT,[B(k(Xd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,TT,D(n.value),1),r.value?(I(),L(`code`,ET,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),OT={key:0,class:`mb-2 grid gap-0.5 text-xs`},kT={key:2,class:`whitespace-pre-wrap`},AT=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,OT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(DT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(xT,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,kT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),jT={class:`w-full self-center justify-self-center py-6 text-center`},MT={class:`grid gap-2`},NT=[`onClick`],PT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,jT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>rA?`${n.slice(0,rA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var aA=[`title`],oA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>jk(n.event)),a=W(()=>iA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?SO(n.event.at):`—`);return(e,t)=>(I(),R(k(tA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,aA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function sA(e,t){return`${e}:${t??0}`}function cA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=sA(iA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var lA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},uA={class:`max-h-[28rem] overflow-y-auto`},dA=[`aria-expanded`,`aria-label`,`onClick`],fA=[`title`],pA=M({__name:`LiveActivityCard`,setup(e){let t=rE(),{activity:n,streamKind:r,streamState:i}=od(ik()),a=rn(new Set),o=W(()=>cA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return iA(e.representative)}function u(e){return e.representative.at?SO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(mO),null,{default:A(()=>[B(k(yO),null,{default:A(()=>[B(k(bO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(hO),null,{default:A(()=>[B(k(eO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(gO),null,{default:A(()=>[z(`div`,lA,[z(`div`,uA,[B(k($k),null,{default:A(()=>[B(k(nA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(tA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(eA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(tA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(KD),null,{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(oA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(tA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(eO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,dA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,fA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(oA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),mA=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=nC(t,`class`);return(e,r)=>(I(),R(k(Ax),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(jx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function mj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function hj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function gj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function _j(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var vj=M({__name:`InputGroup`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(I(),L(`div`,{"data-slot":`input-group`,role:`group`,class:E(k(q)(`border-input dark:bg-input/30 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-disabled:bg-input/50 dark:has-disabled:bg-input/80 h-8 rounded-lg border transition-colors in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-3 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5 group/input-group relative flex w-full min-w-0 items-center outline-none has-[>textarea]:h-auto`,t.class))},[P(e.$slots,`default`)],2))}}),yj=[`data-align`],bj=M({__name:`InputGroupAddon`,props:{align:{default:`inline-start`},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;function n(e){let t=e.currentTarget,n=e.target;n&&n.closest(`button`)||t&&t?.parentElement&&t.parentElement?.querySelector(`input`)?.focus()}return(e,r)=>(I(),L(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t.align,class:E(k(q)(k(Cj)({align:t.align}),t.class)),onClick:n},[P(e.$slots,`default`)],10,yj))}}),xj=M({__name:`InputGroupButton`,props:{variant:{default:`ghost`},size:{default:`xs`},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(I(),R(k(Z),{type:`button`,"data-size":t.size,variant:t.variant,class:E(k(q)(k(wj)({size:t.size}),t.class))},{default:A(()=>[P(e.$slots,`default`)]),_:3},8,[`data-size`,`variant`,`class`]))}}),Sj=M({__name:`InputGroupInput`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,n)=>(I(),R(k(PO),{"data-slot":`input-group-control`,class:E(k(q)(`rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent flex-1`,t.class))},null,8,[`class`]))}}),Cj=OC(`text-muted-foreground h-auto gap-2 py-1.5 text-sm font-medium group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*=size-])]:size-4 flex cursor-text items-center justify-center select-none`,{variants:{align:{"inline-start":`pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem] order-first`,"inline-end":`pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem] order-last`,"block-start":`px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2 order-first w-full justify-start`,"block-end":`px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2 order-last w-full justify-start`}},defaultVariants:{align:`inline-start`}}),wj=OC(`gap-2 text-sm flex items-center shadow-none`,{variants:{size:{xs:`h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*=size-])]:size-3.5`,sm:``,"icon-xs":`size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0`,"icon-sm":`size-8 p-0 has-[>svg]:p-0`}},defaultVariants:{size:`xs`}}),Tj=`archie.theme`,Ej=`archie.density`,Dj=`archie.motion`,Oj=`archie.tooltips`;function kj(e,t,n){try{let r=localStorage.getItem(e);return t.includes(r)?r:n}catch{return n}}function Aj(e,t){try{localStorage.setItem(e,t)}catch{}}function jj(e){if(e!==`system`)return e;try{return matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}catch{return`dark`}}var Mj=ad(`appearance`,()=>{let e=O(kj(Tj,[`system`,`dark`,`light`],`dark`)),t=O(kj(Ej,[`comfortable`,`compact`],`comfortable`)),n=O(kj(Dj,[`system`,`reduced`],`system`)),r Line truncated
Defaulting to \`null\`.`),null)}function Mx(e){return Ax(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Dx}\`.`),Dx)}var Nx=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Dx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Ax(e)?`${Math.round(e/t*Dx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Eh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Eh(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=jx(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=Mx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>Xm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return kx({modelValue:i,max:a,progressState:o}),(e,t)=>(I(),R(k(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":k(a),"aria-valuemin":0,"aria-valuenow":Ax(k(i))?k(i):void 0,"aria-valuetext":e.getValueText?.(k(i),k(a)),"aria-label":e.getValueLabel(k(i),k(a)),role:`progressbar`,"data-state":o.value,"data-value":k(i)??void 0,"data-max":k(a)},{default:A(()=>[P(e.$slots,`default`,{modelValue:k(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Px=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Ox();return Y(),(e,r)=>(I(),R(k(X),U(t,{"data-state":k(n).progressState.value,"data-value":k(n).modelValue?.value??void 0,"data-max":k(n).max.value}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Fx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Ix=[` `,`Enter`];function Lx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Rx(e,t,n)):Rx(e,t,n)}function Rx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Gm(e,t)}function zx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Bx=[`value`],[Vx,Hx]=qm(`SelectRoot`),Ux=M({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Eh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Eh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=O(),d=O(),f=O({x:0,y:0}),p=W(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Xm(c.value));P_({isProvider:!0});let m=Hh(s),h=qh(u),g=O(new Set),_=W(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Rx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Lx(e,t.value,n.by))}return Hx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(I(),R(k(q_),null,{default:A(()=>[P(e.$slots,`default`,{modelValue:k(c),open:k(l)}),k(h)&&e.name?(I(),R(Wx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:k(o),required:k(i),name:e.name,autocomplete:e.autocomplete,disabled:k(a),value:k(c)},{default:A(()=>[k(Xm)(k(c))?(I(),L(`option`,{key:0,value:e.nullableValue},null,8,Bx)):H(`v-if`,!0),(I(!0),L(F,null,N(Array.from(g.value),e=>(I(),L(`option`,U({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):H(`v-if`,!0)]),_:3}))}}),Wx=M({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=O(),r=Vx();j(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:lT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>lT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=dT(c),u=e+1<n.length?dT(n[e+1]):null;if(l&&u&&fT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=dT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>lT(e)),rows:r.map(e=>e.map(e=>lT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:lT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:lT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function dT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function fT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var pT={class:`[overflow-wrap:anywhere]`},mT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},hT={class:`font-mono text-[0.85em]`},gT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},_T={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},vT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},yT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},bT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},xT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},ST={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},CT={key:8,class:`mb-2.5 last:mb-0`},wT=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>uT(t.text));return(e,t)=>(I(),L(`div`,pT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,mT,[z(`code`,hT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,gT,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(sT,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(sT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,_T,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,vT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,yT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,bT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,xT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,ST,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,CT,[B(sT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),TT={class:`truncate`},ET=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,TT,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),DT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},OT={class:`font-semibold text-foreground`},kT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},AT=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(ET,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,DT,[B(k($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,OT,D(n.value),1),r.value?(I(),L(`code`,kT,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),jT={key:0,class:`mb-2 grid gap-0.5 text-xs`},MT={key:2,class:`whitespace-pre-wrap`},NT=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,jT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(AT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(wT,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,MT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),PT={class:`w-full self-center justify-self-center py-6 text-center`},FT={class:`grid gap-2`},IT=[`onClick`],LT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,PT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>oA?`${n.slice(0,oA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var cA=[`title`],lA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>Pk(n.event)),a=W(()=>sA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?TO(n.event.at):`—`);return(e,t)=>(I(),R(k(iA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,cA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function uA(e,t){return`${e}:${t??0}`}function dA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=uA(sA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA={class:`max-h-[28rem] overflow-y-auto`},mA=[`aria-expanded`,`aria-label`,`onClick`],hA=[`title`],gA=M({__name:`LiveActivityCard`,setup(e){let t=oE(),{activity:n,streamKind:r,streamState:i}=od(sk()),a=rn(new Set),o=W(()=>dA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return sA(e.representative)}function u(e){return e.representative.at?TO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(_O),null,{default:A(()=>[B(k(SO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(vO),null,{default:A(()=>[B(k(rO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(yO),null,{default:A(()=>[z(`div`,fA,[z(`div`,pA,[B(k(nA),null,{default:A(()=>[B(k(aA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(iA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(rA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(iA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[B(k(tO),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(lA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(iA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(rO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,mA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,hA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(lA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),_A=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=aC(t,`class`);return(e,r)=>(I(),R(k(Nx),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(Px),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Bj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Vj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Hj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Uj(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}function Wj(e,t){return t?e.filter(e=>e.event_type_id===t):[]}var Gj={pending_approval:`pending approval`,armed:`armed`},Kj={pending_approval:`warn`,armed:`ok`};function qj(e){return e?Gj[e]??e:`unknown`}function Jj(e){return Kj[e??``]??`idle`}function Yj(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``}}function Xj(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``}}function Zj(e,t){let n=t.find(t=>t.id===e.eventTypeId);return{name:e.name,matcher:{source:n?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:e.owner,repo:e.repo}}function Qj(e){return e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function $j(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var eM={class:`grid grid-cols-2 items-start gap-3`},tM=M({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=O(Yj());j(r,e=>{e&&(a.value=n.binding?Xj(n.binding,n.mappings):Yj())},{immediate:!0});let o=W(()=>Wj(n.mappings,a.value.eventTypeId));j(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=W(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(I(),R(k(Mj),{open:r.value,"onUpdate:open":t[9]||=e=>r.value=e},{default:A(()=>[B(k(Pj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:A(()=>[B(k(Lj),null,{default:A(()=>[B(k(Rj),null,{default:A(()=>[V(D(s.value),1)]),_:1}),B(k(Fj),null,{default:A(()=>[...t[10]||=[V(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),z(`form`,{onSubmit:t[8]||=uu(e=>i(`save`,a.value),[`prevent`])},[B(k(IC),null,{default:A(()=>[B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-name`},{default:A(()=>[...t[11]||=[V(`Name`,-1)]]),_:1}),B(k(LO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-event-type`},{default:A(()=>[...t[12]||=[V(`Event type`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:A(()=>[B(k(CC),{id:`binding-event-type`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:`Pick an event type`})]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(n.eventTypes,e=>(I(),R(k(bC),{key:e.id,value:e.id},{default:A(()=>[V(D(k(Vj)(e.id,n.eventTypes)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-mapping`},{default:A(()=>[...t[13]||=[V(`Field mapping`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.mappingId,"onUpdate:modelValue":t[2]||=e=>a.value.mappingId=e,disabled:!o.value.length},{default:A(()=>[B(k(CC),{id:`binding-mapping`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:a.value.eventTypeId&&!o.value.length?`No mappings for this event type`:`Pick a mapping`},null,8,[`placeholder`])]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(o.value,e=>(I(),R(k(bC),{key:e.id,value:String(e.id)},{default:A(()=>[V(D(e.name),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`,`disabled`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-filter`},{default:A(()=>[...t[14]||=[V(`Filter`,-1)]]),_:1}),B(k(LO),{id:`binding-filter`,modelValue:a.value.filter,"onUpdate:modelValue":t[3]||=e=>a.value.filter=e,class:`font-mono text-xs`,placeholder:`severity in ["high", "critical"]`},null,8,[`modelValue`]),B(k(FC),null,{default:A(()=>[...t[15]||=[V(`Optional CEL over the mapping's parameters.`,-1)]]),_:1})]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-workflow`},{default:A(()=>[...t[16]||=[V(`Workflow`,-1)]]),_:1}),B(k(JS),{modelValue:a.va Line truncated
+3 -45
View File
@@ -1,5 +1,4 @@
<script setup lang="ts">
import { Check, Copy, RefreshCw } from "@lucide/vue";
import { computed, ref, watch } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
@@ -8,14 +7,11 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { eventTypeLabel, type EventType } from "@/captures/event-types";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
draftFromBinding,
emptyDraft,
generateSecret,
mappingsForEventType,
type Binding,
type BindingDraft,
@@ -25,8 +21,8 @@ import {
/**
* The binding editor: name, the event type it applies to, one of that type's
* mappings, an optional filter over the mapping's parameters, the workflow, an
* optional repo pin, and the shared secret senders sign with.
* mappings, an optional filter over the mapping's parameters, the workflow and
* an optional repo pin. Signing is the source's.
*/
const props = defineProps<{
@@ -65,17 +61,11 @@ watch(
);
const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
const copied = ref(false);
async function copySecret(): Promise<void> {
await navigator.clipboard.writeText(draft.value.secret);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
}
</script>
<template>
<Dialog v-model:open="open">
<!-- Seven fields make this taller than a short window; the dialog itself
<!-- Six fields make this taller than a short window; the dialog itself
scrolls rather than clipping its own Save button. -->
<DialogContent class="max-h-[85vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
@@ -162,38 +152,6 @@ async function copySecret(): Promise<void> {
</FieldDescription>
</Field>
<Field>
<FieldLabel for="binding-secret">Signing secret</FieldLabel>
<InputGroup v-if="draft.secret">
<InputGroupInput id="binding-secret" :model-value="draft.secret" class="font-mono text-xs" readonly />
<InputGroupAddon align="inline-end">
<Tooltip>
<TooltipTrigger as-child>
<InputGroupButton size="icon-xs" aria-label="Copy secret" @click="copySecret">
<Check v-if="copied" />
<Copy v-else />
</InputGroupButton>
</TooltipTrigger>
<TooltipContent>Copy secret</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<InputGroupButton size="icon-xs" aria-label="Regenerate secret" @click="draft.secret = generateSecret()">
<RefreshCw />
</InputGroupButton>
</TooltipTrigger>
<TooltipContent>Regenerate</TooltipContent>
</Tooltip>
</InputGroupAddon>
</InputGroup>
<div v-else class="flex h-9 items-center justify-between rounded-md border px-3 text-sm">
<span class="text-fg-muted">Stored · HMAC-SHA256</span>
<Button type="button" variant="ghost" size="sm" @click="draft.secret = generateSecret()">
<RefreshCw data-icon="inline-start" />
Replace
</Button>
</div>
</Field>
</FieldGroup>
<!-- Beside the buttons, not at the top: the dialog scrolls, and Save is
+5 -1
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { Check, Pencil, Trash2 } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { TableCell, TableRow } from "@/components/ui/table";
import BindingStatusBadge from "./BindingStatusBadge.vue";
@@ -20,7 +21,10 @@ const emit = defineEmits<{
<TableRow>
<TableCell class="font-medium">{{ props.binding.name }}</TableCell>
<TableCell class="font-mono text-fg-muted">
{{ eventTypeLabel(bindingEventType(props.binding, props.mappings), props.eventTypes) }}
<div class="flex items-center gap-2">
{{ eventTypeLabel(bindingEventType(props.binding, props.mappings), props.eventTypes) }}
<Badge v-if="props.binding.unsigned" variant="warn">Unsigned</Badge>
</div>
</TableCell>
<TableCell class="max-w-56 truncate font-mono text-xs text-fg-muted" :title="props.binding.filter">
{{ props.binding.filter || "—" }}
+3
View File
@@ -4,6 +4,7 @@ import { onMounted, ref } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import SourcesPanel from "@/sources/SourcesPanel.vue";
import { useLiveResource } from "@/stores/live-updates";
import BindingEditor from "./BindingEditor.vue";
import BindingsTable from "./BindingsTable.vue";
@@ -70,6 +71,8 @@ async function handleDelete(binding: Binding): Promise<void> {
<template>
<div>
<SourcesPanel />
<!-- The tab owns the actions that belong to it. The page's header names the
page, not this panel, so nothing here repeats "Events". -->
<div class="mb-4 flex flex-wrap items-center justify-end gap-2">
+3 -15
View File
@@ -8,9 +8,8 @@
import type { EventType } from "../captures/event-types";
/**
* A binding as GET /api/bindings returns it. Secret is never returned: the
* daemon strips it from every read, and a blank secret on update is its
* server-side "keep the current one".
* A binding as GET /api/bindings returns it. Signing belongs to the source the
* matcher names; unsigned is set when that source takes unsigned events.
*/
export interface Binding {
id: string;
@@ -25,6 +24,7 @@ export interface Binding {
repo?: string;
status?: string;
version?: number;
unsigned?: boolean;
}
/** The fields of GET /api/mappings this page needs. */
@@ -85,7 +85,6 @@ export interface BindingDraft {
workflow: string;
owner: string;
repo: string;
secret: string;
}
export function emptyDraft(): BindingDraft {
@@ -98,7 +97,6 @@ export function emptyDraft(): BindingDraft {
workflow: "",
owner: "",
repo: "",
secret: generateSecret(),
};
}
@@ -113,9 +111,6 @@ export function draftFromBinding(binding: Binding, mappings: MappingOption[]): B
workflow: binding.workflow || "",
owner: binding.owner || "",
repo: binding.repo || "",
// Deliberately blank: the secret is never sent to the browser, and an
// empty one on update keeps whatever the sender already signs with.
secret: "",
};
}
@@ -130,16 +125,9 @@ export function bindingPayload(draft: BindingDraft, eventTypes: EventType[]): Re
workflow: draft.workflow,
owner: draft.owner,
repo: draft.repo,
secret: draft.secret,
};
}
/** A 32-byte hex signing secret for a new binding. */
export function generateSecret(): string {
const bytes = crypto.getRandomValues(new Uint8Array(32));
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
/** The repo pin a row shows, or an em dash when the binding takes the
* single-configured-repo default. */
export function repoPin(binding: Binding): string {
+8 -1
View File
@@ -3,7 +3,9 @@ import { useMediaQuery } from "@vueuse/core";
import { computed, ref, watch } from "vue";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ago } from "@/lib/format";
import { captureSignature } from "./capture-signature";
import CapturePayload from "./CapturePayload.vue";
import { selected } from "./state";
@@ -36,6 +38,8 @@ const stacked = useMediaQuery("(max-width: 1099px)");
const cap = computed(() => (stacked.value || !props.maxHeight ? undefined : `${props.maxHeight}px`));
const signature = computed(() => (selected.value ? captureSignature(selected.value) : null));
const meta = computed(() => {
const capture = selected.value;
if (!capture) return "";
@@ -54,7 +58,10 @@ watch(selected, () => {
<div v-if="selected" ref="pane" class="min-w-0">
<Card class="flex flex-col" :style="cap ? { maxHeight: cap } : undefined">
<CardHeader>
<CardTitle class="font-mono">{{ selected.source || "Unknown source" }}</CardTitle>
<CardTitle class="flex items-center gap-2 font-mono">
{{ selected.source || "Unknown source" }}
<Badge v-if="signature" :variant="signature.kind">{{ signature.label }}</Badge>
</CardTitle>
<CardDescription>{{ meta }}</CardDescription>
</CardHeader>
<!-- Stacked there is no sibling to be bound by, so the panel caps itself
+8 -3
View File
@@ -7,6 +7,7 @@ import { TableCell, TableRow } from "@/components/ui/table";
import { ago } from "@/lib/format";
import { eventTypes } from "./event-type-state";
import { captureIdentity } from "./event-types";
import { captureSignature } from "./capture-signature";
import { selected, type Capture } from "./state";
/**
@@ -19,6 +20,7 @@ const props = defineProps<{ capture: Capture }>();
const identity = computed(() => captureIdentity(props.capture, eventTypes.value));
const signature = computed(() => captureSignature(props.capture));
const isSelected = computed(() => selected.value?.id === props.capture.id);
// The name is set here because role="button" makes the cells presentational:
@@ -46,9 +48,12 @@ function open(): void {
<TableCell :title="props.capture.received_at || ''">{{ ago(props.capture.received_at) }}</TableCell>
<!-- An unidentified capture is never dispatched. -->
<TableCell>
<Badge :variant="identity.identified ? 'ok' : 'warn'" class="max-w-40">
<span class="truncate">{{ identity.label }}</span>
</Badge>
<div class="flex items-center gap-1">
<Badge :variant="identity.identified ? 'ok' : 'warn'" class="max-w-40">
<span class="truncate">{{ identity.label }}</span>
</Badge>
<Badge :variant="signature.kind">{{ signature.label }}</Badge>
</div>
</TableCell>
<TableCell class="font-mono">{{ props.capture.content_type || "—" }}</TableCell>
<TableCell class="text-right">
+15
View File
@@ -0,0 +1,15 @@
/**
* How a capture may dispatch: signed by its source's secret, taken on a
* source approved for unsigned events, or neither -- in which case nothing
* starts from it.
*/
export interface CaptureSignature {
label: "Signed" | "Unsigned" | "Unverified";
kind: "ok" | "warn" | "idle";
}
export function captureSignature(capture: { authenticated?: boolean; unsigned?: boolean }): CaptureSignature {
if (capture.unsigned) return { label: "Unsigned", kind: "warn" };
if (capture.authenticated) return { label: "Signed", kind: "ok" };
return { label: "Unverified", kind: "idle" };
}
+1
View File
@@ -28,6 +28,7 @@ export interface Capture {
authenticated?: boolean;
/** The event type it was identified as on arrival; empty is unidentified. */
event_type?: string;
unsigned?: boolean;
}
interface CapturesResponse {
+8
View File
@@ -178,6 +178,14 @@ export const api = {
request<T>(`/api/bindings/${encodeURIComponent(id)}`, { method: "PATCH", body: binding }),
bindingDelete: (id: string) => request<void>(`/api/bindings/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
bindingApprove: <T = unknown>(id: string) => request<T>(`/api/bindings/${encodeURIComponent(id)}/approve`, { method: "POST" }),
sources: <T = unknown>() => request<T>("/api/sources"),
sourceCreate: <T = unknown>(path: string) => request<T>("/api/sources", { method: "POST", body: { path } }),
sourceSigning: <T = unknown>(path: string, signed: boolean) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/signing`, { method: "POST", body: { signed } }),
sourceApproveUnsigned: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/approve-unsigned`, { method: "POST" }),
sourceSecret: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/secret`, { method: "POST" }),
chatSessions: <T = unknown>() => request<T>("/api/chat/sessions"),
chatMessages: <T = unknown>(id: string) => request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: <T = unknown>(id: string) => request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
+148
View File
@@ -0,0 +1,148 @@
<script setup lang="ts">
import { Check, Copy, KeyRound, Lock, LockOpen, Plus, X } from "@lucide/vue";
import { onMounted, ref } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useLiveResource } from "@/stores/live-updates";
import { signingKind, signingLabel, sourceURL, type Source } from "./source-signing";
import { useSources } from "./use-sources";
/**
* Capture sources: the endpoint each sender posts to and its signing setting
* (docs/prds/event-automation.md "Sources"). Turning signing off is a request
* that takes effect only once approved.
*/
const { sources, failure, revealed, busy, load, create, newSecret, requestUnsigned, requireSigning, approveUnsigned } =
useSources();
const customPath = ref("");
const copied = ref<string | null>(null);
useLiveResource(null, () => void load());
onMounted(load);
async function copy(value: string): Promise<void> {
await navigator.clipboard.writeText(value);
copied.value = value;
setTimeout(() => (copied.value = null), 1500);
}
async function submit(): Promise<void> {
await create(customPath.value);
if (!failure.value) customPath.value = "";
}
function url(source: Source): string {
return sourceURL(window.location.origin, source.path);
}
</script>
<template>
<section class="mb-6 flex flex-col gap-3">
<form class="flex flex-wrap items-center justify-end gap-2" @submit.prevent="submit">
<Input v-model="customPath" class="w-64 font-mono" placeholder="Custom path (optional)" aria-label="Custom path" />
<Button type="submit" variant="outline" :disabled="busy">
<Plus data-icon="inline-start" />
New source
</Button>
</form>
<Alert v-if="failure" variant="destructive">
<AlertTitle>That did not take effect</AlertTitle>
<AlertDescription>{{ failure }}</AlertDescription>
</Alert>
<Alert v-if="revealed">
<KeyRound />
<AlertTitle class="flex items-center justify-between gap-2">
<span class="font-mono">{{ revealed.path }} · signing secret, shown once</span>
<Button variant="ghost" size="icon-sm" aria-label="Dismiss" @click="revealed = null"><X /></Button>
</AlertTitle>
<AlertDescription class="flex items-center gap-2">
<code class="min-w-0 break-all font-mono text-xs">{{ revealed.secret }}</code>
<Button variant="ghost" size="icon-sm" aria-label="Copy secret" @click="copy(revealed.secret || '')">
<Check v-if="copied === revealed.secret" />
<Copy v-else />
</Button>
</AlertDescription>
</Alert>
<Card v-if="sources && sources.length">
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Source</TableHead>
<TableHead>Signing</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="source in sources" :key="source.path">
<TableCell class="max-w-0 truncate font-mono text-fg-muted" :title="url(source)">{{ source.path }}</TableCell>
<TableCell>
<Badge :variant="signingKind(source.signing)">{{ signingLabel(source.signing) }}</Badge>
</TableCell>
<TableCell>
<div class="flex items-center justify-end gap-1">
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Copy URL" @click="copy(url(source))">
<Check v-if="copied === url(source)" />
<Copy v-else />
</Button>
</TooltipTrigger>
<TooltipContent>Copy URL</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="New secret" :disabled="busy" @click="newSecret(source)">
<KeyRound />
</Button>
</TooltipTrigger>
<TooltipContent>New secret</TooltipContent>
</Tooltip>
<Button
v-if="source.signing === 'signed'"
variant="outline"
size="sm"
:disabled="busy"
@click="requestUnsigned(source)"
>
<LockOpen data-icon="inline-start" />
Turn off signing
</Button>
<Button
v-if="source.signing === 'unsigned_pending_approval'"
size="sm"
:disabled="busy"
@click="approveUnsigned(source)"
>
<Check data-icon="inline-start" />
Approve unsigned
</Button>
<Button
v-if="source.signing !== 'signed'"
variant="outline"
size="sm"
:disabled="busy"
@click="requireSigning(source)"
>
<Lock data-icon="inline-start" />
Require signing
</Button>
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
</CardContent>
</Card>
</section>
</template>
+41
View File
@@ -0,0 +1,41 @@
/**
* The sources vocabulary: the wire shape GET /api/sources returns and the
* signing states it carries. A source's secret is only ever in the response
* to the write that generated it.
*/
export interface Source {
path: string;
signing?: string;
/** Present only on create and on a new secret. */
secret?: string;
created_at?: string;
}
export type SigningKind = "ok" | "info" | "warn" | "idle";
const LABELS: Record<string, string> = {
signed: "signed",
unsigned_pending_approval: "unsigned pending approval",
unsigned: "unsigned",
};
const KINDS: Record<string, SigningKind> = {
signed: "ok",
unsigned_pending_approval: "info",
unsigned: "warn",
};
export function signingLabel(signing?: string): string {
if (!signing) return "unknown";
return LABELS[signing] ?? signing;
}
export function signingKind(signing?: string): SigningKind {
return KINDS[signing ?? ""] ?? "idle";
}
/** The URL a sender posts to. */
export function sourceURL(origin: string, path: string): string {
return `${origin}/webhooks/capture/${encodeURIComponent(path)}`;
}
+58
View File
@@ -0,0 +1,58 @@
import { ref } from "vue";
import { api } from "@/lib/api";
import type { Source } from "./source-signing";
/**
* The sources list and its writes. A write that generates a secret keeps the
* returned source in `revealed` until dismissed: it is the only time the
* browser ever holds that secret.
*/
export function useSources() {
// null means loading, [] means loaded and empty.
const sources = ref<Source[] | null>(null);
const failure = ref<string | null>(null);
const revealed = ref<Source | null>(null);
const busy = ref(false);
function message(err: unknown): string {
return err instanceof Error && err.message ? err.message : String(err);
}
async function load(): Promise<void> {
try {
const res = await api.sources<{ sources?: Source[] }>();
sources.value = res.sources || [];
failure.value = null;
} catch (err) {
failure.value = message(err);
}
}
async function run(write: () => Promise<Source | void>): Promise<void> {
busy.value = true;
failure.value = null;
try {
const result = await write();
if (result?.secret) revealed.value = result;
await load();
} catch (err) {
failure.value = message(err);
} finally {
busy.value = false;
}
}
return {
sources,
failure,
revealed,
busy,
load,
create: (path: string) => run(() => api.sourceCreate<Source>(path.trim())),
newSecret: (source: Source) => run(() => api.sourceSecret<Source>(source.path)),
requestUnsigned: (source: Source) => run(() => api.sourceSigning<Source>(source.path, false)),
requireSigning: (source: Source) => run(() => api.sourceSigning<Source>(source.path, true)),
approveUnsigned: (source: Source) => run(() => api.sourceApproveUnsigned<Source>(source.path)),
};
}
+5 -1
View File
@@ -21,7 +21,11 @@ const line = computed(() => describeTimelineEvent(props.event));
<template>
<li class="flex items-start gap-3">
<span class="mt-[5px] size-2 shrink-0 rounded-full bg-primary" aria-hidden="true" />
<span
class="mt-[5px] size-2 shrink-0 rounded-full"
:class="line.tone === 'warn' ? 'bg-warn' : 'bg-primary'"
aria-hidden="true"
/>
<div>
<div class="text-sm font-medium">{{ line.title }}</div>
<div v-if="line.detail" class="mt-0.5 text-xs text-fg-muted">{{ line.detail }}</div>
+6
View File
@@ -48,6 +48,8 @@ function text(value: unknown): string {
export interface TimelineLine {
title: string;
detail: string;
/** Set for an event a reader must not skim past. */
tone?: "warn";
}
export function describeTimelineEvent(ev: TaskEvent = {}): TimelineLine {
@@ -112,6 +114,10 @@ export function describeTimelineEvent(ev: TaskEvent = {}): TimelineLine {
detail: "The effective task-runtime configuration for this run.",
};
}
if (ev.kind === "unsigned_event") {
const source = text(data.source);
return { title: "Started by an unsigned event", detail: source ? `source ${source}` : "", tone: "warn" };
}
if (ev.kind === "changes_captured") {
const totals = (data.totals ?? {}) as { files?: unknown };
const fileCount = Number(totals.files);
+52
View File
@@ -0,0 +1,52 @@
import assert from "node:assert/strict";
import test from "node:test";
import { bindingPayload, emptyDraft } from "../src/bindings/binding-draft.ts";
import { captureSignature } from "../src/captures/capture-signature.ts";
import { signingKind, signingLabel, sourceURL } from "../src/sources/source-signing.ts";
import { describeTimelineEvent } from "../src/tasks/timeline-event.ts";
test("a capture shows how it may dispatch", () => {
const cases: Array<[{ authenticated?: boolean; unsigned?: boolean }, string, string]> = [
[{ authenticated: true }, "Signed", "ok"],
[{ unsigned: true }, "Unsigned", "warn"],
[{}, "Unverified", "idle"],
[{ authenticated: false, unsigned: false }, "Unverified", "idle"],
];
for (const [capture, label, kind] of cases) {
assert.deepEqual(captureSignature(capture), { label, kind }, JSON.stringify(capture));
}
});
test("a source's signing state names itself and its tone", () => {
const cases: Array<[string | undefined, string, string]> = [
["signed", "signed", "ok"],
["unsigned_pending_approval", "unsigned pending approval", "info"],
["unsigned", "unsigned", "warn"],
["something_new", "something_new", "idle"],
[undefined, "unknown", "idle"],
];
for (const [signing, label, kind] of cases) {
assert.equal(signingLabel(signing), label, String(signing));
assert.equal(signingKind(signing), kind, String(signing));
}
});
test("a source's URL escapes nothing a valid path can hold", () => {
assert.equal(
sourceURL("https://archie.example", "0199a0b2-0000-7000-8000-000000000000"),
"https://archie.example/webhooks/capture/0199a0b2-0000-7000-8000-000000000000",
);
assert.equal(sourceURL("http://h", "a b"), "http://h/webhooks/capture/a%20b");
});
test("a task started by an unsigned event says so on its timeline", () => {
const line = describeTimelineEvent({ kind: "unsigned_event", data: { source: "firewall" } });
assert.deepEqual(line, { title: "Started by an unsigned event", detail: "source firewall", tone: "warn" });
assert.equal(describeTimelineEvent({ kind: "stage_start", stage: "plan" }).tone, undefined);
});
test("a binding no longer carries a signing secret", () => {
const payload = bindingPayload(emptyDraft(), []);
assert.equal("secret" in payload, false);
});