Simple HTTP Auth designed

This commit is contained in:
aodulov
2025-10-13 17:21:28 +03:00
parent 3e2c3bf9f3
commit 6e587e8aa7
9 changed files with 414 additions and 37 deletions

View File

@@ -1,50 +1,36 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
# Unisono Constitution
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### I. Conventions
Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### II. Libraries/Frameworks
NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### III. Style & Structure
Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### IV. Idiomatic Changes
When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
### V. Comments
Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
## Quality Gates
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
### I. Proactiveness
Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
### II. Verification (Tests)
If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
### III. Verification (Standards)
VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
All PRs/reviews must verify compliance with these principles. Complexity must be justified.
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
**Version**: 1.0 | **Ratified**: 2025-10-13 | **Last Amended**: 2025-10-13
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->

View File

@@ -9,6 +9,8 @@ Auto-generated from all feature plans. Last updated: 2025-10-13
- WebSocket library (for real-time communication)
- Google Cloud Natural Language API (for semantic comparison)
- Ephemeral server-side storage (in-memory/session store) for encrypted session data, purged on session termination.
- Node.js (LTS), TypeScript 5.x + React, Material-UI / MUI, WebSocket library, Express.js (005-simple-http-auth)
- Ephemeral server-side storage (in-memory/session store) for encrypted session data, `.env` file for passphrase. (005-simple-http-auth)
## Project Structure
```
@@ -39,10 +41,9 @@ npm run lint
Node.js (LTS), TypeScript 5.x: Follow standard conventions
## Recent Changes
- 005-simple-http-auth: Added Node.js (LTS), TypeScript 5.x + React, Material-UI / MUI, WebSocket library, Express.js
- 004-afraid-to-ask: Implemented ephemeral server-side storage for encrypted session data, WebSocket communication, and Google Cloud Natural Language API.
- 003-redesign-you-find: Added Material-UI / MUI
- 002-result-preparation-refactoring: Added TypeScript (v5.x)
- 001-people-tend-to: Added Node.js (LTS), TypeScript 5.x
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Simple HTTP Auth
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: October 13, 2025
**Feature**: [Link to spec.md]
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`

View File

@@ -0,0 +1,44 @@
openapi: 3.0.0
info:
title: Simple HTTP Auth API
version: 1.0.0
paths:
/api/auth/passphrase:
post:
summary: Authenticate with a passphrase
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
passphrase:
type: string
description: The passphrase to authenticate with.
required:
- passphrase
responses:
'200':
description: Authentication successful
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: "Authentication successful"
sessionToken:
type: string
description: A token to maintain the session.
'401':
description: Invalid passphrase
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: "Invalid passphrase"

View File

@@ -0,0 +1,15 @@
# Data Model: Simple HTTP Auth
## Entities
### Passphrase
- **Description**: A secret string used for authentication.
- **Attributes**:
- `value`: string (The actual passphrase, stored securely in .env)
### Session
- **Description**: Represents a period of continuous interaction between the user and the SPA, during which access is maintained.
- **Attributes**:
- `id`: string (Unique identifier for the session)
- `isAuthenticated`: boolean (Indicates if the session is authenticated)
- `expiry`: datetime (Timestamp when the session expires, if applicable)

View File

