package notification import ( "context" "errors" "fmt" "regexp" "strings" "time" "unicode/utf8" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) var ( ErrInboxUnavailable = errors.New("notification inbox is unavailable") // ErrInboxForbidden reports an account that may not use the requested // cabinet inbox: a missing or unverified account, or an account of the // other scenario. ErrInboxForbidden = errors.New("notification inbox is forbidden") // ErrInboxEmailNotVerified reports an employer account whose email is not // confirmed; the organization operations answer it as email_not_verified. ErrInboxEmailNotVerified = errors.New("notification inbox requires a confirmed email") // ErrInboxContentUnavailable means the referenced source is missing or its // current visibility no longer permits the original presentation. ErrInboxContentUnavailable = errors.New("notification content is unavailable") ) const ( maxInboxTitleRunes = 120 maxInboxSummaryRunes = 500 ) // inboxLinkPathPattern is the shape of a content link: a same-origin // absolute path of at most 256 characters from a narrow alphabet, so it has // no query, fragment, escape, dot segment, or backslash. The public contract // states the same pattern. var inboxLinkPathPattern = regexp.MustCompile(`^/[A-Za-z0-9/_-]{0,255}$`) // InboxContent is resolved from the current source at read time. It is never // written to notification_inbox_events. type InboxContent struct { title string summary string linkPath string } // NewInboxContent validates a small same-origin presentation returned by a // source resolver after its current visibility checks. func NewInboxContent(title, summary, linkPath string) (InboxContent, error) { const location = "notification.NewInboxContent" if !validInboxText(title, maxInboxTitleRunes, false) || !validInboxText(summary, maxInboxSummaryRunes, true) { return InboxContent{}, fmt.Errorf("%s - title and summary are invalid: %w", location, ErrInboxUnavailable) } if linkPath != "" && !validInboxLinkPath(linkPath) { return InboxContent{}, fmt.Errorf("%s - link path must be relative and same-origin: %w", location, ErrInboxUnavailable) } return InboxContent{title: title, summary: summary, linkPath: linkPath}, nil } func (content InboxContent) Title() string { return content.title } func (content InboxContent) Summary() string { return content.summary } func (content InboxContent) LinkPath() string { return content.linkPath } func validInboxText(value string, maxRunes int, allowNewlines bool) bool { if !utf8.ValidString(value) || value == "" || strings.TrimSpace(value) != value || utf8.RuneCountInString(value) > maxRunes { return false } for _, character := range value { allowedControl := allowNewlines && (character == '\n' || character == '\t') if character == 0 || (character < 0x20 && !allowedControl) || character == 0x7f { return false } } return true } func validInboxLinkPath(value string) bool { return inboxLinkPathPattern.MatchString(value) && !strings.HasPrefix(value, "//") } // InboxContentResolver reads the current source under its current visibility // rules, inside the read transaction that also authorized the viewer. It must // return ErrInboxContentUnavailable when that source is gone or no longer // safe to present to the recipient. type InboxContentResolver interface { Resolve(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) } // InboxItem pairs immutable event metadata with content resolved for this // read. Content is nil when a safe generic fallback is required. type InboxItem struct { Entry domain.NotificationInboxEntry Content *InboxContent ContentUnavailable bool } // InboxListRequest is built from the authenticated recipient. A nil // OrganizationID is the candidate cabinet: every organization that sent to // the recipient. A set OrganizationID is the employer cabinet of that // organization and requires the recipient's current active membership. The // organization ID filters items but is never authorization by itself. type InboxListRequest struct { RecipientUserID uuid.UUID OrganizationID *uuid.UUID After *outbound.NotificationInboxPosition Limit int32 } // InboxMarkReadRequest names one inbox item in the same cabinet scope as // InboxListRequest. type InboxMarkReadRequest struct { RecipientUserID uuid.UUID OrganizationID *uuid.UUID EventID uuid.UUID } type InboxPage struct { Items []InboxItem HasMore bool } // InboxService lists and marks the inbox of the authenticated recipient. // Every operation authorizes the recipient for the requested cabinet and // reads the inbox in one transaction, so a membership revoked a moment ago // cannot authorize a later read. The inbox stores references only: the text // of an item is resolved from its current source at each list, so a hiding, a // revoked membership, or a withdrawn source removes the content from every // later read. Mail delivery is a separate concern: an item exists whether or // not any email was sent, and an email failure never blocks it. type InboxService struct { transactor outbound.Transactor resolver InboxContentResolver clock func() time.Time } func NewInboxService( transactor outbound.Transactor, resolver InboxContentResolver, clock func() time.Time, ) (*InboxService, error) { if transactor == nil || resolver == nil || clock == nil { return nil, fmt.Errorf("notification.NewInboxService - transactor, resolver, and clock are required: %w", ErrInboxUnavailable) } return &InboxService{transactor: transactor, resolver: resolver, clock: clock}, nil } // List returns one newest-first page and resolves each stored reference // against its current source. A source that is missing or no longer visible // is returned without content. func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) { const location = "InboxService.List" if err := validateInboxListRequest(request); err != nil { return InboxPage{}, err } var page InboxPage err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil { return err } stored, err := unit.NotificationInbox().List(ctx, outbound.NotificationInboxListQuery{ RecipientUserID: request.RecipientUserID, OrganizationID: request.OrganizationID, After: request.After, Limit: request.Limit, }) if err != nil { return fmt.Errorf("%s - list recipient events: %w", location, err) } resolved := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore} for _, entry := range stored.Items { if !inboxEntryMatchesRequest(entry, request) { return fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable) } item := InboxItem{Entry: entry} content, resolveErr := service.resolver.Resolve(ctx, unit, entry) switch { case errors.Is(resolveErr, ErrInboxContentUnavailable): item.ContentUnavailable = true case resolveErr != nil: return fmt.Errorf("%s - resolve current event content: %w", location, resolveErr) default: item.Content = &content } resolved.Items = append(resolved.Items, item) } page = resolved return nil }) if err != nil { return InboxPage{}, fmt.Errorf("%s - run transaction: %w", location, err) } return page, nil } // MarkRead persists the first read timestamp of one item of the recipient. A // repeat keeps the first timestamp. The source is not read and no content is // returned. An item of another recipient, of another organization context, // or an unknown item all return outbound.ErrNotificationInboxEntryNotFound. func (service *InboxService) MarkRead(ctx context.Context, request InboxMarkReadRequest) (domain.NotificationInboxEntry, error) { const location = "InboxService.MarkRead" if request.RecipientUserID == uuid.Nil || request.EventID == uuid.Nil || (request.OrganizationID != nil && *request.OrganizationID == uuid.Nil) { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient and event IDs are required: %w", location, ErrInboxUnavailable) } at := service.clock() if at.IsZero() { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable) } var entry domain.NotificationInboxEntry err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil { return err } marked, err := unit.NotificationInbox().MarkRead(ctx, request.RecipientUserID, request.OrganizationID, request.EventID, at) if err != nil { return fmt.Errorf("%s - mark event read: %w", location, err) } entry = marked return nil }) if err != nil { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - run transaction: %w", location, err) } return entry, nil } // authorizeInboxViewer checks the account against the requested cabinet. The // candidate cabinet needs a verified candidate account. The employer cabinet // needs an employer account with a verified email (otherwise // ErrInboxEmailNotVerified, like the other organization operations) and an // active membership of any role in the named organization. The membership is // locked FOR SHARE until the transaction ends, like the card reads, so a // revocation cannot commit between this check and the read that follows. A // missing or inactive membership returns outbound.ErrOrganizationNotFound, so // an organization that exists cannot be told from one that does not. func authorizeInboxViewer(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, organizationID *uuid.UUID) error { const location = "notification.authorizeInboxViewer" user, err := unit.Users().GetByID(ctx, userID) if errors.Is(err, outbound.ErrUserNotFound) { return fmt.Errorf("%s - account does not exist: %w", location, ErrInboxForbidden) } if err != nil { return fmt.Errorf("%s - read account: %w", location, err) } if organizationID == nil { if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() { return fmt.Errorf("%s - the candidate inbox needs a verified candidate account: %w", location, ErrInboxForbidden) } return nil } if user.Scenario != domain.ScenarioEmployer { return fmt.Errorf("%s - the organization inbox needs an employer account: %w", location, ErrInboxForbidden) } if !user.EmailVerified() { return fmt.Errorf("%s - email is not verified: %w", location, ErrInboxEmailNotVerified) } if _, err := unit.Organizations().LockActiveMembership(ctx, *organizationID, userID); err != nil { if errors.Is(err, outbound.ErrOrganizationNotFound) { return fmt.Errorf("%s - no active membership: %w", location, outbound.ErrOrganizationNotFound) } return fmt.Errorf("%s - lock active membership: %w", location, err) } return nil } func validateInboxListRequest(request InboxListRequest) error { const location = "notification.validateInboxListRequest" if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize { return fmt.Errorf("%s - recipient and a bounded page size are required: %w", location, ErrInboxUnavailable) } if request.OrganizationID != nil && *request.OrganizationID == uuid.Nil { return fmt.Errorf("%s - organization context cannot be zero: %w", location, ErrInboxUnavailable) } if request.After != nil && (request.After.EventID == uuid.Nil || request.After.OccurredAt.IsZero()) { return fmt.Errorf("%s - page position is invalid: %w", location, ErrInboxUnavailable) } return nil } func inboxEntryMatchesRequest(entry domain.NotificationInboxEntry, request InboxListRequest) bool { if entry.IsZero() || entry.RecipientUserID() != request.RecipientUserID { return false } return request.OrganizationID == nil || entry.OrganizationID() == *request.OrganizationID }