Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91d03b730d | ||
|
|
0e56fe7662 | ||
|
|
2d2615b734 | ||
|
|
5a07a13ac8 | ||
|
|
4016820541 | ||
|
|
0a188ddafe |
@@ -7,6 +7,7 @@ import (
|
||||
"reflect"
|
||||
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
@@ -112,24 +113,58 @@ func (r *CommitRepository) LoadLatestAttempt(ctx context.Context, id commitcontr
|
||||
return attempt, err
|
||||
}
|
||||
|
||||
func (r *CommitRepository) FindLatestAttempt(ctx context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
|
||||
attempt, err := r.LoadLatestAttempt(ctx, id)
|
||||
if errors.Is(err, ErrActionAttemptNotFound) {
|
||||
return commitcontract.ActionAttempt{}, false, nil
|
||||
}
|
||||
return attempt, err == nil, err
|
||||
}
|
||||
|
||||
func (r *CommitRepository) ListAuthorizedByOwner(ctx context.Context, actorID identity.ActorID, principalID identity.PrincipalID, limit int) ([]commitcontract.AuthorizedAction, error) {
|
||||
if actorID == "" || principalID == "" || limit < 1 || limit > 50 {
|
||||
return nil, fmt.Errorf("invalid authorized action owner query")
|
||||
}
|
||||
rows, err := r.pool.Query(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
|
||||
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
|
||||
proposal_state,action_state,authorized_at_unix_millis
|
||||
FROM commit.authorized_action_envelopes
|
||||
WHERE actor_id=$1 AND principal_id=$2
|
||||
ORDER BY authorized_at_unix_millis DESC, authorized_action_id DESC LIMIT $3`, actorID, principalID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list authorized actions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
actions := make([]commitcontract.AuthorizedAction, 0)
|
||||
for rows.Next() {
|
||||
var action commitcontract.AuthorizedAction
|
||||
if err := scanAuthorized(rows, &action); err != nil {
|
||||
return nil, fmt.Errorf("scan authorized action: %w", err)
|
||||
}
|
||||
actions = append(actions, action)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("list authorized actions: %w", err)
|
||||
}
|
||||
return actions, nil
|
||||
}
|
||||
|
||||
type commitRowQuerier interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
type commitRowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcontract.AuthorizedActionID) (commitcontract.AuthorizedAction, error) {
|
||||
var action commitcontract.AuthorizedAction
|
||||
err := querier.QueryRow(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
err := scanAuthorized(querier.QueryRow(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
|
||||
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
|
||||
proposal_state,action_state,authorized_at_unix_millis
|
||||
FROM commit.authorized_action_envelopes WHERE authorized_action_id=$1`, id).Scan(
|
||||
&action.ID, &action.Proposal.IntentID, &action.Proposal.ActorID, &action.PrincipalID,
|
||||
&action.GrantID, &action.GrantRevision, &action.ScopeID, &action.Proposal.Target.TaskID,
|
||||
&action.Proposal.Target.GoalID, &action.Proposal.Target.ScopeID, &action.Proposal.Target.Revision,
|
||||
&action.Proposal.CapabilityID, &action.Proposal.Operation, &action.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
&action.Proposal.ContinuitySubject.ExpectedRevision, &action.Proposal.ContinuitySubject.FromState,
|
||||
&action.Proposal.ContinuitySubject.ToState, &action.Proposal.ContinuitySubject.EvidenceRef,
|
||||
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis)
|
||||
FROM commit.authorized_action_envelopes WHERE authorized_action_id=$1`, id), &action)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return commitcontract.AuthorizedAction{}, ErrAuthorizedActionNotFound
|
||||
}
|
||||
@@ -138,3 +173,14 @@ func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcont
|
||||
}
|
||||
return action, nil
|
||||
}
|
||||
|
||||
func scanAuthorized(row commitRowScanner, action *commitcontract.AuthorizedAction) error {
|
||||
return row.Scan(
|
||||
&action.ID, &action.Proposal.IntentID, &action.Proposal.ActorID, &action.PrincipalID,
|
||||
&action.GrantID, &action.GrantRevision, &action.ScopeID, &action.Proposal.Target.TaskID,
|
||||
&action.Proposal.Target.GoalID, &action.Proposal.Target.ScopeID, &action.Proposal.Target.Revision,
|
||||
&action.Proposal.CapabilityID, &action.Proposal.Operation, &action.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
&action.Proposal.ContinuitySubject.ExpectedRevision, &action.Proposal.ContinuitySubject.FromState,
|
||||
&action.Proposal.ContinuitySubject.ToState, &action.Proposal.ContinuitySubject.EvidenceRef,
|
||||
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -37,6 +38,8 @@ type creatorAuthoritySource interface {
|
||||
type creatorCommitRepository interface {
|
||||
executionRepository
|
||||
SaveAuthorized(context.Context, commitcontract.AuthorizedAction) error
|
||||
ListAuthorizedByOwner(context.Context, identity.ActorID, identity.PrincipalID, int) ([]commitcontract.AuthorizedAction, error)
|
||||
FindLatestAttempt(context.Context, commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error)
|
||||
}
|
||||
|
||||
type creatorCommandHandler struct {
|
||||
@@ -64,9 +67,66 @@ type creatorActionResponse struct {
|
||||
State commitcontract.ActionState
|
||||
}
|
||||
|
||||
type creatorActionHistoryItem struct {
|
||||
AuthorizedActionID commitcontract.AuthorizedActionID
|
||||
ActionIntentID commitcontract.ActionIntentID
|
||||
ActionAttemptID commitcontract.ActionAttemptID
|
||||
Operation commitcontract.ExternalOperation
|
||||
ProspectiveItemID continuity.ProspectiveItemID
|
||||
State commitcontract.ActionState
|
||||
AuthorizedAtUnixMillis int64
|
||||
}
|
||||
|
||||
type creatorActionHistoryResponse struct {
|
||||
Items []creatorActionHistoryItem
|
||||
}
|
||||
|
||||
func registerCreatorCommandRoutes(mux *http.ServeMux, handler creatorCommandHandler) {
|
||||
mux.HandleFunc("POST /v1/creator/continuity/satisfy-delivered", handler.satisfyDelivered)
|
||||
mux.HandleFunc("POST /v1/creator/authorized-actions/{id}/reconcile", handler.reconcile)
|
||||
mux.HandleFunc("GET /v1/creator/authorized-actions", handler.listAuthorizedActions)
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) listAuthorizedActions(w http.ResponseWriter, r *http.Request) {
|
||||
session, sessionOK := h.creatorSession(w, r, r.Header.Get("Authorization"))
|
||||
if !sessionOK {
|
||||
return
|
||||
}
|
||||
limit := 25
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 50 {
|
||||
http.Error(w, "invalid action history limit", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
actions, err := h.repository.ListAuthorizedByOwner(r.Context(), session.ActorID, session.PrincipalID, limit)
|
||||
if err != nil {
|
||||
http.Error(w, "Commit history unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
items := make([]creatorActionHistoryItem, 0, len(actions))
|
||||
for _, action := range actions {
|
||||
attempt, found, findErr := h.repository.FindLatestAttempt(r.Context(), action.ID)
|
||||
if findErr != nil {
|
||||
http.Error(w, "Commit history unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
item := creatorActionHistoryItem{
|
||||
AuthorizedActionID: action.ID, ActionIntentID: action.Proposal.IntentID,
|
||||
Operation: action.Proposal.Operation, ProspectiveItemID: action.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
State: action.State, AuthorizedAtUnixMillis: action.AuthorizedAtUnixMillis,
|
||||
}
|
||||
if found {
|
||||
item.ActionAttemptID = attempt.ID
|
||||
item.State = attempt.State
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(creatorActionHistoryResponse{Items: items})
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) satisfyDelivered(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -53,6 +53,43 @@ func (f fakeCreatorAuthority) LoadGrant(context.Context, authority.GrantID) (aut
|
||||
return f.grant, f.scope, nil
|
||||
}
|
||||
|
||||
func (f *fakeExecutionRepository) ListAuthorizedByOwner(context.Context, identity.ActorID, identity.PrincipalID, int) ([]commitcontract.AuthorizedAction, error) {
|
||||
if f.action.ID == "" {
|
||||
return []commitcontract.AuthorizedAction{}, nil
|
||||
}
|
||||
return []commitcontract.AuthorizedAction{f.action}, nil
|
||||
}
|
||||
|
||||
func (f *fakeExecutionRepository) FindLatestAttempt(_ context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
|
||||
for index := len(f.attempts) - 1; index >= 0; index-- {
|
||||
if f.attempts[index].AuthorizedID == id {
|
||||
return f.attempts[index], true, nil
|
||||
}
|
||||
}
|
||||
return commitcontract.ActionAttempt{}, false, nil
|
||||
}
|
||||
|
||||
type fakeCreatorHistoryRepository struct {
|
||||
fakeExecutionRepository
|
||||
actions []commitcontract.AuthorizedAction
|
||||
latest map[commitcontract.AuthorizedActionID]commitcontract.ActionAttempt
|
||||
actorID identity.ActorID
|
||||
principalID identity.PrincipalID
|
||||
limit int
|
||||
listCalls int
|
||||
}
|
||||
|
||||
func (f *fakeCreatorHistoryRepository) ListAuthorizedByOwner(_ context.Context, actorID identity.ActorID, principalID identity.PrincipalID, limit int) ([]commitcontract.AuthorizedAction, error) {
|
||||
f.actorID, f.principalID, f.limit = actorID, principalID, limit
|
||||
f.listCalls++
|
||||
return f.actions, nil
|
||||
}
|
||||
|
||||
func (f *fakeCreatorHistoryRepository) FindLatestAttempt(_ context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
|
||||
attempt, ok := f.latest[id]
|
||||
return attempt, ok, nil
|
||||
}
|
||||
|
||||
func TestCreatorCommandDerivesAuthorityAndActionFieldsServerSide(t *testing.T) {
|
||||
handler, repository, executor := validCreatorCommandHandler()
|
||||
mux := http.NewServeMux()
|
||||
@@ -127,6 +164,69 @@ func TestCreatorCommandRejectsSessionForeignOwnerStaleStateAndRevokedGrant(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorActionHistoryUsesSessionOwnerAndShowsMissingAttempt(t *testing.T) {
|
||||
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
|
||||
repository := &fakeCreatorHistoryRepository{
|
||||
actions: []commitcontract.AuthorizedAction{
|
||||
{ID: "authorized-new", PrincipalID: session.PrincipalID, AuthorizedAtUnixMillis: 20, State: commitcontract.ActionAuthorized, Proposal: commitcontract.ActionProposal{ActorID: session.ActorID, IntentID: "intent-new", Operation: commitcontract.OperationSatisfyDelivered, ContinuitySubject: continuity.SatisfyDeliveredSubject{ProspectiveItemID: "prospective-new"}}},
|
||||
{ID: "authorized-pending", PrincipalID: session.PrincipalID, AuthorizedAtUnixMillis: 10, State: commitcontract.ActionAuthorized, Proposal: commitcontract.ActionProposal{ActorID: session.ActorID, IntentID: "intent-pending", Operation: commitcontract.OperationSatisfyDelivered, ContinuitySubject: continuity.SatisfyDeliveredSubject{ProspectiveItemID: "prospective-pending"}}},
|
||||
},
|
||||
latest: map[commitcontract.AuthorizedActionID]commitcontract.ActionAttempt{
|
||||
"authorized-new": {ID: "attempt-new", AuthorizedID: "authorized-new", IntentID: "intent-new", State: commitcontract.ActionSucceeded},
|
||||
},
|
||||
}
|
||||
handler := creatorCommandHandler{core: fakeCreatorCore{session: session}, repository: repository}
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
request := httptest.NewRequest(http.MethodGet, "/v1/creator/authorized-actions?limit=2", nil)
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var result creatorActionHistoryResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repository.actorID != session.ActorID || repository.principalID != session.PrincipalID || repository.limit != 2 || repository.listCalls != 1 {
|
||||
t.Fatalf("owner query actor=%q principal=%q limit=%d calls=%d", repository.actorID, repository.principalID, repository.limit, repository.listCalls)
|
||||
}
|
||||
if len(result.Items) != 2 || result.Items[0].State != commitcontract.ActionSucceeded || result.Items[0].ActionAttemptID != "attempt-new" ||
|
||||
result.Items[1].State != commitcontract.ActionAuthorized || result.Items[1].ActionAttemptID != "" {
|
||||
t.Fatalf("history=%#v", result.Items)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "EvidenceRef") || strings.Contains(response.Body.String(), "GrantID") {
|
||||
t.Fatalf("history leaked restricted envelope fields: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorActionHistoryRejectsSessionAndInvalidLimitBeforeQuery(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
sessionErr error
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{name: "session", sessionErr: errCreatorSessionDenied, path: "/v1/creator/authorized-actions", status: http.StatusUnauthorized},
|
||||
{name: "zero", path: "/v1/creator/authorized-actions?limit=0", status: http.StatusBadRequest},
|
||||
{name: "too large", path: "/v1/creator/authorized-actions?limit=51", status: http.StatusBadRequest},
|
||||
{name: "invalid", path: "/v1/creator/authorized-actions?limit=many", status: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repository := &fakeCreatorHistoryRepository{}
|
||||
handler := creatorCommandHandler{core: fakeCreatorCore{session: identity.CreatorSession{ActorID: "actor", PrincipalID: "principal"}, sessionErr: test.sessionErr}, repository: repository}
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
if response.Code != test.status || repository.listCalls != 0 {
|
||||
t.Fatalf("status=%d calls=%d", response.Code, repository.listCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func validCreatorCommandHandler() (creatorCommandHandler, *fakeExecutionRepository, *knownExecutor) {
|
||||
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
|
||||
target := work.TaskTarget{TaskID: "task-1", GoalID: "goal-1", ScopeID: "scope-1", Revision: 3}
|
||||
|
||||
@@ -155,6 +155,8 @@ func creatorRoute(method, path string) (routeTarget, string, bool) {
|
||||
}
|
||||
case method == http.MethodGet && path == "/api/prospective-items":
|
||||
return targetContinuity, "/v1/creator/prospective-items", true
|
||||
case method == http.MethodGet && path == "/api/actions":
|
||||
return targetCommit, "/v1/creator/authorized-actions", true
|
||||
case method == http.MethodPost && path == "/api/actions/satisfy-delivered":
|
||||
return targetCommit, "/v1/creator/continuity/satisfy-delivered", true
|
||||
case method == http.MethodPost && strings.HasPrefix(path, "/api/actions/") && strings.HasSuffix(path, "/reconcile"):
|
||||
|
||||
@@ -158,6 +158,30 @@ func TestGatewayRoutesOnlyBoundedCreatorCommandsToCommit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayRoutesCreatorActionHistoryToCommit(t *testing.T) {
|
||||
commitRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/creator/authorized-actions" || r.URL.RawQuery != "limit=25" || r.Method != http.MethodGet {
|
||||
t.Fatalf("unexpected Commit history target %s?%s %s", r.URL.Path, r.URL.RawQuery, r.Method)
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer bounded-session" {
|
||||
t.Fatal("authorization header was not forwarded")
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"Items":[{"AuthorizedActionID":"authorized-1"}]}`)
|
||||
}))
|
||||
defer commitRuntime.Close()
|
||||
handler, err := newHandler("http://core-runtime.invalid", "http://continuity-runtime.invalid", commitRuntime.URL, commitRuntime.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/actions?limit=25", nil)
|
||||
request.Header.Set("Authorization", "Bearer bounded-session")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "authorized-1") {
|
||||
t.Fatalf("response = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleAndSecurityHeaders(t *testing.T) {
|
||||
handler, err := newHandler("http://core-runtime:8080", "http://continuity-runtime:8081", "http://commit-runtime:8082", http.DefaultClient)
|
||||
if err != nil {
|
||||
@@ -168,6 +192,7 @@ func TestConsoleAndSecurityHeaders(t *testing.T) {
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "Домовой") ||
|
||||
!strings.Contains(response.Body.String(), "satisfaction-dialog") || !strings.Contains(response.Body.String(), "Подтверждаю переход") ||
|
||||
!strings.Contains(response.Body.String(), "action-history") || !strings.Contains(response.Body.String(), "Журнал действий") ||
|
||||
!strings.Contains(response.Body.String(), "creator-username") || !strings.Contains(response.Body.String(), "creator-password") ||
|
||||
strings.Contains(response.Body.String(), "bootstrap-token") {
|
||||
t.Fatalf("console response = %d", response.Code)
|
||||
|
||||
@@ -112,6 +112,33 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
||||
.register-row em.bad { color: var(--bad); }
|
||||
.register-empty { margin: 0; padding: 22px 18px; color: var(--faint); font-size: 11px; }
|
||||
|
||||
.activity-panel { margin-bottom: 18px; border: 1px solid var(--line); background: rgba(13, 20, 17, .9); }
|
||||
.activity-panel > header { min-height: 66px; padding: 13px 18px; display: flex; align-items: center; justify-content: space-between; gap: 18px; border-bottom: 1px solid var(--line); }
|
||||
.activity-panel header p { margin: 0 0 6px; color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .13em; text-transform: uppercase; }
|
||||
.activity-panel h2 { margin: 0; font: 400 22px/1 var(--serif); }
|
||||
.activity-tools { display: flex; align-items: center; gap: 12px; color: var(--muted); font: 9px/1 var(--mono); letter-spacing: .1em; }
|
||||
.activity-tools .icon-button { color: var(--muted); font-size: 18px; }
|
||||
.activity-list { max-height: 300px; overflow: auto; scrollbar-color: var(--faint) transparent; }
|
||||
.activity-list[aria-busy="true"] { opacity: .72; }
|
||||
.activity-row { min-height: 68px; padding: 11px 18px; display: grid; grid-template-columns: 112px minmax(150px, .8fr) minmax(210px, 1.2fr) 145px auto; gap: 16px; align-items: center; border-bottom: 1px solid var(--line-soft); }
|
||||
.activity-row:last-child { border-bottom: 0; }
|
||||
.activity-row:hover { background: var(--panel-high); }
|
||||
.activity-state { width: fit-content; padding: 5px 8px; border: 1px solid currentColor; border-radius: 100px; color: var(--faint); font: 600 8px/1 var(--mono); letter-spacing: .06em; }
|
||||
.activity-state[data-state="SUCCEEDED"] { color: var(--good); }
|
||||
.activity-state[data-state="FAILED"] { color: var(--bad); }
|
||||
.activity-state[data-state="UNKNOWN_OUTCOME"], .activity-state[data-state="EXECUTING"] { color: var(--warn); }
|
||||
.activity-state[data-state="AUTHORIZED"] { color: var(--signal); }
|
||||
.activity-operation, .activity-identity { min-width: 0; }
|
||||
.activity-operation b, .activity-operation span, .activity-identity code, .activity-identity small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.activity-operation b { color: var(--ink); font: 600 10px/1.4 var(--mono); }
|
||||
.activity-operation span, .activity-identity small { margin-top: 4px; color: var(--faint); font: 9px/1.3 var(--mono); }
|
||||
.activity-identity code { color: var(--muted); font: 10px/1.4 var(--mono); }
|
||||
.activity-row time { color: var(--muted); font: 9px/1.4 var(--mono); white-space: nowrap; }
|
||||
.activity-reconcile { min-height: 34px; padding: 0 11px; border: 1px solid var(--warn); border-radius: var(--radius); color: var(--warn); background: transparent; cursor: pointer; font: 600 9px/1 var(--mono); }
|
||||
.activity-reconcile:hover:not(:disabled) { color: var(--base); background: var(--warn); }
|
||||
.activity-reconcile:disabled { opacity: .55; cursor: wait; }
|
||||
.activity-error { color: var(--bad); }
|
||||
|
||||
.data-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
|
||||
.data-card { min-width: 0; padding: 24px; border: 1px solid var(--line); background: linear-gradient(145deg, rgba(22, 31, 27, .94), rgba(13, 20, 17, .98)); box-shadow: 0 10px 40px rgba(0,0,0,.12); animation: reveal .55s both; }
|
||||
.task-card { animation-delay: .08s; }
|
||||
@@ -215,6 +242,14 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
||||
.signal-strip { grid-template-columns: 1fr; }
|
||||
.signal-strip div { border-right: 0; border-bottom: 1px solid var(--line); }
|
||||
.register-panel > header { align-items: start; }
|
||||
.activity-panel > header { align-items: flex-start; }
|
||||
.activity-tools { align-items: flex-end; flex-direction: column-reverse; }
|
||||
.activity-row { padding: 14px 16px; grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; }
|
||||
.activity-state { grid-column: 2; grid-row: 1; }
|
||||
.activity-operation { grid-column: 1; grid-row: 1; }
|
||||
.activity-identity { grid-column: 1 / -1; grid-row: 2; }
|
||||
.activity-row time { grid-column: 1; grid-row: 3; }
|
||||
.activity-reconcile { grid-column: 2; grid-row: 2 / span 2; }
|
||||
.register-row { padding: 13px 16px; grid-template-columns: minmax(0, 1fr) auto; gap: 7px 12px; }
|
||||
.register-row time { grid-column: 1; grid-row: 2; }
|
||||
.register-row span { display: none; }
|
||||
|
||||
@@ -80,6 +80,7 @@ async function showConsole() {
|
||||
restoreContext();
|
||||
const context = saveContext();
|
||||
if (context["session-id"] && context["workspace-id"]) loadDashboard();
|
||||
else loadActionHistory();
|
||||
}
|
||||
|
||||
function endSession(message = "Сессия завершена.") {
|
||||
@@ -136,6 +137,7 @@ contextForm.addEventListener("submit", (event) => {
|
||||
});
|
||||
|
||||
byId("refresh-all").addEventListener("click", loadDashboard);
|
||||
byId("refresh-actions").addEventListener("click", loadActionHistory);
|
||||
byId("logout").addEventListener("click", () => endSession());
|
||||
|
||||
async function loadDashboard() {
|
||||
@@ -162,6 +164,7 @@ async function loadDashboard() {
|
||||
updateActionReadiness();
|
||||
}
|
||||
work.push(loadProspectiveRegister(context["prospective-id"]));
|
||||
work.push(loadActionHistory());
|
||||
if (context["capability-id"]) work.push(loadCapability(context["capability-id"]));
|
||||
else setSignal("capability", "не выбрана", "idle");
|
||||
|
||||
@@ -169,6 +172,96 @@ async function loadDashboard() {
|
||||
setText("last-update", `Обновлено ${new Intl.DateTimeFormat("ru-RU", {hour: "2-digit", minute: "2-digit", second: "2-digit"}).format(new Date())}`);
|
||||
}
|
||||
|
||||
async function loadActionHistory() {
|
||||
const list = byId("action-history");
|
||||
list.setAttribute("aria-busy", "true");
|
||||
list.replaceChildren();
|
||||
const loading = document.createElement("p");
|
||||
loading.className = "register-empty";
|
||||
loading.textContent = "Читаю канонический журнал Commit…";
|
||||
list.append(loading);
|
||||
try {
|
||||
const result = await request("/api/actions?limit=25");
|
||||
const items = Array.isArray(result.Items) ? result.Items : [];
|
||||
setText("action-count", `${items.length} ${items.length === 1 ? "ЗАПИСЬ" : "ЗАПИСЕЙ"}`);
|
||||
list.replaceChildren();
|
||||
if (items.length === 0) {
|
||||
const empty = document.createElement("p");
|
||||
empty.className = "register-empty";
|
||||
empty.textContent = "У текущего Создателя пока нет авторизованных действий.";
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
items.forEach((item) => list.append(createActionHistoryRow(item)));
|
||||
} catch (error) {
|
||||
list.replaceChildren();
|
||||
const failed = document.createElement("p");
|
||||
failed.className = "register-empty activity-error";
|
||||
failed.textContent = error.message;
|
||||
list.append(failed);
|
||||
setText("action-count", "ОШИБКА");
|
||||
} finally {
|
||||
list.setAttribute("aria-busy", "false");
|
||||
}
|
||||
}
|
||||
|
||||
function createActionHistoryRow(item) {
|
||||
const row = document.createElement("article");
|
||||
row.className = "activity-row";
|
||||
const state = document.createElement("strong");
|
||||
state.className = "activity-state";
|
||||
state.dataset.state = item.State || "UNKNOWN";
|
||||
state.textContent = item.State || "UNKNOWN";
|
||||
const operation = document.createElement("div");
|
||||
operation.className = "activity-operation";
|
||||
const operationName = document.createElement("b");
|
||||
operationName.textContent = item.Operation || "неизвестная операция";
|
||||
const subject = document.createElement("span");
|
||||
subject.textContent = item.ProspectiveItemID || "без subject";
|
||||
operation.append(operationName, subject);
|
||||
const identity = document.createElement("div");
|
||||
identity.className = "activity-identity";
|
||||
const actionID = document.createElement("code");
|
||||
actionID.textContent = item.AuthorizedActionID || "—";
|
||||
actionID.title = item.AuthorizedActionID || "";
|
||||
const attemptID = document.createElement("small");
|
||||
attemptID.textContent = item.ActionAttemptID ? `attempt ${item.ActionAttemptID}` : "попытка ещё не создана";
|
||||
attemptID.title = item.ActionAttemptID || "";
|
||||
identity.append(actionID, attemptID);
|
||||
const time = document.createElement("time");
|
||||
time.dateTime = item.AuthorizedAtUnixMillis ? new Date(item.AuthorizedAtUnixMillis).toISOString() : "";
|
||||
time.textContent = item.AuthorizedAtUnixMillis ? new Date(item.AuthorizedAtUnixMillis).toLocaleString("ru-RU") : "время неизвестно";
|
||||
row.append(state, operation, identity, time);
|
||||
if (item.State === "UNKNOWN_OUTCOME" && item.AuthorizedActionID) {
|
||||
const reconcile = document.createElement("button");
|
||||
reconcile.type = "button";
|
||||
reconcile.className = "activity-reconcile";
|
||||
reconcile.textContent = "Сверить";
|
||||
reconcile.setAttribute("aria-label", `Сверить исход действия ${item.AuthorizedActionID}`);
|
||||
reconcile.addEventListener("click", () => reconcileHistoryAction(item.AuthorizedActionID, reconcile));
|
||||
row.append(reconcile);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
async function reconcileHistoryAction(actionID, button) {
|
||||
button.disabled = true;
|
||||
button.textContent = "Сверяю…";
|
||||
try {
|
||||
const result = await request(`/api/actions/${encodeURIComponent(actionID)}/reconcile`, {
|
||||
method: "POST", headers: {"Content-Type": "application/json"}, body: "{}",
|
||||
});
|
||||
renderActionResult(result);
|
||||
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
|
||||
await loadActionHistory();
|
||||
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
||||
} catch (error) {
|
||||
notify(error.message);
|
||||
button.disabled = false;
|
||||
button.textContent = "Сверить";
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFocus(query) {
|
||||
setSignal("focus", "загрузка", "loading");
|
||||
try {
|
||||
@@ -398,6 +491,7 @@ byId("confirm-satisfaction").addEventListener("click", async () => {
|
||||
pendingCommand = null;
|
||||
byId("satisfaction-dialog").close();
|
||||
renderActionResult(result);
|
||||
await loadActionHistory();
|
||||
notify(result.State === "SUCCEEDED" ? "Исполнение зафиксировано через Commit." : "Исход требует проверки.");
|
||||
await loadProspectiveRegister(command.ProspectiveItemID);
|
||||
} catch (error) {
|
||||
@@ -431,6 +525,7 @@ byId("reconcile-action").addEventListener("click", async () => {
|
||||
body: "{}",
|
||||
});
|
||||
renderActionResult(result);
|
||||
await loadActionHistory();
|
||||
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
|
||||
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
||||
} catch (error) {
|
||||
|
||||
@@ -102,6 +102,19 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="activity-panel" aria-labelledby="activity-title">
|
||||
<header>
|
||||
<div><p>Commit / владелец</p><h2 id="activity-title">Журнал действий</h2></div>
|
||||
<div class="activity-tools">
|
||||
<span id="action-count">0 ЗАПИСЕЙ</span>
|
||||
<button id="refresh-actions" class="icon-button" type="button" aria-label="Обновить журнал действий" title="Обновить журнал действий">↻</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="action-history" class="activity-list" aria-live="polite" aria-busy="false">
|
||||
<p class="register-empty">Журнал ещё не загружен.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="data-grid">
|
||||
<article class="data-card focus-card">
|
||||
<header><span class="card-number">01</span><div><p>Situation</p><h2>Активный фокус</h2></div><span id="focus-badge" class="status-badge neutral">НЕ ЗАГРУЖЕН</span></header>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$HealthScriptPath = (Join-Path $PSScriptRoot 'Test-DomovoyProductionHealth.ps1'),
|
||||
[string]$NotificationScriptPath = (Join-Path $PSScriptRoot 'Send-DomovoyHealthNotification.ps1')
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
if (-not (Test-Path -LiteralPath $HealthScriptPath -PathType Leaf)) { throw 'Health monitoring script not found' }
|
||||
if (-not (Test-Path -LiteralPath $NotificationScriptPath -PathType Leaf)) { throw 'Health notification script not found' }
|
||||
|
||||
$pwsh = (Get-Command pwsh.exe -ErrorAction Stop).Source
|
||||
& $pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $HealthScriptPath
|
||||
$healthExitCode = $LASTEXITCODE
|
||||
|
||||
& $pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $NotificationScriptPath
|
||||
$notificationExitCode = $LASTEXITCODE
|
||||
if ($notificationExitCode -ne 0) { exit 2 }
|
||||
exit $healthExitCode
|
||||
@@ -0,0 +1,20 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ScriptPath = '\\nas\MST\codex\assistent\deploy\windows\Invoke-DomovoyProductionMonitoring.ps1',
|
||||
[string]$TaskName = 'Domovoy Production Health Monitor'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ScriptPath -PathType Leaf)) { throw 'Monitoring script not found' }
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$pwsh = (Get-Command pwsh.exe -ErrorAction Stop).Source
|
||||
$arguments = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$ScriptPath`""
|
||||
$action = New-ScheduledTaskAction -Execute $pwsh -Argument $arguments
|
||||
$repeat = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Days 3650)
|
||||
$logon = New-ScheduledTaskTrigger -AtLogOn -User $identity
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger @($repeat, $logon) -Principal $principal -Settings $settings -Description 'Monitor Domovoy production health and notify the interactive user about transitions.' -Force | Out-Null
|
||||
Write-Output "Scheduled task registered: $TaskName"
|
||||
@@ -0,0 +1,52 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ScriptPath = '\\nas\MST\codex\assistent\deploy\windows\Sync-PostgresBackupToNas.ps1',
|
||||
[string]$KeyRecordPath = "$env:LOCALAPPDATA\Domovoy\postgres-backup-key.dpapi.json",
|
||||
[string]$NasKeyBackupPath = '\\nas\MST\codex\_backups\domovoy\keys\postgres-backup-key.dpapi.json',
|
||||
[string]$TaskName = 'Domovoy PostgreSQL Off-host Backup'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
$keyDirectory = Split-Path -Parent $KeyRecordPath
|
||||
New-Item -ItemType Directory -Force -Path $keyDirectory | Out-Null
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
if (-not (Test-Path -LiteralPath $KeyRecordPath) -and (Test-Path -LiteralPath $NasKeyBackupPath -PathType Leaf)) {
|
||||
Copy-Item -LiteralPath $NasKeyBackupPath -Destination $KeyRecordPath
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $KeyRecordPath)) {
|
||||
$random = [byte[]]::new(48)
|
||||
[Security.Cryptography.RandomNumberGenerator]::Fill($random)
|
||||
$plain = [Convert]::ToBase64String($random)
|
||||
try {
|
||||
$protected = ConvertFrom-SecureString (ConvertTo-SecureString $plain -AsPlainText -Force)
|
||||
$record = [ordered]@{ version = 1; project = 'domovoy'; purpose = 'postgres off-host backup'; protected_value = $protected; created_at_utc = [DateTime]::UtcNow.ToString('o') }
|
||||
[IO.File]::WriteAllText($KeyRecordPath, ($record | ConvertTo-Json) + "`n", [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
finally {
|
||||
[Array]::Clear($random, 0, $random.Length)
|
||||
$plain = $null
|
||||
}
|
||||
}
|
||||
& icacls.exe $KeyRecordPath /inheritance:r /grant:r "${identity}:F" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DPAPI key ACL hardening failed' }
|
||||
|
||||
$nasKeyDirectory = Split-Path -Parent $NasKeyBackupPath
|
||||
New-Item -ItemType Directory -Force -Path $nasKeyDirectory | Out-Null
|
||||
$nasKeyPartial = "$NasKeyBackupPath.$PID.partial"
|
||||
Copy-Item -LiteralPath $KeyRecordPath -Destination $nasKeyPartial
|
||||
Move-Item -LiteralPath $nasKeyPartial -Destination $NasKeyBackupPath -Force
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ScriptPath -PathType Leaf)) { throw "Scheduled sync script not found" }
|
||||
$pwsh = (Get-Command pwsh.exe -ErrorAction Stop).Source
|
||||
$arguments = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$ScriptPath`""
|
||||
$action = New-ScheduledTaskAction -Execute $pwsh -Argument $arguments
|
||||
$daily = New-ScheduledTaskTrigger -Daily -At '04:00'
|
||||
$logon = New-ScheduledTaskTrigger -AtLogOn -User $identity
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 2)
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger @($daily, $logon) -Principal $principal -Settings $settings -Description 'Encrypt and replicate the latest Domovoy PostgreSQL backup to the private NAS.' -Force | Out-Null
|
||||
Write-Output "Scheduled task registered: $TaskName"
|
||||
@@ -0,0 +1,125 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$StatusPath = (Join-Path $env:LOCALAPPDATA 'Domovoy\monitoring\status.json'),
|
||||
[string]$StatePath = (Join-Path $env:LOCALAPPDATA 'Domovoy\monitoring\notification-state.json'),
|
||||
[ValidateRange(1, 168)]
|
||||
[int]$ReminderHours = 6,
|
||||
[switch]$Force,
|
||||
[switch]$NoDisplay
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
function Write-AtomicJson {
|
||||
param([Parameter(Mandatory)]$Value, [Parameter(Mandatory)][string]$Path)
|
||||
|
||||
$directory = Split-Path -Parent $Path
|
||||
if (-not (Test-Path -LiteralPath $directory -PathType Container)) {
|
||||
New-Item -ItemType Directory -Path $directory -Force | Out-Null
|
||||
}
|
||||
$temporary = Join-Path $directory ('.{0}.{1}.tmp' -f (Split-Path -Leaf $Path), [guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
$Value | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temporary -Encoding utf8NoBOM
|
||||
Move-Item -LiteralPath $temporary -Destination $Path -Force
|
||||
}
|
||||
finally {
|
||||
if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $StatusPath -PathType Leaf)) { throw "Health status not found: $StatusPath" }
|
||||
$status = Get-Content -LiteralPath $StatusPath -Raw | ConvertFrom-Json
|
||||
if ($status.version -ne 1 -or $status.overall -notin @('healthy', 'degraded')) { throw 'Unsupported health status document' }
|
||||
|
||||
$now = [DateTimeOffset]::UtcNow
|
||||
$previous = $null
|
||||
if (Test-Path -LiteralPath $StatePath -PathType Leaf) {
|
||||
$previous = Get-Content -LiteralPath $StatePath -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
$kind = $null
|
||||
if ($Force) {
|
||||
$kind = if ($status.overall -eq 'healthy') { 'recovered' } else { 'degraded' }
|
||||
}
|
||||
elseif ($status.overall -eq 'degraded') {
|
||||
if ($null -eq $previous -or $previous.last_status -ne 'degraded') {
|
||||
$kind = 'degraded'
|
||||
}
|
||||
elseif ($null -ne $previous.last_notification_at_utc) {
|
||||
$lastNotification = if ($previous.last_notification_at_utc -is [DateTime]) {
|
||||
[DateTimeOffset]$previous.last_notification_at_utc
|
||||
}
|
||||
else {
|
||||
[DateTimeOffset]::Parse([string]$previous.last_notification_at_utc, [Globalization.CultureInfo]::InvariantCulture)
|
||||
}
|
||||
if (($now - $lastNotification).TotalHours -ge $ReminderHours) { $kind = 'reminder' }
|
||||
}
|
||||
}
|
||||
elseif ($null -ne $previous -and $previous.last_status -eq 'degraded') {
|
||||
$kind = 'recovered'
|
||||
}
|
||||
|
||||
$lastNotificationAt = if ($null -ne $previous -and $null -ne $previous.last_notification_at_utc) {
|
||||
([DateTimeOffset]$previous.last_notification_at_utc).ToString('o')
|
||||
}
|
||||
else { $null }
|
||||
$lastNotificationKind = if ($null -ne $previous) { $previous.last_notification_kind } else { $null }
|
||||
|
||||
if ($null -ne $kind) {
|
||||
$failedNames = @($status.checks | Where-Object { -not $_.ok } | ForEach-Object { [string]$_.name })
|
||||
switch ($kind) {
|
||||
'degraded' {
|
||||
$title = 'Домовой: требуется внимание'
|
||||
$body = if ($failedNames.Count -gt 0) { 'Сбой: ' + ($failedNames -join ', ') } else { 'Мониторинг обнаружил сбой.' }
|
||||
$icon = 'Error'
|
||||
}
|
||||
'reminder' {
|
||||
$title = 'Домовой: сбой продолжается'
|
||||
$body = if ($failedNames.Count -gt 0) { 'Не исправлено: ' + ($failedNames -join ', ') } else { 'Состояние остается ухудшенным.' }
|
||||
$icon = 'Warning'
|
||||
}
|
||||
default {
|
||||
$title = 'Домовой: работа восстановлена'
|
||||
$body = 'Все проверки снова проходят успешно.'
|
||||
$icon = 'Info'
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $NoDisplay) {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$notification = [System.Windows.Forms.NotifyIcon]::new()
|
||||
try {
|
||||
$notification.Icon = switch ($icon) {
|
||||
'Error' { [System.Drawing.SystemIcons]::Error }
|
||||
'Warning' { [System.Drawing.SystemIcons]::Warning }
|
||||
default { [System.Drawing.SystemIcons]::Information }
|
||||
}
|
||||
$notification.Visible = $true
|
||||
$notification.BalloonTipIcon = [System.Enum]::Parse([System.Windows.Forms.ToolTipIcon], $icon)
|
||||
$notification.BalloonTipTitle = $title
|
||||
$notification.BalloonTipText = $body
|
||||
$notification.ShowBalloonTip(8000)
|
||||
Start-Sleep -Seconds 9
|
||||
}
|
||||
finally {
|
||||
$notification.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$lastNotificationAt = $now.ToString('o')
|
||||
$lastNotificationKind = $kind
|
||||
}
|
||||
|
||||
$state = [ordered]@{
|
||||
version = 1
|
||||
last_status = [string]$status.overall
|
||||
last_observed_at_utc = $now.ToString('o')
|
||||
last_notification_at_utc = $lastNotificationAt
|
||||
last_notification_kind = $lastNotificationKind
|
||||
}
|
||||
Write-AtomicJson -Value $state -Path $StatePath
|
||||
|
||||
$result = if ($null -eq $kind) { 'suppressed' } elseif ($NoDisplay) { 'simulated' } else { 'sent' }
|
||||
Write-Output "notification=$result status=$($status.overall) kind=$kind"
|
||||
@@ -0,0 +1,115 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$SshHost = 'docker',
|
||||
[string]$RemoteBackupRoot = '/home/m/assistant-backups/postgres',
|
||||
[string]$NasBackupRoot = '\\nas\MST\codex\_backups\domovoy\postgres',
|
||||
[string]$KeyRecordPath = "$env:LOCALAPPDATA\Domovoy\postgres-backup-key.dpapi.json",
|
||||
[string]$GpgPath = 'gpg.exe'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
function Assert-SourceHashes([string]$Directory) {
|
||||
$allowed = @('assistant.dump', 'globals.sql', 'database.name', 'owner.name')
|
||||
$expected = @{}
|
||||
foreach ($line in Get-Content -LiteralPath (Join-Path $Directory 'SHA256SUMS')) {
|
||||
if ($line -notmatch '^([0-9a-f]{64}) ([A-Za-z0-9.]+)$' -or $matches[2] -notin $allowed) {
|
||||
throw "Invalid SHA256SUMS entry"
|
||||
}
|
||||
$expected[$matches[2]] = $matches[1]
|
||||
}
|
||||
foreach ($name in $allowed) {
|
||||
if (-not $expected.ContainsKey($name)) { throw "Missing SHA256SUMS entry: $name" }
|
||||
$actual = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $Directory $name)).Hash.ToLowerInvariant()
|
||||
if ($actual -ne $expected[$name]) { throw "Source hash mismatch: $name" }
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RecoveryPassphrase([string]$Path) {
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "DPAPI recovery key is missing" }
|
||||
$record = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
|
||||
if ($record.version -ne 1 -or [string]::IsNullOrWhiteSpace($record.protected_value)) { throw "Invalid DPAPI recovery key record" }
|
||||
$secure = ConvertTo-SecureString -String $record.protected_value
|
||||
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
|
||||
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
|
||||
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
|
||||
}
|
||||
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
|
||||
$work = Join-Path $tempRoot ("domovoy-backup-sync-" + [guid]::NewGuid().ToString('N'))
|
||||
if (-not ([IO.Path]::GetFullPath($work)).StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe temporary path' }
|
||||
New-Item -ItemType Directory -Path $work | Out-Null
|
||||
$passphrase = $null
|
||||
$cipherPartial = $null
|
||||
$manifestPartial = $null
|
||||
|
||||
try {
|
||||
$latest = ((& ssh.exe $SshHost "find '$RemoteBackupRoot' -mindepth 1 -maxdepth 1 -type d ! -name '.*' -printf '%f\n' | sort | tail -n1") -join '').Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $latest -notmatch '^\d{8}T\d{6}Z$') { throw 'No valid completed production backup found' }
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $NasBackupRoot | Out-Null
|
||||
$cipherPath = Join-Path $NasBackupRoot "$latest.tar.gz.gpg"
|
||||
$manifestPath = Join-Path $NasBackupRoot "$latest.json"
|
||||
if ((Test-Path -LiteralPath $cipherPath) -xor (Test-Path -LiteralPath $manifestPath)) {
|
||||
# Neither lone file is a completed backup. Remove only this exact incomplete pair before retry.
|
||||
Remove-Item -LiteralPath $cipherPath, $manifestPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ((Test-Path -LiteralPath $cipherPath) -or (Test-Path -LiteralPath $manifestPath)) {
|
||||
if (-not ((Test-Path -LiteralPath $cipherPath -PathType Leaf) -and (Test-Path -LiteralPath $manifestPath -PathType Leaf))) { throw 'Incomplete existing NAS artifact' }
|
||||
$existing = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
|
||||
$actualCipherHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $cipherPath).Hash.ToLowerInvariant()
|
||||
if ($existing.source_backup -ne $latest -or $existing.ciphertext_sha256 -ne $actualCipherHash) { throw 'Existing NAS artifact does not match its manifest' }
|
||||
Write-Output "Off-host backup already current: $latest"
|
||||
return
|
||||
}
|
||||
|
||||
& scp.exe -q -r "${SshHost}:${RemoteBackupRoot}/${latest}" $work
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SCP backup copy failed' }
|
||||
$sourceDirectory = Join-Path $work $latest
|
||||
Assert-SourceHashes $sourceDirectory
|
||||
|
||||
$archive = Join-Path $work "$latest.tar.gz"
|
||||
& tar.exe -czf $archive -C $work $latest
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $archive -PathType Leaf)) { throw 'Archive creation failed' }
|
||||
$archiveHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant()
|
||||
|
||||
$passphrase = Get-RecoveryPassphrase $KeyRecordPath
|
||||
$passphraseFile = Join-Path $work 'passphrase.txt'
|
||||
[IO.File]::WriteAllText($passphraseFile, $passphrase, [Text.UTF8Encoding]::new($false))
|
||||
& icacls.exe $work /inheritance:r /grant:r "$([Security.Principal.WindowsIdentity]::GetCurrent().Name):(OI)(CI)F" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Temporary ACL hardening failed' }
|
||||
|
||||
$cipherPartial = Join-Path $NasBackupRoot (".$latest.$PID.gpg.partial")
|
||||
$manifestPartial = Join-Path $NasBackupRoot (".$latest.$PID.json.partial")
|
||||
& $GpgPath --batch --yes --pinentry-mode loopback --passphrase-file $passphraseFile --symmetric --cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-cipher-algo AES256 --s2k-count 65011712 --compress-algo none --output $cipherPartial $archive
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $cipherPartial -PathType Leaf)) { throw 'GnuPG encryption failed' }
|
||||
|
||||
$roundTrip = Join-Path $work 'roundtrip.tar.gz'
|
||||
& $GpgPath --batch --yes --pinentry-mode loopback --passphrase-file $passphraseFile --decrypt --output $roundTrip $cipherPartial
|
||||
if ($LASTEXITCODE -ne 0) { throw 'GnuPG round-trip decryption failed' }
|
||||
if ((Get-FileHash -Algorithm SHA256 -LiteralPath $roundTrip).Hash.ToLowerInvariant() -ne $archiveHash) { throw 'Encrypted round-trip archive hash mismatch' }
|
||||
|
||||
$manifest = [ordered]@{
|
||||
version = 1
|
||||
project = 'domovoy'
|
||||
source_host = 'docker.cin.su'
|
||||
source_backup = $latest
|
||||
source_sha256sums_sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $sourceDirectory 'SHA256SUMS')).Hash.ToLowerInvariant()
|
||||
archive_sha256 = $archiveHash
|
||||
ciphertext_sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $cipherPartial).Hash.ToLowerInvariant()
|
||||
encryption = 'GnuPG symmetric AES256, SHA512 S2K'
|
||||
created_at_utc = [DateTime]::UtcNow.ToString('o')
|
||||
}
|
||||
[IO.File]::WriteAllText($manifestPartial, ($manifest | ConvertTo-Json) + "`n", [Text.UTF8Encoding]::new($false))
|
||||
Move-Item -LiteralPath $cipherPartial -Destination $cipherPath
|
||||
Move-Item -LiteralPath $manifestPartial -Destination $manifestPath
|
||||
Write-Output "Off-host backup created: $latest"
|
||||
}
|
||||
finally {
|
||||
$passphrase = $null
|
||||
foreach ($partial in @($cipherPartial, $manifestPartial)) {
|
||||
if ($partial -and (Test-Path -LiteralPath $partial)) { Remove-Item -LiteralPath $partial -Force }
|
||||
}
|
||||
if (Test-Path -LiteralPath $work) { Remove-Item -LiteralPath $work -Recurse -Force }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$DockerContext = 'docker-prod',
|
||||
[string]$SshHost = 'docker',
|
||||
[string]$Endpoint = 'https://assistent.cin.su/healthz',
|
||||
[string]$RemoteBackupRoot = '/home/m/assistant-backups/postgres',
|
||||
[string]$NasBackupRoot = '\\nas\MST\codex\_backups\domovoy\postgres',
|
||||
[string]$NasStatusPath = '\\nas\MST\codex\_monitoring\domovoy\status.json',
|
||||
[string]$LocalStatusPath = "$env:LOCALAPPDATA\Domovoy\monitoring\status.json",
|
||||
[double]$MaxProductionBackupAgeHours = 30,
|
||||
[double]$MaxNasBackupAgeHours = 36,
|
||||
[int]$MinimumCertificateDays = 21,
|
||||
[string[]]$ExpectedContainers = @(
|
||||
'assistant-core-runtime-1',
|
||||
'assistant-creator-web-1',
|
||||
'assistant-commit-runtime-1',
|
||||
'assistant-continuity-runtime-1',
|
||||
'assistant-cognitive-worker-1',
|
||||
'assistant-postgres-1',
|
||||
'assistant-nats-1',
|
||||
'assistant-gitea-runner'
|
||||
)
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$checks = [Collections.Generic.List[object]]::new()
|
||||
|
||||
function Add-Check([string]$Name, [bool]$Ok, [string]$Detail) {
|
||||
$checks.Add([ordered]@{ name = $Name; ok = $Ok; detail = $Detail })
|
||||
}
|
||||
|
||||
function Write-AtomicJson([string]$Path, [string]$Json) {
|
||||
$directory = Split-Path -Parent $Path
|
||||
New-Item -ItemType Directory -Force -Path $directory | Out-Null
|
||||
$partial = Join-Path $directory ('.' + [IO.Path]::GetFileName($Path) + ".${PID}.partial")
|
||||
try {
|
||||
[IO.File]::WriteAllText($partial, $Json + "`n", [Text.UTF8Encoding]::new($false))
|
||||
Move-Item -LiteralPath $partial -Destination $Path -Force
|
||||
}
|
||||
finally {
|
||||
if (Test-Path -LiteralPath $partial) { Remove-Item -LiteralPath $partial -Force }
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($container in $ExpectedContainers) {
|
||||
try {
|
||||
$raw = ((& docker.exe --context $DockerContext inspect $container --format '{{json .State}}') -join '').Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($raw)) { throw 'inspect failed' }
|
||||
$state = $raw | ConvertFrom-Json
|
||||
$ok = $state.Status -eq 'running'
|
||||
$detail = "status=$($state.Status)"
|
||||
if ($state.PSObject.Properties.Name -contains 'Health' -and $null -ne $state.Health) {
|
||||
$ok = $ok -and $state.Health.Status -eq 'healthy'
|
||||
$detail += " health=$($state.Health.Status)"
|
||||
}
|
||||
Add-Check "container:$container" $ok $detail
|
||||
}
|
||||
catch { Add-Check "container:$container" $false $_.Exception.Message }
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Invoke-RestMethod -Uri $Endpoint -TimeoutSec 15
|
||||
$ok = $response.status -eq 'ok'
|
||||
Add-Check 'https-health' $ok "status=$($response.status) runtime=$($response.runtime)"
|
||||
}
|
||||
catch { Add-Check 'https-health' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$uri = [Uri]$Endpoint
|
||||
$tcp = [Net.Sockets.TcpClient]::new()
|
||||
try {
|
||||
$tcp.Connect($uri.Host, 443)
|
||||
$ssl = [Net.Security.SslStream]::new($tcp.GetStream(), $false)
|
||||
try {
|
||||
$ssl.AuthenticateAsClient($uri.Host)
|
||||
$certificate = [Security.Cryptography.X509Certificates.X509Certificate2]::new($ssl.RemoteCertificate)
|
||||
$days = [math]::Floor(($certificate.NotAfter.ToUniversalTime() - [DateTime]::UtcNow).TotalDays)
|
||||
Add-Check 'tls-certificate' ($days -ge $MinimumCertificateDays) "expires=$($certificate.NotAfter.ToUniversalTime().ToString('o')) days=$days"
|
||||
}
|
||||
finally { $ssl.Dispose() }
|
||||
}
|
||||
finally { $tcp.Dispose() }
|
||||
}
|
||||
catch { Add-Check 'tls-certificate' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$assistantAddresses = @(Resolve-DnsName assistent.cin.su -Server 8.8.8.8 -Type A -DnsOnly | Where-Object Type -eq A | Select-Object -ExpandProperty IPAddress | Sort-Object -Unique)
|
||||
$dockerAddresses = @(Resolve-DnsName docker.cin.su -Server 8.8.8.8 -Type A -DnsOnly | Where-Object Type -eq A | Select-Object -ExpandProperty IPAddress | Sort-Object -Unique)
|
||||
$same = $assistantAddresses.Count -gt 0 -and $dockerAddresses.Count -gt 0 -and @(Compare-Object $assistantAddresses $dockerAddresses).Count -eq 0
|
||||
Add-Check 'public-dns' $same "assistent=$($assistantAddresses -join ',') docker=$($dockerAddresses -join ',')"
|
||||
}
|
||||
catch { Add-Check 'public-dns' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$latestProduction = ((& ssh.exe $SshHost "find '$RemoteBackupRoot' -mindepth 1 -maxdepth 1 -type d ! -name '.*' -printf '%f\n' | sort | tail -n1") -join '').Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $latestProduction -notmatch '^\d{8}T\d{6}Z$') { throw 'invalid latest production backup' }
|
||||
$productionTime = [DateTime]::ParseExact($latestProduction, "yyyyMMdd'T'HHmmss'Z'", [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AdjustToUniversal)
|
||||
$age = ([DateTime]::UtcNow - $productionTime).TotalHours
|
||||
$verify = (& ssh.exe $SshHost "cd '$RemoteBackupRoot/$latestProduction' && sha256sum -c SHA256SUMS") -join '; '
|
||||
if ($LASTEXITCODE -ne 0) { throw 'production backup hash verification failed' }
|
||||
Add-Check 'production-backup' ($age -le $MaxProductionBackupAgeHours) ("backup=$latestProduction age_hours={0:N2} hashes=ok" -f $age)
|
||||
}
|
||||
catch { Add-Check 'production-backup' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$manifestFile = Get-ChildItem -LiteralPath $NasBackupRoot -Filter '*.json' -File | Sort-Object BaseName | Select-Object -Last 1
|
||||
if (-not $manifestFile -or $manifestFile.BaseName -notmatch '^\d{8}T\d{6}Z$') { throw 'invalid latest NAS backup manifest' }
|
||||
$manifest = Get-Content -LiteralPath $manifestFile.FullName -Raw | ConvertFrom-Json
|
||||
$nasTime = [DateTime]::ParseExact($manifestFile.BaseName, "yyyyMMdd'T'HHmmss'Z'", [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AdjustToUniversal)
|
||||
$age = ([DateTime]::UtcNow - $nasTime).TotalHours
|
||||
$cipher = Join-Path $NasBackupRoot "$($manifestFile.BaseName).tar.gz.gpg"
|
||||
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $cipher).Hash.ToLowerInvariant()
|
||||
$ok = $hash -eq $manifest.ciphertext_sha256 -and $age -le $MaxNasBackupAgeHours
|
||||
Add-Check 'nas-backup' $ok ("backup=$($manifestFile.BaseName) age_hours={0:N2} ciphertext_hash={1}" -f $age, $(if ($hash -eq $manifest.ciphertext_sha256) { 'ok' } else { 'mismatch' }))
|
||||
}
|
||||
catch { Add-Check 'nas-backup' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$cron = ((& ssh.exe $SshHost "systemctl is-active cron && crontab -l | grep -F '/home/m/assistant-ops/backup-postgres.sh'") -join '; ').Trim()
|
||||
Add-Check 'production-backup-cron' ($LASTEXITCODE -eq 0 -and $cron -match '^active') $cron
|
||||
}
|
||||
catch { Add-Check 'production-backup-cron' $false $_.Exception.Message }
|
||||
|
||||
try {
|
||||
$backupTask = Get-ScheduledTask -TaskName 'Domovoy PostgreSQL Off-host Backup'
|
||||
$backupInfo = Get-ScheduledTaskInfo -TaskName $backupTask.TaskName
|
||||
$ok = $backupTask.State -ne 'Disabled' -and $backupInfo.LastTaskResult -eq 0
|
||||
Add-Check 'offhost-backup-task' $ok "state=$($backupTask.State) last_result=$($backupInfo.LastTaskResult) next=$($backupInfo.NextRunTime.ToString('o'))"
|
||||
}
|
||||
catch { Add-Check 'offhost-backup-task' $false $_.Exception.Message }
|
||||
|
||||
$overall = if (@($checks | Where-Object { -not $_.ok }).Count -eq 0) { 'healthy' } else { 'degraded' }
|
||||
$record = [ordered]@{
|
||||
version = 1
|
||||
project = 'domovoy'
|
||||
observed_at_utc = [DateTime]::UtcNow.ToString('o')
|
||||
overall = $overall
|
||||
checks = $checks
|
||||
}
|
||||
$json = $record | ConvertTo-Json -Depth 6
|
||||
Write-AtomicJson $LocalStatusPath $json
|
||||
try { Write-AtomicJson $NasStatusPath $json }
|
||||
catch {
|
||||
Add-Check 'nas-status-publication' $false $_.Exception.Message
|
||||
$record.overall = 'degraded'
|
||||
$record.checks = $checks
|
||||
Write-AtomicJson $LocalStatusPath ($record | ConvertTo-Json -Depth 6)
|
||||
$overall = 'degraded'
|
||||
}
|
||||
|
||||
Write-Output "Domovoy production health: $overall"
|
||||
if ($overall -ne 'healthy') { exit 1 }
|
||||
@@ -0,0 +1,75 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$NasBackupRoot = '\\nas\MST\codex\_backups\domovoy\postgres',
|
||||
[string]$KeyRecordPath = "$env:LOCALAPPDATA\Domovoy\postgres-backup-key.dpapi.json",
|
||||
[string]$GpgPath = 'gpg.exe',
|
||||
[string]$SshHost = 'docker',
|
||||
[switch]$VerifyRemoteRestore
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
function Get-RecoveryPassphrase([string]$Path) {
|
||||
$record = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
|
||||
if ($record.version -ne 1 -or [string]::IsNullOrWhiteSpace($record.protected_value)) { throw 'Invalid DPAPI recovery key record' }
|
||||
$secure = ConvertTo-SecureString -String $record.protected_value
|
||||
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
|
||||
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
|
||||
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
|
||||
}
|
||||
|
||||
$manifestFile = Get-ChildItem -LiteralPath $NasBackupRoot -Filter '*.json' -File | Sort-Object BaseName | Select-Object -Last 1
|
||||
if (-not $manifestFile -or $manifestFile.BaseName -notmatch '^\d{8}T\d{6}Z$') { throw 'No valid NAS backup manifest found' }
|
||||
$manifest = Get-Content -LiteralPath $manifestFile.FullName -Raw | ConvertFrom-Json
|
||||
$latest = $manifestFile.BaseName
|
||||
$cipherPath = Join-Path $NasBackupRoot "$latest.tar.gz.gpg"
|
||||
if ((Get-FileHash -Algorithm SHA256 -LiteralPath $cipherPath).Hash.ToLowerInvariant() -ne $manifest.ciphertext_sha256) { throw 'NAS ciphertext hash mismatch' }
|
||||
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
|
||||
$work = Join-Path $tempRoot ("domovoy-backup-test-" + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $work | Out-Null
|
||||
$passphrase = $null
|
||||
$remoteCheck = $null
|
||||
|
||||
try {
|
||||
& icacls.exe $work /inheritance:r /grant:r "$([Security.Principal.WindowsIdentity]::GetCurrent().Name):(OI)(CI)F" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Temporary ACL hardening failed' }
|
||||
$passphrase = Get-RecoveryPassphrase $KeyRecordPath
|
||||
$passphraseFile = Join-Path $work 'passphrase.txt'
|
||||
[IO.File]::WriteAllText($passphraseFile, $passphrase, [Text.UTF8Encoding]::new($false))
|
||||
$archive = Join-Path $work "$latest.tar.gz"
|
||||
& $GpgPath --batch --yes --pinentry-mode loopback --passphrase-file $passphraseFile --decrypt --output $archive $cipherPath
|
||||
if ($LASTEXITCODE -ne 0) { throw 'NAS backup decryption failed' }
|
||||
if ((Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant() -ne $manifest.archive_sha256) { throw 'Decrypted archive hash mismatch' }
|
||||
& tar.exe -xzf $archive -C $work
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Decrypted archive extraction failed' }
|
||||
$sourceDirectory = Join-Path $work $latest
|
||||
Push-Location $sourceDirectory
|
||||
try {
|
||||
foreach ($line in Get-Content -LiteralPath 'SHA256SUMS') {
|
||||
if ($line -notmatch '^([0-9a-f]{64}) ([A-Za-z0-9.]+)$') { throw 'Invalid decrypted SHA256SUMS' }
|
||||
if ((Get-FileHash -Algorithm SHA256 -LiteralPath $matches[2]).Hash.ToLowerInvariant() -ne $matches[1]) { throw "Decrypted file hash mismatch: $($matches[2])" }
|
||||
}
|
||||
}
|
||||
finally { Pop-Location }
|
||||
|
||||
if ($VerifyRemoteRestore) {
|
||||
$remoteCheck = "/home/m/assistant-backups/offhost-restore-check/$latest-$([guid]::NewGuid().ToString('N'))"
|
||||
if ($remoteCheck -notmatch '^/home/m/assistant-backups/offhost-restore-check/\d{8}T\d{6}Z-[0-9a-f]{32}$') { throw 'Unsafe remote restore path' }
|
||||
& ssh.exe $SshHost "mkdir -p '$remoteCheck'"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Remote restore-check directory creation failed' }
|
||||
& scp.exe -q -r "$sourceDirectory\*" "${SshHost}:${remoteCheck}/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Remote restore-check copy failed' }
|
||||
& ssh.exe $SshHost "/home/m/assistant-ops/verify-postgres-restore.sh '$remoteCheck'"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Remote PostgreSQL restore check failed' }
|
||||
}
|
||||
Write-Output "Off-host backup verified: $latest"
|
||||
}
|
||||
finally {
|
||||
if ($remoteCheck -and $remoteCheck -match '^/home/m/assistant-backups/offhost-restore-check/\d{8}T\d{6}Z-[0-9a-f]{32}$') {
|
||||
& ssh.exe $SshHost "rm -rf -- '$remoteCheck'" | Out-Null
|
||||
}
|
||||
$passphrase = $null
|
||||
if (Test-Path -LiteralPath $work) { Remove-Item -LiteralPath $work -Recurse -Force }
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"task_file": "dev/tasks/DEV-000036-creator-secret-files.json",
|
||||
"task_id": "DEV-000036",
|
||||
"task_file": "dev/tasks/DEV-000040-creator-action-history.json",
|
||||
"task_id": "DEV-000040",
|
||||
"task_revision": 1
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"task_id": "DEV-000037",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0004",
|
||||
"base_repo_revision": "03dde8c1961f214fbb5ebdefa131eb38fd0bef57",
|
||||
"risk_tier": "E",
|
||||
"intent": "Replicate verified production PostgreSQL backups to the private NAS as authenticated encrypted artifacts, with a DPAPI-protected recovery key and tested restore path, without using docker-test.",
|
||||
"requirement_ids": ["CONSTITUTION-1.3.36", "USER-DOCKER-PROD-ONLY"],
|
||||
"allowed_change_scope": {
|
||||
"modules": [],
|
||||
"paths": [
|
||||
"deploy/windows/Sync-PostgresBackupToNas.ps1",
|
||||
"deploy/windows/Test-PostgresBackupFromNas.ps1",
|
||||
"deploy/windows/Register-PostgresBackupNasTask.ps1",
|
||||
"docs/CREDENTIALS_AND_SECRETS.md",
|
||||
"docs/DEPLOYMENT.md",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000037-encrypted-offhost-backup.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"ci/**",
|
||||
".gitea/**",
|
||||
"cmd/**",
|
||||
"contracts/**",
|
||||
"modules/**",
|
||||
"database/**",
|
||||
"security/**",
|
||||
"deploy/docker-compose*.yml"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_operator_dependencies": 1
|
||||
},
|
||||
"dependencies": {
|
||||
"operator": ["GnuPG 2.4+ already installed on the authorized Windows backup workstation"]
|
||||
},
|
||||
"contracts": {
|
||||
"consume": ["DEV-000035 verified PostgreSQL backup directory", "SSH key to docker.cin.su", "authenticated NAS session", "Windows DPAPI CurrentUser"],
|
||||
"may_change": []
|
||||
},
|
||||
"semantic_owner": "none; disaster-recovery transport only",
|
||||
"canonical_state": ["none; backup artifacts are exported recovery copies"],
|
||||
"state_transitions": ["verified local backup -> encrypted off-host copy -> decrypt-and-restore verified copy"],
|
||||
"side_effects_and_privileges": ["reads completed production backup artifacts over SSH", "writes encrypted artifacts to the private NAS", "stores a random recovery passphrase as CurrentUser DPAPI ciphertext outside Git", "registers a current-user scheduled task"],
|
||||
"persistence_and_migrations": ["no database migration", "encrypted .gpg artifact plus non-secret JSON manifest on NAS", "no automatic deletion or retention policy"],
|
||||
"failure_retry_restart": ["NAS completion is indicated only after ciphertext and manifest are atomically renamed", "existing matching artifacts are idempotently retained", "temporary plaintext is confined to a validated per-run Windows temp directory and removed on exit", "scheduled retries run at logon and daily", "failed remote restore checks remove only their generated temporary directory"],
|
||||
"assumptions": [
|
||||
"The authorized Windows user retains access to both the SSH alias docker and the private NAS share",
|
||||
"GnuPG 2.4+ remains installed on that workstation",
|
||||
"The DPAPI profile and NAS are independent from the production Docker host",
|
||||
"docker-test remains prohibited"
|
||||
],
|
||||
"acceptance_scenarios": [
|
||||
"the latest completed production backup is copied and source hashes are checked before encryption",
|
||||
"NAS contains ciphertext and a non-secret manifest but no plaintext PostgreSQL dump",
|
||||
"the recovery passphrase is random and stored only as DPAPI ciphertext outside the repository",
|
||||
"ciphertext decrypts and reproduces the source archive hash",
|
||||
"the decrypted off-host copy passes SHA-256 checks and an isolated PostgreSQL restore on docker.cin.su",
|
||||
"daily and logon triggers are registered for the current user",
|
||||
"no backup is automatically deleted",
|
||||
"exact diff validation observes only declared paths"
|
||||
],
|
||||
"required_tests": [
|
||||
"PowerShell parser",
|
||||
"architecture preflight",
|
||||
"exact diff scope",
|
||||
"source SHA-256 validation",
|
||||
"GnuPG encrypt/decrypt round trip",
|
||||
"NAS ciphertext hash validation",
|
||||
"isolated restore from decrypted NAS artifact",
|
||||
"scheduled task registration and manual invocation",
|
||||
"production health",
|
||||
"CI"
|
||||
],
|
||||
"terminal_gap_states": [
|
||||
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||
"BLOCKED_BY_CONFLICT"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"task_id": "DEV-000038",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0004",
|
||||
"base_repo_revision": "0a188ddafe24dc2b31271f0d47ac31baed1d237f",
|
||||
"risk_tier": "E",
|
||||
"intent": "Add an external production health monitor for Domovoy containers, HTTPS certificate, public DNS, verified backups, and scheduled jobs without creating canonical Monitor semantics or using docker-test.",
|
||||
"requirement_ids": ["CONSTITUTION-1.3.11", "CONSTITUTION-1.3.31", "USER-DOCKER-PROD-ONLY"],
|
||||
"allowed_change_scope": {
|
||||
"modules": [],
|
||||
"paths": [
|
||||
"deploy/windows/Test-DomovoyProductionHealth.ps1",
|
||||
"deploy/windows/Register-DomovoyProductionHealthTask.ps1",
|
||||
"docs/DEPLOYMENT.md",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000038-production-health-monitor.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"ci/**",
|
||||
".gitea/**",
|
||||
"cmd/**",
|
||||
"contracts/**",
|
||||
"modules/**",
|
||||
"database/**",
|
||||
"security/**",
|
||||
"deploy/docker-compose*.yml"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0
|
||||
},
|
||||
"contracts": {
|
||||
"consume": ["Docker read-only inspection", "HTTPS/TLS endpoint", "public DNS", "DEV-000035 backup manifest", "DEV-000037 NAS manifest", "Windows Scheduled Tasks"],
|
||||
"may_change": []
|
||||
},
|
||||
"semantic_owner": "none; external rebuildable operational projection",
|
||||
"canonical_state": ["none; status JSON is non-canonical and may be regenerated"],
|
||||
"state_transitions": ["observed checks -> healthy or degraded operational snapshot"],
|
||||
"side_effects_and_privileges": ["read-only inspection of production Docker and backup state", "atomic write of local and NAS status JSON", "registration of a current-user scheduled task"],
|
||||
"persistence_and_migrations": ["no database migration", "latest status JSON only; no hidden retention deletion"],
|
||||
"failure_retry_restart": ["checks are independent and record explicit failure details", "the monitor exits nonzero when any check fails", "local status remains available if NAS publication fails", "scheduled execution retries every 15 minutes and at logon"],
|
||||
"assumptions": [
|
||||
"The authorized Windows user retains Docker context docker-prod, SSH alias docker, public DNS, and NAS access",
|
||||
"Production backup should be younger than 30 hours and off-host backup younger than 36 hours",
|
||||
"TLS certificate should retain at least 21 days",
|
||||
"docker-test remains prohibited"
|
||||
],
|
||||
"acceptance_scenarios": [
|
||||
"all expected Assistant containers are running and health-enabled containers are healthy",
|
||||
"HTTPS returns healthy and the certificate has at least 21 remaining days",
|
||||
"public assistent.cin.su and docker.cin.su A records agree",
|
||||
"production and NAS backups are recent and their hashes validate",
|
||||
"backup scheduled tasks and production cron report success",
|
||||
"status JSON is atomically published locally and to NAS",
|
||||
"a failed check produces overall degraded and a nonzero exit code",
|
||||
"monitor runs every 15 minutes and at logon",
|
||||
"exact diff validation observes only declared paths"
|
||||
],
|
||||
"required_tests": [
|
||||
"PowerShell parser",
|
||||
"architecture preflight",
|
||||
"exact diff scope",
|
||||
"healthy live monitoring run",
|
||||
"synthetic degraded run",
|
||||
"atomic local and NAS status validation",
|
||||
"scheduled task registration and manual invocation",
|
||||
"go test",
|
||||
"go vet",
|
||||
"CI"
|
||||
],
|
||||
"terminal_gap_states": [
|
||||
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||
"BLOCKED_BY_CONFLICT"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"task_id": "DEV-000039",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0004",
|
||||
"base_repo_revision": "4016820541229544aae81240cb2e12513fb2ce12",
|
||||
"risk_tier": "E",
|
||||
"intent": "Add transition-aware local Windows notifications to the external Domovoy production health monitor without external services, canonical Monitor semantics, or docker-test.",
|
||||
"requirement_ids": ["CONSTITUTION-1.3.11", "CONSTITUTION-1.3.31", "USER-DOCKER-PROD-ONLY"],
|
||||
"allowed_change_scope": {
|
||||
"modules": [],
|
||||
"paths": [
|
||||
"deploy/windows/Send-DomovoyHealthNotification.ps1",
|
||||
"deploy/windows/Invoke-DomovoyProductionMonitoring.ps1",
|
||||
"deploy/windows/Register-DomovoyProductionHealthTask.ps1",
|
||||
"docs/DEPLOYMENT.md",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000039-production-health-notifications.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"ci/**",
|
||||
".gitea/**",
|
||||
"cmd/**",
|
||||
"contracts/**",
|
||||
"modules/**",
|
||||
"database/**",
|
||||
"security/**",
|
||||
"deploy/docker-compose*.yml"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0
|
||||
},
|
||||
"contracts": {
|
||||
"consume": ["DEV-000038 local production health status JSON", "Windows interactive notification area", "Windows Scheduled Tasks"],
|
||||
"may_change": []
|
||||
},
|
||||
"semantic_owner": "none; external rebuildable operational projection",
|
||||
"canonical_state": ["none; notification suppression state is non-canonical and may be regenerated"],
|
||||
"state_transitions": ["first degraded observation -> degraded notification", "healthy to degraded -> degraded notification", "degraded to healthy -> recovery notification", "continued degraded after reminder interval -> reminder notification"],
|
||||
"side_effects_and_privileges": ["display a local Windows notification for the current interactive user", "atomically write local non-canonical notification state", "update the current-user scheduled task action"],
|
||||
"persistence_and_migrations": ["no database migration", "single local notification state JSON; no history or retention deletion"],
|
||||
"failure_retry_restart": ["health collection runs in a child process and publishes status before notification evaluation", "duplicate degraded observations are suppressed for six hours", "notification failure is distinct from health degradation", "the scheduled task returns the health exit code unless notification delivery itself fails"],
|
||||
"assumptions": [
|
||||
"The scheduled task runs for an interactive Windows user so notification balloons are visible",
|
||||
"The DEV-000038 status schema remains version 1 with overall and checks fields",
|
||||
"Local notification state is not authoritative and can be deleted safely",
|
||||
"docker-test remains prohibited"
|
||||
],
|
||||
"acceptance_scenarios": [
|
||||
"an initial healthy observation records state without notifying",
|
||||
"a transition to degraded sends one notification naming failed checks",
|
||||
"a repeated degraded observation within six hours is suppressed",
|
||||
"a transition back to healthy sends one recovery notification",
|
||||
"the wrapper evaluates notifications even when the health child exits nonzero",
|
||||
"the registered task invokes the wrapper every 15 minutes and at logon",
|
||||
"exact diff validation observes only declared paths"
|
||||
],
|
||||
"required_tests": [
|
||||
"PowerShell parser",
|
||||
"architecture preflight",
|
||||
"exact diff scope",
|
||||
"synthetic healthy/degraded/repeated/recovered notification transitions",
|
||||
"healthy live wrapper run",
|
||||
"scheduled task registration and manual invocation",
|
||||
"go test",
|
||||
"go vet",
|
||||
"CI"
|
||||
],
|
||||
"terminal_gap_states": [
|
||||
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||
"BLOCKED_BY_CONFLICT"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
{
|
||||
"task_id": "DEV-000040",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0004",
|
||||
"base_repo_revision": "2d2615b734e0df053bced78e51f548b37ea0e60c",
|
||||
"risk_tier": "E",
|
||||
"intent": "Expose a bounded, owner-scoped, read-only Creator action history from Commit canonical state and render it in the Domovoy console without new mutation authority, persistence, credentials, or docker-test.",
|
||||
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "CONSTITUTION-1.3.23", "USER-DOCKER-PROD-ONLY"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["commit"],
|
||||
"paths": [
|
||||
"adapters/postgres/commit_repository.go",
|
||||
"cmd/commit-runtime/creator_command.go",
|
||||
"cmd/commit-runtime/creator_command_test.go",
|
||||
"cmd/creator-web/server.go",
|
||||
"cmd/creator-web/server_test.go",
|
||||
"cmd/creator-web/static/index.html",
|
||||
"cmd/creator-web/static/assets/console.js",
|
||||
"cmd/creator-web/static/assets/console.css",
|
||||
"tests/creator_commit/verify-remote.ps1",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000040-creator-action-history.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"ci/**",
|
||||
".gitea/**",
|
||||
"contracts/**",
|
||||
"modules/identity/**",
|
||||
"modules/authority/**",
|
||||
"modules/work/**",
|
||||
"modules/continuity/**",
|
||||
"database/**",
|
||||
"security/**",
|
||||
"deploy/**"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0
|
||||
},
|
||||
"contracts": {
|
||||
"consume": ["Creator session", "contracts.commit@v1 canonical action envelope and attempt", "existing Creator gateway"],
|
||||
"may_change": []
|
||||
},
|
||||
"semantic_owner": "commit for canonical action data; Creator UI is a read-only projection",
|
||||
"canonical_state": ["existing Commit authorized action envelopes and action attempts; no new canonical state"],
|
||||
"state_transitions": ["none; public query is read-only"],
|
||||
"side_effects_and_privileges": ["authenticated HTTP reads from the existing commit schema", "browser renders a replaceable projection"],
|
||||
"persistence_and_migrations": ["none; bounded owner-local SELECT only"],
|
||||
"failure_retry_restart": ["invalid or expired session is denied before repository access", "invalid limits are rejected", "an authorized action with no attempt remains visible as AUTHORIZED", "query failure returns explicit service unavailability and does not mutate state", "UI refresh is explicit and safe to repeat"],
|
||||
"assumptions": [
|
||||
"The first page of at most 50 newest actions is sufficient for the V1 operational console",
|
||||
"AuthorizedAtUnixMillis plus AuthorizedActionID provides deterministic descending order",
|
||||
"EvidenceRef and grant details are intentionally omitted from the list response",
|
||||
"docker-test remains prohibited"
|
||||
],
|
||||
"acceptance_scenarios": [
|
||||
"missing or invalid Creator session is denied before Commit history query",
|
||||
"Actor and Principal filters are taken only from the validated server session",
|
||||
"history is bounded to 1 through 50 and ordered deterministically newest first",
|
||||
"only Commit-owned tables are queried",
|
||||
"an action without an attempt is returned as AUTHORIZED with no attempt identity",
|
||||
"the gateway allowlists only the exact GET action-history route",
|
||||
"the console renders loading, empty, error, succeeded, failed, unknown, executing, and authorized states without exposing evidence or credentials",
|
||||
"desktop and mobile layouts remain usable and keyboard accessible",
|
||||
"production smoke observes the newly committed Creator action through the authenticated history endpoint",
|
||||
"exact diff validation observes only declared paths"
|
||||
],
|
||||
"required_tests": [
|
||||
"unit",
|
||||
"owner filter and bounded query",
|
||||
"gateway allowlist",
|
||||
"runtime HTTP",
|
||||
"responsive browser",
|
||||
"browser console",
|
||||
"remote Docker smoke",
|
||||
"PowerShell parser",
|
||||
"architecture preflight",
|
||||
"exact diff scope",
|
||||
"go test",
|
||||
"go vet",
|
||||
"CI"
|
||||
],
|
||||
"terminal_gap_states": [
|
||||
"BLOCKED_BY_ARCHITECTURE_GAP",
|
||||
"BLOCKED_BY_SPEC_GAP",
|
||||
"BLOCKED_BY_CONFLICT",
|
||||
"BLOCKED_BY_MISSING_CAPABILITY"
|
||||
]
|
||||
}
|
||||
@@ -22,3 +22,5 @@ Do not guess Portainer credentials and do not search other project source trees
|
||||
Each privileged runtime gets only its required secret/capability bindings. `commit-runtime` is intentionally isolated from the general Core Runtime.
|
||||
|
||||
Creator authentication secrets are stored in the external Docker volume `assistant_core_secrets` and mounted read-only only at `/run/secrets` in `core-runtime`. The production container environment contains `_FILE` paths, not the secret values. Files are owned by runtime uid 100/gid 101 with mode 0400. `CREATOR_USERNAME` is not secret and remains an environment value. Development may continue to use direct environment values, but a direct value and its matching `_FILE` setting must never be configured together.
|
||||
|
||||
The PostgreSQL off-host backup passphrase is generated randomly and stored as CurrentUser DPAPI ciphertext at `%LOCALAPPDATA%\Domovoy\postgres-backup-key.dpapi.json`. An atomic copy of that DPAPI ciphertext, never the plaintext passphrase, is retained at `\\nas\MST\codex\_backups\domovoy\keys\postgres-backup-key.dpapi.json`. The passphrase is never stored in Git, the production Docker host, a scheduled-task argument, or NAS plaintext. The NAS backup directory receives only GnuPG AES-256 ciphertext and a non-secret integrity manifest. Recovery therefore requires both the NAS artifacts and the authorized Windows DPAPI profile.
|
||||
|
||||
@@ -27,3 +27,17 @@ Production backups run only on `docker.cin.su`; this project must not use the sh
|
||||
`deploy/verify-postgres-restore.sh <backup-directory>` verifies all hashes and restores into an isolated PostgreSQL 18.6 container backed by tmpfs. It never mounts or writes `assistant_assistant_pg`, and removes its temporary container on exit. A backup is operationally accepted only after this restore check passes.
|
||||
|
||||
The production user crontab installs the single entry from `deploy/cron/assistant-postgres-backup.crontab`. It runs the backup and restore check daily at 00:15 UTC (03:15 Europe/Moscow), survives host reboot without a persistent login session, and writes a private operational log beside the backups.
|
||||
|
||||
## Encrypted off-host backup
|
||||
|
||||
`deploy/windows/Sync-PostgresBackupToNas.ps1` copies only a completed, hash-verified production backup over SSH, archives it locally, encrypts it with GnuPG AES-256, verifies an immediate decrypt round trip, and atomically publishes ciphertext plus a non-secret manifest under `\\nas\MST\codex\_backups\domovoy\postgres`. Temporary plaintext is removed on exit. The script is idempotent and never deletes existing backups.
|
||||
|
||||
`deploy/windows/Test-PostgresBackupFromNas.ps1 -VerifyRemoteRestore` verifies the NAS ciphertext hash, decrypts it with the DPAPI-protected recovery key, checks every source hash, and performs a full isolated PostgreSQL restore on `docker.cin.su`. `deploy/windows/Register-PostgresBackupNasTask.ps1` generates the key when absent, atomically backs up only its DPAPI ciphertext to the NAS, and registers current-user daily and logon triggers. The task intentionally does not use `docker-test`.
|
||||
|
||||
## Production health monitoring
|
||||
|
||||
`deploy/windows/Test-DomovoyProductionHealth.ps1` is an external, rebuildable operational projection; it is not a canonical Core `Monitor`. It checks all expected production containers, HTTPS health, TLS expiry, public DNS agreement, production backup age and hashes, NAS backup age and ciphertext hash, cron, and the off-host backup task. Thresholds are 30 hours for the production backup, 36 hours for the NAS copy, and 21 remaining certificate days.
|
||||
|
||||
The script atomically writes the latest JSON snapshot to `%LOCALAPPDATA%\Domovoy\monitoring\status.json` and `\\nas\MST\codex\_monitoring\domovoy\status.json`, then exits nonzero when any check is degraded. `deploy/windows/Register-DomovoyProductionHealthTask.ps1` registers a current-user execution every 15 minutes and at logon. Monitoring never uses `docker-test` and never mutates product state.
|
||||
|
||||
`deploy/windows/Invoke-DomovoyProductionMonitoring.ps1` runs health collection in a child process and then evaluates `deploy/windows/Send-DomovoyHealthNotification.ps1`, including when health is degraded. The notifier shows a local Windows notification on the first degraded observation, recovery, and no more than one continuing-failure reminder per six hours. Its suppression state is an external, non-canonical JSON file at `%LOCALAPPDATA%\Domovoy\monitoring\notification-state.json` and may be regenerated. Notifications require the registered user to have an interactive Windows session; no external notification service or credential is used.
|
||||
|
||||
@@ -37,6 +37,12 @@ function Creator-Post([string]$url, [object]$body, [string]$token) {
|
||||
}
|
||||
}
|
||||
|
||||
function Creator-Get([string]$url, [string]$token) {
|
||||
$result = docker --context $DockerContext exec --env "CREATOR_TEST_SESSION=$token" $commitContainer sh -c 'wget -qO- --header="Authorization: Bearer $CREATOR_TEST_SESSION" "$1"' sh $url
|
||||
if ($LASTEXITCODE -ne 0) { throw "Creator GET $url failed" }
|
||||
return ($result -join "`n")
|
||||
}
|
||||
|
||||
function Expect-CreatorStatus([string]$url, [object]$body, [string]$token, [int]$status) {
|
||||
$json = $body | ConvertTo-Json -Depth 10 -Compress
|
||||
$local = New-TemporaryFile
|
||||
@@ -55,11 +61,12 @@ function Expect-CreatorStatus([string]$url, [object]$body, [string]$token, [int]
|
||||
}
|
||||
}
|
||||
|
||||
$environment = docker --context $DockerContext inspect --format '{{range .Config.Env}}{{println .}}{{end}}' $coreContainer
|
||||
$bootstrapEntry = $environment | Where-Object { $_ -like "CREATOR_BOOTSTRAP_TOKEN=*" } | Select-Object -First 1
|
||||
if (-not $bootstrapEntry) { throw "Creator bootstrap metadata unavailable" }
|
||||
$bootstrapToken = $bootstrapEntry.Substring("CREATOR_BOOTSTRAP_TOKEN=".Length)
|
||||
$sessionResponse = docker --context $DockerContext exec --env "CREATOR_TEST_BOOTSTRAP=$bootstrapToken" $coreContainer sh -c 'wget -qO- --header="Authorization: Bearer $CREATOR_TEST_BOOTSTRAP" --post-data="" "$1/v1/creator/sessions"' sh http://localhost:8080
|
||||
$sessionResponse = docker --context $DockerContext exec $coreContainer sh -c '
|
||||
token="$CREATOR_BOOTSTRAP_TOKEN"
|
||||
if [ -n "$CREATOR_BOOTSTRAP_TOKEN_FILE" ]; then token=$(cat "$CREATOR_BOOTSTRAP_TOKEN_FILE"); fi
|
||||
if [ -z "$token" ]; then exit 7; fi
|
||||
wget -qO- --header="Authorization: Bearer $token" --post-data="" "$1/v1/creator/sessions"
|
||||
' sh http://localhost:8080
|
||||
if ($LASTEXITCODE -ne 0) { throw "Creator session issuance failed" }
|
||||
$creatorSession = ($sessionResponse | ConvertFrom-Json).Token
|
||||
|
||||
@@ -82,6 +89,13 @@ $action = Creator-Post http://localhost:8082/v1/creator/continuity/satisfy-deliv
|
||||
if ($action.State -ne "SUCCEEDED" -or -not $action.AuthorizedActionID -or -not $action.ActionIntentID -or -not $action.ActionAttemptID) {
|
||||
throw "Creator command response is incomplete"
|
||||
}
|
||||
$historyRaw = Creator-Get 'http://localhost:8082/v1/creator/authorized-actions?limit=50' $creatorSession
|
||||
$history = $historyRaw | ConvertFrom-Json
|
||||
$historyItem = @($history.Items | Where-Object { $_.AuthorizedActionID -eq $action.AuthorizedActionID })
|
||||
if ($historyItem.Count -ne 1 -or $historyItem[0].ActionAttemptID -ne $action.ActionAttemptID -or $historyItem[0].State -ne 'SUCCEEDED') {
|
||||
throw "Creator action history does not contain the committed outcome"
|
||||
}
|
||||
if ($historyRaw -match 'EvidenceRef|GrantID') { throw "Creator action history exposed restricted envelope fields" }
|
||||
$updated = docker --context $DockerContext exec $continuityContainer wget -qO- "http://localhost:8081/v1/prospective-items/$prospective" | ConvertFrom-Json
|
||||
if ($updated.State -ne "SATISFIED" -or $updated.Revision -ne 2) { throw "Creator command did not satisfy item exactly once" }
|
||||
Expect-CreatorStatus http://localhost:8082/v1/creator/continuity/satisfy-delivered $command $creatorSession 409
|
||||
|
||||
Reference in New Issue
Block a user