@@ -0,0 +1,86 @@
# Implementation Plan: Simple HTTP Auth
**Branch**: `005-simple-http-auth` | **Date**: October 13, 2025 | **Spec**: D:/Coding/unisono/specs/005-simple-http-auth/spec.md
**Input**: Feature specification from `/specs/005-simple-http-auth/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
## Summary
The feature provides a simple HTTP authentication mechanism for the Single Page Application (SPA). Users will be prompted to enter a passphrase, configured via an `.env` file, to gain access. Access will be preserved for the duration of the browser session. Failed attempts will not be rate-limited, and if the passphrase is missing or invalid in the `.env` file, the application will default to no authentication. Authentication attempts (success/failure) will be logged to a text file. User management, password reset, and multi-factor authentication are explicitly out-of-scope.
## Technical Context
**Language/Version**: Node.js (LTS), TypeScript 5.x
**Primary Dependencies**: React, Material-UI / MUI, WebSocket library, Express.js
**Storage**: Ephemeral server-side storage (in-memory/session store) for encrypted session data, `.env` file for passphrase.
**Testing**: `npm test`
**Target Platform**: Web (SPA)
**Project Type**: Web application (frontend + backend)
**Performance Goals**: No specific target for passphrase validation.
**Constraints**: Access preserved during browser session.
**Scale/Scope**: Simple HTTP authentication for a single SPA.
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
The plan aligns with the project constitution:
- **I. Conventions**: The plan adheres to existing project conventions by using Node.js/TypeScript, React, Material-UI, Express.js, and the established `backend/` and `frontend/` structure.
- **II. Libraries/Frameworks**: The plan explicitly lists primary dependencies (React, Material-UI / MUI, WebSocket library, Express.js) which are established in `GEMINI.md`.
- **III. Style & Structure**: The plan follows the existing `backend/` and `frontend/` structure and uses TypeScript, aligning with the project's established patterns.
- **IV. Idiomatic Changes**: The plan proposes changes that integrate naturally within the existing web application structure.
- **V. Comments**: This is a code-level principle, not directly applicable to the plan document itself, but the plan doesn't suggest violating it.
**Quality Gates Alignment:**
- **I. Proactiveness**: The tasks include unit/integration and end-to-end tests for both user stories.
- **II. Verification (Tests)**: The plan specifies `npm test` for testing, consistent with `GEMINI.md`.
- **III. Verification (Standards)**: The plan implies adherence to these standards by using TypeScript and `npm test`.
**Status**: All principles and quality gates are aligned.
## Project Structure
### Documentation (this feature)
```
specs/005-simple-http-auth/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
```
backend/
├── src/
│ ├── models/
│ ├── services/
│ ├── api/
│ └── ws/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
```
**Structure Decision**: The project uses a web application structure with separate `backend/` and `frontend/` directories. The authentication logic will primarily reside in the `backend/` for validation and session management, and the `frontend/` will handle the passphrase input and display.
## Complexity Tracking
*Fill ONLY if Constitution Check has violations that must be justified*
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |

View File

@@ -0,0 +1,60 @@
# Quickstart: Simple HTTP Auth
This document provides a quick guide to setting up and testing the Simple HTTP Auth feature.
## Prerequisites
- Node.js (LTS)
- npm (usually comes with Node.js)
- Docker and Docker Compose (for running the full application stack)
## Setup
1. **Clone the repository**:
```bash
git clone <repository_url>
cd unisono
```
2. **Create a `.env` file in the `backend/` directory**:
```
cd backend
touch .env
```
Add the following line to `backend/.env`, replacing `YOUR_PASSPHRASE_HERE` with your desired secret passphrase:
```
AUTH_PASSPHRASE=YOUR_PASSPHRASE_HERE
```
*Note: If `AUTH_PASSPHRASE` is missing or empty, the application will start without authentication.*
3. **Build and run the application using Docker Compose**:
```bash
cd ../.. # Go back to the project root if you are in backend/
docker-compose up --build
```
This will build the frontend and backend services and start them.
## Usage
1. **Access the application**:
Open your web browser and navigate to `http://localhost:80`.
2. **Enter the passphrase**:
You will be presented with a screen prompting you to enter the passphrase. Enter the passphrase you configured in `backend/.env`.
3. **Access the SPA**:
Upon successful authentication, you will gain access to the Single Page Application. Your access will be preserved for the duration of your browser session.
## Testing
To run the tests for the backend and frontend:
```bash
# For backend tests
cd backend
npm test
# For frontend tests
cd frontend
npm test
```

View File

