feat(eda): sources own signing, with UUIDv7 paths and approved unsigned option
A source is the capture endpoint: a UUIDv7 path by default or a unique URL-safe custom path, signed by default with an Archie-generated secret (encrypted via the bindings cipher), or unsigned after an approval. Intake verifies X-Hub-Signature-256/X-Signature-256 against the source secret before redaction; an unauthenticated event on a signed source is captured but never dispatched, an event on an approved unsigned source dispatches and is marked unsigned. The binding secret is retired; migration 0006 derives sources from existing binding and capture source strings, moving each binding's secret onto its source. SourceStore crosses the State Store gRPC contract. The dashboard gains a sources panel and flags unsigned in the capture inspector, binding list and task timeline.
This commit is contained in:
1 parent
5009288729
commit
6adbdc55a9
59 files changed
+3741
-1660
No files matched your search
@@ -593,7 +593,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)
|
||||
@@ -604,7 +604,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)
|
||||
}
|
||||
|
||||
@@ -131,21 +131,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()
|
||||
@@ -154,7 +158,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),
|
||||
|
||||
+1283
-693
File diff suppressed because it is too large.
Load diff
@@ -79,6 +79,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"
|
||||
@@ -204,6 +209,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)
|
||||
@@ -849,6 +861,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)
|
||||
@@ -1045,6 +1107,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)
|
||||
@@ -1251,6 +1320,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")
|
||||
}
|
||||
@@ -2359,6 +2443,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 {
|
||||
@@ -2717,6 +2891,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,
|
||||
|
||||
@@ -611,7 +611,7 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) {
|
||||
// single cycle's worst-case latency on a backlog.
|
||||
const bindingDispatchBatchLimit = 100
|
||||
|
||||
// dispatchBindings walks authenticated captures whose source has at
|
||||
// dispatchBindings walks dispatchable captures whose source has at
|
||||
// least one armed binding, evaluates each binding's matcher against
|
||||
// the capture, resolves fields through the binding's mapping, and
|
||||
// enqueues a task per matched (binding, capture) pair.
|
||||
@@ -662,7 +662,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)
|
||||
@@ -737,6 +737,16 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
|
||||
d.Log.Warn("binding dispatch: record", "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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hasBlockingFailure reports whether any of the failures belongs to a
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -38,9 +38,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"`
|
||||
@@ -57,52 +56,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")
|
||||
}
|
||||
@@ -121,18 +83,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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 == '~'
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"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"
|
||||
@@ -192,6 +193,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
|
||||
@@ -271,8 +286,15 @@ type CapturedEvent struct {
|
||||
Headers string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// 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.
|
||||
//
|
||||
@@ -370,6 +392,13 @@ var (
|
||||
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
|
||||
// ErrMappingNotFound is returned when a mapping ID does not exist.
|
||||
ErrMappingNotFound = errors.New("store: mapping 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -15,14 +15,13 @@ package captureintake
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"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"
|
||||
@@ -42,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
|
||||
@@ -61,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
|
||||
@@ -92,10 +96,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
armed, ok := rc.armedBindings(w, r, source)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
src := rc.resolveSource(r, path)
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytesOrFallback(rc.MaxBodyBytes))
|
||||
body, err := io.ReadAll(r.Body)
|
||||
@@ -106,20 +107,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// HMAC verification -- only when exactly one binding is armed for this
|
||||
// source. 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.
|
||||
authenticated := false
|
||||
if len(armed) == 1 {
|
||||
sig := r.Header.Get("X-Hub-Signature-256")
|
||||
if sig == "" {
|
||||
sig = r.Header.Get("X-Signature-256")
|
||||
}
|
||||
authenticated = webhookguard.VerifyHMAC(body, sig, armed[0].Secret)
|
||||
}
|
||||
// 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)
|
||||
@@ -137,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
|
||||
}
|
||||
@@ -161,42 +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. If a future phase wants fail-closed semantics,
|
||||
// that is a separate decision and should not silently land here.
|
||||
//
|
||||
// Two armed bindings for one source would race over every inbound webhook for
|
||||
// that source: the write-time overlap check should make this state
|
||||
// impossible, but the dispatch loop needs a single binding per capture, so
|
||||
// the overlap surfaces as 409 at capture time (belt-and-braces TOCTOU guard
|
||||
// -- see the store's ApproveBinding).
|
||||
func (rc *Receiver) armedBindings(w http.ResponseWriter, r *http.Request, source string) ([]binding.Binding, bool) {
|
||||
if rc.Bindings == nil {
|
||||
return nil, true
|
||||
// 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)
|
||||
return nil, true
|
||||
rc.logger().Warn("source lookup", "source", path, "err", err)
|
||||
return nil
|
||||
}
|
||||
if len(armed) > 1 {
|
||||
http.Error(w,
|
||||
fmt.Sprintf("multiple armed bindings for source %q -- overlap rejected", source),
|
||||
http.StatusConflict)
|
||||
return nil, false
|
||||
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
|
||||
}
|
||||
return armed, true
|
||||
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,92 +74,6 @@ func captureTestServer(t *testing.T) testReceiver {
|
||||
}
|
||||
}
|
||||
|
||||
// stubBindingStore injects a configurable armed-binding lookup result so
|
||||
// handleCapture tests can exercise the single-binding HMAC path and the
|
||||
// belt-and-braces 409-on-multiple path without seeding the real store
|
||||
// (which would either run into the overlap-rejection guard or require
|
||||
// bypassing the draft -> pending_approval -> armed lifecycle). The 409
|
||||
// path exists exactly for the case where the write-time check was
|
||||
// bypassed somehow, so simulating that case directly is the most honest
|
||||
// way to cover it.
|
||||
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 {
|
||||
@@ -440,230 +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()
|
||||
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
|
||||
sources SourceResolver
|
||||
header, sig string
|
||||
authenticated bool
|
||||
unsigned bool
|
||||
}{
|
||||
{"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) {
|
||||
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))
|
||||
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 (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)")
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
if len(captures.rows) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(captures.rows))
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureWithMultipleArmedBindingsReturns409 covers the
|
||||
// belt-and-braces TOCTOU guard: two armed bindings for the same source
|
||||
// would race over every inbound webhook for that source, so the
|
||||
// capture-time handler returns 409 Conflict instead of silently picking
|
||||
// a winner. The store's overlap check should make this impossible in
|
||||
// practice; the 409 is the safety net. The stub injects the state
|
||||
// directly to exercise that safety net.
|
||||
func TestHandleCaptureWithMultipleArmedBindingsReturns409(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"},
|
||||
},
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d (multiple armed bindings must surface as 409 at capture time)", w.Code, http.StatusConflict)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (a 409 must never persist a row)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// 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},
|
||||
|
||||
@@ -23,6 +23,13 @@ var droppedColumns = map[string]bool{
|
||||
"playbook_dispatches.id": true,
|
||||
}
|
||||
|
||||
// addedColumns are target columns with no legacy column by design; an
|
||||
// imported row takes the column default. captures.unsigned: no legacy source
|
||||
// could take unsigned events.
|
||||
var addedColumns = map[string]bool{
|
||||
"captures.unsigned": true,
|
||||
}
|
||||
|
||||
// targetKeys override a table's legacy key where the target has no column
|
||||
// for it.
|
||||
var targetKeys = map[string][]string{
|
||||
@@ -166,6 +173,7 @@ func plan(ctx context.Context, tx pgx.Tx, t legacyread.Table, problems *refusal)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("legacy import: %s columns: %w", t.Name, err)
|
||||
}
|
||||
cols = slices.DeleteFunc(cols, func(c column) bool { return addedColumns[t.Name+"."+c.name] })
|
||||
gap := len(cols) == 0
|
||||
if gap {
|
||||
problems.add("%s: no target table", t.Name)
|
||||
|
||||
@@ -44,7 +44,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.
|
||||
@@ -93,6 +93,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(),
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert capture: %w", err)
|
||||
@@ -127,6 +128,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
|
||||
Headers: r.Headers,
|
||||
Body: r.Body,
|
||||
Authenticated: r.Authenticated,
|
||||
Unsigned: r.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,19 +278,10 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
|
||||
|
||||
// --- 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},
|
||||
@@ -298,18 +291,9 @@ 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. "One binding per
|
||||
@@ -317,14 +301,6 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
|
||||
// second insert for the same source is refused by the database and surfaced
|
||||
// here as ErrBindingOverlap.
|
||||
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,
|
||||
@@ -335,7 +311,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 isUniqueViolation(err) {
|
||||
return "", storecontract.ErrBindingOverlap
|
||||
@@ -357,10 +332,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
|
||||
}
|
||||
|
||||
@@ -371,11 +343,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
|
||||
}
|
||||
@@ -388,28 +356,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,
|
||||
@@ -419,7 +373,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 isUniqueViolation(err) {
|
||||
return storecontract.ErrBindingOverlap
|
||||
|
||||
@@ -127,79 +127,6 @@ func TestConcurrentInsertBindingSameSource(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,33 @@ import (
|
||||
)
|
||||
|
||||
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
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
|
||||
}
|
||||
|
||||
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 +48,6 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
@@ -101,14 +114,37 @@ 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 getBinding = `-- name: GetBinding :one
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
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
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -119,7 +155,6 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
@@ -145,9 +180,26 @@ func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
|
||||
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, workflow, owner, repo, version, status, secret)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9)
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8)
|
||||
`
|
||||
|
||||
type InsertBindingParams struct {
|
||||
@@ -159,7 +211,6 @@ type InsertBindingParams struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Status string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
|
||||
@@ -172,7 +223,6 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
|
||||
arg.Owner,
|
||||
arg.Repo,
|
||||
arg.Status,
|
||||
arg.Secret,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -201,8 +251,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)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
`
|
||||
|
||||
type InsertCaptureParams struct {
|
||||
@@ -214,6 +264,7 @@ type InsertCaptureParams struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
}
|
||||
|
||||
// EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
|
||||
@@ -227,6 +278,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
|
||||
arg.Body,
|
||||
arg.Authenticated,
|
||||
arg.ReceivedAt,
|
||||
arg.Unsigned,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -275,6 +327,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)
|
||||
@@ -304,19 +371,33 @@ 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
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
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
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -327,7 +408,6 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
@@ -342,7 +422,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
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1
|
||||
@@ -366,6 +446,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.Unsigned,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -409,8 +490,38 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, 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 id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
|
||||
FROM captures
|
||||
WHERE source = ANY($1::text[])
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
@@ -441,6 +552,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.Unsigned,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -464,6 +576,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
|
||||
@@ -510,9 +669,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, workflow = $5, owner = $6, repo = $7,
|
||||
version = version + 1, status = $8,
|
||||
secret = CASE WHEN $9::text = '' THEN secret ELSE $9 END,
|
||||
updated_at = now()
|
||||
version = version + 1, status = $8, updated_at = now()
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
@@ -525,12 +682,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,
|
||||
@@ -541,7 +694,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
|
||||
|
||||
@@ -48,6 +48,7 @@ type Capture struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
}
|
||||
|
||||
type ChannelStatus struct {
|
||||
@@ -189,6 +190,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,17 +1,17 @@
|
||||
-- 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)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
|
||||
-- name: ListCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1;
|
||||
|
||||
-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
|
||||
FROM captures
|
||||
WHERE source = ANY(@sources::text[])
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
@@ -47,30 +47,25 @@ WHERE id = $1;
|
||||
DELETE FROM mappings WHERE id = $1;
|
||||
|
||||
-- name: InsertBinding :exec
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9);
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8);
|
||||
|
||||
-- name: GetBinding :one
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings WHERE id = $1;
|
||||
|
||||
-- name: ListBindings :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
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
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
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, workflow = $5, owner = $6, repo = $7,
|
||||
version = version + 1, status = $8,
|
||||
secret = CASE WHEN sqlc.arg(secret)::text = '' THEN secret ELSE sqlc.arg(secret) END,
|
||||
updated_at = now()
|
||||
version = version + 1, status = $8, updated_at = now()
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: SetBindingArmed :execrows
|
||||
@@ -97,3 +92,25 @@ VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||
-- 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;
|
||||
|
||||
-- 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();
|
||||
@@ -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,156 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"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)
|
||||
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.BindingTaskCreator = (*Client)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*Client)(nil)
|
||||
@@ -460,6 +462,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")
|
||||
@@ -77,6 +79,7 @@ type Deps struct {
|
||||
ApplyStatus storecontract.ApplyStatusStore
|
||||
Mappings storecontract.MappingStore
|
||||
Bindings storecontract.BindingStore
|
||||
Sources storecontract.SourceStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
// PlaybookDispatcher is the side-effecting-action idempotency ledger
|
||||
@@ -646,6 +649,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)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"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"
|
||||
@@ -149,7 +150,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
|
||||
return &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,
|
||||
Body: c.Body, Authenticated: c.Authenticated, Unsigned: c.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +161,24 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
|
||||
return 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,
|
||||
Body: c.Body, Authenticated: c.Authenticated, 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +216,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, 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),
|
||||
}
|
||||
}
|
||||
@@ -214,7 +232,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, 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),
|
||||
}
|
||||
}
|
||||
@@ -270,6 +288,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
|
||||
@@ -315,6 +336,12 @@ func mapError(err error) error {
|
||||
return status.Error(codes.FailedPrecondition, msgBindingTransition)
|
||||
case errors.Is(err, storecontract.ErrAlreadyDispatched):
|
||||
return status.Error(codes.AlreadyExists, msgAlreadyDispatched)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
return status.Error(codes.NotFound, msgSourceNotFound)
|
||||
case errors.Is(err, storecontract.ErrSourcePathTaken):
|
||||
return status.Error(codes.AlreadyExists, msgSourcePathTaken)
|
||||
case errors.Is(err, storecontract.ErrSourceSigningStale):
|
||||
return status.Error(codes.FailedPrecondition, msgSourceSigning)
|
||||
default:
|
||||
return status.Error(codes.Internal, msgInternal)
|
||||
}
|
||||
@@ -373,6 +400,8 @@ func sentinelForStatus(st *status.Status) error {
|
||||
return storecontract.ErrBindingOverlap
|
||||
case msgBindingTransition:
|
||||
return storecontract.ErrBindingTransition
|
||||
case msgSourceSigning:
|
||||
return storecontract.ErrSourceSigningStale
|
||||
}
|
||||
case codes.NotFound:
|
||||
switch st.Message() {
|
||||
@@ -380,10 +409,15 @@ func sentinelForStatus(st *status.Status) error {
|
||||
return storecontract.ErrBindingNotFound
|
||||
case msgMappingNotFound:
|
||||
return storecontract.ErrMappingNotFound
|
||||
case msgSourceNotFound:
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
case codes.AlreadyExists:
|
||||
if st.Message() == msgAlreadyDispatched {
|
||||
switch st.Message() {
|
||||
case msgAlreadyDispatched:
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
case msgSourcePathTaken:
|
||||
return storecontract.ErrSourcePathTaken
|
||||
}
|
||||
case codes.Unavailable:
|
||||
if st.Message() == msgTaskLogsUnavailable {
|
||||
|
||||
@@ -21,9 +21,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) {
|
||||
@@ -37,8 +43,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) {
|
||||
@@ -70,7 +85,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 {
|
||||
@@ -93,7 +107,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)
|
||||
}
|
||||
@@ -118,7 +131,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)
|
||||
}
|
||||
|
||||
@@ -157,9 +169,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
|
||||
}
|
||||
@@ -181,7 +192,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)
|
||||
}
|
||||
|
||||
@@ -243,15 +253,5 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "approve binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated.Secret = ""
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
// 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 = ""
|
||||
}
|
||||
}
|
||||
@@ -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 TestHandleBindingCreateRejectsOverlap(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
@@ -220,10 +182,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())
|
||||
@@ -277,35 +237,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")
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,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
|
||||
@@ -266,6 +271,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) {
|
||||
|
||||
@@ -128,6 +128,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);
|
||||
@@ -308,6 +316,8 @@ message CapturedEvent {
|
||||
string headers = 6;
|
||||
string body = 7;
|
||||
bool authenticated = 8;
|
||||
// unsigned marks an event taken on an approved unsigned source.
|
||||
bool unsigned = 9;
|
||||
}
|
||||
|
||||
// MappingField mirrors internal/domain/mapping.Field.
|
||||
@@ -344,11 +354,21 @@ 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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
@@ -709,6 +729,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; }
|
||||
|
||||
|
||||
Vendored
+12
-12
@@ -1,19 +1,19 @@
|
||||
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=>T(e)===`[object Map]`,g=e=>T(e)===`[object Set]`,_=e=>T(e)===`[object Date]`,v=e=>T(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,T=e=>w.call(e),ee=e=>T(e).slice(8,-1),te=e=>T(e)===`[object Object]`,ne=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,re=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ie=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},ae=/-\w/g,oe=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),se=/\B([A-Z])/g,ce=ie(e=>e.replace(se,`-$1`).toLowerCase()),le=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),E=ie(e=>e?`on${le(e)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},fe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=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 ve(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Se(r):ve(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var ye=/;(?![^(]*\))/g,be=/:([^]+)/,xe=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Se(e){let t={};return e.replace(xe,e=>e.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Ce(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=D(t)),n&&(e.style=ve(n)),e}var we=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Te=r(we);we+``;function Ee(e){return!!e||e===``}function De(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=je(e[i],t[i],n);return r}function Oe(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]&&je(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function ke(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?Oe(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||!je(e[r],t[r],n))return!1}return String(e)===String(t)}function Ae(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 je(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?Ae(e,t,n,De):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:Ae(e,t,n,ke):String(e)===String(t))))}function Me(e,t){return e.findIndex(e=>je(e,t))}var Ne=e=>!!(e&&e.__v_isRef===!0),O=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Ne(e)?O(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:x(t)?FLine truncated
|
||||
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,`
|
||||
`)&&(ki(e,0)||yi(),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)&&!re(a)||a[0]===`.`||t&&!re(a)||u&&u.includes(a)){if(Ei(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&&cn(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ns(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ls(()=>{x&&Ns(x,n,t),l&&g.enter(e),h&&wr(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]=As(d[t]),g=h.type===fs;e?(g&&!u&&t+1<p&&As(d[t+1]).type===fs&&(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,ki(r,1)||yi()),n(null,h,r,null,o,s,Si(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&&Ci(f)&&f.data===`]`?a(t.anchor=f):(yi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(ji(e,t)||yi(),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,Si(d),c),r&&(r.vnode.el=t.el,So(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ci(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 Ti=new Set([`src`,`srcset`,`href`,`poster`]);function Ei(e,t,n){return Ti.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Di=`data-allow-mismatch`,Oi={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ki(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Di);)e=e.parentElement;return Ai(e&&e.getAttribute(Di),t)}function Ai(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Oi[t])}}function ji(e,t){return ki(e.parentElement,1)||Mi(e)||Ni(t)}function Mi(e){return e.nodeType===1&&Ai(e.getAttribute(Di),1)}function Ni({props:e}){let t=e&&e[Di];return typeof t==`string`&&Ai(t,1)}var Pi=ge().requestIdleCallback||(e=>setTimeout(e,1)),Fi=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ii=(e=1e4)=>t=>{let n=Pi(t,{timeout:e});return()=>Fi(n)};function Li(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 Ri=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(Li(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},zi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Bi=(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 Vi(e,t){if(Ci(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ci(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Hi=e=>!!e.type.__asyncLoader;function Ui(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 N({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=>Vi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ls;if(fi(e),u)return()=>Wi(u,e);let t=t=>{l=null,Xn(t,e,13,!r)};if(s&&e.suspense||Ws)return p().then(t=>()=>Wi(t,e)).catch(e=>(t(e),()=>r?V(r,{error:e}):null));let a=k(!1),c=k(),d=k(!!i),f,m;return sa(()=>{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&&Gi(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Wi(u,e);if(c.value&&r)return V(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Gl]=Hl(i);let a=r||i.props&&i.props.type===`number`;ll(e,t?`change`:`input`,t=>{t.target.composing||e[Gl](ql(e.value,n,a))}),(n||a)&&ll(e,`change`,()=>{e.value=ql(e.value,n,a)}),t||(ll(e,`compositionstart`,Ul),ll(e,`compositionend`,Wl),ll(e,`change`,Wl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[Kl];delete e[Kl],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Gl](ql(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Gl]=Hl(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(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)}},Yl={deep:!0,created(e,t,n){e[Gl]=Hl(n),ll(e,`change`,()=>{let t=e._modelValue,n=tu(e),r=e.checked,i=e[Gl];if(m(t)){let e=Me(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(nu(e,r))})},mounted:Xl,beforeUpdate(e,t,n){e[Gl]=Hl(n),Xl(e,t,n)}};function Xl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Me(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,nu(e,!0))}e.checked!==i&&(e.checked=i)}var Zl={created(e,{value:t},n){e.checked=je(t,n.props.value),e[Gl]=Hl(n),ll(e,`change`,()=>{e[Gl](tu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Gl]=Hl(r),t!==n&&(e.checked=je(t,r.props.value))}},Ql={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ll(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(tu(e)):tu(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[Gl](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Gl]=Hl(r)},mounted(e,{value:t}){eu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Gl]=Hl(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!$l(t,n[1],n[0]))&&eu(e,t)}};function $l(e,t,n){if(!n||m(e))return je(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 eu(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=tu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Me(t,o)>-1}else a.selected=t.has(o)}else if(je(tu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function tu(e){return`_value`in e?e._value:e.value}function nu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var ru={created(e,t,n){au(e,t,n,null,`created`)},mounted(e,t,n){au(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){au(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){au(e,t,n,r,`updated`)}};function iu(e,t){switch(e){case`SELECT`:return Ql;case`TEXTAREA`:return Jl;default:switch(t){case`checkbox`:return Yl;case`radio`:return Zl;default:return Jl}}}function au(e,t,n,r,i){let a=iu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function ou(){Jl.getSSRProps=({value:e})=>({value:e}),Zl.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},Yl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Me(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}},ru.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=iu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var su=[`ctrl`,`shift`,`alt`,`meta`],cu={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)=>su.some(n=>e[`${n}Key`]&&!t.includes(n))},lu=(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=cu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},uu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=ce(n.key);if(t.some(e=>e===r||uu[e]===r))return e(n)}))},fu=u({patchProp:xl},xc),pu,mu=!1;function hu(){return pu||=Ho(fu)}function gu(){return pu=mu?pu:Uo(fu),mu=!0,pu}var _u=((...e)=>{hu().render(...e)}),vu=((...e)=>{gu().hydrate(...e)}),yu=((...e)=>{let t=hu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Su(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,xu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),bu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var kp;function Ap(e){kp=e}var jp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Mp(e){let t=e instanceof jp?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 Np(e,t){let n=await fetch(e,t);if(kp?.(n.status===401),!n.ok)throw new jp(await Op(n),n.status);return n}async function Pp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Ep,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 Np(e,s);return a?await c.json():void 0}var Y={health:()=>Pp(`/health/detailed`),summary:()=>Pp(`/api/summary`),tasks:()=>Pp(`/api/tasks`),taskMeta:()=>Pp(`/api/task-meta`),task:e=>Pp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Pp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/changes`+Dp(t)),taskDebug:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/debug`+Dp(t)),taskAction:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Pp(`/api/setup`),capabilities:()=>Pp(`/api/capabilities`),workflows:()=>Pp(`/api/workflows`),workRequest:e=>Pp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Pp(`/api/skills`),channels:()=>Pp(`/api/channels`),curators:()=>Pp(`/api/curators`),channelReload:e=>Pp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Pp(`/api/config`),logs:e=>Pp(`/api/logs`+Dp(e)),taskLogs:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/logs`+Dp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Pp(`/api/version`),updateSnapshot:()=>Pp(`/api/chat/update`),updateInstall:e=>Pp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Pp(`/api/captures`+Dp({limit:e})),mappings:()=>Pp(`/api/mappings`),mappingCreate:e=>Pp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Pp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Pp(`/api/bindings`),bindingCreate:e=>Pp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Pp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Pp(`/api/chat/sessions`),chatMessages:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Pp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Pp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Tp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Pp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Pp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Np(`/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 Fp(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 Ip(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(wp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Lp=`archie.web.chat.channel`;function Rp(){let e=localStorage.getItem(Lp);return e||(e=Tp(),localStorage.setItem(Lp,e)),e}var zp=/(?:^|\s)\/([^\s]*)$/,Bp=/(?:^|\s)\/[^\s]*$/,Vp=8;function Hp(e,t,n){let r=t.slice(0,n).match(zp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Vp)}function Up(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(Bp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}${n} ${i}`,cursor:o+n.length+1}}function Wp(e,t){let n=t.trim();return e.some(e=>e.command===n)}function Gp(e){return{text:e,sourceID:Tp()}}function Kp(e){return{...e}}function qp(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.tri
Line truncated
|
||||
`)&&(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 Np;function Pp(e){Np=e}var Fp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Ip(e){let t=e instanceof Fp?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 Lp(e,t){let n=await fetch(e,t);if(Np?.(n.status===401),!n.ok)throw new Fp(await Mp(n),n.status);return n}async function Rp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Ap,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 Lp(e,s);return a?await c.json():void 0}var J={health:()=>Rp(`/health/detailed`),summary:()=>Rp(`/api/summary`),tasks:()=>Rp(`/api/tasks`),taskMeta:()=>Rp(`/api/task-meta`),task:e=>Rp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Rp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Rp(`/api/tasks/${encodeURIComponent(e)}/changes`+jp(t)),taskDebug:(e,t)=>Rp(`/api/tasks/${encodeURIComponent(e)}/debug`+jp(t)),taskAction:(e,t)=>Rp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Rp(`/api/setup`),capabilities:()=>Rp(`/api/capabilities`),workflows:()=>Rp(`/api/workflows`),workRequest:e=>Rp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Rp(`/api/skills`),channels:()=>Rp(`/api/channels`),curators:()=>Rp(`/api/curators`),channelReload:e=>Rp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Rp(`/api/config`),logs:e=>Rp(`/api/logs`+jp(e)),taskLogs:(e,t)=>Rp(`/api/tasks/${encodeURIComponent(e)}/logs`+jp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Rp(`/api/version`),updateSnapshot:()=>Rp(`/api/chat/update`),updateInstall:e=>Rp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Rp(`/api/captures`+jp({limit:e})),mappings:()=>Rp(`/api/mappings`),mappingCreate:e=>Rp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Rp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Rp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Rp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Rp(`/api/bindings`),bindingCreate:e=>Rp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Rp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Rp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Rp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>Rp(`/api/sources`),sourceCreate:e=>Rp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Rp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Rp(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>Rp(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>Rp(`/api/chat/sessions`),chatMessages:e=>Rp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Rp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Rp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Rp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:kp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Rp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Rp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Rp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Rp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Lp(`/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 zp(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 Bp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Op(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Vp=`archie.web.chat.channel`;function Hp(){let e=localStorage.getItem(Vp);return e||(e=kp(),localStorage.setItem(Vp,e)),e}var Up=/(?:^|\s)\/([^\s]*)$/,Wp=/(?:^|\s)\/[^\s]*$/,Gp=8;function Kp(e,t,n){let r=t.slice(0,n).match(Up);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Gp)}function qp(e,t,
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&&(Zp.value=n.session_id),n.type===`delta`&&(o+=n.text,nm.value=nm.value?{...nm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],nm.value=nm.value?{...nm.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`);Qp.value=[...Qp.value,{from:`assistant`,text:o,tool_calls:a}],nm.value=null,em.value=`Ready`,await _m()}catch(e){let t=e;t.name===`AbortError`&&!c?(nm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},em.value=`Stopped`):(nm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Kp(r):void 0,isRetry:i},em.value=`Error — retry available`)}finally{clearTimeout(l),hm=null,tm.value=!1}}function Am(){em.value=`Stopping…`,Zp.value&&Y.chatCancel(Zp.value).catch(()=>{}),gm()}function jm(){ra(()=>{_m().catch(e=>{em.value=e.message||`Chat unavailable`})}),sa(()=>{gm()})}var Mm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Nm=N({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return J(`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)=>(L(),R(`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":A(Jp),onClick:i[0]||=e=>n(`toggle`)},[B(`span`,{"aria-hidden":`true`,class:D(r(!e.open))},[V(A(Md),{size:22})],2),B(`span`,{"aria-hidden":`true`,class:D(r(e.open))},[V(A(Jd),{size:22})],2)],8,Mm))}});function Pm(e){return typeof e==`string`?`'${e}'`:new Rm().serialize(e)}var Fm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Im=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Fm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Lm(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&&Im[n]?Im[n]:n+128,s=a<128&&Im[a]?Im[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 Rm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Lm(e,t):n===`number`&&r===`number`?e-t:Lm(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(Lm),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&&(tm.value=n.session_id),n.type===`delta`&&(o+=n.text,om.value=om.value?{...om.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],om.value=om.value?{...om.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`);nm.value=[...nm.value,{from:`assistant`,text:o,tool_calls:a}],om.value=null,im.value=`Ready`,await xm()}catch(e){let t=e;t.name===`AbortError`&&!c?(om.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},im.value=`Stopped`):(om.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Xp(r):void 0,isRetry:i},im.value=`Error — retry available`)}finally{clearTimeout(l),ym=null,am.value=!1}}function Pm(){im.value=`Stopping…`,tm.value&&J.chatCancel(tm.value).catch(()=>{}),bm()}function Fm(){ia(()=>{xm().catch(e=>{im.value=e.message||`Chat unavailable`})}),ca(()=>{bm()})}var Im=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Lm=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(Qp),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Id),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(Qd),{size:22})],2)],8,Im))}});function Rm(e){return typeof e==`string`?`'${e}'`:new Hm().serialize(e)}var zm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Bm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[zm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Vm(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&&Bm[n]?Bm[n]:n+128,s=a<128&&Bm[a]?Bm[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 Hm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Vm(e,t):n===`number`&&r===`number`?e-t:Vm(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(Vm),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?ic(t.default({present:o.value})[0],{ref:e=>{let t=fh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),vg=N({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=xh(n.default()),r=e.findIndex(e=>e.type!==ps);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?W(t,i.props):t,o=Os({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),yg=[`area`,`img`,`input`],Z=N({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`&&yg.includes(r)?()=>ic(r,t):r===`template`?()=>ic(vg,t,{default:n.default}):()=>ic(e.as,t,{default:n.default})}});function bg(){let e=k();return{primitiveElement:e,currentElement:G(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:fh(e))}}function xg({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 Sg({type:e,defaultValue:t,modelValue:n}){return e||xg({type:e,defaultValue:t,modelValue:n})}function Cg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function wg(e,t){let n=G(()=>Sg(e)),r=bh(e,`modelValue`,t,{defaultValue:Cg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=zm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Gm(t,e)){let n=t.findIndex(t=>zm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:G(()=>n.value===`single`)}}var[Tg,Eg]=Vm(`DialogRoot`),Dg=N({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=bh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=k(),a=k(),{modal:o,unmountOnHide:s}=En(n);return Eg({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)=>F(e.$slots,`default`,{open:A(r),close:()=>r.value=!1})}}),Og=N({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;X();let n=Tg();return(e,r)=>(L(),z(A(Z),W(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>A(n).onOpenChange(!1)}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`type`]))}}),kg=`dismissableLayer.pointerDownOutside`,Ag=`dismissableLayer.focusOutside`;function jg(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 Mg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1),a=k(()=>{});return Ar(o=>{if(!Ym||!xn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(jg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Um(kg,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:()=>{xn(n)&&(i.value=!0)}}}function Ng(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1);return Ar(a=>{if(!Ym||!xn(n))return;let o=async n=>{if(!t?.value)return;await ar(),await ar();let r=n.target;t.value&&r&&!jg(t.value,r)&&n.target&&!i.value&&Um(Ag,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{xn(n)&&(i.value=!0)},onBlurCapture:()=>{xn(n)&&(i.value=!1)}}}var Pg=N({__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}=X(),o=G(()=>a.value?.ownerDocument??globalThis.document),s=G(()=>Dh.layersRoot),c=G(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=G(()=>Dh.layersWithOutsidePointerEventsDisabled.size>0),u=G(()=>{let e=Array.from(s.value),[t]=[...Dh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Mg
Line truncated
|
||||
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=gh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),Sg=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=Th(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)}}}),Cg=[`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`&&Cg.includes(r)?()=>ac(r,t):r===`template`?()=>ac(Sg,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function wg(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:gh(e))}}function Tg({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 Eg({type:e,defaultValue:t,modelValue:n}){return e||Tg({type:e,defaultValue:t,modelValue:n})}function Dg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Og(e,t){let n=W(()=>Eg(e)),r=wh(e,`modelValue`,t,{defaultValue:Dg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Um(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Ym(t,e)){let n=t.findIndex(t=>Um(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[kg,Ag]=Gm(`DialogRoot`),jg=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=wh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return Ag({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})}}),Mg=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=kg();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`]))}}),Ng=`dismissableLayer.pointerDownOutside`,Pg=`dismissableLayer.focusOutside`;function Fg(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 Ig(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!$m||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(Fg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){qm(Ng,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 Lg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!$m||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!Fg(t.value,r)&&n.target&&!i.value&&qm(Pg,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 Rg=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(()=>jh.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>jh.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...jh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Ig
Line truncated
|
||||
- a positive number
|
||||
- less than the value passed to \`max\` (or ${xx} if no \`max\` prop is set)
|
||||
- less than the value passed to \`max\` (or ${Tx} if no \`max\` prop is set)
|
||||
- \`null\` or \`undefined\` if the progress is indeterminate.
|
||||
|
||||
Defaulting to \`null\`.`),null)}function Ex(e){return wx(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 \`${xx}\`.`),xx)}var Dx=N({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:xx},getValueLabel:{type:Function,required:!1,default:(e,t)=>wx(e)?`${Math.round(e/t*xx)}%`: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;X();let i=bh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=bh(n,`max`,r,{passive:n.max===void 0});M(()=>i.value,async e=>{let t=Tx(e,n.max);t!==e&&(await ar(),i.value=t)},{immediate:!0}),M(()=>n.max,e=>{let t=Ex(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=G(()=>Wm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Cx({modelValue:i,max:a,progressState:o}),(e,t)=>(L(),z(A(Z),{"as-child":e.asChild,as:e.as,"aria-valuemax":A(a),"aria-valuemin":0,"aria-valuenow":wx(A(i))?A(i):void 0,"aria-valuetext":e.getValueText?.(A(i),A(a)),"aria-label":e.getValueLabel(A(i),A(a)),role:`progressbar`,"data-state":o.value,"data-value":A(i)??void 0,"data-max":A(a)},{default:j(()=>[F(e.$slots,`default`,{modelValue:A(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Ox=N({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Sx();return X(),(e,r)=>(L(),z(A(Z),W(t,{"data-state":A(n).progressState.value,"data-value":A(n).modelValue?.value??void 0,"data-max":A(n).max.value}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),kx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Ax=[` `,`Enter`];function jx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Mx(e,t,n)):Mx(e,t,n)}function Mx(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]:zm(e,t)}function Nx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Px=[`value`],[Fx,Ix]=Vm(`SelectRoot`),Lx=N({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}=En(n),c=bh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=bh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=k(),d=k(),f=k({x:0,y:0}),p=G(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Wm(c.value));O_({isProvider:!0});let m=Ih(s),h=Vh(u),g=k(new Set),_=G(()=>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=>Mx(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=>jx(e,t.value,n.by))}return Ix({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)=>(L(),z(A(V_),null,{default:j(()=>[F(e.$slots,`default`,{modelValue:A(c),open:A(l)}),A(h)&&e.name?(L(),z(Rx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:A(o),required:A(i),name:e.name,autocomplete:e.autocomplete,disabled:A(a),value:A(c)},{default:j(()=>[A(Wm)(A(c))?(L(),R(`option`,{key:0,value:e.nullableValue},null,8,Px)):U(`v-if`,!0),(L(!0),R(I,null,P(Array.from(g.value),e=>(L(),R(`option`,W({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):U(`v-if`,!0)]),_:3}))}}),Rx=N({__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=k(),r=Fx();M(()=>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:rT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>rT(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=aT(c),u=e+1<n.length?aT(n[e+1]):null;if(l&&u&&oT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=aT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>rT(e)),rows:r.map(e=>e.map(e=>rT(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:rT(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:rT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function aT(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 oT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var sT={class:`[overflow-wrap:anywhere]`},cT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},lT={class:`font-mono text-[0.85em]`},uT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},dT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},fT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},pT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},mT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},hT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},gT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},_T={key:8,class:`mb-2.5 last:mb-0`},vT=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>iT(t.text));return(e,t)=>(L(),R(`div`,sT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,cT,[B(`code`,lT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,uT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(tT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(tT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,dT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,fT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,pT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,mT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,gT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,_T,[V(tT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),yT={class:`truncate`},bT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(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:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,yT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),xT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},ST={class:`font-semibold text-foreground`},CT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},wT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>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?(L(),z(bT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,xT,[V(A(qd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,ST,O(n.value),1),r.value?(L(),R(`code`,CT,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),TT={key:0,class:`mb-2 grid gap-0.5 text-xs`},ET={key:2,class:`whitespace-pre-wrap`},DT=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`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?(L(),R(`div`,TT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(wT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(vT,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,ET,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),OT={class:`w-full self-center justify-self-center py-6 text-center`},kT={class:`grid gap-2`},AT=[`onClick`],jT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,OT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>tA?`${n.slice(0,tA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var rA=[`title`],iA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Ok(n.event)),a=G(()=>nA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?yO(n.event.at):`—`);return(e,t)=>(L(),z(A(Qk),{class:D(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:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,rA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function aA(e,t){return`${e}:${t??0}`}function oA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=aA(nA(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 sA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},cA={class:`max-h-[28rem] overflow-y-auto`},lA=[`aria-expanded`,`aria-label`,`onClick`],uA=[`title`],dA=N({__name:`LiveActivityCard`,setup(e){let t=eE(),{activity:n,streamKind:r,streamState:i}=ad(tk()),a=nn(new Set),o=G(()=>oA(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 nA(e.representative)}function u(e){return e.representative.at?yO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(dO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[V(A(_O),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(fO),null,{default:j(()=>[V(A(ZD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(pO),null,{default:j(()=>[B(`div`,sA,[B(`div`,cA,[V(A(Xk),null,{default:j(()=>[V(A(eA),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[V(A(Qk),null,{default:j(()=>[V(A($k),null,{default:j(()=>[...t[1]||=[H(`Event`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[2]||=[H(`Task`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[3]||=[H(`Detail`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[4]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(Zk),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(Qk),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(UD),null,{default:j(()=>[V(A(KD),null,{default:j(()=>[V(A(YD),null,{default:j(()=>[...t[5]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(iA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(Qk),{class:D(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:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`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:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(ZD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,lA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,uA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(iA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),fA=N({__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=$S(t,`class`);return(e,r)=>(L(),z(A(Dx),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Ox),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`tLine truncated
|
||||
Defaulting to \`null\`.`),null)}function Ax(e){return Ox(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 \`${Tx}\`.`),Tx)}var jx=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Tx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Ox(e)?`${Math.round(e/t*Tx)}%`: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=wh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=wh(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=kx(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=Ax(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>Jm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Dx({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":Ox(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`]))}}),Mx=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Ex();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`]))}}),Nx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Px=[` `,`Enter`];function Fx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Ix(e,t,n)):Ix(e,t,n)}function Ix(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]:Um(e,t)}function Lx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Rx=[`value`],[zx,Bx]=Gm(`SelectRoot`),Vx=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=wh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=wh(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:Jm(c.value));M_({isProvider:!0});let m=Bh(s),h=Gh(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=>Ix(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=>Fx(e,t.value,n.by))}return Bx({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(G_),null,{default:A(()=>[P(e.$slots,`default`,{modelValue:k(c),open:k(l)}),k(h)&&e.name?(I(),R(Hx,{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(Jm)(k(c))?(I(),L(`option`,{key:0,value:e.nullableValue},null,8,Rx)):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}))}}),Hx=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=zx();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:sT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>sT(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=lT(c),u=e+1<n.length?lT(n[e+1]):null;if(l&&u&&uT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=lT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>sT(e)),rows:r.map(e=>e.map(e=>sT(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:sT(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:sT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function lT(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 uT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var dT={class:`[overflow-wrap:anywhere]`},fT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},pT={class:`font-mono text-[0.85em]`},mT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},hT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},gT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},_T={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},vT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},yT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},bT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},xT={key:8,class:`mb-2.5 last:mb-0`},ST=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>cT(t.text));return(e,t)=>(I(),L(`div`,dT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,fT,[z(`code`,pT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,mT,[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(aT,{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(aT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,hT,[B(aT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,gT,[B(aT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,_T,[B(aT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,vT,[B(aT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,yT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(aT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,bT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(aT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,xT,[B(aT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),CT={class:`truncate`},wT=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`,CT,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),TT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},ET={class:`font-semibold text-foreground`},DT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},OT=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(wT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,TT,[B(k(Zd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,ET,D(n.value),1),r.value?(I(),L(`code`,DT,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),kT={key:0,class:`mb-2 grid gap-0.5 text-xs`},AT={key:2,class:`whitespace-pre-wrap`},jT=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`,kT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(OT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(ST,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,AT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),MT={class:`w-full self-center justify-self-center py-6 text-center`},NT={class:`grid gap-2`},PT=[`onClick`],FT=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`,MT,[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>iA?`${n.slice(0,iA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var oA=[`title`],sA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>Mk(n.event)),a=W(()=>aA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?CO(n.event.at):`—`);return(e,t)=>(I(),R(k(nA),{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,oA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function cA(e,t){return`${e}:${t??0}`}function lA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=cA(aA(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 uA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},dA={class:`max-h-[28rem] overflow-y-auto`},fA=[`aria-expanded`,`aria-label`,`onClick`],pA=[`title`],mA=M({__name:`LiveActivityCard`,setup(e){let t=iE(),{activity:n,streamKind:r,streamState:i}=od(ak()),a=rn(new Set),o=W(()=>lA(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 aA(e.representative)}function u(e){return e.representative.at?CO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(hO),null,{default:A(()=>[B(k(bO),null,{default:A(()=>[B(k(xO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(gO),null,{default:A(()=>[B(k(tO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(_O),null,{default:A(()=>[z(`div`,uA,[z(`div`,dA,[B(k(eA),null,{default:A(()=>[B(k(rA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(nA),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(tA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(nA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(qD),null,{default:A(()=>[B(k(XD),null,{default:A(()=>[B(k($D),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(sA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(nA),{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(tO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,fA)]),_: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,pA)]),_: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(sA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),hA=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=rC(t,`class`);return(e,r)=>(I(),R(k(jx),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(Mx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
|
||||
@@ -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";
|
||||
@@ -7,14 +6,11 @@ import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
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,
|
||||
type Binding,
|
||||
type BindingDraft,
|
||||
type MappingOption,
|
||||
@@ -23,8 +19,7 @@ import {
|
||||
|
||||
/**
|
||||
* The binding editor: name, the matcher source senders POST to, the field
|
||||
* mapping, the workflow, an optional repo pin, and the shared secret their
|
||||
* signature is checked against.
|
||||
* mapping, the workflow and an optional repo pin. Signing is the source's.
|
||||
*/
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -51,17 +46,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>
|
||||
@@ -81,7 +70,7 @@ async function copySecret(): Promise<void> {
|
||||
<Field>
|
||||
<FieldLabel for="binding-source">Source</FieldLabel>
|
||||
<Input id="binding-source" v-model="draft.source" />
|
||||
<FieldDescription>The path segment senders POST to, for example "sentry".</FieldDescription>
|
||||
<FieldDescription>The path of a source, from the sources list above.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
@@ -132,38 +121,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
|
||||
|
||||
@@ -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";
|
||||
@@ -18,7 +19,12 @@ const emit = defineEmits<{
|
||||
<template>
|
||||
<TableRow>
|
||||
<TableCell class="font-medium">{{ props.binding.name }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{ matcherSource(props.binding) }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">
|
||||
<div class="flex items-center gap-2">
|
||||
{{ matcherSource(props.binding) }}
|
||||
<Badge v-if="props.binding.unsigned" variant="warn">Unsigned</Badge>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>{{ props.binding.workflow || "—" }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{ repoPin(props.binding) }}</TableCell>
|
||||
<TableCell><BindingStatusBadge :status="props.binding.status" /></TableCell>
|
||||
|
||||
@@ -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";
|
||||
@@ -69,6 +70,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">
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -21,6 +20,7 @@ export interface Binding {
|
||||
repo?: string;
|
||||
status?: string;
|
||||
version?: number;
|
||||
unsigned?: boolean;
|
||||
}
|
||||
|
||||
/** The fields of GET /api/mappings this page needs. */
|
||||
@@ -71,7 +71,6 @@ export interface BindingDraft {
|
||||
workflow: string;
|
||||
owner: string;
|
||||
repo: string;
|
||||
secret: string;
|
||||
}
|
||||
|
||||
export function emptyDraft(): BindingDraft {
|
||||
@@ -83,7 +82,6 @@ export function emptyDraft(): BindingDraft {
|
||||
workflow: "",
|
||||
owner: "",
|
||||
repo: "",
|
||||
secret: generateSecret(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -96,9 +94,6 @@ export function draftFromBinding(binding: Binding): BindingDraft {
|
||||
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: "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,16 +106,9 @@ export function bindingPayload(draft: BindingDraft): Record<string, unknown> {
|
||||
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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,6 +5,7 @@ import { computed } from "vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { TableCell, TableRow } from "@/components/ui/table";
|
||||
import { ago } from "@/lib/format";
|
||||
import { captureSignature } from "./capture-signature";
|
||||
import { selected, type Capture } from "./state";
|
||||
|
||||
/**
|
||||
@@ -15,6 +16,7 @@ import { selected, type Capture } from "./state";
|
||||
*/
|
||||
const props = defineProps<{ capture: Capture }>();
|
||||
|
||||
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:
|
||||
@@ -43,7 +45,12 @@ function open(): void {
|
||||
<!-- A stored capture carries no claim from a binding, so this reads Unbound
|
||||
for every row: the column is where a claim would appear, not a state a
|
||||
reader can act on today. -->
|
||||
<TableCell><Badge variant="idle">Unbound</Badge></TableCell>
|
||||
<TableCell>
|
||||
<div class="flex items-center gap-1">
|
||||
<Badge variant="idle">Unbound</Badge>
|
||||
<Badge :variant="signature.kind">{{ signature.label }}</Badge>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell class="font-mono">{{ props.capture.content_type || "—" }}</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<ChevronRight class="size-4 text-fg-subtle" />
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -25,6 +25,7 @@ export interface Capture {
|
||||
headers?: string;
|
||||
body?: string;
|
||||
authenticated?: boolean;
|
||||
unsigned?: boolean;
|
||||
}
|
||||
|
||||
interface CapturesResponse {
|
||||
|
||||
@@ -173,6 +173,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`),
|
||||
|
||||
@@ -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>
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -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)),
|
||||
};
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user