openapi: 3.0.3
info:
  title: Easerix Notifications API
  description: |
    Platform notifications (backend/services/shared/notifications): the
    device registry, the per-user notification feed, category preferences,
    and a live SSE stream of the unread count.

    Product services do NOT call this service directly. They emit domain
    events to the platform event outbox (backend/packages/eventkit) inside
    their own transactions; the notifications consumer fans those events out
    into per-user feed rows. The feed row in Postgres is the durable
    deliverable; a push is a best-effort doorbell on top of it, so a provider
    outage never loses a notification. With no push provider configured the
    service still records and serves everything and logs what it would send.

    Notifications are a platform capability rather than a tool, so /v1 routes
    require a valid session but no RequireTool gate. Responses are camelCase.

    One inbox across workspaces. A person's own session (an identity token)
    can read the feed, the counts and the stream across every workspace they
    belong to now. For now the feed and read-all default to the token's own
    workspace for every caller, and the stream's unread stays that workspace's
    count, so today's bell is unchanged. Reading or clearing every workspace
    takes an explicit scope "all". Slice 6 of the workspace-links work (the
    bell's workspace chips and cross-workspace click) flips these defaults to
    all workspaces for identity sessions.

    A request that acts on the token's own workspace, with a token that names
    none, is 404 and is never widened to every workspace. For a delegated
    token that is every feed request. A deleted workspace's items are never
    listed or counted. A delegated token (an API key or an OAuth grant) is bound to
    the workspace it was issued for: it is held there whatever it asks for.
    Every feed read shows only items created at or after the caller joined
    the item's workspace, so someone removed and re-invited never gets the old
    items back. Unread counts come from counters kept up to date on every
    write, never from counting rows.
  version: 2.1.0
  contact:
    name: Perizer Labs
    url: https://easerix.com
servers:
  - url: https://notifications-api.easerix.com
    description: Production
tags:
  - name: system
    description: Health and liveness
  - name: devices
    description: Push device registry
  - name: feed
    description: The notification feed
  - name: preferences
    description: Per-category opt-outs

security:
  - bearer: []

paths:
  /health:
    get:
      operationId: health
      tags: [system]
      summary: Liveness probe
      description: Unauthenticated liveness check used by the platform and monitors.
      security: []
      responses:
        "200":
          description: Service is up
          content:
            application/json:
              schema:
                type: object

  /health/consumers:
    get:
      operationId: healthConsumers
      tags: [system]
      summary: Event consumer health, for an uptime monitor
      description: >-
        200 while every event consumer is ok, 503 when one is stalled (events
        wait and its cursor hasn't moved) or has open dead letters. The body is
        {"status":"ok"} or {"status":"unavailable"} only: consumer names, lag
        and dead-letter counts are served on the service's internal port, never
        here. /health stays 200 for pod probes; this one is for the external
        uptime monitor (EAS-467).
      security: []
      responses:
        "200":
          description: Every consumer is ok
          content:
            application/json:
              schema:
                type: object
        "503":
          description: A consumer is stalled or has dead letters
          content:
            application/json:
              schema:
                type: object

  /v1/devices:
    post:
      operationId: registerDevice
      tags: [devices]
      summary: Register this install for push
      description: >-
        Idempotent on the token — apps re-register on every launch. A token
        that reappears under a different user moves to that user rather than
        duplicating, so a shared device never receives the previous
        signed-in user's notifications.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token, platform]
              properties:
                token: { type: string }
                platform: { type: string, enum: [ios, android] }
                appVersion: { type: string }
                locale: { type: string }
      responses:
        "200":
          description: Device registered
          content:
            application/json:
              schema:
                type: object
                required: [device]
                properties:
                  device: { $ref: "#/components/schemas/Device" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/devices/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string } }
    delete:
      operationId: deleteDevice
      tags: [devices]
      summary: Stop pushing to this install
      description: Called on sign-out. Owner-scoped.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Message" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/notifications:
    get:
      operationId: listNotifications
      tags: [feed]
      summary: The caller's feed
      description: >-
        Newest first, paged by cursor. scope=current (the default for now)
        lists the token's workspace only. scope=all lists every workspace the
        caller belongs to now, for a person's own session. Slice 6 makes all
        the default for identity sessions. A delegated token (API key, OAuth
        grant) always gets its own workspace, whatever scope it asks for. Each
        item names its workspace. unread is the badge number for the scope
        returned. Pass the nextCursor of one page as cursor to get the next.
        nextCursor is null on the last page.
      parameters:
        - name: scope
          in: query
          schema: { type: string, enum: [all, current], default: current }
          description: >-
            current (the default for now) or all. Slice 6 makes all the default
            for a person's own session. Ignored for a delegated token, which is
            always current.
        - name: cursor
          in: query
          schema: { type: string }
          description: Opaque. The nextCursor of the previous page.
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 50, default: 30 }
          description: Page size. Values over 50 are read as 50.
        - name: unread
          in: query
          schema: { type: string, enum: ["true"] }
          description: Unread only when exactly "true"
      responses:
        "200":
          description: Feed
          content:
            application/json:
              schema:
                type: object
                required: [notifications, unread, nextCursor]
                properties:
                  notifications:
                    type: array
                    maxItems: 50
                    items: { $ref: "#/components/schemas/Notification" }
                  unread: { type: integer, format: int64 }
                  nextCursor:
                    type: string
                    nullable: true
                    description: Pass as cursor for the next page. Null on the last page.
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/notifications/counts:
    get:
      operationId: countNotifications
      tags: [feed]
      summary: Unread counts per workspace
      description: >-
        The total and the unread count of every workspace the caller belongs
        to now, zero included, read from counters (no rows are counted). A
        delegated token (API key, OAuth grant) gets its own workspace only.
      responses:
        "200":
          description: Counts
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UnreadCounts" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/notifications/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string } }
    patch:
      operationId: markNotificationRead
      tags: [feed]
      summary: Mark read or unread
      description: >-
        Returns the updated notification. The item must be the caller's, in a
        workspace they belong to now and created after they joined it. A
        delegated token reaches its own workspace's items only. Anything else
        is 404.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                read: { type: boolean, description: Omitted or false marks unread }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                type: object
                required: [notification]
                properties:
                  notification: { $ref: "#/components/schemas/Notification" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/notifications/read-all:
    post:
      operationId: readAllNotifications
      tags: [feed]
      summary: Clear the badge
      description: >-
        With workspaceId, marks that workspace's unread items read (404 when
        the caller doesn't belong to it). Without, marks the token's own
        workspace read, as before. scope "all" (and no workspaceId) marks
        every workspace read, for a person's own session only. Slice 6 makes
        all workspaces the default for identity sessions. A delegated token
        (API key, OAuth grant) always clears its own workspace only.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                workspaceId:
                  type: string
                  format: uuid
                  description: The workspace to clear. Omit for the token's own workspace.
                scope:
                  type: string
                  enum: [all, current]
                  default: current
                  description: >-
                    all clears every workspace (identity sessions only, and
                    only without workspaceId). current, the default for now,
                    clears the token's own workspace.
      responses:
        "200":
          description: All read
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Message" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/preferences:
    get:
      operationId: listPreferences
      tags: [preferences]
      summary: Category preferences
      description: >-
        The full matrix of known categories. Absence of a stored row means
        enabled, so a new category starts on for everyone without a backfill.
      responses:
        "200":
          description: Preferences
          content:
            application/json:
              schema:
                type: object
                required: [preferences]
                properties:
                  preferences:
                    type: array
                    items: { $ref: "#/components/schemas/Preference" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    put:
      operationId: setPreference
      tags: [preferences]
      summary: Toggle one category
      description: Single-category upsert; returns the full matrix.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [category, enabled]
              properties:
                category:
                  type: string
                  enum:
                    [
                      forms.submission,
                      sign.awaiting_you,
                      sign.activity,
                      croncrunch.reminder,
                      croncrunch.budget,
                      croncrunch.timesheet,
                      tasks.assigned,
                      tasks.comment,
                      notes.comment,
                      notes.mentioned,
                      notes.review_due,
                    ]
                enabled: { type: boolean }
      responses:
        "200":
          description: Full preference matrix after the change
          content:
            application/json:
              schema:
                type: object
                required: [preferences]
                properties:
                  preferences:
                    type: array
                    items: { $ref: "#/components/schemas/Preference" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "500": { $ref: "#/components/responses/ServerError" }

  /v1/stream:
    get:
      operationId: streamNotifications
      tags: [feed]
      summary: Live unread stream (SSE)
      description: >-
        A Server-Sent Events stream of the caller's unread counts. The
        connection emits `data: {"unread": N, "workspaces": {"<id>": n}}`
        immediately on connect and again whenever the counts change, plus
        `: ping` heartbeat comments. unread is the token's own workspace's
        count, as before (slice 6 makes it the total for identity sessions).
        workspaces has every workspace the caller belongs to for a
        person's own session, and only the token's own workspace for a
        delegated token. At most one frame a second per connection: changes
        inside that window arrive as one frame. At most 10 open streams per
        user per server: opening another closes the oldest with
        `event: closed`, `data: {"reason":"too_many_streams"}` and a `retry:`
        hint. One-way and stateless by design: any replica can serve any
        client. Product notifications reach the feed asynchronously via the
        platform event outbox (eventkit), not a direct call to this service.
      responses:
        "200":
          description: An event stream
          content:
            text/event-stream:
              schema:
                type: string
                example: 'data: {"unread":2,"workspaces":{"6f1c2a4e-0000-4000-8000-000000000001":2,"6f1c2a4e-0000-4000-8000-000000000002":1}}'
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { $ref: "#/components/responses/ServerError" }

components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      bearerFormat: JWT
  schemas:
    Device:
      type: object
      required: [id, platform, appVersion, lastSeenAt, created]
      properties:
        id: { type: string, format: uuid }
        platform: { type: string, enum: [ios, android] }
        appVersion: { type: string }
        lastSeenAt: { type: string, format: date-time }
        created: { type: string, format: date-time }
    Notification:
      type: object
      required: [id, category, title, body, deepLink, href, entityType, entityId, created, workspace]
      properties:
        id: { type: string, format: uuid }
        category: { type: string }
        title: { type: string }
        body: { type: string }
        deepLink: { type: string }
        href:
          type: string
          example: https://app.easerix.com/notes/w/acme-studio/p/8f2c1d2e-3f4a-4b6c-9d7e-1a2b3c4d5e6f
          description: >-
            The item's web page, built by the service from deepLink and the
            workspace's slug. For a tool that serves workspace routes it is
            https://app.easerix.com/<tool>/w/<slug>/<route>; for any other
            tool, or when the slug can't be used, it is the URL without the
            workspace segment, which the app still opens. The same URL is
            the email's button and the push's href. Empty when the item has
            no web page. A client navigates to it only after checking it is a
            suite tool path on https://app.easerix.com, and a click never
            changes anything but the item's read state.
        entityType: { type: string }
        entityId: { type: string }
        readAt: { type: string, format: date-time, nullable: true }
        created: { type: string, format: date-time }
        workspace: { $ref: "#/components/schemas/WorkspaceRef" }
    WorkspaceRef:
      type: object
      description: The workspace an item belongs to.
      required: [id, slug, name]
      properties:
        id: { type: string, format: uuid }
        slug: { type: string }
        name: { type: string }
    UnreadCounts:
      type: object
      required: [total, workspaces]
      properties:
        total: { type: integer, format: int64 }
        workspaces:
          type: array
          items:
            type: object
            required: [id, unread]
            properties:
              id: { type: string, format: uuid }
              unread: { type: integer, format: int64 }
    Preference:
      type: object
      required: [category, enabled]
      properties:
        category: { type: string }
        enabled: { type: boolean }
    Message:
      type: object
      required: [message]
      properties:
        message: { type: string }
    Error:
      type: object
      required: [error]
      properties:
        error: { type: string }
  responses:
    BadRequest:
      description: Invalid or incomplete request body
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Unauthorized:
      description: Missing or invalid bearer token
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    NotFound:
      description: Resource not found or not owned by the caller
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ServerError:
      description: Internal error
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