@@ -0,0 +1,87 @@
# Feature Specification: Simple HTTP Auth
**Feature Branch**: `005-simple-http-auth`
**Created**: October 13, 2025
**Status**: Draft
**Input**: User description: "Simple HTTP Auth. I create a passphrase in the .env file, and users must enter the passphrase (without username) to get access to the SPA. The access must be preserved during session."
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Accessing the SPA (Priority: P1)
A user attempts to access the Single Page Application (SPA). They are prompted to enter a passphrase. Upon entering the correct passphrase, they gain access to the SPA. This access is maintained throughout their session.
**Why this priority**: This is the core functionality of the feature, enabling controlled access to the application.
**Independent Test**: Can be fully tested by navigating to the SPA, entering a valid passphrase, and verifying access to content.
**Acceptance Scenarios**:
1. **Given** a user navigates to the SPA, **When** they are presented with a passphrase input, **Then** they can enter the correct passphrase.
2. **Given** a user has entered the correct passphrase, **When** they are redirected to the SPA content, **Then** their access is preserved across page navigations within the SPA.
3. **Given** a user has entered the correct passphrase, **When** they close and reopen the browser (within a reasonable session timeout), **Then** they are still granted access without re-entering the passphrase.
---
### User Story 2 - Invalid Passphrase (Priority: P2)
A user attempts to access the SPA but enters an incorrect passphrase. They should be denied access and prompted to try again.
**Why this priority**: Essential for security and user experience, preventing unauthorized access.
**Independent Test**: Can be tested by entering an incorrect passphrase and verifying that access is denied.
**Acceptance Scenarios**:
1. **Given** a user navigates to the SPA, **When** they enter an incorrect passphrase, **Then** they are shown an error message and remain on the passphrase entry screen.
---
### Edge Cases
- What happens when the passphrase in the `.env` file is missing or invalid? (Answer: Default to No Authentication - the application starts without requiring a passphrase.)
- How does the system handle multiple failed passphrase attempts? (Answer: No Rate Limiting - unlimited attempts allowed.)
What defines “session” for preserving access? (Answer: Browser Session - Access is preserved only as long as the browser tab/window remains open. Closing the browser or tab will require re-entry of the passphrase.)
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The system MUST prompt users to enter a passphrase before granting access to the SPA.
- **FR-002**: The system MUST validate the entered passphrase against a configured passphrase.
- **FR-003**: The system MUST grant access to the SPA upon successful passphrase validation.
- **FR-004**: The system MUST deny access and provide feedback upon unsuccessful passphrase validation.
- **FR-005**: The system MUST preserve user access to the SPA for the duration of their session.
- **FR-006**: The passphrase MUST be configurable via an environment variable (e.g., `.env` file).
- **FR-007**: The authentication mechanism MUST NOT require a username.
- **FR-008**: The system MUST log both successful and failed authentication attempts to a text file, without sensitive data.
### Key Entities *(include if feature involves data)*
- **Passphrase**: A secret string used for authentication.
- **Session**: A period of continuous interaction between the user and the SPA, during which access is maintained.
## Out of Scope
- User management (creation, deletion, modification of users)
- Password reset or recovery functionality
- Multi-factor authentication (MFA)
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: 100% of users who enter the correct passphrase gain immediate access to the SPA.
- **SC-002**: 0% of users who enter an incorrect passphrase gain access to the SPA.
- **SC-003**: User access to the SPA is maintained for the entire browser session (or defined session duration) without re-authentication.
- **SC-004**: The passphrase can be updated in the `.env` file and takes effect upon application restart.
## Clarifications
### Session 2025-10-13
- Q: What is the desired rate limiting behavior for multiple failed passphrase attempts? → A: No Rate Limiting
- Q: How should the system behave if the passphrase is missing or invalid in the `.env` file? → A: Default to No Authentication
- Q: Are there any specific performance targets (e.g., latency) for the passphrase validation process? → A: No target
- Q: What kind of logging or monitoring should be in place for authentication attempts (success/failure)? → A: Standard Logging (both successful and failed attempts, without sensitive data, to a text file)
- Q: Are there any explicit functionalities that are out-of-scope for this simple HTTP authentication (e.g., user management, password reset, multi-factor authentication)? → A: All of the above (User management, password reset, and MFA are all out-of-scope).

View File

@@ -0,0 +1,64 @@
# Tasks: Simple HTTP Auth
**Feature**: Simple HTTP Auth
**Branch**: `005-simple-http-auth`
**Date**: October 13, 2025
## Phase 1: Setup Tasks (Project Initialization)
- T001: Create `backend/.env` file for passphrase configuration.
- T002: Update `docker-compose.yaml` to include `AUTH_PASSPHRASE` environment variable for the backend service.
## Phase 2: Foundational Tasks (Blocking Prerequisites for all User Stories)
- T003: Implement a logging utility in the backend to write authentication attempts to a text file. (FR-008)
- T004: Implement a service in the backend to read `AUTH_PASSPHRASE` from `.env` and handle its absence/invalidity (default to no authentication). (FR-006, Edge Case)
- T005: Implement a session management mechanism in the backend to preserve user access during a browser session. (FR-005, SC-003)
## Phase 3: User Story 1 - Accessing the SPA (Priority: P1)
**Goal**: A user attempts to access the Single Page Application (SPA). They are prompted to enter a passphrase. Upon entering the correct passphrase, they gain access to the SPA. This access is maintained throughout their session.
**Independent Test**: Can be fully tested by navigating to the SPA, entering a valid passphrase, and verifying access to content.
- T006 [US1]: Implement the `/api/auth/passphrase` POST endpoint in `backend/src/api/` to validate the entered passphrase. (FR-001, FR-002, FR-003, FR-007, contracts/openapi.yaml)
- T007 [US1]: Integrate the session management mechanism with the `/api/auth/passphrase` endpoint to issue a session token upon successful authentication. (FR-005)
- T008 [US1]: Implement a middleware or guard in the backend to protect SPA routes, redirecting unauthenticated users to the passphrase entry page.
- T009 [US1][P]: Create a passphrase input component in `frontend/src/components/` to capture user input. (FR-001)
- T010 [US1][P]: Implement a service in `frontend/src/services/` to send the passphrase to the backend and handle the session token.
- T011 [US1][P]: Create a login page in `frontend/src/pages/` that uses the passphrase input component and handles authentication flow. (FR-001)
- T012 [US1][P]: Implement routing in the frontend to redirect to the login page if unauthenticated and to the SPA content upon successful authentication.
- T013 [US1]: Write unit/integration tests for the `/api/auth/passphrase` endpoint (success case). (SC-001)
- T014 [US1]: Write end-to-end tests for successful SPA access after passphrase entry.
## Phase 4: User Story 2 - Invalid Passphrase (Priority: P2)
**Goal**: A user attempts to access the SPA but enters an incorrect passphrase. They should be denied access and prompted to try again.
**Independent Test**: Can be tested by entering an incorrect passphrase and verifying that access is denied.
- T015 [US2]: Enhance the `/api/auth/passphrase` POST endpoint to return a 401 status for invalid passphrases. (FR-004, contracts/openapi.yaml)
- T016 [US2][P]: Update the frontend login page to display an error message for invalid passphrase attempts. (FR-004)
- T017 [US2]: Write unit/integration tests for the `/api/auth/passphrase` endpoint (failure case). (SC-002)
- T018 [US2]: Write end-to-end tests for denied SPA access after incorrect passphrase entry.
## Final Phase: Polish & Cross-Cutting Concerns
- T019: Review and refine logging messages for clarity and completeness.
- T020: Ensure `.env` file handling is robust and secure (e.g., not committed to VCS).
- T021: Update `README.md` with setup and usage instructions for the authentication feature.
- T022: Verify that the passphrase can be updated in the `.env` file and takes effect upon application restart. (SC-004)
## Dependencies
- Phase 2 depends on Phase 1.
- Phase 3 depends on Phase 2.
- Phase 4 depends on Phase 3.
- Final Phase depends on Phase 4.
## Parallel Execution Examples
- Within Phase 3 (US1), T009, T010, T011, T012 can be developed in parallel with T006, T007, T008.
- Within Phase 4 (US2), T015 and T016 can be developed in parallel.
## Implementation Strategy
This feature will be implemented incrementally, delivering User Story 1 as a Minimum Viable Product (MVP) first, followed by User Story 2. Each user story is designed to be independently testable and deployable.