feat: implement shared-album multi-user photo album
Backend (Go/Gin/pgx): env config, pgx pool with retries, Garage S3 client (path-style, region garage), embedded golang-migrate migrations, JWT auth with refresh rotation, albums CRUD, members/roles/invites with no-escalation matrix, photo upload + async imaging/goexif WebP variants, cursor pagination, presigned URLs, likes/comments, SSE hub (album + personal), notifications, share links. Frontend (SvelteKit 2 + Svelte 5 + Tailwind v4): API wrapper with 401 refresh, auth store, all screens, Uploader/PhotoGrid/Lightbox/Comments, SSE client with reconnect + REST catch-up, three themes + system via data-theme. Deploy without Docker: Makefile builds the frontend into backend/static and embeds it (go:embed) into a single statically linked binary; systemd unit and nginx SSE example included. Use gen2brain/webp (-tags nodynamic) instead of cgo kolesa-team/go-webp to keep CGO_ENABLED=0 static builds; design.md/proposal.md updated accordingly.
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
# PostgreSQL (pg.localnet)
|
||||
PG_HOST=pg.localnet
|
||||
PG_PORT=5432
|
||||
PG_USER=album
|
||||
PG_PASSWORD=change_me
|
||||
PG_DATABASE=shared_album
|
||||
PG_SSLMODE=disable
|
||||
|
||||
# S3 (Garage on s3.localnet)
|
||||
S3_ENDPOINT=http://s3.localnet:3900
|
||||
S3_REGION=garage
|
||||
S3_ACCESS_KEY=GKchange_me
|
||||
S3_SECRET_KEY=change_me
|
||||
S3_BUCKET=galo-data
|
||||
S3_USE_PATH_STYLE=true
|
||||
S3_PUBLIC_URL=http://s3.localnet:3900/galo-data
|
||||
S3_PRESIGN_TTL=1h
|
||||
|
||||
# Auth
|
||||
JWT_SECRET=change_me_long_random
|
||||
JWT_ACCESS_TTL=15m
|
||||
JWT_REFRESH_TTL=720h
|
||||
|
||||
# Server
|
||||
HTTP_ADDR=:8080
|
||||
APP_BASE_URL=http://localhost:8080
|
||||
|
||||
# SSE
|
||||
SSE_HEARTBEAT_INTERVAL=25s
|
||||
SSE_CLIENT_BUFFER=64
|
||||
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
/bin/
|
||||
backend/static/*
|
||||
!backend/static/.gitkeep
|
||||
frontend/node_modules/
|
||||
frontend/build/
|
||||
frontend/.svelte-kit/
|
||||
node_modules/
|
||||
*.log
|
||||
@@ -0,0 +1,198 @@
|
||||
---
|
||||
description: "Implement tasks from an OpenSpec change (Experimental)"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx-apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status, source path, and source line
|
||||
- Dynamic instruction based on current state
|
||||
- Optional `context`: current required project instruction input from the selected root
|
||||
- Optional `operationGuidance`: current advisory guidance for apply
|
||||
- `missingArtifacts` (when present): required artifact ids with no output
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"`: show the message and pause implementation.
|
||||
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
|
||||
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||
apply relevant project facts, conventions, and constraints while implementing.
|
||||
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||
entry, and follow entries that are applicable and compatible with the built-in
|
||||
workflow.
|
||||
|
||||
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||
evidence of task completion, do not replace the built-in instruction, and do
|
||||
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||
conflicts with those controlling inputs, do not follow it and explain why.
|
||||
These are prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||
files or planning artifacts unless the user separately asks for that content.
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
|
||||
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
|
||||
- Rerun the apply instructions and confirm that task is now done and progress changed
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx-archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
|
||||
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
- Use each task's sourcePath and line to update its exact checkbox
|
||||
- Do not use context or operation guidance as proof that a task is complete
|
||||
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,261 @@
|
||||
---
|
||||
description: "Archive a completed change in the experimental workflow"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx-archive` (e.g., `/opsx-archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-archive <other>`).
|
||||
|
||||
**Load current archive inputs before the existing archive checks:**
|
||||
|
||||
After resolving the selected change and planning root, run:
|
||||
```bash
|
||||
openspec instructions archive --change "<name>" --json
|
||||
```
|
||||
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||
does not support this command yet — continue the archive workflow with no
|
||||
context and no operation guidance. Do not report an error and do not stop.
|
||||
|
||||
A successful response may omit both optional fields. Treat `context` as a
|
||||
required prompt-level input: read and consider it, and apply relevant project
|
||||
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||
additive advice: read and consider every entry, and follow entries that are
|
||||
applicable and compatible with the built-in archive workflow.
|
||||
|
||||
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||
controlling inputs, report the conflict and preserve the controlling value. If
|
||||
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||
or archive summaries unless the user separately asks for it. These are
|
||||
prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||
|
||||
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Run `openspec list --json` with the same selected-root flags and find the
|
||||
entry in `changes` whose `name` exactly matches the selected change.
|
||||
Require exactly one match and nonnegative integer `totalTasks` and
|
||||
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
|
||||
the schema's tracked task files, including custom artifact names, output
|
||||
paths, and globs.
|
||||
Incomplete tasks = `totalTasks - completedTasks`.
|
||||
|
||||
Do not infer task completion from artifact status or the absence of a
|
||||
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
|
||||
duplicates the selected change, or returns invalid counts, report the problem
|
||||
and stop before syncing or archiving.
|
||||
The CLI counts only `x`/`X` checkbox markers as complete;
|
||||
other markers, including unfamiliar ones, remain incomplete.
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If `totalTasks` is zero:** Proceed without a task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||
delta-spec source. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||
delta specs from other artifacts.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
|
||||
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
|
||||
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
|
||||
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
|
||||
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
|
||||
|
||||
**Prompt options:**
|
||||
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
|
||||
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
Route on the answer:
|
||||
- "Cancel" — stop, do not archive
|
||||
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
|
||||
- Anything else — ask again rather than archiving
|
||||
|
||||
Before a selected sync writes any main spec, run
|
||||
`openspec instructions specs --change "<name>" --json` once with the same
|
||||
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||
before writing any main spec or moving the change. A valid response with omitted
|
||||
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||
form of main specs produced by this merge; do not use them as archive guidance,
|
||||
change CLI behavior, or copy the rule text into any output file.
|
||||
|
||||
Then run the `/opsx-sync` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||
|
||||
If the sync reports any stop or blocking condition, treat the sync as failed.
|
||||
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
|
||||
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
|
||||
|
||||
After the sync writes each main spec, verify its structure against the canonical sync contract:
|
||||
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
|
||||
- Preserve existing `## Purpose` sections completely untouched for established main specs.
|
||||
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
|
||||
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
|
||||
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
|
||||
|
||||
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||
- ADDED requirements present
|
||||
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
|
||||
- RENAMED requirements present under the new name and absent under the old one
|
||||
|
||||
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```markdown
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```markdown
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Announce the selected change; prompt for selection when it is ambiguous
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, run the `/opsx-sync` workflow inline (agent-driven)
|
||||
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||
@@ -0,0 +1,236 @@
|
||||
---
|
||||
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/opsx-propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: The argument after `/opsx-explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## Planning a Change
|
||||
|
||||
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
|
||||
|
||||
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
|
||||
|
||||
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
|
||||
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
|
||||
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
|
||||
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
|
||||
|
||||
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
|
||||
|
||||
For example, after inspecting the relevant code:
|
||||
|
||||
```text
|
||||
The CLI already uses SQLite and has no remote service. Is sharing state
|
||||
across devices in scope? That determines whether local storage is enough.
|
||||
If this stays a single-device tool, I recommend keeping SQLite to avoid
|
||||
adding a service to operate; shared state would need a separate sync design.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
+------------------------------------------+
|
||||
| Use ASCII diagrams liberally |
|
||||
+------------------------------------------+
|
||||
| |
|
||||
| [State A] -------> [State B] |
|
||||
| | |
|
||||
| v |
|
||||
| [State C] |
|
||||
| |
|
||||
| System diagrams, state machines, |
|
||||
| data flows, architecture sketches, |
|
||||
| dependency graphs, comparison tables |
|
||||
| |
|
||||
+------------------------------------------+
|
||||
```
|
||||
|
||||
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
|
||||
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names and task status
|
||||
- What the user might be working on
|
||||
|
||||
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
|
||||
```bash
|
||||
openspec list --specs
|
||||
```
|
||||
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
|
||||
|
||||
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
|
||||
|
||||
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||
- `context`: project background - tech stack, conventions, constraints
|
||||
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||
|
||||
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
|
||||
|
||||
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||
|
||||
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|-------------------------------------|
|
||||
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? Run `/opsx-propose` and this becomes a change."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/opsx-propose` turns the discussion into a change, and the work happens there.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
|
||||
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
description: "Propose a new change - create it and generate all artifacts in one step"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||
|
||||
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||
- proposal.md (what & why)
|
||||
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||
|
||||
---
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: The argument after `/opsx-propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Understand the request and clarify material ambiguity**
|
||||
|
||||
If no input is provided, ask the user (open-ended, no preset options):
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||
|
||||
2. **Load project context**
|
||||
|
||||
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
|
||||
|
||||
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
|
||||
|
||||
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
|
||||
|
||||
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
|
||||
|
||||
3. **Determine the workflow schema**
|
||||
|
||||
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user:**
|
||||
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
|
||||
|
||||
Otherwise, omit `--schema` to preserve the configured default.
|
||||
|
||||
4. **Create the change directory**
|
||||
|
||||
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||
|
||||
Using the configured default:
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
|
||||
Using an explicitly requested schema:
|
||||
```bash
|
||||
openspec new change "<name>" --schema "<schema-name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
5. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
6. **Create every artifact in the required set**
|
||||
|
||||
Use a todo list to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
|
||||
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
|
||||
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
|
||||
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
|
||||
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Ask the user to clarify
|
||||
- Then continue with creation
|
||||
|
||||
7. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||
- What's ready: "All artifacts needed for implementation are ready."
|
||||
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx-apply`."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,283 @@
|
||||
---
|
||||
description: "Sync delta specs from a change to main specs"
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx-sync` (e.g., `/opsx-sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-sync <other>`).
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||
only source of delta spec paths. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||
do not infer them from other artifacts, and stop without requesting artifact
|
||||
instructions or writing a main spec.
|
||||
|
||||
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||
A caller narrows it by naming an explicit list of complete entries from
|
||||
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||
this inline, and a user can too (for example, by selecting the entry ending
|
||||
in `/specs/billing/invoices/spec.md`).
|
||||
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||
bulk archive excludes a delta whose implementation it could not find, and
|
||||
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||
Carry that narrowed selection through step 4; never widen it back to the full
|
||||
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||
report it and stop, rather than dropping it silently. If the named list is
|
||||
empty, report that there is nothing to sync and stop without writing a main
|
||||
spec.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||
fetch the same instructions again.
|
||||
- Otherwise run that command once now with the same selected-root flags.
|
||||
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||
failure as an absent rule set.
|
||||
- A valid response with omitted `rules` means no artifact rules are configured
|
||||
and the existing semantic merge continues.
|
||||
|
||||
Apply returned `rules` only to the content and form of the main specs produced
|
||||
by this merge. Artifact rules are not operation guidance and cannot change
|
||||
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||
constraints without copying it verbatim into a main spec or summary.
|
||||
|
||||
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||
|
||||
**If it does not exist yet** (a new capability), match what `openspec archive` does:
|
||||
only ADDED requirements may be applied - step d creates the spec from them.
|
||||
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
|
||||
capability and report that its main spec does not exist and only ADDED is allowed
|
||||
for a new spec; never invent the missing requirement. REMOVED has nothing to
|
||||
remove - skip it and warn.
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios the main spec does not have yet
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||
nothing else is left in it - only when ALL of these hold:
|
||||
1. removing the requirements *this run* left no requirement blocks;
|
||||
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||
3. the main spec was not already empty before this sync - if you removed
|
||||
nothing, change nothing;
|
||||
4. every other nonblank line in the whole file is accounted for as the
|
||||
title, Purpose, Requirements header, or a canonical requirement's
|
||||
statement, scenarios, or fenced examples;
|
||||
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||
capability-directory symlink to delete an external file).
|
||||
If removing the selected requirements would leave no requirement blocks and
|
||||
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||
the sync for that capability, report the blocking condition, and tell the user
|
||||
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||
When only the marker is missing, say that too - it is the one thing the user
|
||||
can add to make the retirement go through.
|
||||
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||
`git checkout` only when the spec lived in the caller's checkout;
|
||||
otherwise give checkout-scoped recovery guidance.
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
**`## Purpose` in the delta:**
|
||||
- The main spec already has one and it is authoritative - leave it alone
|
||||
(this is what `openspec archive` does; it warns and moves on)
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
|
||||
RENAMED requirements blocked this capability in step b. Otherwise create nothing
|
||||
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
|
||||
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
|
||||
and continue without recreating the spec. Without that marker, report the sync as blocked:
|
||||
`openspec archive` rejects it with `Spec must have at least one requirement`.
|
||||
An empty delta has no operations to sync; report it as blocked too.
|
||||
Never write an empty `## Requirements` section.
|
||||
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||
- Add Requirements section with the ADDED requirements
|
||||
- Follow the **Main Spec Format Reference** below
|
||||
|
||||
5. **Validate updated main specs**
|
||||
|
||||
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||
If validation fails, report the problems and do not claim the sync succeeded.
|
||||
|
||||
6. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||
now rather than lingering
|
||||
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
The system SHALL keep doing the existing thing, now also handling A.
|
||||
|
||||
#### Scenario: Scenario the main spec already has
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Main Spec Format Reference**
|
||||
|
||||
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||
|
||||
```markdown
|
||||
# <capability> Specification
|
||||
|
||||
## Purpose
|
||||
Short description of what this capability does and why it exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you merge rather than overwrite:
|
||||
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||
- Keep anything the delta does not mention, in the main spec's existing order
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
description: "Update a change - revise existing planning artifacts and keep them coherent (Experimental)"
|
||||
---
|
||||
|
||||
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx-update` (e.g., `/opsx-update add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
**Provided arguments**: $ARGUMENTS
|
||||
|
||||
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write it.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
|
||||
|
||||
When prompting, present the top 3-4 most recently modified changes as options, showing:
|
||||
- Change name
|
||||
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||
- How recently it was modified (from `lastModified` field)
|
||||
|
||||
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-update <other>`).
|
||||
|
||||
2. **Get the change's artifacts**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand current state. The response includes:
|
||||
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
|
||||
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
|
||||
|
||||
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
|
||||
|
||||
3. **Understand the request**
|
||||
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
|
||||
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
|
||||
|
||||
4. **Read and reconcile**
|
||||
- Read the artifact(s) the request touches and the change's other existing artifacts.
|
||||
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
|
||||
- Note everything that is now inconsistent, missing, or contradictory.
|
||||
- Propose revisions to files that already exist (`existingOutputPaths`). If an artifact has no existing output files and status `ready` or `blocked`, note it and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create them. Leave `skipped` artifacts untouched; do not treat them as missing or defer them to the continue workflow.
|
||||
- A glob artifact (e.g. `specs/**/*.md`) is marked `done` after at least one file matches, and the continue workflow only handles `ready` artifacts. When reconciliation identifies a missing file for a glob artifact whose `existingOutputPaths` is non-empty:
|
||||
1. Run `openspec instructions "<artifact-id>" --change "<name>" --json` and use its `instruction` and `template`. Treat `context` and `rules` as constraints; do not copy them into the file. If instructions report `skipped: true`, do not create the file. Read current dependency files from disk; if a required non-skipped dependency is missing, stop and ask the user to restore it first.
|
||||
2. Choose a concrete path inside `changeRoot` that matches `artifactPaths.<id>.outputPath` and does not already exist. Verify it remains inside `changeRoot` after resolving any symlinked parent directories. The glob `resolvedOutputPath` is not a valid target.
|
||||
3. Include the new file in step 5's proposed revisions and create it only after the user confirms.
|
||||
4. After confirmation, immediately before creation, refresh status and instructions. Verify the artifact is still in scope, not skipped, and partially populated; repeat the concrete-path checks above.
|
||||
5. Use a create operation that fails if the target already exists. If `instruction` delegates creation to another skill or command, invoke it only if it can honor the confirmed path and these guardrails; otherwise stop. If any check fails or the confirmed draft is no longer valid, stop and reconcile with the user rather than replacing existing content or choosing a different path.
|
||||
- If the change is already coherent, say so and propose no revisions.
|
||||
|
||||
5. **Confirm and apply, one artifact at a time**
|
||||
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
|
||||
- Show each proposed revision and why - including the requested edit drafted in step 4. Write only after the user confirms.
|
||||
- If the user rejects a revision, do not write it - leave that artifact unchanged.
|
||||
- When a substantial rewrite is needed, get that artifact's rules and template first:
|
||||
```bash
|
||||
openspec instructions "<artifact-id>" --change "<name>" --json
|
||||
```
|
||||
|
||||
6. **Point to the next step (guidance only - NEVER act on it)**
|
||||
- Artifacts with empty `existingOutputPaths` and status `ready` or `blocked` -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
|
||||
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/opsx-apply` to carry the delta into code.
|
||||
- Everything done and implemented -> suggest `/opsx-archive`.
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||
- Any file created under a glob artifact that was already partially populated
|
||||
- Anything deferred because it does not exist yet (artifacts with no files and status `ready` or `blocked`, never `skipped` artifacts)
|
||||
- Where the change stands and the recommended next command
|
||||
|
||||
**Guardrails**
|
||||
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/opsx-apply`.
|
||||
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
|
||||
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
|
||||
- Do not advance the build frontier: if an artifact has empty `existingOutputPaths` and status `ready` or `blocked`, creating them is a separate step, outside this workflow. Leave `skipped` artifacts untouched. The only new-file scope is a confirmed concrete path under a glob artifact whose `existingOutputPaths` is non-empty.
|
||||
- Confirm every edit with the user before writing.
|
||||
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
|
||||
@@ -0,0 +1,205 @@
|
||||
---
|
||||
name: openspec-apply-change
|
||||
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks. Also use when the user says "openspec apply", "opsx apply", or "openspec implement".
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx-apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status, source path, and source line
|
||||
- Dynamic instruction based on current state
|
||||
- Optional `context`: current required project instruction input from the selected root
|
||||
- Optional `operationGuidance`: current advisory guidance for apply
|
||||
- `missingArtifacts` (when present): required artifact ids with no output
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"`: show the message and pause implementation.
|
||||
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
|
||||
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||
apply relevant project facts, conventions, and constraints while implementing.
|
||||
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||
entry, and follow entries that are applicable and compatible with the built-in
|
||||
workflow.
|
||||
|
||||
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||
evidence of task completion, do not replace the built-in instruction, and do
|
||||
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||
conflicts with those controlling inputs, do not follow it and explain why.
|
||||
These are prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||
files or planning artifacts unless the user separately asks for that content.
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
|
||||
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
|
||||
- Rerun the apply instructions and confirm that task is now done and progress changed
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx-archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
|
||||
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
- Use each task's sourcePath and line to update its exact checkbox
|
||||
- Do not use context or operation guidance as proof that a task is complete
|
||||
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,221 @@
|
||||
---
|
||||
name: openspec-archive-change
|
||||
description: Archive a completed OpenSpec change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete. Also use when the user says "openspec archive" or "opsx archive".
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-archive <other>`).
|
||||
|
||||
**Load current archive inputs before the existing archive checks:**
|
||||
|
||||
After resolving the selected change and planning root, run:
|
||||
```bash
|
||||
openspec instructions archive --change "<name>" --json
|
||||
```
|
||||
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||
does not support this command yet — continue the archive workflow with no
|
||||
context and no operation guidance. Do not report an error and do not stop.
|
||||
|
||||
A successful response may omit both optional fields. Treat `context` as a
|
||||
required prompt-level input: read and consider it, and apply relevant project
|
||||
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||
additive advice: read and consider every entry, and follow entries that are
|
||||
applicable and compatible with the built-in archive workflow.
|
||||
|
||||
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||
controlling inputs, report the conflict and preserve the controlling value. If
|
||||
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||
or archive summaries unless the user separately asks for it. These are
|
||||
prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||
|
||||
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||
- Display warning listing incomplete artifacts
|
||||
- Ask the user to confirm they want to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Run `openspec list --json` with the same selected-root flags and find the
|
||||
entry in `changes` whose `name` exactly matches the selected change.
|
||||
Require exactly one match and nonnegative integer `totalTasks` and
|
||||
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
|
||||
the schema's tracked task files, including custom artifact names, output
|
||||
paths, and globs.
|
||||
Incomplete tasks = `totalTasks - completedTasks`.
|
||||
|
||||
Do not infer task completion from artifact status or the absence of a
|
||||
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
|
||||
duplicates the selected change, or returns invalid counts, report the problem
|
||||
and stop before syncing or archiving.
|
||||
The CLI counts only `x`/`X` checkbox markers as complete;
|
||||
other markers, including unfamiliar ones, remain incomplete.
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Ask the user to confirm they want to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If `totalTasks` is zero:** Proceed without a task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||
delta-spec source. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||
delta specs from other artifacts.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
|
||||
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
|
||||
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
|
||||
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
|
||||
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
|
||||
|
||||
**Prompt options:**
|
||||
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
|
||||
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
Route on the answer:
|
||||
- "Cancel" — stop, do not archive
|
||||
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
|
||||
- Anything else — ask again rather than archiving
|
||||
|
||||
Before a selected sync writes any main spec, run
|
||||
`openspec instructions specs --change "<name>" --json` once with the same
|
||||
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||
before writing any main spec or moving the change. A valid response with omitted
|
||||
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||
form of main specs produced by this merge; do not use them as archive guidance,
|
||||
change CLI behavior, or copy the rule text into any output file.
|
||||
|
||||
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||
|
||||
If the sync reports any stop or blocking condition, treat the sync as failed.
|
||||
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
|
||||
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
|
||||
|
||||
After the sync writes each main spec, verify its structure against the canonical sync contract:
|
||||
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
|
||||
- Preserve existing `## Purpose` sections completely untouched for established main specs.
|
||||
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
|
||||
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
|
||||
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
|
||||
|
||||
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||
- ADDED requirements present
|
||||
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
|
||||
- RENAMED requirements present under the new name and absent under the old one
|
||||
|
||||
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Whether specs were synced (if applicable)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
|
||||
|
||||
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Announce the selected change; prompt for selection when it is ambiguous
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
|
||||
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
name: openspec-explore
|
||||
description: Enter OpenSpec explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements in a project that uses OpenSpec. Use when the user wants to think through something before or during an OpenSpec change. Also use when the user says "openspec explore" or "opsx explore".
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/opsx-propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## Planning a Change
|
||||
|
||||
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
|
||||
|
||||
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
|
||||
|
||||
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
|
||||
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
|
||||
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
|
||||
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
|
||||
|
||||
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
|
||||
|
||||
For example, after inspecting the relevant code:
|
||||
|
||||
```text
|
||||
The CLI already uses SQLite and has no remote service. Is sharing state
|
||||
across devices in scope? That determines whether local storage is enough.
|
||||
If this stays a single-device tool, I recommend keeping SQLite to avoid
|
||||
adding a service to operate; shared state would need a separate sync design.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
+------------------------------------------+
|
||||
| Use ASCII diagrams liberally |
|
||||
+------------------------------------------+
|
||||
| |
|
||||
| [State A] -------> [State B] |
|
||||
| | |
|
||||
| v |
|
||||
| [State C] |
|
||||
| |
|
||||
| System diagrams, state machines, |
|
||||
| data flows, architecture sketches, |
|
||||
| dependency graphs, comparison tables |
|
||||
| |
|
||||
+------------------------------------------+
|
||||
```
|
||||
|
||||
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
|
||||
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names and task status
|
||||
- What the user might be working on
|
||||
|
||||
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
|
||||
```bash
|
||||
openspec list --specs
|
||||
```
|
||||
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
|
||||
|
||||
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
|
||||
|
||||
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||
- `context`: project background - tech stack, conventions, constraints
|
||||
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||
|
||||
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
|
||||
|
||||
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||
|
||||
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|-------------------------------------|
|
||||
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Handling Different Entry Points
|
||||
|
||||
**User brings a vague idea:**
|
||||
```
|
||||
User: I'm thinking about adding real-time collaboration
|
||||
|
||||
You: Real-time collab is a big space. Let me think about this...
|
||||
|
||||
COLLABORATION SPECTRUM
|
||||
============================================
|
||||
|
||||
Awareness Coordination Sync
|
||||
| | |
|
||||
v v v
|
||||
+--------+ +--------+ +--------+
|
||||
|Presence| |Cursors | | CRDT |
|
||||
| "3 | | Multi | |Conflict|
|
||||
|online" | | select | | free |
|
||||
+--------+ +--------+ +--------+
|
||||
| | |
|
||||
trivial moderate complex
|
||||
|
||||
Where's your head at?
|
||||
```
|
||||
|
||||
**User brings a specific problem:**
|
||||
```
|
||||
User: The auth system is a mess
|
||||
|
||||
You: [reads codebase]
|
||||
|
||||
+---------------------------------------------+
|
||||
| CURRENT AUTH FLOW |
|
||||
+---------------------------------------------+
|
||||
|
|
||||
+-------------+-------------+
|
||||
v v v
|
||||
+---------+ +---------+ +---------+
|
||||
| Google | | GitHub | | Email |
|
||||
| OAuth | | OAuth | | Magic |
|
||||
+----+----+ +----+----+ +----+----+
|
||||
| | |
|
||||
+-------------+-------------+
|
||||
v
|
||||
+-----------+
|
||||
| Session |
|
||||
+-----+-----+
|
||||
|
|
||||
v
|
||||
+-----------+
|
||||
| Perms |
|
||||
+-----------+
|
||||
|
||||
I see three tangles. Which one's burning?
|
||||
```
|
||||
|
||||
**User is stuck mid-implementation:**
|
||||
```
|
||||
User: /opsx-explore add-auth-system
|
||||
The OAuth integration is more complex than expected
|
||||
|
||||
You: [reads change artifacts]
|
||||
|
||||
You're on task 4: "Implement OAuth flow"
|
||||
|
||||
Let me trace what's involved...
|
||||
|
||||
[draws diagram, explores options, suggests paths]
|
||||
|
||||
Want to update the design to reflect this?
|
||||
Or add a spike task to investigate?
|
||||
```
|
||||
|
||||
**User wants to compare options:**
|
||||
```
|
||||
User: Should we use Postgres or SQLite?
|
||||
|
||||
You: Generic answer is boring. What's the context?
|
||||
|
||||
User: A CLI tool that tracks local dev environments
|
||||
|
||||
You: That changes everything.
|
||||
|
||||
+-------------------------------------------------+
|
||||
| CLI TOOL DATA STORAGE |
|
||||
+-------------------------------------------------+
|
||||
|
||||
Key constraints:
|
||||
- No daemon running
|
||||
- Must work offline
|
||||
- Single user
|
||||
|
||||
SQLite Postgres
|
||||
Deployment embedded needs server
|
||||
Offline yes no
|
||||
Single file yes no
|
||||
|
||||
SQLite. Not even close.
|
||||
|
||||
Unless... is there a sync component?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? Run `/opsx-propose` and this becomes a change."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When it feels like things are crystallizing, you might summarize:
|
||||
|
||||
```
|
||||
## What We Figured Out
|
||||
|
||||
**The problem**: [crystallized understanding]
|
||||
|
||||
**The approach**: [if one emerged]
|
||||
|
||||
**Open questions**: [if any remain]
|
||||
|
||||
**Next steps** (if ready):
|
||||
- Turn this into a change: `/opsx-propose`
|
||||
- Keep exploring: just keep talking
|
||||
```
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/opsx-propose` turns the discussion into a change, and the work happens there.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
|
||||
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
name: openspec-propose
|
||||
description: Propose a new OpenSpec change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation. Also use when the user says "openspec propose" or "opsx propose".
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||
|
||||
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||
- proposal.md (what & why)
|
||||
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||
|
||||
---
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Understand the request and clarify material ambiguity**
|
||||
|
||||
If no clear input is provided, ask the user (open-ended, no preset options):
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||
|
||||
2. **Load project context**
|
||||
|
||||
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
|
||||
|
||||
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
|
||||
|
||||
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
|
||||
|
||||
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
|
||||
|
||||
3. **Determine the workflow schema**
|
||||
|
||||
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user:**
|
||||
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
|
||||
|
||||
Otherwise, omit `--schema` to preserve the configured default.
|
||||
|
||||
4. **Create the change directory**
|
||||
|
||||
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||
|
||||
Using the configured default:
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
|
||||
Using an explicitly requested schema:
|
||||
```bash
|
||||
openspec new change "<name>" --schema "<schema-name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
5. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
6. **Create every artifact in the required set**
|
||||
|
||||
Use a todo list to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
|
||||
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
|
||||
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
|
||||
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
|
||||
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Ask the user to clarify
|
||||
- Then continue with creation
|
||||
|
||||
7. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||
- What's ready: "All artifacts needed for implementation are ready."
|
||||
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx-apply` or ask me to apply this change."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,290 @@
|
||||
---
|
||||
name: openspec-sync-specs
|
||||
description: Sync delta specs from an OpenSpec change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change. Also use when the user says "openspec sync" or "opsx sync".
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-sync <other>`).
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||
only source of delta spec paths. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||
do not infer them from other artifacts, and stop without requesting artifact
|
||||
instructions or writing a main spec.
|
||||
|
||||
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||
A caller narrows it by naming an explicit list of complete entries from
|
||||
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||
this inline, and a user can too (for example, by selecting the entry ending
|
||||
in `/specs/billing/invoices/spec.md`).
|
||||
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||
bulk archive excludes a delta whose implementation it could not find, and
|
||||
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||
Carry that narrowed selection through step 4; never widen it back to the full
|
||||
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||
report it and stop, rather than dropping it silently. If the named list is
|
||||
empty, report that there is nothing to sync and stop without writing a main
|
||||
spec.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||
fetch the same instructions again.
|
||||
- Otherwise run that command once now with the same selected-root flags.
|
||||
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||
failure as an absent rule set.
|
||||
- A valid response with omitted `rules` means no artifact rules are configured
|
||||
and the existing semantic merge continues.
|
||||
|
||||
Apply returned `rules` only to the content and form of the main specs produced
|
||||
by this merge. Artifact rules are not operation guidance and cannot change
|
||||
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||
constraints without copying it verbatim into a main spec or summary.
|
||||
|
||||
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||
|
||||
**If it does not exist yet** (a new capability), match what `openspec archive` does:
|
||||
only ADDED requirements may be applied - step d creates the spec from them.
|
||||
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
|
||||
capability and report that its main spec does not exist and only ADDED is allowed
|
||||
for a new spec; never invent the missing requirement. REMOVED has nothing to
|
||||
remove - skip it and warn.
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios the main spec does not have yet
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||
nothing else is left in it - only when ALL of these hold:
|
||||
1. removing the requirements *this run* left no requirement blocks;
|
||||
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||
3. the main spec was not already empty before this sync - if you removed
|
||||
nothing, change nothing;
|
||||
4. every other nonblank line in the whole file is accounted for as the
|
||||
title, Purpose, Requirements header, or a canonical requirement's
|
||||
statement, scenarios, or fenced examples;
|
||||
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||
capability-directory symlink to delete an external file).
|
||||
If removing the selected requirements would leave no requirement blocks and
|
||||
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||
the sync for that capability, report the blocking condition, and tell the user
|
||||
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||
When only the marker is missing, say that too - it is the one thing the user
|
||||
can add to make the retirement go through.
|
||||
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||
`git checkout` only when the spec lived in the caller's checkout;
|
||||
otherwise give checkout-scoped recovery guidance.
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
**`## Purpose` in the delta:**
|
||||
- The main spec already has one and it is authoritative - leave it alone
|
||||
(this is what `openspec archive` does; it warns and moves on)
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
|
||||
RENAMED requirements blocked this capability in step b. Otherwise create nothing
|
||||
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
|
||||
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
|
||||
and continue without recreating the spec. Without that marker, report the sync as blocked:
|
||||
`openspec archive` rejects it with `Spec must have at least one requirement`.
|
||||
An empty delta has no operations to sync; report it as blocked too.
|
||||
Never write an empty `## Requirements` section.
|
||||
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||
- Add Requirements section with the ADDED requirements
|
||||
- Follow the **Main Spec Format Reference** below
|
||||
|
||||
5. **Validate updated main specs**
|
||||
|
||||
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||
If validation fails, report the problems and do not claim the sync succeeded.
|
||||
|
||||
6. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||
now rather than lingering
|
||||
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
The system SHALL keep doing the existing thing, now also handling A.
|
||||
|
||||
#### Scenario: Scenario the main spec already has
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Main Spec Format Reference**
|
||||
|
||||
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||
|
||||
```markdown
|
||||
# <capability> Specification
|
||||
|
||||
## Purpose
|
||||
Short description of what this capability does and why it exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you merge rather than overwrite:
|
||||
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||
- Keep anything the delta does not mention, in the main spec's existing order
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: openspec-update-change
|
||||
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Also use when the user says "openspec update change" or "opsx update". If the user means the openspec update CLI command, which refreshes generated files, run that command instead. Never edits code.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.14.0"
|
||||
---
|
||||
|
||||
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write it.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
|
||||
|
||||
When prompting, present the top 3-4 most recently modified changes as options, showing:
|
||||
- Change name
|
||||
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||
- How recently it was modified (from `lastModified` field)
|
||||
|
||||
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-update <other>`).
|
||||
|
||||
2. **Get the change's artifacts**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand current state. The response includes:
|
||||
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
|
||||
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
|
||||
|
||||
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
|
||||
|
||||
3. **Understand the request**
|
||||
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
|
||||
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
|
||||
|
||||
4. **Read and reconcile**
|
||||
- Read the artifact(s) the request touches and the change's other existing artifacts.
|
||||
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
|
||||
- Note everything that is now inconsistent, missing, or contradictory.
|
||||
- Propose revisions to files that already exist (`existingOutputPaths`). If an artifact has no existing output files and status `ready` or `blocked`, note it and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create them. Leave `skipped` artifacts untouched; do not treat them as missing or defer them to the continue workflow.
|
||||
- A glob artifact (e.g. `specs/**/*.md`) is marked `done` after at least one file matches, and the continue workflow only handles `ready` artifacts. When reconciliation identifies a missing file for a glob artifact whose `existingOutputPaths` is non-empty:
|
||||
1. Run `openspec instructions "<artifact-id>" --change "<name>" --json` and use its `instruction` and `template`. Treat `context` and `rules` as constraints; do not copy them into the file. If instructions report `skipped: true`, do not create the file. Read current dependency files from disk; if a required non-skipped dependency is missing, stop and ask the user to restore it first.
|
||||
2. Choose a concrete path inside `changeRoot` that matches `artifactPaths.<id>.outputPath` and does not already exist. Verify it remains inside `changeRoot` after resolving any symlinked parent directories. The glob `resolvedOutputPath` is not a valid target.
|
||||
3. Include the new file in step 5's proposed revisions and create it only after the user confirms.
|
||||
4. After confirmation, immediately before creation, refresh status and instructions. Verify the artifact is still in scope, not skipped, and partially populated; repeat the concrete-path checks above.
|
||||
5. Use a create operation that fails if the target already exists. If `instruction` delegates creation to another skill or command, invoke it only if it can honor the confirmed path and these guardrails; otherwise stop. If any check fails or the confirmed draft is no longer valid, stop and reconcile with the user rather than replacing existing content or choosing a different path.
|
||||
- If the change is already coherent, say so and propose no revisions.
|
||||
|
||||
5. **Confirm and apply, one artifact at a time**
|
||||
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
|
||||
- Show each proposed revision and why - including the requested edit drafted in step 4. Write only after the user confirms.
|
||||
- If the user rejects a revision, do not write it - leave that artifact unchanged.
|
||||
- When a substantial rewrite is needed, get that artifact's rules and template first:
|
||||
```bash
|
||||
openspec instructions "<artifact-id>" --change "<name>" --json
|
||||
```
|
||||
|
||||
6. **Point to the next step (guidance only - NEVER act on it)**
|
||||
- Artifacts with empty `existingOutputPaths` and status `ready` or `blocked` -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
|
||||
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/opsx-apply` to carry the delta into code.
|
||||
- Everything done and implemented -> suggest `/opsx-archive`.
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||
- Any file created under a glob artifact that was already partially populated
|
||||
- Anything deferred because it does not exist yet (artifacts with no files and status `ready` or `blocked`, never `skipped` artifacts)
|
||||
- Where the change stands and the recommended next command
|
||||
|
||||
**Guardrails**
|
||||
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/opsx-apply`.
|
||||
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
|
||||
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
|
||||
- Do not advance the build frontier: if an artifact has empty `existingOutputPaths` and status `ready` or `blocked`, creating them is a separate step, outside this workflow. Leave `skipped` artifacts untouched. The only new-file scope is a confirmed concrete path under a glob artifact whose `existingOutputPaths` is non-empty.
|
||||
- Confirm every edit with the user before writing.
|
||||
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
|
||||
@@ -0,0 +1,31 @@
|
||||
.PHONY: build frontend backend run migrate tidy test clean
|
||||
|
||||
frontend:
|
||||
cd frontend && npm ci && npm run build
|
||||
rm -rf backend/static/*
|
||||
cp -r frontend/build/* backend/static/
|
||||
|
||||
backend:
|
||||
mkdir -p bin
|
||||
# -tags nodynamic forces gen2brain/webp to use its pure-Go transpiled path
|
||||
# (no purego/dlopen), keeping the binary fully static.
|
||||
cd backend && CGO_ENABLED=0 go build -tags nodynamic -trimpath -ldflags="-s -w" \
|
||||
-o ../bin/shared-album ./cmd/server
|
||||
|
||||
build: frontend backend
|
||||
|
||||
run: backend
|
||||
cd backend && ../bin/shared-album
|
||||
|
||||
migrate:
|
||||
cd backend && go run ./cmd/migrate
|
||||
|
||||
tidy:
|
||||
cd backend && go mod tidy
|
||||
|
||||
test:
|
||||
cd backend && go test ./...
|
||||
|
||||
clean:
|
||||
rm -rf bin backend/static/*
|
||||
touch backend/static/.gitkeep
|
||||
@@ -0,0 +1,163 @@
|
||||
# Galo — многопользовательский фотоальбом
|
||||
|
||||
Self-hosted веб-приложение: общие фотоальбомы с ролями, загрузкой фото в S3,
|
||||
live-обновлениями через SSE и доступом по ссылке без аккаунта.
|
||||
|
||||
Без Docker: один статичный Go-бинарник (`CGO_ENABLED=0`) со вшитой статикой
|
||||
SvelteKit через `go:embed`, запуск через systemd.
|
||||
|
||||
## Стек
|
||||
|
||||
- **Backend:** Go, Gin, pgx (PostgreSQL на `pg.localnet`), AWS SDK v2 (Garage на
|
||||
`s3.localnet`, path-style), нативный SSE, golang-migrate, slog.
|
||||
- **Frontend:** SvelteKit 2 + Svelte 5, adapter-static, TypeScript, TailwindCSS.
|
||||
- **Обработка изображений:** `disintegration/imaging` + `gen2brain/webp` +
|
||||
`rwcarlsen/goexif` (всё чистый Go).
|
||||
|
||||
## Требования
|
||||
|
||||
- Go 1.22+ (сборка проверена на 1.26)
|
||||
- Node.js 20+ (только для сборки фронтенда)
|
||||
- Доступ к `pg.localnet:5432` (PostgreSQL) и `s3.localnet:3900` (Garage)
|
||||
- `make`
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Скопируйте `.env.example` в `.env` и заполните значения:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Ключевые переменные: `PG_*`, `S3_*` (обязательны `UsePathStyle=true` и регион
|
||||
`garage`), `JWT_SECRET`, `JWT_ACCESS_TTL`, `JWT_REFRESH_TTL`, `HTTP_ADDR`,
|
||||
`SSE_HEARTBEAT_INTERVAL`, `SSE_CLIENT_BUFFER`.
|
||||
|
||||
## Сборка
|
||||
|
||||
```bash
|
||||
make build # frontend -> backend/static -> go:embed -> bin/shared-album
|
||||
```
|
||||
|
||||
Отдельные шаги:
|
||||
|
||||
```bash
|
||||
make frontend # npm ci && npm run build, копирует статику в backend/static
|
||||
make backend # CGO_ENABLED=0 go build -tags nodynamic -o bin/shared-album
|
||||
```
|
||||
|
||||
> `-tags nodynamic` обязателен: он заставляет `gen2brain/webp` использовать
|
||||
> транспилированный в Go libwebp вместо динамической загрузки через purego,
|
||||
> благодаря чему бинарник остаётся полностью статическим.
|
||||
|
||||
Проверка:
|
||||
|
||||
```bash
|
||||
file bin/shared-album # => statically linked
|
||||
```
|
||||
|
||||
## Миграции
|
||||
|
||||
Миграции встроены в бинарник и применяются автоматически при старте сервера.
|
||||
Отдельно:
|
||||
|
||||
```bash
|
||||
make migrate # go run ./cmd/migrate — применяет up-миграции к pg.localnet
|
||||
```
|
||||
|
||||
## Локальный запуск
|
||||
|
||||
```bash
|
||||
make run # соберёт backend и запустит ./bin/shared-album
|
||||
# или напрямую:
|
||||
./bin/shared-album
|
||||
```
|
||||
|
||||
Сервер слушает `HTTP_ADDR` (по умолчанию `:8080`). Health-check:
|
||||
|
||||
```bash
|
||||
curl -s localhost:8080/api/health # {"status":"ok","db":"ok","s3":"ok"}
|
||||
```
|
||||
|
||||
Разработка фронтенда с HMR:
|
||||
|
||||
```bash
|
||||
cd frontend && npm run dev # Vite проксирует /api на :8080
|
||||
```
|
||||
|
||||
## Тесты
|
||||
|
||||
```bash
|
||||
make test
|
||||
# интеграционные тесты репозиториев требуют тестовую БД:
|
||||
TEST_DATABASE_URL='postgres://user:pass@pg.localnet:5432/galo?sslmode=disable' \
|
||||
cd backend && go test ./internal/repo/ -v
|
||||
```
|
||||
|
||||
## Деплой через systemd
|
||||
|
||||
1. Соберите бинарник: `make build`.
|
||||
2. Создайте пользователя и каталог:
|
||||
|
||||
```bash
|
||||
sudo useradd --system --home /opt/shared-album album
|
||||
sudo mkdir -p /opt/shared-album
|
||||
sudo cp bin/shared-album /opt/shared-album/
|
||||
sudo cp .env /opt/shared-album/.env
|
||||
sudo chown -R album:album /opt/shared-album
|
||||
```
|
||||
|
||||
3. Установите unit:
|
||||
|
||||
```bash
|
||||
sudo cp deploy/shared-album.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now shared-album
|
||||
sudo journalctl -u shared-album -f
|
||||
```
|
||||
|
||||
## nginx (опционально)
|
||||
|
||||
Пример в `deploy/nginx-sse.conf`. Для SSE критично `proxy_buffering off` и
|
||||
`X-Accel-Buffering: no` (последнее сервер выставляет сам).
|
||||
|
||||
## Структура
|
||||
|
||||
```
|
||||
backend/
|
||||
cmd/server/ # точка входа
|
||||
cmd/migrate/ # применение миграций
|
||||
internal/config # чтение env
|
||||
internal/db # pgx + golang-migrate
|
||||
internal/storage # S3 (Garage)
|
||||
internal/auth # JWT, bcrypt, refresh
|
||||
internal/albums # альбомы
|
||||
internal/members # участники, роли, инвайты
|
||||
internal/photos # загрузка, варианты, presigned URL
|
||||
internal/social # лайки, комментарии
|
||||
internal/notifications # персональные уведомления
|
||||
internal/sharelinks # ссылки для просмотра
|
||||
internal/sse # SSE-хаб
|
||||
internal/app # маршруты и статика
|
||||
migrations/ # SQL-миграции
|
||||
static/ # сюда копируется build SvelteKit
|
||||
frontend/ # SvelteKit 2 + Svelte 5
|
||||
deploy/ # systemd unit, пример nginx
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
Полный список эндпоинтов: `project.md`, раздел 11. Кратко:
|
||||
|
||||
- `POST /api/auth/register|login|refresh|logout`, `GET /api/auth/me`
|
||||
- `GET|POST /api/albums`, `GET|PATCH|DELETE /api/albums/:id`
|
||||
- `GET /api/albums/:id/members`, `POST /api/albums/:id/invites`,
|
||||
`POST /api/invites/:token/accept`, `PATCH|DELETE /api/albums/:id/members/:user_id`
|
||||
- `GET|POST /api/albums/:id/photos`, `GET|DELETE /api/photos/:id`,
|
||||
`GET /api/photos/:id/download`
|
||||
- `POST|DELETE /api/photos/:id/likes`, `GET|POST /api/photos/:id/comments`,
|
||||
`DELETE /api/comments/:id`
|
||||
- `GET /api/sse/albums/:id`, `GET /api/sse/me`
|
||||
- `POST|GET /api/albums/:id/share`, `DELETE /api/albums/:id/share/:link_id`,
|
||||
`GET /api/share/:token[/photos[/:photo_id[/download]]]`
|
||||
- `GET /api/notifications`, `POST /api/notifications/:id/read`
|
||||
@@ -0,0 +1,78 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
assets "shared-album"
|
||||
"shared-album/internal/config"
|
||||
"shared-album/internal/db"
|
||||
)
|
||||
|
||||
func main() {
|
||||
loadDotEnv(".env")
|
||||
loadDotEnv("../.env")
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
slog.Error("config error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
migFS, err := fs.Sub(assets.Migrations, "migrations")
|
||||
if err != nil {
|
||||
slog.Error("migrations fs", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := db.Migrate(cfg.Postgres.DSN(), migFS); err != nil {
|
||||
slog.Error("migration failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("migrations applied")
|
||||
}
|
||||
|
||||
func loadDotEnv(path string) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, line := range splitLines(string(data)) {
|
||||
if line == "" || line[0] == '#' {
|
||||
continue
|
||||
}
|
||||
for i := 0; i < len(line); i++ {
|
||||
if line[i] == '=' {
|
||||
key := line[:i]
|
||||
val := line[i+1:]
|
||||
if _, exists := os.LookupEnv(key); !exists {
|
||||
_ = os.Setenv(key, val)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func splitLines(s string) []string {
|
||||
var out []string
|
||||
start := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\n' {
|
||||
out = append(out, trim(s[start:i]))
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
out = append(out, trim(s[start:]))
|
||||
return out
|
||||
}
|
||||
|
||||
func trim(s string) string {
|
||||
start, end := 0, len(s)
|
||||
for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\r') {
|
||||
start++
|
||||
}
|
||||
for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\r') {
|
||||
end--
|
||||
}
|
||||
return s[start:end]
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
assets "shared-album"
|
||||
"shared-album/internal/app"
|
||||
"shared-album/internal/config"
|
||||
"shared-album/internal/db"
|
||||
"shared-album/internal/sse"
|
||||
"shared-album/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
loadDotEnv(".env")
|
||||
loadDotEnv("../.env")
|
||||
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
slog.Error("config error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
migFS, err := fs.Sub(assets.Migrations, "migrations")
|
||||
if err != nil {
|
||||
slog.Error("migrations fs", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := db.Migrate(cfg.Postgres.DSN(), migFS); err != nil {
|
||||
slog.Error("migration failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("migrations applied")
|
||||
|
||||
pool, err := db.Connect(ctx, cfg.Postgres.DSN())
|
||||
if err != nil {
|
||||
slog.Error("database connect failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
store, err := storage.New(ctx, cfg.S3)
|
||||
if err != nil {
|
||||
slog.Error("storage init failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := store.EnsureBucket(ctx); err != nil {
|
||||
slog.Warn("could not ensure bucket", "error", err)
|
||||
} else {
|
||||
slog.Info("storage bucket ready", "bucket", store.Bucket())
|
||||
}
|
||||
|
||||
hub := sse.NewHub(cfg.SSE.ClientBuffer)
|
||||
server := app.New(cfg, pool, store, hub)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.Server.Addr,
|
||||
Handler: server.Router(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
slog.Info("listening", "addr", cfg.Server.Addr)
|
||||
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Error("server error", "error", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
slog.Info("shutting down")
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = httpServer.Shutdown(shutdownCtx)
|
||||
}
|
||||
|
||||
func loadDotEnv(path string) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
key, value, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
value = strings.TrimSpace(value)
|
||||
if _, exists := os.LookupEnv(key); !exists {
|
||||
_ = os.Setenv(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package backend
|
||||
|
||||
import "embed"
|
||||
|
||||
// Static holds the built SvelteKit frontend, copied into backend/static by the Makefile.
|
||||
//
|
||||
//go:embed all:static
|
||||
var Static embed.FS
|
||||
|
||||
// Migrations holds the SQL migration files.
|
||||
//
|
||||
//go:embed migrations/*.sql
|
||||
var Migrations embed.FS
|
||||
@@ -0,0 +1,71 @@
|
||||
module shared-album
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
|
||||
github.com/aws/smithy-go v1.28.5
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/gen2brain/webp v0.6.4
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
|
||||
golang.org/x/crypto v0.58.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3/go.mod h1:BRjf4L/Yx2hY54o+ZibPbLJyMMeSwqYQXwcJfqW66a8=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4/go.mod h1:+FEO9jrVMpc9oN3CdAxJbtlQEu3z8UddDPSedpeM3PY=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 h1:OKEfbf2tcfsF2pBk/S9QqNpo6alaAtiBs4hysCsBjPw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.4/go.mod h1:mCd6qGo9b8hTtfjgsmNkFlzwjyce4owd7HDVFnCLXhM=
|
||||
github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
|
||||
github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4=
|
||||
github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM=
|
||||
github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU=
|
||||
github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||
github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY=
|
||||
github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,87 @@
|
||||
package albums
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
list, err := h.svc.List(c.Request.Context(), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"albums": list})
|
||||
}
|
||||
|
||||
type albumRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var req albumRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "title is required"))
|
||||
return
|
||||
}
|
||||
a, err := h.svc.Create(c.Request.Context(), auth.UserID(c), CreateInput(req))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"album": a})
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
a, role, err := h.svc.Get(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"album": a, "role": role})
|
||||
}
|
||||
|
||||
type updateRequest struct {
|
||||
Title *string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
CoverPhotoID *string `json:"cover_photo_id"`
|
||||
ClearCover bool `json:"clear_cover"`
|
||||
}
|
||||
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
var req updateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "invalid body"))
|
||||
return
|
||||
}
|
||||
a, err := h.svc.Update(c.Request.Context(), c.Param("id"), auth.UserID(c), UpdateInput{
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
CoverPhotoID: req.CoverPhotoID,
|
||||
ClearCover: req.ClearCover,
|
||||
})
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"album": a})
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
if err := h.svc.Delete(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package albums
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/roles"
|
||||
"shared-album/internal/sse"
|
||||
"shared-album/internal/storage"
|
||||
)
|
||||
|
||||
type MemberLookup interface {
|
||||
Role(ctx context.Context, albumID, userID string) (string, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
members MemberLookup
|
||||
hub *sse.Hub
|
||||
storage *storage.Client
|
||||
}
|
||||
|
||||
func NewService(store *Store, members MemberLookup, hub *sse.Hub, storage *storage.Client) *Service {
|
||||
return &Service{store: store, members: members, hub: hub, storage: storage}
|
||||
}
|
||||
|
||||
type CreateInput struct {
|
||||
Title string
|
||||
Description string
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, userID string, in CreateInput) (*models.Album, error) {
|
||||
title := strings.TrimSpace(in.Title)
|
||||
if title == "" {
|
||||
return nil, httpx.BadRequest("invalid_title", "title is required")
|
||||
}
|
||||
a := &models.Album{
|
||||
ID: auth.NewID(),
|
||||
OwnerID: userID,
|
||||
Title: title,
|
||||
Description: strings.TrimSpace(in.Description),
|
||||
}
|
||||
if err := s.store.Create(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, userID string) ([]models.Album, error) {
|
||||
return s.store.ListForUser(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Service) Access(ctx context.Context, albumID, userID string) (*models.Album, string, error) {
|
||||
a, err := s.store.GetByID(ctx, albumID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, "", httpx.NotFound("album_not_found", "album not found")
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if a.OwnerID == userID {
|
||||
return a, roles.Owner, nil
|
||||
}
|
||||
role, err := s.members.Role(ctx, albumID, userID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if role == "" {
|
||||
return nil, "", httpx.NotFound("album_not_found", "album not found")
|
||||
}
|
||||
return a, role, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, albumID, userID string) (*models.Album, string, error) {
|
||||
return s.Access(ctx, albumID, userID)
|
||||
}
|
||||
|
||||
type UpdateInput struct {
|
||||
Title *string
|
||||
Description *string
|
||||
CoverPhotoID *string
|
||||
ClearCover bool
|
||||
}
|
||||
|
||||
func (s *Service) Update(ctx context.Context, albumID, userID string, in UpdateInput) (*models.Album, error) {
|
||||
a, role, err := s.Access(ctx, albumID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !roles.CanEditAlbum(role) {
|
||||
return nil, httpx.Forbidden("forbidden", "only owner and admin can edit the album")
|
||||
}
|
||||
if in.Title != nil {
|
||||
title := strings.TrimSpace(*in.Title)
|
||||
if title == "" {
|
||||
return nil, httpx.BadRequest("invalid_title", "title cannot be empty")
|
||||
}
|
||||
a.Title = title
|
||||
}
|
||||
if in.Description != nil {
|
||||
a.Description = strings.TrimSpace(*in.Description)
|
||||
}
|
||||
if in.ClearCover {
|
||||
a.CoverPhotoID = nil
|
||||
} else if in.CoverPhotoID != nil {
|
||||
a.CoverPhotoID = in.CoverPhotoID
|
||||
}
|
||||
if err := s.store.Update(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.hub.Publish(albumID, "album.updated", a)
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, albumID, userID string) error {
|
||||
a, role, err := s.Access(ctx, albumID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if role != roles.Owner {
|
||||
return httpx.Forbidden("forbidden", "only the owner can delete the album")
|
||||
}
|
||||
if err := s.store.Delete(ctx, a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.storage != nil {
|
||||
_ = s.storage.DeletePrefix(ctx, "albums/"+a.ID+"/")
|
||||
}
|
||||
s.hub.Publish(albumID, "album.deleted", map[string]string{"id": a.ID})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package albums
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("album not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Create(ctx context.Context, a *models.Album) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO albums (id, owner_id, title, description, cover_photo_id)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING created_at, updated_at`,
|
||||
a.ID, a.OwnerID, a.Title, a.Description, a.CoverPhotoID,
|
||||
).Scan(&a.CreatedAt, &a.UpdatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) OwnerID(ctx context.Context, id string) (string, error) {
|
||||
var ownerID string
|
||||
err := s.pool.QueryRow(ctx, `SELECT owner_id FROM albums WHERE id = $1`, id).Scan(&ownerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", httpx.NotFound("album_not_found", "album not found")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return ownerID, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetByID(ctx context.Context, id string) (*models.Album, error) {
|
||||
var a models.Album
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, owner_id, title, description, cover_photo_id, created_at, updated_at
|
||||
FROM albums WHERE id = $1`, id).
|
||||
Scan(&a.ID, &a.OwnerID, &a.Title, &a.Description, &a.CoverPhotoID, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListForUser(ctx context.Context, userID string) ([]models.Album, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT a.id, a.owner_id, a.title, a.description, a.cover_photo_id, a.created_at, a.updated_at
|
||||
FROM albums a
|
||||
LEFT JOIN album_members m ON m.album_id = a.id AND m.user_id = $1
|
||||
WHERE a.owner_id = $1 OR m.user_id IS NOT NULL
|
||||
ORDER BY a.created_at DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.Album{}
|
||||
for rows.Next() {
|
||||
var a models.Album
|
||||
if err := rows.Scan(&a.ID, &a.OwnerID, &a.Title, &a.Description, &a.CoverPhotoID, &a.CreatedAt, &a.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) Update(ctx context.Context, a *models.Album) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`UPDATE albums
|
||||
SET title = $2, description = $3, cover_photo_id = $4, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING updated_at`,
|
||||
a.ID, a.Title, a.Description, a.CoverPhotoID,
|
||||
).Scan(&a.UpdatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, id string) error {
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM albums WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
assets "shared-album"
|
||||
"shared-album/internal/albums"
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/config"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/members"
|
||||
"shared-album/internal/notifications"
|
||||
"shared-album/internal/photos"
|
||||
"shared-album/internal/sharelinks"
|
||||
"shared-album/internal/social"
|
||||
"shared-album/internal/sse"
|
||||
"shared-album/internal/storage"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
cfg *config.Config
|
||||
pool *pgxpool.Pool
|
||||
storage *storage.Client
|
||||
hub *sse.Hub
|
||||
|
||||
albumsStore *albums.Store
|
||||
albums *albums.Service
|
||||
|
||||
auth *auth.Service
|
||||
|
||||
membersSvc *members.Service
|
||||
|
||||
photos *photos.Service
|
||||
|
||||
social *social.Service
|
||||
|
||||
notifications *notifications.Service
|
||||
|
||||
share *sharelinks.Service
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, pool *pgxpool.Pool, st *storage.Client, hub *sse.Hub) *Server {
|
||||
authStore := auth.NewStore(pool)
|
||||
tm := auth.NewTokenManager(cfg.Auth.JWTSecret, cfg.Auth.AccessTTL, cfg.Auth.RefreshTTL)
|
||||
authSvc := auth.NewService(authStore, tm)
|
||||
|
||||
albumsStore := albums.NewStore(pool)
|
||||
membersStore := members.NewStore(pool)
|
||||
|
||||
notifStore := notifications.NewStore(pool)
|
||||
notifSvc := notifications.NewService(notifStore, hub)
|
||||
|
||||
albumsSvc := albums.NewService(albumsStore, membersStore, hub, st)
|
||||
membersSvc := members.NewService(membersStore, albumsStore, hub, notifSvc)
|
||||
|
||||
photosStore := photos.NewStore(pool)
|
||||
photosSvc := photos.NewService(photosStore, albumsSvc, st, hub)
|
||||
|
||||
socialStore := social.NewStore(pool)
|
||||
socialSvc := social.NewService(socialStore, albumsSvc, photosStore, hub, notifSvc)
|
||||
|
||||
shareStore := sharelinks.NewStore(pool)
|
||||
shareSvc := sharelinks.NewService(shareStore, albumsSvc)
|
||||
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
pool: pool,
|
||||
storage: st,
|
||||
hub: hub,
|
||||
albumsStore: albumsStore,
|
||||
albums: albumsSvc,
|
||||
auth: authSvc,
|
||||
membersSvc: membersSvc,
|
||||
photos: photosSvc,
|
||||
social: socialSvc,
|
||||
notifications: notifSvc,
|
||||
share: shareSvc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Router() *gin.Engine {
|
||||
r := gin.New()
|
||||
r.Use(gin.Recovery())
|
||||
|
||||
authHandler := auth.NewHandler(s.auth)
|
||||
albumsHandler := albums.NewHandler(s.albums)
|
||||
membersHandler := members.NewHandler(s.membersSvc)
|
||||
photosHandler := photos.NewHandler(s.photos)
|
||||
socialHandler := social.NewHandler(s.social)
|
||||
notifHandler := notifications.NewHandler(s.notifications)
|
||||
shareHandler := sharelinks.NewHandler(s.share)
|
||||
|
||||
api := r.Group("/api")
|
||||
api.GET("/health", s.health)
|
||||
|
||||
api.POST("/auth/register", authHandler.Register)
|
||||
api.POST("/auth/login", authHandler.Login)
|
||||
api.POST("/auth/refresh", authHandler.Refresh)
|
||||
api.POST("/auth/logout", authHandler.Logout)
|
||||
|
||||
api.GET("/invites/:token", membersHandler.InviteInfo)
|
||||
|
||||
api.GET("/share/:token", s.shareAlbum)
|
||||
api.GET("/share/:token/photos", s.sharePhotos)
|
||||
api.GET("/share/:token/photos/:photo_id", s.sharePhoto)
|
||||
api.GET("/share/:token/photos/:photo_id/download", s.sharePhotoDownload)
|
||||
|
||||
authed := api.Group("")
|
||||
authed.Use(s.auth.Middleware())
|
||||
|
||||
authed.GET("/auth/me", authHandler.Me)
|
||||
authed.GET("/sse/albums/:id", s.albumSSE)
|
||||
authed.GET("/sse/me", s.meSSE)
|
||||
|
||||
authed.GET("/albums", albumsHandler.List)
|
||||
authed.POST("/albums", albumsHandler.Create)
|
||||
authed.GET("/albums/:id", albumsHandler.Get)
|
||||
authed.PATCH("/albums/:id", albumsHandler.Update)
|
||||
authed.DELETE("/albums/:id", albumsHandler.Delete)
|
||||
|
||||
authed.GET("/albums/:id/members", membersHandler.List)
|
||||
authed.POST("/albums/:id/invites", membersHandler.CreateInvite)
|
||||
authed.POST("/invites/:token/accept", membersHandler.AcceptInvite)
|
||||
authed.PATCH("/albums/:id/members/:user_id", membersHandler.ChangeRole)
|
||||
authed.DELETE("/albums/:id/members/:user_id", membersHandler.Remove)
|
||||
|
||||
authed.GET("/albums/:id/photos", photosHandler.List)
|
||||
authed.POST("/albums/:id/photos", photosHandler.Upload)
|
||||
authed.GET("/photos/:id", photosHandler.Get)
|
||||
authed.DELETE("/photos/:id", photosHandler.Delete)
|
||||
authed.GET("/photos/:id/download", photosHandler.Download)
|
||||
|
||||
authed.POST("/photos/:id/likes", socialHandler.AddLike)
|
||||
authed.DELETE("/photos/:id/likes", socialHandler.RemoveLike)
|
||||
authed.GET("/photos/:id/comments", socialHandler.ListComments)
|
||||
authed.POST("/photos/:id/comments", socialHandler.AddComment)
|
||||
authed.DELETE("/comments/:id", socialHandler.DeleteComment)
|
||||
|
||||
authed.GET("/albums/:id/share", shareHandler.List)
|
||||
authed.POST("/albums/:id/share", shareHandler.Create)
|
||||
authed.DELETE("/albums/:id/share/:link_id", shareHandler.Revoke)
|
||||
|
||||
authed.GET("/notifications", notifHandler.List)
|
||||
authed.POST("/notifications/:id/read", notifHandler.MarkRead)
|
||||
|
||||
s.registerStatic(r)
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Server) health(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
dbStatus := "ok"
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
dbStatus = "error"
|
||||
}
|
||||
s3Status := "ok"
|
||||
if err := s.storage.Ping(ctx); err != nil {
|
||||
s3Status = "error"
|
||||
}
|
||||
status := http.StatusOK
|
||||
overall := "ok"
|
||||
if dbStatus != "ok" || s3Status != "ok" {
|
||||
status = http.StatusServiceUnavailable
|
||||
overall = "degraded"
|
||||
}
|
||||
c.JSON(status, gin.H{"status": overall, "db": dbStatus, "s3": s3Status})
|
||||
}
|
||||
|
||||
func (s *Server) albumSSE(c *gin.Context) {
|
||||
userID := auth.UserID(c)
|
||||
albumID := c.Param("id")
|
||||
if _, _, err := s.albums.Access(c.Request.Context(), albumID, userID); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
sub := s.hub.SubscribeAlbum(albumID)
|
||||
defer sub.Close()
|
||||
sse.Serve(c, sub, s.cfg.SSE.HeartbeatInterval)
|
||||
}
|
||||
|
||||
func (s *Server) meSSE(c *gin.Context) {
|
||||
sub := s.hub.SubscribeUser(auth.UserID(c))
|
||||
defer sub.Close()
|
||||
sse.Serve(c, sub, s.cfg.SSE.HeartbeatInterval)
|
||||
}
|
||||
|
||||
func (s *Server) shareAlbum(c *gin.Context) {
|
||||
link, err := s.share.Resolve(c.Request.Context(), c.Param("token"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
album, err := s.albumsStore.GetByID(c.Request.Context(), link.AlbumID)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, httpx.NotFound("album_not_found", "album not found"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"album": album})
|
||||
}
|
||||
|
||||
func (s *Server) sharePhotos(c *gin.Context) {
|
||||
link, err := s.share.Resolve(c.Request.Context(), c.Param("token"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
var since *time.Time
|
||||
list, next, err := s.photos.ListPublic(c.Request.Context(), link.AlbumID, c.Query("cursor"), since, limit)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"photos": list, "next_cursor": next})
|
||||
}
|
||||
|
||||
func (s *Server) sharePhoto(c *gin.Context) {
|
||||
link, err := s.share.Resolve(c.Request.Context(), c.Param("token"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.photos.GetPublic(c.Request.Context(), c.Param("photo_id"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
if p.AlbumID != link.AlbumID {
|
||||
httpx.RespondError(c, httpx.NotFound("photo_not_found", "photo not found"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"photo": p})
|
||||
}
|
||||
|
||||
func (s *Server) sharePhotoDownload(c *gin.Context) {
|
||||
link, err := s.share.Resolve(c.Request.Context(), c.Param("token"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.photos.GetPublic(c.Request.Context(), c.Param("photo_id"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
if p.AlbumID != link.AlbumID {
|
||||
httpx.RespondError(c, httpx.NotFound("photo_not_found", "photo not found"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"url": p.DownloadURL})
|
||||
}
|
||||
|
||||
func (s *Server) registerStatic(r *gin.Engine) {
|
||||
sub, err := fs.Sub(assets.Static, "static")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fileServer := http.FileServer(http.FS(sub))
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
if strings.HasPrefix(path, "/api/") {
|
||||
c.JSON(http.StatusNotFound, httpx.ErrorResponse{Error: httpx.ErrorBody{Code: "not_found", Message: "not found"}})
|
||||
return
|
||||
}
|
||||
clean := strings.TrimPrefix(path, "/")
|
||||
if clean != "" {
|
||||
if f, err := sub.Open(clean); err == nil {
|
||||
f.Close()
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
return
|
||||
}
|
||||
}
|
||||
index, err := fs.ReadFile(sub, "index.html")
|
||||
if err != nil {
|
||||
c.String(http.StatusNotFound, "frontend not built")
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "text/html; charset=utf-8", index)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
type registerRequest struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *Handler) Register(c *gin.Context) {
|
||||
var req registerRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "email, password and name are required"))
|
||||
return
|
||||
}
|
||||
u, pair, err := h.svc.Register(c.Request.Context(), req.Email, req.Password, req.Name)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"user": u.Public(), "tokens": pair})
|
||||
}
|
||||
|
||||
type loginRequest struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *Handler) Login(c *gin.Context) {
|
||||
var req loginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "email and password are required"))
|
||||
return
|
||||
}
|
||||
u, pair, err := h.svc.Login(c.Request.Context(), req.Email, req.Password)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": u.Public(), "tokens": pair})
|
||||
}
|
||||
|
||||
type refreshRequest struct {
|
||||
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *Handler) Refresh(c *gin.Context) {
|
||||
var req refreshRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "refresh_token is required"))
|
||||
return
|
||||
}
|
||||
pair, err := h.svc.Refresh(c.Request.Context(), req.RefreshToken)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"tokens": pair})
|
||||
}
|
||||
|
||||
func (h *Handler) Logout(c *gin.Context) {
|
||||
var req refreshRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
if req.RefreshToken != "" {
|
||||
if err := h.svc.Logout(c.Request.Context(), req.RefreshToken); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) Me(c *gin.Context) {
|
||||
u, err := h.svc.store.GetUserByID(c.Request.Context(), UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, httpx.Unauthorized("unauthorized", "user not found"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": u.Public()})
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID string `json:"uid"`
|
||||
Email string `json:"email"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type TokenManager struct {
|
||||
secret []byte
|
||||
accessTTL time.Duration
|
||||
refreshTTL time.Duration
|
||||
}
|
||||
|
||||
func NewTokenManager(secret string, accessTTL, refreshTTL time.Duration) *TokenManager {
|
||||
return &TokenManager{secret: []byte(secret), accessTTL: accessTTL, refreshTTL: refreshTTL}
|
||||
}
|
||||
|
||||
func (m *TokenManager) AccessTTL() time.Duration { return m.accessTTL }
|
||||
func (m *TokenManager) RefreshTTL() time.Duration { return m.refreshTTL }
|
||||
|
||||
func (m *TokenManager) GenerateAccess(userID, email string) (string, error) {
|
||||
now := time.Now()
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(m.accessTTL)),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(m.secret)
|
||||
}
|
||||
|
||||
func (m *TokenManager) ParseAccess(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return m.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func NewRefreshToken() (raw string, hash string, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err = rand.Read(buf); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
raw = base64.RawURLEncoding.EncodeToString(buf)
|
||||
return raw, HashRefreshToken(raw), nil
|
||||
}
|
||||
|
||||
func HashRefreshToken(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func NewID() string {
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
const (
|
||||
ctxUserID = "auth.user_id"
|
||||
ctxEmail = "auth.email"
|
||||
)
|
||||
|
||||
func (s *Service) Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token := extractToken(c)
|
||||
if token == "" {
|
||||
httpx.Abort(c, httpx.Unauthorized("unauthorized", "missing access token"))
|
||||
return
|
||||
}
|
||||
claims, err := s.tm.ParseAccess(token)
|
||||
if err != nil {
|
||||
httpx.Abort(c, httpx.Unauthorized("unauthorized", "invalid or expired access token"))
|
||||
return
|
||||
}
|
||||
c.Set(ctxUserID, claims.UserID)
|
||||
c.Set(ctxEmail, claims.Email)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func extractToken(c *gin.Context) string {
|
||||
h := c.GetHeader("Authorization")
|
||||
if strings.HasPrefix(h, "Bearer ") {
|
||||
return strings.TrimPrefix(h, "Bearer ")
|
||||
}
|
||||
if t := c.Query("token"); t != "" {
|
||||
return t
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func UserID(c *gin.Context) string {
|
||||
if v, ok := c.Get(ctxUserID); ok {
|
||||
return v.(string)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func Email(c *gin.Context) string {
|
||||
if v, ok := c.Get(ctxEmail); ok {
|
||||
return v.(string)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Service) ParseToken(token string) (*Claims, error) {
|
||||
return s.tm.ParseAccess(token)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package auth
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func CheckPassword(hash, password string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
type TokenPair struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
tm *TokenManager
|
||||
}
|
||||
|
||||
func NewService(store *Store, tm *TokenManager) *Service {
|
||||
return &Service{store: store, tm: tm}
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, email, password, name string) (*models.User, *TokenPair, error) {
|
||||
email = strings.TrimSpace(strings.ToLower(email))
|
||||
name = strings.TrimSpace(name)
|
||||
if email == "" || !strings.Contains(email, "@") {
|
||||
return nil, nil, httpx.BadRequest("invalid_email", "valid email is required")
|
||||
}
|
||||
if len(password) < 8 {
|
||||
return nil, nil, httpx.BadRequest("weak_password", "password must be at least 8 characters")
|
||||
}
|
||||
if name == "" {
|
||||
return nil, nil, httpx.BadRequest("invalid_name", "name is required")
|
||||
}
|
||||
|
||||
if _, err := s.store.GetUserByEmail(ctx, email); err == nil {
|
||||
return nil, nil, httpx.Conflict("email_taken", "email is already registered")
|
||||
} else if !errors.Is(err, ErrNotFound) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
u := &models.User{
|
||||
ID: NewID(),
|
||||
Email: email,
|
||||
PasswordHash: hash,
|
||||
Name: name,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if err := s.store.CreateUser(ctx, u); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pair, err := s.issuePair(ctx, u)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return u, pair, nil
|
||||
}
|
||||
|
||||
func (s *Service) Login(ctx context.Context, email, password string) (*models.User, *TokenPair, error) {
|
||||
email = strings.TrimSpace(strings.ToLower(email))
|
||||
u, err := s.store.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, nil, httpx.Unauthorized("invalid_credentials", "invalid email or password")
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if !CheckPassword(u.PasswordHash, password) {
|
||||
return nil, nil, httpx.Unauthorized("invalid_credentials", "invalid email or password")
|
||||
}
|
||||
pair, err := s.issuePair(ctx, u)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return u, pair, nil
|
||||
}
|
||||
|
||||
func (s *Service) Refresh(ctx context.Context, refreshToken string) (*TokenPair, error) {
|
||||
hash := HashRefreshToken(refreshToken)
|
||||
t, err := s.store.GetRefreshToken(ctx, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.Unauthorized("invalid_refresh_token", "refresh token is invalid or expired")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if t.RevokedAt != nil || time.Now().After(t.ExpiresAt) {
|
||||
return nil, httpx.Unauthorized("invalid_refresh_token", "refresh token is invalid or expired")
|
||||
}
|
||||
u, err := s.store.GetUserByID(ctx, t.UserID)
|
||||
if err != nil {
|
||||
return nil, httpx.Unauthorized("invalid_refresh_token", "refresh token is invalid or expired")
|
||||
}
|
||||
if err := s.store.RevokeRefreshToken(ctx, t.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.issuePair(ctx, u)
|
||||
}
|
||||
|
||||
func (s *Service) Logout(ctx context.Context, refreshToken string) error {
|
||||
hash := HashRefreshToken(refreshToken)
|
||||
t, err := s.store.GetRefreshToken(ctx, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return s.store.RevokeRefreshToken(ctx, t.ID)
|
||||
}
|
||||
|
||||
func (s *Service) issuePair(ctx context.Context, u *models.User) (*TokenPair, error) {
|
||||
access, err := s.tm.GenerateAccess(u.ID, u.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, hash, err := NewRefreshToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rt := &models.RefreshToken{
|
||||
ID: NewID(),
|
||||
UserID: u.ID,
|
||||
TokenHash: hash,
|
||||
ExpiresAt: time.Now().Add(s.tm.RefreshTTL()),
|
||||
}
|
||||
if err := s.store.CreateRefreshToken(ctx, rt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &TokenPair{
|
||||
AccessToken: access,
|
||||
RefreshToken: raw,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int64(s.tm.AccessTTL().Seconds()),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, u *models.User) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO users (id, email, password_hash, name, avatar_url)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Email, u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL),
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
||||
return s.scanUser(s.pool.QueryRow(ctx,
|
||||
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''), created_at
|
||||
FROM users WHERE lower(email) = lower($1)`, email))
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id string) (*models.User, error) {
|
||||
return s.scanUser(s.pool.QueryRow(ctx,
|
||||
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''), created_at
|
||||
FROM users WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Store) scanUser(row pgx.Row) (*models.User, error) {
|
||||
var u models.User
|
||||
if err := row.Scan(&u.ID, &u.Email, &u.PasswordHash, &u.Name, &u.AvatarURL, &u.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateRefreshToken(ctx context.Context, t *models.RefreshToken) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
t.ID, t.UserID, t.TokenHash, t.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) GetRefreshToken(ctx context.Context, hash string) (*models.RefreshToken, error) {
|
||||
var t models.RefreshToken
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, user_id, token_hash, expires_at, revoked_at, created_at
|
||||
FROM refresh_tokens WHERE token_hash = $1`, hash).
|
||||
Scan(&t.ID, &t.UserID, &t.TokenHash, &t.ExpiresAt, &t.RevokedAt, &t.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (s *Store) RevokeRefreshToken(ctx context.Context, id string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`UPDATE refresh_tokens SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) RevokeAllUserTokens(ctx context.Context, userID string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`UPDATE refresh_tokens SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL`, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func nullIfEmpty(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Postgres struct {
|
||||
Host string
|
||||
Port int
|
||||
User string
|
||||
Password string
|
||||
Database string
|
||||
SSLMode string
|
||||
}
|
||||
|
||||
func (p Postgres) DSN() string {
|
||||
return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s",
|
||||
p.User, p.Password, p.Host, p.Port, p.Database, p.SSLMode)
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Bucket string
|
||||
UsePathStyle bool
|
||||
PublicURL string
|
||||
PresignTTL time.Duration
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
JWTSecret string
|
||||
AccessTTL time.Duration
|
||||
RefreshTTL time.Duration
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Addr string
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
type SSE struct {
|
||||
HeartbeatInterval time.Duration
|
||||
ClientBuffer int
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Postgres Postgres
|
||||
S3 S3
|
||||
Auth Auth
|
||||
Server Server
|
||||
SSE SSE
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
pgPort, err := strconv.Atoi(getEnv("PG_PORT", "5432"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid PG_PORT: %w", err)
|
||||
}
|
||||
|
||||
accessTTL, err := time.ParseDuration(getEnv("JWT_ACCESS_TTL", "15m"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid JWT_ACCESS_TTL: %w", err)
|
||||
}
|
||||
|
||||
refreshTTL, err := time.ParseDuration(getEnv("JWT_REFRESH_TTL", "720h"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid JWT_REFRESH_TTL: %w", err)
|
||||
}
|
||||
|
||||
presignTTL, err := time.ParseDuration(getEnv("S3_PRESIGN_TTL", "1h"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid S3_PRESIGN_TTL: %w", err)
|
||||
}
|
||||
|
||||
heartbeat, err := time.ParseDuration(getEnv("SSE_HEARTBEAT_INTERVAL", "25s"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid SSE_HEARTBEAT_INTERVAL: %w", err)
|
||||
}
|
||||
|
||||
bufSize, err := strconv.Atoi(getEnv("SSE_CLIENT_BUFFER", "64"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid SSE_CLIENT_BUFFER: %w", err)
|
||||
}
|
||||
|
||||
pathStyle, err := strconv.ParseBool(getEnv("S3_USE_PATH_STYLE", "true"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid S3_USE_PATH_STYLE: %w", err)
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
Postgres: Postgres{
|
||||
Host: getEnv("PG_HOST", "pg.localnet"),
|
||||
Port: pgPort,
|
||||
User: getEnv("PG_USER", "album"),
|
||||
Password: getEnv("PG_PASSWORD", ""),
|
||||
Database: getEnv("PG_DATABASE", "shared_album"),
|
||||
SSLMode: getEnv("PG_SSLMODE", "disable"),
|
||||
},
|
||||
S3: S3{
|
||||
Endpoint: getEnv("S3_ENDPOINT", "http://s3.localnet:3900"),
|
||||
Region: getEnv("S3_REGION", "garage"),
|
||||
AccessKey: getEnv("S3_ACCESS_KEY", ""),
|
||||
SecretKey: getEnv("S3_SECRET_KEY", ""),
|
||||
Bucket: getEnv("S3_BUCKET", "albums"),
|
||||
UsePathStyle: pathStyle,
|
||||
PublicURL: getEnv("S3_PUBLIC_URL", ""),
|
||||
PresignTTL: presignTTL,
|
||||
},
|
||||
Auth: Auth{
|
||||
JWTSecret: getEnv("JWT_SECRET", ""),
|
||||
AccessTTL: accessTTL,
|
||||
RefreshTTL: refreshTTL,
|
||||
},
|
||||
Server: Server{
|
||||
Addr: getEnv("HTTP_ADDR", ":8080"),
|
||||
BaseURL: getEnv("APP_BASE_URL", "http://localhost:8080"),
|
||||
},
|
||||
SSE: SSE{
|
||||
HeartbeatInterval: heartbeat,
|
||||
ClientBuffer: bufSize,
|
||||
},
|
||||
}
|
||||
|
||||
if cfg.Auth.JWTSecret == "" {
|
||||
return nil, fmt.Errorf("JWT_SECRET is required")
|
||||
}
|
||||
if cfg.Postgres.Password == "" {
|
||||
return nil, fmt.Errorf("PG_PASSWORD is required")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Connect(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = time.Hour
|
||||
cfg.HealthCheckPeriod = time.Minute
|
||||
|
||||
var pool *pgxpool.Pool
|
||||
var lastErr error
|
||||
backoff := time.Second
|
||||
for attempt := 1; attempt <= 10; attempt++ {
|
||||
pool, err = pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err == nil {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err = pool.Ping(pingCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return pool, nil
|
||||
}
|
||||
pool.Close()
|
||||
}
|
||||
lastErr = err
|
||||
slog.Warn("db connect attempt failed", "attempt", attempt, "error", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
if backoff < 15*time.Second {
|
||||
backoff *= 2
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("connect to database after retries: %w", lastErr)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
|
||||
"database/sql"
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// Migrate applies all up migrations from the given fs (root contains *.sql files).
|
||||
func Migrate(dsn string, migrations fs.FS) error {
|
||||
source, err := iofs.New(migrations, ".")
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrations source: %w", err)
|
||||
}
|
||||
|
||||
sqlDB, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open sql db: %w", err)
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
|
||||
driver, err := pgx.WithInstance(sqlDB, &pgx.Config{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate driver: %w", err)
|
||||
}
|
||||
|
||||
m, err := migrate.NewWithInstance("iofs", source, "pgx", driver)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate instance: %w", err)
|
||||
}
|
||||
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||
return fmt.Errorf("migrate up: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string { return e.Message }
|
||||
|
||||
func NewError(status int, code, message string) *AppError {
|
||||
return &AppError{Status: status, Code: code, Message: message}
|
||||
}
|
||||
|
||||
func BadRequest(code, message string) *AppError {
|
||||
return NewError(http.StatusBadRequest, code, message)
|
||||
}
|
||||
|
||||
func Unauthorized(code, message string) *AppError {
|
||||
return NewError(http.StatusUnauthorized, code, message)
|
||||
}
|
||||
|
||||
func Forbidden(code, message string) *AppError {
|
||||
return NewError(http.StatusForbidden, code, message)
|
||||
}
|
||||
|
||||
func NotFound(code, message string) *AppError {
|
||||
return NewError(http.StatusNotFound, code, message)
|
||||
}
|
||||
|
||||
func Conflict(code, message string) *AppError {
|
||||
return NewError(http.StatusConflict, code, message)
|
||||
}
|
||||
|
||||
func Internal(message string) *AppError {
|
||||
return NewError(http.StatusInternalServerError, "internal_error", message)
|
||||
}
|
||||
|
||||
func Abort(c *gin.Context, err error) {
|
||||
var appErr *AppError
|
||||
if errors.As(err, &appErr) {
|
||||
c.AbortWithStatusJSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}})
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}})
|
||||
}
|
||||
|
||||
func RespondError(c *gin.Context, err error) {
|
||||
var appErr *AppError
|
||||
if errors.As(err, &appErr) {
|
||||
c.JSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}})
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package members
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
list, err := h.svc.List(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"members": list})
|
||||
}
|
||||
|
||||
type inviteRequest struct {
|
||||
Role string `json:"role" binding:"required"`
|
||||
ExpiresIn string `json:"expires_in"`
|
||||
MaxUses int `json:"max_uses"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateInvite(c *gin.Context) {
|
||||
var req inviteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "role is required"))
|
||||
return
|
||||
}
|
||||
var ttl time.Duration
|
||||
if req.ExpiresIn != "" {
|
||||
d, err := time.ParseDuration(req.ExpiresIn)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_expires_in", "invalid expires_in duration"))
|
||||
return
|
||||
}
|
||||
ttl = d
|
||||
}
|
||||
inv, err := h.svc.CreateInvite(c.Request.Context(), c.Param("id"), auth.UserID(c), CreateInviteInput{
|
||||
Role: req.Role,
|
||||
TTL: ttl,
|
||||
MaxUses: req.MaxUses,
|
||||
})
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"invite": inv})
|
||||
}
|
||||
|
||||
func (h *Handler) AcceptInvite(c *gin.Context) {
|
||||
inv, err := h.svc.Accept(c.Request.Context(), c.Param("token"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"album_id": inv.AlbumID, "role": inv.Role})
|
||||
}
|
||||
|
||||
func (h *Handler) InviteInfo(c *gin.Context) {
|
||||
inv, err := h.svc.InviteInfo(c.Request.Context(), c.Param("token"))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"invite": gin.H{
|
||||
"album_id": inv.AlbumID,
|
||||
"role": inv.Role,
|
||||
"expires_at": inv.ExpiresAt,
|
||||
}})
|
||||
}
|
||||
|
||||
type roleRequest struct {
|
||||
Role string `json:"role" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *Handler) ChangeRole(c *gin.Context) {
|
||||
var req roleRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "role is required"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.ChangeRole(c.Request.Context(), c.Param("id"), auth.UserID(c), c.Param("user_id"), req.Role); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) Remove(c *gin.Context) {
|
||||
if err := h.svc.Remove(c.Request.Context(), c.Param("id"), auth.UserID(c), c.Param("user_id")); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package members
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/roles"
|
||||
"shared-album/internal/sse"
|
||||
)
|
||||
|
||||
type AlbumReader interface {
|
||||
OwnerID(ctx context.Context, albumID string) (string, error)
|
||||
}
|
||||
|
||||
type Notifier interface {
|
||||
Create(ctx context.Context, userID, typ string, payload map[string]any) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
albums AlbumReader
|
||||
hub *sse.Hub
|
||||
notify Notifier
|
||||
}
|
||||
|
||||
func NewService(store *Store, albums AlbumReader, hub *sse.Hub, notify Notifier) *Service {
|
||||
return &Service{store: store, albums: albums, hub: hub, notify: notify}
|
||||
}
|
||||
|
||||
func (s *Service) Role(ctx context.Context, albumID, userID string) (string, error) {
|
||||
return s.store.Role(ctx, albumID, userID)
|
||||
}
|
||||
|
||||
func (s *Service) actorRole(ctx context.Context, albumID, actorID string) (string, error) {
|
||||
ownerID, err := s.albums.OwnerID(ctx, albumID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ownerID == actorID {
|
||||
return roles.Owner, nil
|
||||
}
|
||||
role, err := s.store.Role(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if role == "" {
|
||||
return "", httpx.NotFound("album_not_found", "album not found")
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
type CreateInviteInput struct {
|
||||
Role string
|
||||
TTL time.Duration
|
||||
MaxUses int
|
||||
}
|
||||
|
||||
func (s *Service) CreateInvite(ctx context.Context, albumID, actorID string, in CreateInviteInput) (*models.Invite, error) {
|
||||
role, err := s.actorRole(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !roles.CanInvite(role, in.Role) {
|
||||
return nil, httpx.Forbidden("forbidden", "you cannot invite with this role")
|
||||
}
|
||||
if in.TTL <= 0 {
|
||||
in.TTL = 7 * 24 * time.Hour
|
||||
}
|
||||
if in.MaxUses <= 0 {
|
||||
in.MaxUses = 1
|
||||
}
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inv := &models.Invite{
|
||||
ID: auth.NewID(),
|
||||
AlbumID: albumID,
|
||||
Token: token,
|
||||
Role: in.Role,
|
||||
CreatedBy: actorID,
|
||||
ExpiresAt: time.Now().Add(in.TTL),
|
||||
MaxUses: in.MaxUses,
|
||||
}
|
||||
if err := s.store.CreateInvite(ctx, inv); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
func (s *Service) Accept(ctx context.Context, token, userID string) (*models.Invite, error) {
|
||||
inv, err := s.store.GetInviteByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("invite_not_found", "invite not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if time.Now().After(inv.ExpiresAt) {
|
||||
return nil, httpx.BadRequest("invite_expired", "invite has expired")
|
||||
}
|
||||
if inv.Uses >= inv.MaxUses {
|
||||
return nil, httpx.BadRequest("invite_exhausted", "invite has no remaining uses")
|
||||
}
|
||||
if err := s.store.Add(ctx, inv.AlbumID, userID, inv.Role, &inv.CreatedBy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.store.IncrementUses(ctx, inv.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.hub.Publish(inv.AlbumID, "member.joined", map[string]string{"album_id": inv.AlbumID, "user_id": userID, "role": inv.Role})
|
||||
if s.notify != nil {
|
||||
ownerID, err := s.albums.OwnerID(ctx, inv.AlbumID)
|
||||
if err == nil && ownerID != userID {
|
||||
_ = s.notify.Create(ctx, ownerID, "member.joined", map[string]any{"album_id": inv.AlbumID, "user_id": userID, "role": inv.Role})
|
||||
}
|
||||
}
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, albumID, actorID string) ([]models.AlbumMember, error) {
|
||||
if _, err := s.actorRole(ctx, albumID, actorID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.store.List(ctx, albumID)
|
||||
}
|
||||
|
||||
func (s *Service) InviteInfo(ctx context.Context, token string) (*models.Invite, error) {
|
||||
inv, err := s.store.GetInviteByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("invite_not_found", "invite not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if time.Now().After(inv.ExpiresAt) || inv.Uses >= inv.MaxUses {
|
||||
return nil, httpx.BadRequest("invite_inactive", "invite is expired or exhausted")
|
||||
}
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
func (s *Service) ChangeRole(ctx context.Context, albumID, actorID, targetID, newRole string) error {
|
||||
actor, err := s.actorRole(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := s.store.Role(ctx, albumID, targetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current == "" {
|
||||
if ownerID, oerr := s.albums.OwnerID(ctx, albumID); oerr == nil && ownerID == targetID {
|
||||
return httpx.Forbidden("forbidden", "cannot change the owner's role")
|
||||
}
|
||||
return httpx.NotFound("member_not_found", "member not found")
|
||||
}
|
||||
if !roles.CanChangeRole(actor, current, newRole) {
|
||||
return httpx.Forbidden("forbidden", "you cannot assign this role")
|
||||
}
|
||||
if err := s.store.UpdateRole(ctx, albumID, targetID, newRole); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("member_not_found", "member not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.hub.Publish(albumID, "member.updated", map[string]string{"album_id": albumID, "user_id": targetID, "role": newRole})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Remove(ctx context.Context, albumID, actorID, targetID string) error {
|
||||
actor, err := s.actorRole(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetRole, err := s.store.Role(ctx, albumID, targetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if targetRole == "" {
|
||||
if ownerID, oerr := s.albums.OwnerID(ctx, albumID); oerr == nil && ownerID == targetID {
|
||||
return httpx.Forbidden("forbidden", "cannot remove the album owner")
|
||||
}
|
||||
return httpx.NotFound("member_not_found", "member not found")
|
||||
}
|
||||
if !roles.CanRemoveMember(actor, targetRole) {
|
||||
return httpx.Forbidden("forbidden", "you cannot remove this member")
|
||||
}
|
||||
if err := s.store.Remove(ctx, albumID, targetID); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("member_not_found", "member not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.hub.Publish(albumID, "member.left", map[string]string{"album_id": albumID, "user_id": targetID})
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
raw, _, err := auth.NewRefreshToken()
|
||||
return raw, err
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package members
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Role(ctx context.Context, albumID, userID string) (string, error) {
|
||||
var role string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT role FROM album_members WHERE album_id = $1 AND user_id = $2`,
|
||||
albumID, userID).Scan(&role)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, albumID string) ([]models.AlbumMember, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT m.album_id, m.user_id, m.role, m.invited_by, m.joined_at,
|
||||
u.id, u.email, u.name, COALESCE(u.avatar_url, '')
|
||||
FROM album_members m
|
||||
JOIN users u ON u.id = m.user_id
|
||||
WHERE m.album_id = $1
|
||||
ORDER BY m.joined_at`, albumID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.AlbumMember{}
|
||||
for rows.Next() {
|
||||
var m models.AlbumMember
|
||||
if err := rows.Scan(&m.AlbumID, &m.UserID, &m.Role, &m.InvitedBy, &m.JoinedAt,
|
||||
&m.User.ID, &m.User.Email, &m.User.Name, &m.User.AvatarURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) Add(ctx context.Context, albumID, userID, role string, invitedBy *string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO album_members (album_id, user_id, role, invited_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (album_id, user_id) DO UPDATE SET role = EXCLUDED.role`,
|
||||
albumID, userID, role, invitedBy)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateRole(ctx context.Context, albumID, userID, role string) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`UPDATE album_members SET role = $3 WHERE album_id = $1 AND user_id = $2`,
|
||||
albumID, userID, role)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Remove(ctx context.Context, albumID, userID string) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM album_members WHERE album_id = $1 AND user_id = $2`, albumID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateInvite(ctx context.Context, inv *models.Invite) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO invites (id, album_id, token, role, created_by, expires_at, max_uses)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING created_at`,
|
||||
inv.ID, inv.AlbumID, inv.Token, inv.Role, inv.CreatedBy, inv.ExpiresAt, inv.MaxUses,
|
||||
).Scan(&inv.CreatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) GetInviteByToken(ctx context.Context, token string) (*models.Invite, error) {
|
||||
var inv models.Invite
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, album_id, token, role, created_by, expires_at, max_uses, uses, created_at
|
||||
FROM invites WHERE token = $1`, token).
|
||||
Scan(&inv.ID, &inv.AlbumID, &inv.Token, &inv.Role, &inv.CreatedBy, &inv.ExpiresAt, &inv.MaxUses, &inv.Uses, &inv.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &inv, nil
|
||||
}
|
||||
|
||||
func (s *Store) IncrementUses(ctx context.Context, id string) error {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE invites SET uses = uses + 1 WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
PasswordHash string `json:"-"`
|
||||
Name string `json:"name"`
|
||||
AvatarURL string `json:"avatar_url,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type PublicUser struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Name string `json:"name"`
|
||||
AvatarURL string `json:"avatar_url,omitempty"`
|
||||
}
|
||||
|
||||
func (u *User) Public() PublicUser {
|
||||
if u == nil {
|
||||
return PublicUser{}
|
||||
}
|
||||
return PublicUser{ID: u.ID, Email: u.Email, Name: u.Name, AvatarURL: u.AvatarURL}
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
ID string `json:"id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
CoverPhotoID *string `json:"cover_photo_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type AlbumMember struct {
|
||||
AlbumID string `json:"album_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Role string `json:"role"`
|
||||
InvitedBy *string `json:"invited_by,omitempty"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
User PublicUser `json:"user"`
|
||||
}
|
||||
|
||||
type Invite struct {
|
||||
ID string `json:"id"`
|
||||
AlbumID string `json:"album_id"`
|
||||
Token string `json:"token"`
|
||||
Role string `json:"role"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
MaxUses int `json:"max_uses"`
|
||||
Uses int `json:"uses"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Photo struct {
|
||||
ID string `json:"id"`
|
||||
AlbumID string `json:"album_id"`
|
||||
UploaderID string `json:"uploader_id"`
|
||||
StorageKey string `json:"-"`
|
||||
ThumbKey string `json:"-"`
|
||||
PreviewKey string `json:"-"`
|
||||
OriginalFilename string `json:"original_filename"`
|
||||
Size int64 `json:"size"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
MimeType string `json:"mime_type"`
|
||||
TakenAt *time.Time `json:"taken_at,omitempty"`
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
Caption string `json:"caption"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Uploader PublicUser `json:"uploader"`
|
||||
LikesCount int `json:"likes_count"`
|
||||
CommentsCount int `json:"comments_count"`
|
||||
LikedByMe bool `json:"liked_by_me"`
|
||||
ThumbURL string `json:"thumb_url,omitempty"`
|
||||
PreviewURL string `json:"preview_url,omitempty"`
|
||||
OriginalURL string `json:"original_url,omitempty"`
|
||||
DownloadURL string `json:"download_url,omitempty"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
ID string `json:"id"`
|
||||
PhotoID string `json:"photo_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
User PublicUser `json:"user"`
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Type string `json:"type"`
|
||||
PayloadJSON map[string]any `json:"payload"`
|
||||
ReadAt *time.Time `json:"read_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type ShareLink struct {
|
||||
ID string `json:"id"`
|
||||
AlbumID string `json:"album_id"`
|
||||
Token string `json:"token"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||
}
|
||||
|
||||
func (s *ShareLink) Active(now time.Time) bool {
|
||||
return s.RevokedAt == nil && now.Before(s.ExpiresAt)
|
||||
}
|
||||
|
||||
type RefreshToken struct {
|
||||
ID string
|
||||
UserID string
|
||||
TokenHash string
|
||||
ExpiresAt time.Time
|
||||
RevokedAt *time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
|
||||
list, err := h.svc.List(c.Request.Context(), auth.UserID(c), limit)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"notifications": list})
|
||||
}
|
||||
|
||||
func (h *Handler) MarkRead(c *gin.Context) {
|
||||
if err := h.svc.MarkRead(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/sse"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
hub *sse.Hub
|
||||
}
|
||||
|
||||
func NewService(store *Store, hub *sse.Hub) *Service {
|
||||
return &Service{store: store, hub: hub}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, userID, typ string, payload map[string]any) error {
|
||||
n := &models.Notification{
|
||||
ID: auth.NewID(),
|
||||
UserID: userID,
|
||||
Type: typ,
|
||||
PayloadJSON: payload,
|
||||
}
|
||||
if err := s.store.Create(ctx, n); err != nil {
|
||||
return err
|
||||
}
|
||||
s.hub.PublishUser(userID, "notification", n)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, userID string, limit int) ([]models.Notification, error) {
|
||||
return s.store.List(ctx, userID, limit)
|
||||
}
|
||||
|
||||
func (s *Service) MarkRead(ctx context.Context, id, userID string) error {
|
||||
if err := s.store.MarkRead(ctx, id, userID); err != nil {
|
||||
return httpx.NotFound("notification_not_found", "notification not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Create(ctx context.Context, n *models.Notification) error {
|
||||
payload, err := json.Marshal(n.PayloadJSON)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO notifications (id, user_id, type, payload_json)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at`,
|
||||
n.ID, n.UserID, n.Type, payload,
|
||||
).Scan(&n.CreatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, userID string, limit int) ([]models.Notification, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 100
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT id, user_id, type, payload_json, read_at, created_at
|
||||
FROM notifications
|
||||
WHERE user_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2`, userID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.Notification{}
|
||||
for rows.Next() {
|
||||
var n models.Notification
|
||||
var payload []byte
|
||||
if err := rows.Scan(&n.ID, &n.UserID, &n.Type, &payload, &n.ReadAt, &n.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal(payload, &n.PayloadJSON)
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) MarkRead(ctx context.Context, id, userID string) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`UPDATE notifications SET read_at = now() WHERE id = $1 AND user_id = $2 AND read_at IS NULL`,
|
||||
id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT true FROM notifications WHERE id = $1 AND user_id = $2`, id, userID).Scan(&exists); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package photos
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
const maxUploadSize = 50 << 20
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
|
||||
var since *time.Time
|
||||
if raw := c.Query("since"); raw != "" {
|
||||
if t, err := time.Parse(time.RFC3339, raw); err == nil {
|
||||
since = &t
|
||||
} else if ms, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
||||
t := time.UnixMilli(ms)
|
||||
since = &t
|
||||
}
|
||||
}
|
||||
list, next, err := h.svc.List(c.Request.Context(), c.Param("id"), auth.UserID(c), c.Query("cursor"), since, limit)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"photos": list, "next_cursor": next})
|
||||
}
|
||||
|
||||
func (h *Handler) Upload(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxUploadSize)
|
||||
form, err := c.MultipartForm()
|
||||
if err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "expected multipart form"))
|
||||
return
|
||||
}
|
||||
files := form.File["files"]
|
||||
if len(files) == 0 {
|
||||
files = form.File["file"]
|
||||
}
|
||||
if len(files) == 0 {
|
||||
httpx.RespondError(c, httpx.BadRequest("no_files", "no files provided"))
|
||||
return
|
||||
}
|
||||
|
||||
created := make([]any, 0, len(files))
|
||||
for _, fh := range files {
|
||||
f, err := fh.Open()
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxUploadSize))
|
||||
f.Close()
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := h.svc.Upload(c.Request.Context(), UploadInput{
|
||||
AlbumID: c.Param("id"),
|
||||
UserID: auth.UserID(c),
|
||||
Filename: fh.Filename,
|
||||
MimeType: fh.Header.Get("Content-Type"),
|
||||
Data: data,
|
||||
})
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
created = append(created, p)
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"photos": created})
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
p, err := h.svc.Get(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"photo": p})
|
||||
}
|
||||
|
||||
func (h *Handler) Download(c *gin.Context) {
|
||||
url, err := h.svc.Download(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"url": url})
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
if err := h.svc.Delete(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package photos
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"time"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gen2brain/webp"
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
)
|
||||
|
||||
type ImageMeta struct {
|
||||
Width int
|
||||
Height int
|
||||
MimeType string
|
||||
TakenAt *time.Time
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
Thumb []byte
|
||||
Preview []byte
|
||||
}
|
||||
|
||||
func inspect(data []byte) (width, height int, ok bool) {
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
return cfg.Width, cfg.Height, true
|
||||
}
|
||||
|
||||
func extractEXIF(data []byte) (taken *time.Time, lat, lon *float64) {
|
||||
x, err := exif.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
if dt, err := x.Get(exif.DateTimeOriginal); err == nil {
|
||||
if s, err := dt.StringVal(); err == nil {
|
||||
if t, err := time.Parse("2006:01:02 15:04:05", s); err == nil {
|
||||
utc := t.UTC()
|
||||
taken = &utc
|
||||
}
|
||||
}
|
||||
}
|
||||
if la, lo, err := x.LatLong(); err == nil {
|
||||
lat, lon = &la, &lo
|
||||
}
|
||||
return taken, lat, lon
|
||||
}
|
||||
|
||||
func buildVariants(data []byte) (thumb, preview []byte, err error) {
|
||||
img, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
thumbImg := imaging.Fit(img, 200, 200, imaging.Lanczos)
|
||||
previewImg := imaging.Fit(img, 1200, 1200, imaging.Lanczos)
|
||||
|
||||
opts := webp.Options{Quality: 82}
|
||||
var thumbBuf bytes.Buffer
|
||||
if err := webp.Encode(&thumbBuf, thumbImg, opts); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var previewBuf bytes.Buffer
|
||||
if err := webp.Encode(&previewBuf, previewImg, opts); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return thumbBuf.Bytes(), previewBuf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package photos
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/roles"
|
||||
"shared-album/internal/sse"
|
||||
"shared-album/internal/storage"
|
||||
)
|
||||
|
||||
type AlbumAccess interface {
|
||||
Access(ctx context.Context, albumID, userID string) (*models.Album, string, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
albums AlbumAccess
|
||||
storage *storage.Client
|
||||
hub *sse.Hub
|
||||
}
|
||||
|
||||
func NewService(store *Store, albums AlbumAccess, storage *storage.Client, hub *sse.Hub) *Service {
|
||||
return &Service{store: store, albums: albums, storage: storage, hub: hub}
|
||||
}
|
||||
|
||||
type UploadInput struct {
|
||||
AlbumID string
|
||||
UserID string
|
||||
Filename string
|
||||
MimeType string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func (s *Service) Upload(ctx context.Context, in UploadInput) (*models.Photo, error) {
|
||||
_, role, err := s.albums.Access(ctx, in.AlbumID, in.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !roles.CanUpload(role) {
|
||||
return nil, httpx.Forbidden("forbidden", "you do not have permission to upload photos")
|
||||
}
|
||||
|
||||
mime := in.MimeType
|
||||
if mime == "" {
|
||||
mime = http.DetectContentType(in.Data)
|
||||
}
|
||||
if !strings.HasPrefix(mime, "image/") {
|
||||
return nil, httpx.BadRequest("invalid_file", "file is not an image")
|
||||
}
|
||||
|
||||
width, height, ok := inspect(in.Data)
|
||||
if !ok {
|
||||
return nil, httpx.BadRequest("invalid_image", "could not decode image")
|
||||
}
|
||||
taken, lat, lon := extractEXIF(in.Data)
|
||||
|
||||
id := auth.NewID()
|
||||
ext := strings.ToLower(filepath.Ext(in.Filename))
|
||||
if ext == "" {
|
||||
ext = ".bin"
|
||||
}
|
||||
storageKey := fmt.Sprintf("albums/%s/original/%s%s", in.AlbumID, id, ext)
|
||||
|
||||
if err := s.storage.Put(ctx, storageKey, bytes.NewReader(in.Data), int64(len(in.Data)), mime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := &models.Photo{
|
||||
ID: id,
|
||||
AlbumID: in.AlbumID,
|
||||
UploaderID: in.UserID,
|
||||
StorageKey: storageKey,
|
||||
OriginalFilename: in.Filename,
|
||||
Size: int64(len(in.Data)),
|
||||
Width: width,
|
||||
Height: height,
|
||||
MimeType: mime,
|
||||
TakenAt: taken,
|
||||
Latitude: lat,
|
||||
Longitude: lon,
|
||||
}
|
||||
if err := s.store.Create(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := in.Data
|
||||
go s.processVariants(p.ID, in.AlbumID, data)
|
||||
|
||||
if err := s.attachURLs(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Service) processVariants(photoID, albumID string, data []byte) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
thumb, preview, err := buildVariants(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
thumbKey := fmt.Sprintf("albums/%s/thumb/%s.webp", albumID, photoID)
|
||||
previewKey := fmt.Sprintf("albums/%s/preview/%s.webp", albumID, photoID)
|
||||
if err := s.storage.Put(ctx, thumbKey, bytes.NewReader(thumb), int64(len(thumb)), "image/webp"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := s.storage.Put(ctx, previewKey, bytes.NewReader(preview), int64(len(preview)), "image/webp"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := s.store.SetVariants(ctx, photoID, thumbKey, previewKey); err != nil {
|
||||
return
|
||||
}
|
||||
s.store.SetCover(ctx, albumID, photoID)
|
||||
if p, err := s.store.GetByID(ctx, photoID, ""); err == nil {
|
||||
if err := s.attachURLs(ctx, p); err == nil {
|
||||
s.hub.Publish(albumID, "photo.created", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) attachURLs(ctx context.Context, p *models.Photo) error {
|
||||
if p.StorageKey != "" {
|
||||
url, err := s.storage.PresignGet(ctx, p.StorageKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.OriginalURL = url
|
||||
p.DownloadURL = url
|
||||
}
|
||||
if p.ThumbKey != "" {
|
||||
if url, err := s.storage.PresignGet(ctx, p.ThumbKey); err == nil {
|
||||
p.ThumbURL = url
|
||||
}
|
||||
}
|
||||
if p.PreviewKey != "" {
|
||||
if url, err := s.storage.PresignGet(ctx, p.PreviewKey); err == nil {
|
||||
p.PreviewURL = url
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, albumID, userID, cursor string, since *time.Time, limit int) ([]models.Photo, string, error) {
|
||||
if _, _, err := s.albums.Access(ctx, albumID, userID); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
out, err := s.store.List(ctx, ListParams{
|
||||
AlbumID: albumID,
|
||||
Viewer: userID,
|
||||
Cursor: cursor,
|
||||
Since: since,
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for i := range out {
|
||||
_ = s.attachURLs(ctx, &out[i])
|
||||
}
|
||||
next := ""
|
||||
if since == nil && len(out) == limit && limit > 0 {
|
||||
next = out[len(out)-1].ID
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
// ListPublic lists photos for a share link (access already validated by token).
|
||||
func (s *Service) ListPublic(ctx context.Context, albumID, cursor string, since *time.Time, limit int) ([]models.Photo, string, error) {
|
||||
out, err := s.store.List(ctx, ListParams{
|
||||
AlbumID: albumID,
|
||||
Viewer: "",
|
||||
Cursor: cursor,
|
||||
Since: since,
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for i := range out {
|
||||
_ = s.attachURLs(ctx, &out[i])
|
||||
}
|
||||
next := ""
|
||||
if since == nil && len(out) == limit && limit > 0 {
|
||||
next = out[len(out)-1].ID
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
// GetPublic returns a single photo for a share link.
|
||||
func (s *Service) GetPublic(ctx context.Context, photoID string) (*models.Photo, error) {
|
||||
p, err := s.store.GetByID(ctx, photoID, "")
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := s.attachURLs(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// DownloadPublic returns a presigned original URL for a share link.
|
||||
func (s *Service) DownloadPublic(ctx context.Context, photoID string) (string, error) {
|
||||
p, err := s.GetPublic(ctx, photoID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.storage.PresignGet(ctx, p.StorageKey)
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, photoID, userID string) (*models.Photo, error) {
|
||||
p, err := s.store.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := s.albums.Access(ctx, p.AlbumID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.attachURLs(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Service) Download(ctx context.Context, photoID, userID string) (string, error) {
|
||||
p, err := s.Get(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
url, err := s.storage.PresignGet(ctx, p.StorageKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return url, nil
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, photoID, userID string) error {
|
||||
p, err := s.store.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
_, role, err := s.albums.Access(ctx, p.AlbumID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
own := p.UploaderID == userID
|
||||
if !(roles.CanDeleteAnyPhoto(role) || (own && roles.CanDeleteOwnPhoto(role))) {
|
||||
return httpx.Forbidden("forbidden", "you cannot delete this photo")
|
||||
}
|
||||
if err := s.store.Delete(ctx, photoID); err != nil {
|
||||
return err
|
||||
}
|
||||
keys := []string{p.StorageKey}
|
||||
if p.ThumbKey != "" {
|
||||
keys = append(keys, p.ThumbKey)
|
||||
}
|
||||
if p.PreviewKey != "" {
|
||||
keys = append(keys, p.PreviewKey)
|
||||
}
|
||||
_ = s.storage.Delete(ctx, keys...)
|
||||
s.hub.Publish(p.AlbumID, "photo.deleted", map[string]string{
|
||||
"id": p.ID, "album_id": p.AlbumID, "uploader_id": p.UploaderID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package photos
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("photo not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
const photoColumns = `p.id, p.album_id, p.uploader_id, p.storage_key,
|
||||
COALESCE(p.thumb_key, ''), COALESCE(p.preview_key, ''),
|
||||
p.original_filename, p.size, p.width, p.height, p.mime_type,
|
||||
p.taken_at, p.latitude, p.longitude, COALESCE(p.caption, ''), p.created_at,
|
||||
u.id, u.name, COALESCE(u.avatar_url, ''),
|
||||
(SELECT count(*) FROM likes l WHERE l.photo_id = p.id),
|
||||
(SELECT count(*) FROM comments c WHERE c.photo_id = p.id),
|
||||
EXISTS(SELECT 1 FROM likes l WHERE l.photo_id = p.id AND l.user_id = $2)`
|
||||
|
||||
func scanPhoto(row pgx.Row) (*models.Photo, error) {
|
||||
var p models.Photo
|
||||
err := row.Scan(&p.ID, &p.AlbumID, &p.UploaderID, &p.StorageKey,
|
||||
&p.ThumbKey, &p.PreviewKey,
|
||||
&p.OriginalFilename, &p.Size, &p.Width, &p.Height, &p.MimeType,
|
||||
&p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt,
|
||||
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
|
||||
&p.LikesCount, &p.CommentsCount, &p.LikedByMe)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, p *models.Photo) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO photos (id, album_id, uploader_id, storage_key, original_filename,
|
||||
size, width, height, mime_type, taken_at, latitude, longitude, caption)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
RETURNING created_at`,
|
||||
p.ID, p.AlbumID, p.UploaderID, p.StorageKey, p.OriginalFilename,
|
||||
p.Size, p.Width, p.Height, p.MimeType, p.TakenAt, p.Latitude, p.Longitude, p.Caption,
|
||||
).Scan(&p.CreatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) SetVariants(ctx context.Context, id, thumbKey, previewKey string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`UPDATE photos SET thumb_key = $2, preview_key = $3 WHERE id = $1`, id, thumbKey, previewKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) GetByID(ctx context.Context, id, viewerID string) (*models.Photo, error) {
|
||||
return scanPhoto(s.pool.QueryRow(ctx,
|
||||
`SELECT `+photoColumns+`
|
||||
FROM photos p JOIN users u ON u.id = p.uploader_id
|
||||
WHERE p.id = $1`, id, viewerID))
|
||||
}
|
||||
|
||||
type ListParams struct {
|
||||
AlbumID string
|
||||
Viewer string
|
||||
Cursor string
|
||||
Since *time.Time
|
||||
Limit int
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, in ListParams) ([]models.Photo, error) {
|
||||
if in.Limit <= 0 || in.Limit > 100 {
|
||||
in.Limit = 50
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT `+photoColumns+`
|
||||
FROM photos p JOIN users u ON u.id = p.uploader_id
|
||||
WHERE p.album_id = $1
|
||||
AND ($3 = '' OR (p.created_at, p.id) < (SELECT created_at, id FROM photos WHERE id = $3))
|
||||
AND ($4::timestamptz IS NULL OR p.created_at > $4)
|
||||
ORDER BY p.created_at DESC, p.id DESC
|
||||
LIMIT $5`,
|
||||
in.AlbumID, in.Viewer, in.Cursor, in.Since, in.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.Photo{}
|
||||
for rows.Next() {
|
||||
var p models.Photo
|
||||
if err := rows.Scan(&p.ID, &p.AlbumID, &p.UploaderID, &p.StorageKey,
|
||||
&p.ThumbKey, &p.PreviewKey,
|
||||
&p.OriginalFilename, &p.Size, &p.Width, &p.Height, &p.MimeType,
|
||||
&p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt,
|
||||
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
|
||||
&p.LikesCount, &p.CommentsCount, &p.LikedByMe); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, id string) error {
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM photos WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) SetCover(ctx context.Context, albumID, photoID string) {
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE albums SET cover_photo_id = $2 WHERE id = $1`, albumID, photoID)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package repo_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/albums"
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/members"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/sharelinks"
|
||||
)
|
||||
|
||||
func testPool(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not set")
|
||||
}
|
||||
pool, err := pgxpool.New(context.Background(), dsn)
|
||||
if err != nil {
|
||||
t.Skipf("cannot connect: %v", err)
|
||||
}
|
||||
if err := pool.Ping(context.Background()); err != nil {
|
||||
t.Skipf("cannot ping: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
func newUser(t *testing.T, ctx context.Context, pool *pgxpool.Pool, name string) *models.User {
|
||||
t.Helper()
|
||||
u := &models.User{
|
||||
ID: auth.NewID(),
|
||||
Email: auth.NewID()[:8] + "@test.local",
|
||||
PasswordHash: "x",
|
||||
Name: name,
|
||||
}
|
||||
if err := auth.NewStore(pool).CreateUser(ctx, u); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func TestUserRepository(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
defer pool.Close()
|
||||
ctx := context.Background()
|
||||
store := auth.NewStore(pool)
|
||||
|
||||
u := newUser(t, ctx, pool, "Tester")
|
||||
t.Cleanup(func() { _, _ = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, u.ID) })
|
||||
|
||||
got, err := store.GetUserByEmail(ctx, u.Email)
|
||||
if err != nil || got.ID != u.ID {
|
||||
t.Fatalf("get by email: %v id=%v", err, got)
|
||||
}
|
||||
if _, err := store.GetUserByID(ctx, u.ID); err != nil {
|
||||
t.Fatalf("get by id: %v", err)
|
||||
}
|
||||
|
||||
tok := &models.RefreshToken{ID: auth.NewID(), UserID: u.ID, TokenHash: auth.HashRefreshToken("abc"), ExpiresAt: time.Now().Add(time.Hour)}
|
||||
if err := store.CreateRefreshToken(ctx, tok); err != nil {
|
||||
t.Fatalf("create refresh: %v", err)
|
||||
}
|
||||
fetched, err := store.GetRefreshToken(ctx, auth.HashRefreshToken("abc"))
|
||||
if err != nil || fetched.ID != tok.ID {
|
||||
t.Fatalf("get refresh: %v", err)
|
||||
}
|
||||
if err := store.RevokeRefreshToken(ctx, tok.ID); err != nil {
|
||||
t.Fatalf("revoke: %v", err)
|
||||
}
|
||||
fetched, _ = store.GetRefreshToken(ctx, auth.HashRefreshToken("abc"))
|
||||
if fetched.RevokedAt == nil {
|
||||
t.Fatalf("refresh not revoked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlbumRepository(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
defer pool.Close()
|
||||
ctx := context.Background()
|
||||
store := albums.NewStore(pool)
|
||||
|
||||
owner := newUser(t, ctx, pool, "Owner")
|
||||
t.Cleanup(func() { _, _ = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, owner.ID) })
|
||||
|
||||
a := &models.Album{ID: auth.NewID(), OwnerID: owner.ID, Title: "Trip", Description: "d"}
|
||||
if err := store.Create(ctx, a); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
|
||||
got, err := store.GetByID(ctx, a.ID)
|
||||
if err != nil || got.Title != "Trip" {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if ownerID, err := store.OwnerID(ctx, a.ID); err != nil || ownerID != owner.ID {
|
||||
t.Fatalf("owner id: %v %v", ownerID, err)
|
||||
}
|
||||
|
||||
list, err := store.ListForUser(ctx, owner.ID)
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("list: %v len=%d", err, len(list))
|
||||
}
|
||||
|
||||
a.Title = "Renamed"
|
||||
if err := store.Update(ctx, a); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
got, _ = store.GetByID(ctx, a.ID)
|
||||
if got.Title != "Renamed" {
|
||||
t.Fatalf("update not applied")
|
||||
}
|
||||
|
||||
if err := store.Delete(ctx, a.ID); err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if _, err := store.GetByID(ctx, a.ID); err != albums.ErrNotFound {
|
||||
t.Fatalf("expected not found after delete, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemberRepository(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
defer pool.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
owner := newUser(t, ctx, pool, "Owner")
|
||||
member := newUser(t, ctx, pool, "Member")
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM users WHERE id IN ($1, $2)`, owner.ID, member.ID)
|
||||
})
|
||||
|
||||
albumStore := albums.NewStore(pool)
|
||||
a := &models.Album{ID: auth.NewID(), OwnerID: owner.ID, Title: "A"}
|
||||
if err := albumStore.Create(ctx, a); err != nil {
|
||||
t.Fatalf("create album: %v", err)
|
||||
}
|
||||
|
||||
store := members.NewStore(pool)
|
||||
if err := store.Add(ctx, a.ID, member.ID, "member", &owner.ID); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
role, err := store.Role(ctx, a.ID, member.ID)
|
||||
if err != nil || role != "member" {
|
||||
t.Fatalf("role: %v %q", err, role)
|
||||
}
|
||||
|
||||
list, err := store.List(ctx, a.ID)
|
||||
if err != nil || len(list) != 1 || list[0].User.Name != "Member" {
|
||||
t.Fatalf("list members: %v %+v", err, list)
|
||||
}
|
||||
|
||||
if err := store.UpdateRole(ctx, a.ID, member.ID, "editor"); err != nil {
|
||||
t.Fatalf("update role: %v", err)
|
||||
}
|
||||
role, _ = store.Role(ctx, a.ID, member.ID)
|
||||
if role != "editor" {
|
||||
t.Fatalf("role not updated: %q", role)
|
||||
}
|
||||
|
||||
inv := &models.Invite{ID: auth.NewID(), AlbumID: a.ID, Token: auth.NewID(), Role: "viewer", CreatedBy: owner.ID, ExpiresAt: time.Now().Add(time.Hour), MaxUses: 2}
|
||||
if err := store.CreateInvite(ctx, inv); err != nil {
|
||||
t.Fatalf("create invite: %v", err)
|
||||
}
|
||||
got, err := store.GetInviteByToken(ctx, inv.Token)
|
||||
if err != nil || got.Role != "viewer" || got.MaxUses != 2 {
|
||||
t.Fatalf("get invite: %v %+v", err, got)
|
||||
}
|
||||
if err := store.IncrementUses(ctx, inv.ID); err != nil {
|
||||
t.Fatalf("increment: %v", err)
|
||||
}
|
||||
got, _ = store.GetInviteByToken(ctx, inv.Token)
|
||||
if got.Uses != 1 {
|
||||
t.Fatalf("uses not incremented: %d", got.Uses)
|
||||
}
|
||||
|
||||
if err := store.Remove(ctx, a.ID, member.ID); err != nil {
|
||||
t.Fatalf("remove: %v", err)
|
||||
}
|
||||
role, _ = store.Role(ctx, a.ID, member.ID)
|
||||
if role != "" {
|
||||
t.Fatalf("member not removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareLinkRepository(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
defer pool.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
owner := newUser(t, ctx, pool, "Owner")
|
||||
t.Cleanup(func() { _, _ = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, owner.ID) })
|
||||
|
||||
albumsStore := albums.NewStore(pool)
|
||||
a := &models.Album{ID: auth.NewID(), OwnerID: owner.ID, Title: "A"}
|
||||
if err := albumsStore.Create(ctx, a); err != nil {
|
||||
t.Fatalf("create album: %v", err)
|
||||
}
|
||||
|
||||
store := sharelinks.NewStore(pool)
|
||||
l := &models.ShareLink{ID: auth.NewID(), AlbumID: a.ID, Token: auth.NewID(), CreatedBy: owner.ID, ExpiresAt: time.Now().Add(time.Hour)}
|
||||
if err := store.Create(ctx, l); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
got, err := store.GetByToken(ctx, l.Token)
|
||||
if err != nil || !got.Active(time.Now()) {
|
||||
t.Fatalf("get token: %v", err)
|
||||
}
|
||||
links, err := store.ListByAlbum(ctx, a.ID)
|
||||
if err != nil || len(links) != 1 {
|
||||
t.Fatalf("list: %v len=%d", err, len(links))
|
||||
}
|
||||
if err := store.Revoke(ctx, l.ID, a.ID); err != nil {
|
||||
t.Fatalf("revoke: %v", err)
|
||||
}
|
||||
got, _ = store.GetByToken(ctx, l.Token)
|
||||
if got.Active(time.Now()) {
|
||||
t.Fatalf("link still active after revoke")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package roles
|
||||
|
||||
const (
|
||||
Owner = "owner"
|
||||
Admin = "admin"
|
||||
Editor = "editor"
|
||||
Member = "member"
|
||||
Viewer = "viewer"
|
||||
)
|
||||
|
||||
var rank = map[string]int{
|
||||
Viewer: 0,
|
||||
Member: 1,
|
||||
Editor: 2,
|
||||
Admin: 3,
|
||||
Owner: 4,
|
||||
}
|
||||
|
||||
func Rank(r string) int { return rank[r] }
|
||||
|
||||
func ValidMemberRole(r string) bool {
|
||||
switch r {
|
||||
case Admin, Editor, Member, Viewer:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func CanUpload(r string) bool {
|
||||
switch r {
|
||||
case Owner, Admin, Editor, Member:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func CanComment(r string) bool {
|
||||
return CanUpload(r)
|
||||
}
|
||||
|
||||
func CanDeleteAnyPhoto(r string) bool {
|
||||
return r == Owner || r == Admin
|
||||
}
|
||||
|
||||
func CanDeleteOwnPhoto(r string) bool {
|
||||
return CanUpload(r)
|
||||
}
|
||||
|
||||
func CanEditAlbum(r string) bool {
|
||||
return r == Owner || r == Admin
|
||||
}
|
||||
|
||||
func CanManageShares(r string) bool {
|
||||
return r == Owner || r == Admin
|
||||
}
|
||||
|
||||
func CanInvite(actorRole, targetRole string) bool {
|
||||
if actorRole == Editor {
|
||||
return targetRole == Member || targetRole == Viewer
|
||||
}
|
||||
if actorRole != Owner && actorRole != Admin {
|
||||
return false
|
||||
}
|
||||
if targetRole == Owner {
|
||||
return false
|
||||
}
|
||||
return Rank(targetRole) <= Rank(actorRole)
|
||||
}
|
||||
|
||||
func CanChangeRole(actorRole, targetCurrent, newRole string) bool {
|
||||
if targetCurrent == Owner || newRole == Owner {
|
||||
return false
|
||||
}
|
||||
if !ValidMemberRole(newRole) {
|
||||
return false
|
||||
}
|
||||
switch actorRole {
|
||||
case Owner:
|
||||
return true
|
||||
case Admin:
|
||||
if targetCurrent == Admin {
|
||||
return false
|
||||
}
|
||||
return newRole == Editor || newRole == Member || newRole == Viewer
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func CanRemoveMember(actorRole, targetRole string) bool {
|
||||
if actorRole != Owner && actorRole != Admin {
|
||||
return false
|
||||
}
|
||||
if targetRole == Owner || targetRole == Admin {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package sharelinks
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
type createRequest struct {
|
||||
ExpiresIn string `json:"expires_in"`
|
||||
}
|
||||
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var req createRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
var ttl time.Duration
|
||||
if req.ExpiresIn != "" {
|
||||
d, err := time.ParseDuration(req.ExpiresIn)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_expires_in", "invalid expires_in duration"))
|
||||
return
|
||||
}
|
||||
ttl = d
|
||||
}
|
||||
link, err := h.svc.Create(c.Request.Context(), c.Param("id"), auth.UserID(c), ttl)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"share_link": link})
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
list, err := h.svc.List(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"share_links": list})
|
||||
}
|
||||
|
||||
func (h *Handler) Revoke(c *gin.Context) {
|
||||
if err := h.svc.Revoke(c.Request.Context(), c.Param("id"), c.Param("link_id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package sharelinks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/roles"
|
||||
)
|
||||
|
||||
type AlbumAccess interface {
|
||||
Access(ctx context.Context, albumID, userID string) (*models.Album, string, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
albums AlbumAccess
|
||||
}
|
||||
|
||||
func NewService(store *Store, albums AlbumAccess) *Service {
|
||||
return &Service{store: store, albums: albums}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, albumID, actorID string, ttl time.Duration) (*models.ShareLink, error) {
|
||||
_, role, err := s.albums.Access(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !roles.CanManageShares(role) {
|
||||
return nil, httpx.Forbidden("forbidden", "only owner and admin can manage share links")
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = 7 * 24 * time.Hour
|
||||
}
|
||||
token, _, err := auth.NewRefreshToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := &models.ShareLink{
|
||||
ID: auth.NewID(),
|
||||
AlbumID: albumID,
|
||||
Token: token,
|
||||
CreatedBy: actorID,
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
if err := s.store.Create(ctx, l); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, albumID, actorID string) ([]models.ShareLink, error) {
|
||||
_, role, err := s.albums.Access(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !roles.CanManageShares(role) {
|
||||
return nil, httpx.Forbidden("forbidden", "only owner and admin can manage share links")
|
||||
}
|
||||
return s.store.ListByAlbum(ctx, albumID)
|
||||
}
|
||||
|
||||
func (s *Service) Revoke(ctx context.Context, albumID, linkID, actorID string) error {
|
||||
_, role, err := s.albums.Access(ctx, albumID, actorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !roles.CanManageShares(role) {
|
||||
return httpx.Forbidden("forbidden", "only owner and admin can manage share links")
|
||||
}
|
||||
if err := s.store.Revoke(ctx, linkID, albumID); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("share_link_not_found", "share link not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Resolve(ctx context.Context, token string) (*models.ShareLink, error) {
|
||||
l, err := s.store.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("share_link_not_found", "share link not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !l.Active(time.Now()) {
|
||||
return nil, httpx.Forbidden("share_link_inactive", "share link is expired or revoked")
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package sharelinks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Create(ctx context.Context, l *models.ShareLink) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO share_links (id, album_id, token, created_by, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING created_at`,
|
||||
l.ID, l.AlbumID, l.Token, l.CreatedBy, l.ExpiresAt,
|
||||
).Scan(&l.CreatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) ListByAlbum(ctx context.Context, albumID string) ([]models.ShareLink, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT id, album_id, token, created_by, created_at, expires_at, revoked_at
|
||||
FROM share_links WHERE album_id = $1 ORDER BY created_at DESC`, albumID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.ShareLink{}
|
||||
for rows.Next() {
|
||||
var l models.ShareLink
|
||||
if err := rows.Scan(&l.ID, &l.AlbumID, &l.Token, &l.CreatedBy, &l.CreatedAt, &l.ExpiresAt, &l.RevokedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) GetByToken(ctx context.Context, token string) (*models.ShareLink, error) {
|
||||
var l models.ShareLink
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, album_id, token, created_by, created_at, expires_at, revoked_at
|
||||
FROM share_links WHERE token = $1`, token).
|
||||
Scan(&l.ID, &l.AlbumID, &l.Token, &l.CreatedBy, &l.CreatedAt, &l.ExpiresAt, &l.RevokedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
func (s *Store) Revoke(ctx context.Context, id, albumID string) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`UPDATE share_links SET revoked_at = now() WHERE id = $1 AND album_id = $2 AND revoked_at IS NULL`,
|
||||
id, albumID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
|
||||
|
||||
func (h *Handler) AddLike(c *gin.Context) {
|
||||
if err := h.svc.AddLike(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) RemoveLike(c *gin.Context) {
|
||||
if err := h.svc.RemoveLike(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) ListComments(c *gin.Context) {
|
||||
list, err := h.svc.ListComments(c.Request.Context(), c.Param("id"), auth.UserID(c))
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"comments": list})
|
||||
}
|
||||
|
||||
type commentRequest struct {
|
||||
Text string `json:"text" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *Handler) AddComment(c *gin.Context) {
|
||||
var req commentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httpx.RespondError(c, httpx.BadRequest("invalid_request", "text is required"))
|
||||
return
|
||||
}
|
||||
comment, err := h.svc.AddComment(c.Request.Context(), c.Param("id"), auth.UserID(c), req.Text)
|
||||
if err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"comment": comment})
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteComment(c *gin.Context) {
|
||||
if err := h.svc.DeleteComment(c.Request.Context(), c.Param("id"), auth.UserID(c)); err != nil {
|
||||
httpx.RespondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"shared-album/internal/auth"
|
||||
"shared-album/internal/httpx"
|
||||
"shared-album/internal/models"
|
||||
"shared-album/internal/roles"
|
||||
"shared-album/internal/sse"
|
||||
)
|
||||
|
||||
type AlbumAccess interface {
|
||||
Access(ctx context.Context, albumID, userID string) (*models.Album, string, error)
|
||||
}
|
||||
|
||||
type PhotoLookup interface {
|
||||
GetByID(ctx context.Context, id, viewerID string) (*models.Photo, error)
|
||||
}
|
||||
|
||||
type Notifier interface {
|
||||
Create(ctx context.Context, userID, typ string, payload map[string]any) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *Store
|
||||
albums AlbumAccess
|
||||
photos PhotoLookup
|
||||
hub *sse.Hub
|
||||
notify Notifier
|
||||
}
|
||||
|
||||
func NewService(store *Store, albums AlbumAccess, photos PhotoLookup, hub *sse.Hub, notify Notifier) *Service {
|
||||
return &Service{store: store, albums: albums, photos: photos, hub: hub, notify: notify}
|
||||
}
|
||||
|
||||
func (s *Service) requireComment(ctx context.Context, photo *models.Photo, userID string) (string, error) {
|
||||
_, role, err := s.albums.Access(ctx, photo.AlbumID, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !roles.CanComment(role) {
|
||||
return "", httpx.Forbidden("forbidden", "you do not have permission to interact with photos")
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
func (s *Service) AddLike(ctx context.Context, photoID, userID string) error {
|
||||
photo, err := s.photos.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if _, err := s.requireComment(ctx, photo, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.store.Like(ctx, photoID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
s.hub.Publish(photo.AlbumID, "like.added", map[string]string{
|
||||
"photo_id": photoID, "album_id": photo.AlbumID, "user_id": userID,
|
||||
})
|
||||
if s.notify != nil && photo.UploaderID != userID {
|
||||
_ = s.notify.Create(ctx, photo.UploaderID, "like.added", map[string]any{
|
||||
"photo_id": photoID, "album_id": photo.AlbumID, "user_id": userID,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) RemoveLike(ctx context.Context, photoID, userID string) error {
|
||||
photo, err := s.photos.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if _, err := s.requireComment(ctx, photo, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.store.Unlike(ctx, photoID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
s.hub.Publish(photo.AlbumID, "like.removed", map[string]string{
|
||||
"photo_id": photoID, "album_id": photo.AlbumID, "user_id": userID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) AddComment(ctx context.Context, photoID, userID, text string) (*models.Comment, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil, httpx.BadRequest("invalid_text", "comment text is required")
|
||||
}
|
||||
photo, err := s.photos.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.requireComment(ctx, photo, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &models.Comment{
|
||||
ID: auth.NewID(),
|
||||
PhotoID: photoID,
|
||||
UserID: userID,
|
||||
Text: text,
|
||||
}
|
||||
if err := s.store.CreateComment(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list, err := s.store.ListComments(ctx, photoID)
|
||||
if err == nil {
|
||||
for _, item := range list {
|
||||
if item.ID == c.ID {
|
||||
c.User = item.User
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
s.hub.Publish(photo.AlbumID, "comment.created", c)
|
||||
if s.notify != nil && photo.UploaderID != userID {
|
||||
_ = s.notify.Create(ctx, photo.UploaderID, "comment.created", map[string]any{
|
||||
"photo_id": photoID, "album_id": photo.AlbumID, "user_id": userID, "comment_id": c.ID,
|
||||
})
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Service) ListComments(ctx context.Context, photoID, userID string) ([]models.Comment, error) {
|
||||
photo, err := s.photos.GetByID(ctx, photoID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, httpx.NotFound("photo_not_found", "photo not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := s.albums.Access(ctx, photo.AlbumID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.store.ListComments(ctx, photoID)
|
||||
}
|
||||
|
||||
func (s *Service) DeleteComment(ctx context.Context, commentID, userID string) error {
|
||||
c, err := s.store.GetComment(ctx, commentID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return httpx.NotFound("comment_not_found", "comment not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
photo, err := s.photos.GetByID(ctx, c.PhotoID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, role, err := s.albums.Access(ctx, photo.AlbumID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.UserID != userID && !roles.CanDeleteAnyPhoto(role) {
|
||||
return httpx.Forbidden("forbidden", "you cannot delete this comment")
|
||||
}
|
||||
return s.store.DeleteComment(ctx, commentID)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shared-album/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Like(ctx context.Context, photoID, userID string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO likes (photo_id, user_id) VALUES ($1, $2)
|
||||
ON CONFLICT (photo_id, user_id) DO NOTHING`, photoID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Unlike(ctx context.Context, photoID, userID string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM likes WHERE photo_id = $1 AND user_id = $2`, photoID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) CreateComment(ctx context.Context, c *models.Comment) error {
|
||||
return s.pool.QueryRow(ctx,
|
||||
`INSERT INTO comments (id, photo_id, user_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at, updated_at`,
|
||||
c.ID, c.PhotoID, c.UserID, c.Text,
|
||||
).Scan(&c.CreatedAt, &c.UpdatedAt)
|
||||
}
|
||||
|
||||
func (s *Store) ListComments(ctx context.Context, photoID string) ([]models.Comment, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT c.id, c.photo_id, c.user_id, c.text, c.created_at, c.updated_at,
|
||||
u.id, u.name, COALESCE(u.avatar_url, '')
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.user_id
|
||||
WHERE c.photo_id = $1
|
||||
ORDER BY c.created_at`, photoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []models.Comment{}
|
||||
for rows.Next() {
|
||||
var c models.Comment
|
||||
if err := rows.Scan(&c.ID, &c.PhotoID, &c.UserID, &c.Text, &c.CreatedAt, &c.UpdatedAt,
|
||||
&c.User.ID, &c.User.Name, &c.User.AvatarURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) GetComment(ctx context.Context, id string) (*models.Comment, error) {
|
||||
var c models.Comment
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, photo_id, user_id, text, created_at, updated_at FROM comments WHERE id = $1`, id).
|
||||
Scan(&c.ID, &c.PhotoID, &c.UserID, &c.Text, &c.CreatedAt, &c.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteComment(ctx context.Context, id string) error {
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM comments WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package sse
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
Type string
|
||||
Data any
|
||||
}
|
||||
|
||||
type subscriber struct {
|
||||
ch chan Event
|
||||
closed bool
|
||||
}
|
||||
|
||||
type Subscription struct {
|
||||
hub *Hub
|
||||
key string
|
||||
personal bool
|
||||
sub *subscriber
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (s *Subscription) Events() <-chan Event { return s.sub.ch }
|
||||
|
||||
func (s *Subscription) Close() {
|
||||
s.once.Do(func() {
|
||||
if s.personal {
|
||||
s.hub.unsubscribeUser(s.key, s.sub)
|
||||
} else {
|
||||
s.hub.unsubscribeAlbum(s.key, s.sub)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
mu sync.RWMutex
|
||||
albums map[string]map[*subscriber]struct{}
|
||||
users map[string]map[*subscriber]struct{}
|
||||
buffer int
|
||||
}
|
||||
|
||||
func NewHub(buffer int) *Hub {
|
||||
if buffer <= 0 {
|
||||
buffer = 64
|
||||
}
|
||||
return &Hub{
|
||||
albums: make(map[string]map[*subscriber]struct{}),
|
||||
users: make(map[string]map[*subscriber]struct{}),
|
||||
buffer: buffer,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) SubscribeAlbum(albumID string) *Subscription {
|
||||
sub := &subscriber{ch: make(chan Event, h.buffer)}
|
||||
h.mu.Lock()
|
||||
if h.albums[albumID] == nil {
|
||||
h.albums[albumID] = make(map[*subscriber]struct{})
|
||||
}
|
||||
h.albums[albumID][sub] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
return &Subscription{hub: h, key: albumID, sub: sub}
|
||||
}
|
||||
|
||||
func (h *Hub) SubscribeUser(userID string) *Subscription {
|
||||
sub := &subscriber{ch: make(chan Event, h.buffer)}
|
||||
h.mu.Lock()
|
||||
if h.users[userID] == nil {
|
||||
h.users[userID] = make(map[*subscriber]struct{})
|
||||
}
|
||||
h.users[userID][sub] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
return &Subscription{hub: h, key: userID, personal: true, sub: sub}
|
||||
}
|
||||
|
||||
func (h *Hub) Publish(albumID, eventType string, data any) {
|
||||
if albumID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
h.broadcast(h.albums[albumID], Event{Type: eventType, Data: data})
|
||||
}
|
||||
|
||||
func (h *Hub) PublishUser(userID, eventType string, data any) {
|
||||
if userID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
h.broadcast(h.users[userID], Event{Type: eventType, Data: data})
|
||||
}
|
||||
|
||||
func (h *Hub) broadcast(subs map[*subscriber]struct{}, ev Event) {
|
||||
for sub := range subs {
|
||||
if sub.closed {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case sub.ch <- ev:
|
||||
default:
|
||||
// slow client: drop it (backpressure)
|
||||
sub.closed = true
|
||||
close(sub.ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) unsubscribeAlbum(albumID string, sub *subscriber) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if subs, ok := h.albums[albumID]; ok {
|
||||
delete(subs, sub)
|
||||
if len(subs) == 0 {
|
||||
delete(h.albums, albumID)
|
||||
}
|
||||
}
|
||||
closeIfOpen(sub)
|
||||
}
|
||||
|
||||
func (h *Hub) unsubscribeUser(userID string, sub *subscriber) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if subs, ok := h.users[userID]; ok {
|
||||
delete(subs, sub)
|
||||
if len(subs) == 0 {
|
||||
delete(h.users, userID)
|
||||
}
|
||||
}
|
||||
closeIfOpen(sub)
|
||||
}
|
||||
|
||||
func closeIfOpen(sub *subscriber) {
|
||||
if !sub.closed {
|
||||
sub.closed = true
|
||||
close(sub.ch)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package sse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Serve(c *gin.Context, sub *Subscription, heartbeat time.Duration) {
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
c.Writer.Header().Set("Cache-Control", "no-cache")
|
||||
c.Writer.Header().Set("Connection", "keep-alive")
|
||||
c.Writer.Header().Set("X-Accel-Buffering", "no")
|
||||
c.Writer.WriteHeader(http.StatusOK)
|
||||
|
||||
flusher, ok := c.Writer.(http.Flusher)
|
||||
if !ok {
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(c.Writer, ": connected\n\n")
|
||||
flusher.Flush()
|
||||
|
||||
if heartbeat <= 0 {
|
||||
heartbeat = 25 * time.Second
|
||||
}
|
||||
ticker := time.NewTicker(heartbeat)
|
||||
defer ticker.Stop()
|
||||
|
||||
ctx := c.Request.Context()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ev, ok := <-sub.Events():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(ev.Data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", ev.Type, payload)
|
||||
flusher.Flush()
|
||||
case <-ticker.C:
|
||||
fmt.Fprint(c.Writer, ": heartbeat\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awsconfig "github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
|
||||
"shared-album/internal/config"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
s3 *s3.Client
|
||||
presign *s3.PresignClient
|
||||
bucket string
|
||||
presignTTL time.Duration
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.S3) (*Client, error) {
|
||||
awsCfg, err := awsconfig.LoadDefaultConfig(ctx,
|
||||
awsconfig.WithRegion(cfg.Region),
|
||||
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
||||
cfg.AccessKey, cfg.SecretKey, "",
|
||||
)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load aws config: %w", err)
|
||||
}
|
||||
|
||||
client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(cfg.Endpoint)
|
||||
o.UsePathStyle = cfg.UsePathStyle
|
||||
})
|
||||
|
||||
return &Client{
|
||||
s3: client,
|
||||
presign: s3.NewPresignClient(client),
|
||||
bucket: cfg.Bucket,
|
||||
presignTTL: cfg.PresignTTL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Bucket() string { return c.bucket }
|
||||
|
||||
func (c *Client) EnsureBucket(ctx context.Context) error {
|
||||
_, err := c.s3.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(c.bucket)})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var nf *types.NotFound
|
||||
if !errors.As(err, &nf) && !isNoSuchBucket(err) {
|
||||
return fmt.Errorf("head bucket: %w", err)
|
||||
}
|
||||
if _, err := c.s3.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(c.bucket)}); err != nil {
|
||||
return fmt.Errorf("create bucket: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
_, err := c.s3.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(c.bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
|
||||
in := &s3.PutObjectInput{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentType: aws.String(contentType),
|
||||
}
|
||||
if size >= 0 {
|
||||
in.ContentLength = aws.Int64(size)
|
||||
}
|
||||
if _, err := c.s3.PutObject(ctx, in); err != nil {
|
||||
return fmt.Errorf("put object %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Delete(ctx context.Context, keys ...string) error {
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
objs := make([]types.ObjectIdentifier, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
objs = append(objs, types.ObjectIdentifier{Key: aws.String(k)})
|
||||
}
|
||||
if _, err := c.s3.DeleteObjects(ctx, &s3.DeleteObjectsInput{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Delete: &types.Delete{Objects: objs, Quiet: aws.Bool(true)},
|
||||
}); err != nil {
|
||||
return fmt.Errorf("delete objects: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) DeletePrefix(ctx context.Context, prefix string) error {
|
||||
var keys []string
|
||||
paginator := s3.NewListObjectsV2Paginator(c.s3, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
})
|
||||
for paginator.HasMorePages() {
|
||||
page, err := paginator.NextPage(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list objects: %w", err)
|
||||
}
|
||||
for _, o := range page.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
}
|
||||
return c.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
func (c *Client) PresignGet(ctx context.Context, key string) (string, error) {
|
||||
out, err := c.presign.PresignGetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Key: aws.String(key),
|
||||
}, s3.WithPresignExpires(c.presignTTL))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("presign %s: %w", key, err)
|
||||
}
|
||||
return out.URL, nil
|
||||
}
|
||||
|
||||
func isNoSuchBucket(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
code := apiErr.ErrorCode()
|
||||
return strings.EqualFold(code, "NoSuchBucket") || strings.EqualFold(code, "NotFound")
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
DROP TABLE IF EXISTS refresh_tokens;
|
||||
DROP TABLE IF EXISTS share_links;
|
||||
DROP TABLE IF EXISTS notifications;
|
||||
DROP TABLE IF EXISTS likes;
|
||||
DROP TABLE IF EXISTS comments;
|
||||
DROP TABLE IF EXISTS photos;
|
||||
DROP TABLE IF EXISTS invites;
|
||||
DROP TABLE IF EXISTS album_members;
|
||||
DROP TABLE IF EXISTS albums;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,110 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id text PRIMARY KEY,
|
||||
email text NOT NULL UNIQUE,
|
||||
password_hash text NOT NULL,
|
||||
name text NOT NULL,
|
||||
avatar_url text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS albums (
|
||||
id text PRIMARY KEY,
|
||||
owner_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
title text NOT NULL,
|
||||
description text NOT NULL DEFAULT '',
|
||||
cover_photo_id text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS album_members (
|
||||
album_id text NOT NULL REFERENCES albums(id) ON DELETE CASCADE,
|
||||
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
invited_by text REFERENCES users(id) ON DELETE SET NULL,
|
||||
joined_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (album_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
id text PRIMARY KEY,
|
||||
album_id text NOT NULL REFERENCES albums(id) ON DELETE CASCADE,
|
||||
token text NOT NULL UNIQUE,
|
||||
role text NOT NULL,
|
||||
created_by text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
max_uses integer NOT NULL DEFAULT 1,
|
||||
uses integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS photos (
|
||||
id text PRIMARY KEY,
|
||||
album_id text NOT NULL REFERENCES albums(id) ON DELETE CASCADE,
|
||||
uploader_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
storage_key text NOT NULL,
|
||||
thumb_key text,
|
||||
preview_key text,
|
||||
original_filename text NOT NULL DEFAULT '',
|
||||
size bigint NOT NULL DEFAULT 0,
|
||||
width integer NOT NULL DEFAULT 0,
|
||||
height integer NOT NULL DEFAULT 0,
|
||||
mime_type text NOT NULL DEFAULT '',
|
||||
taken_at timestamptz,
|
||||
latitude double precision,
|
||||
longitude double precision,
|
||||
caption text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS photos_album_created_idx ON photos (album_id, created_at DESC, id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id text PRIMARY KEY,
|
||||
photo_id text NOT NULL REFERENCES photos(id) ON DELETE CASCADE,
|
||||
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS comments_photo_idx ON comments (photo_id, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS likes (
|
||||
photo_id text NOT NULL REFERENCES photos(id) ON DELETE CASCADE,
|
||||
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (photo_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id text PRIMARY KEY,
|
||||
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
type text NOT NULL,
|
||||
payload_json jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
read_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS notifications_user_idx ON notifications (user_id, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS share_links (
|
||||
id text PRIMARY KEY,
|
||||
album_id text NOT NULL REFERENCES albums(id) ON DELETE CASCADE,
|
||||
token text NOT NULL UNIQUE,
|
||||
created_by text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||
id text PRIMARY KEY,
|
||||
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash text NOT NULL UNIQUE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS refresh_tokens_user_idx ON refresh_tokens (user_id);
|
||||
@@ -0,0 +1,32 @@
|
||||
# Пример nginx-конфигурации перед Go-бэкендом.
|
||||
# Для SSE критично proxy_buffering off, иначе события буферизуются и не доходят.
|
||||
|
||||
upstream shared_album {
|
||||
server 127.0.0.1:8080;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name album.example.com;
|
||||
|
||||
client_max_body_size 60m;
|
||||
|
||||
location /api/sse/ {
|
||||
proxy_pass http://shared_album;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_buffering off; # иначе SSE буферизуется
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 1h;
|
||||
chunked_transfer_encoding on;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://shared_album;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=Shared Album backend
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=album
|
||||
Group=album
|
||||
WorkingDirectory=/opt/shared-album
|
||||
EnvironmentFile=/opt/shared-album/.env
|
||||
ExecStart=/opt/shared-album/shared-album
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
|
||||
# Безопасность
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/opt/shared-album
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Generated
+2020
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "shared-album-frontend",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-static": "^3.0.6",
|
||||
"@sveltejs/kit": "^2.8.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^4.0.0",
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"svelte": "^5.1.0",
|
||||
"svelte-check": "^4.1.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
@import 'tailwindcss';
|
||||
@config '../tailwind.config.ts';
|
||||
|
||||
/* Светлая */
|
||||
:root,
|
||||
[data-theme='light'] {
|
||||
--bg: 0 0% 100%;
|
||||
--bg-elevated: 0 0% 98%;
|
||||
--bg-muted: 0 0% 95%;
|
||||
--border: 0 0% 88%;
|
||||
--text: 0 0% 9%;
|
||||
--text-muted: 0 0% 45%;
|
||||
--text-subtle: 0 0% 60%;
|
||||
--primary: 221 83% 53%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 84% 60%;
|
||||
--success: 142 71% 45%;
|
||||
--shadow: 0 0% 0% / 0.08;
|
||||
}
|
||||
|
||||
/* Тёмная */
|
||||
[data-theme='dark'] {
|
||||
--bg: 0 0% 7%;
|
||||
--bg-elevated: 0 0% 11%;
|
||||
--bg-muted: 0 0% 16%;
|
||||
--border: 0 0% 22%;
|
||||
--text: 0 0% 96%;
|
||||
--text-muted: 0 0% 65%;
|
||||
--text-subtle: 0 0% 45%;
|
||||
--primary: 217 91% 60%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 84% 65%;
|
||||
--success: 142 65% 50%;
|
||||
--shadow: 0 0% 0% / 0.4;
|
||||
}
|
||||
|
||||
/* Нейтральная (тёплая серо-бежевая) */
|
||||
[data-theme='neutral'] {
|
||||
--bg: 40 20% 96%;
|
||||
--bg-elevated: 40 22% 92%;
|
||||
--bg-muted: 40 18% 87%;
|
||||
--border: 40 14% 78%;
|
||||
--text: 30 10% 15%;
|
||||
--text-muted: 30 8% 40%;
|
||||
--text-subtle: 30 6% 55%;
|
||||
--primary: 25 90% 50%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 72% 55%;
|
||||
--success: 142 55% 42%;
|
||||
--shadow: 30 20% 20% / 0.12;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: hsl(var(--bg));
|
||||
color: hsl(var(--text));
|
||||
transition:
|
||||
background-color 200ms ease,
|
||||
color 200ms ease;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html,
|
||||
body {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!doctype html>
|
||||
<html lang="ru" data-theme="light">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
var stored = localStorage.getItem('theme') || 'system';
|
||||
var resolved = stored;
|
||||
if (stored === 'system') {
|
||||
resolved = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
}
|
||||
document.documentElement.setAttribute('data-theme', resolved);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,101 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { auth, type Tokens, type User } from './stores/auth.svelte';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string;
|
||||
constructor(status: number, code: string, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
form?: FormData;
|
||||
}
|
||||
|
||||
let refreshing: Promise<boolean> | null = null;
|
||||
|
||||
async function raw(path: string, opts: RequestOptions): Promise<Response> {
|
||||
const headers = new Headers();
|
||||
if (auth.access) headers.set('Authorization', `Bearer ${auth.access}`);
|
||||
let body: BodyInit | undefined;
|
||||
if (opts.form) {
|
||||
body = opts.form;
|
||||
} else if (opts.body !== undefined) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
body = JSON.stringify(opts.body);
|
||||
}
|
||||
return fetch(`/api${path}`, { method: opts.method ?? 'GET', headers, body });
|
||||
}
|
||||
|
||||
async function doRefresh(): Promise<boolean> {
|
||||
if (!auth.refresh) return false;
|
||||
try {
|
||||
const res = await fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: auth.refresh })
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json();
|
||||
auth.setTokens(data.tokens as Tokens);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, opts: RequestOptions = {}): Promise<T> {
|
||||
let res = await raw(path, opts);
|
||||
if (res.status === 401 && auth.refresh) {
|
||||
if (!refreshing) {
|
||||
refreshing = doRefresh().finally(() => {
|
||||
refreshing = null;
|
||||
});
|
||||
}
|
||||
const ok = await refreshing;
|
||||
if (ok) res = await raw(path, opts);
|
||||
}
|
||||
if (!res.ok) {
|
||||
let code = 'error';
|
||||
let message = res.statusText;
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body?.error) {
|
||||
code = body.error.code ?? code;
|
||||
message = body.error.message ?? message;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (res.status === 401) {
|
||||
auth.clear();
|
||||
goto('/login');
|
||||
}
|
||||
throw new ApiError(res.status, code, message);
|
||||
}
|
||||
if (res.status === 204) return null as T;
|
||||
const ct = res.headers.get('content-type') ?? '';
|
||||
if (ct.includes('application/json')) return (await res.json()) as T;
|
||||
return (await res.text()) as unknown as T;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
register: (email: string, password: string, name: string) =>
|
||||
api<{ user: User; tokens: Tokens }>('/auth/register', {
|
||||
method: 'POST',
|
||||
body: { email, password, name }
|
||||
}),
|
||||
login: (email: string, password: string) =>
|
||||
api<{ user: User; tokens: Tokens }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { email, password }
|
||||
}),
|
||||
logout: (refresh_token: string) =>
|
||||
api('/auth/logout', { method: 'POST', body: { refresh_token } }),
|
||||
me: () => api<{ user: User }>('/auth/me')
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Comment } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
photoId: string;
|
||||
}
|
||||
|
||||
let { photoId }: Props = $props();
|
||||
|
||||
let comments = $state<Comment[]>([]);
|
||||
let text = $state('');
|
||||
let error = $state('');
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api<{ comments: Comment[] }>(`/photos/${photoId}/comments`);
|
||||
comments = data.comments;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
photoId;
|
||||
load();
|
||||
});
|
||||
|
||||
async function submit(ev: Event) {
|
||||
ev.preventDefault();
|
||||
if (!text.trim()) return;
|
||||
try {
|
||||
const data = await api<{ comment: Comment }>(`/photos/${photoId}/comments`, {
|
||||
method: 'POST',
|
||||
body: { text }
|
||||
});
|
||||
comments = [...comments, data.comment];
|
||||
text = '';
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: string) {
|
||||
try {
|
||||
await api(`/comments/${id}`, { method: 'DELETE' });
|
||||
comments = comments.filter((c) => c.id !== id);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mt-2">
|
||||
{#each comments as comment (comment.id)}
|
||||
<div class="border-border mb-1 flex items-start justify-between gap-2 border-b py-1 text-sm">
|
||||
<span class="text-text">
|
||||
<strong>{comment.user.name}</strong>: {comment.text}
|
||||
</span>
|
||||
{#if auth.user?.id === comment.user_id}
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-subtle hover:text-danger text-xs"
|
||||
onclick={() => remove(comment.id)}>удалить</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if auth.isAuthenticated}
|
||||
<form class="mt-2 flex gap-2" onsubmit={submit}>
|
||||
<input
|
||||
bind:value={text}
|
||||
placeholder="Комментарий…"
|
||||
class="border-border bg-bg text-text flex-1 rounded-lg border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-3 py-1.5 text-sm" type="submit"
|
||||
>Отправить</button
|
||||
>
|
||||
</form>
|
||||
{/if}
|
||||
{#if error}
|
||||
<p class="text-danger mt-1 text-xs">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,110 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import type { Photo } from '$lib/types';
|
||||
import Comments from './Comments.svelte';
|
||||
|
||||
interface Props {
|
||||
photos: Photo[];
|
||||
index: number;
|
||||
onClose: () => void;
|
||||
onIndexChange: (index: number) => void;
|
||||
}
|
||||
|
||||
let { photos, index, onClose, onIndexChange }: Props = $props();
|
||||
|
||||
let fresh = $state<Photo | null>(null);
|
||||
let touchX = 0;
|
||||
|
||||
const current = $derived(photos[index]);
|
||||
|
||||
$effect(() => {
|
||||
const id = current?.id;
|
||||
fresh = null;
|
||||
if (!id) return;
|
||||
api<{ photo: Photo }>(`/photos/${id}`)
|
||||
.then((data) => (fresh = data.photo))
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
function prev() {
|
||||
if (index > 0) onIndexChange(index - 1);
|
||||
}
|
||||
function next() {
|
||||
if (index < photos.length - 1) onIndexChange(index + 1);
|
||||
}
|
||||
|
||||
function onKey(ev: KeyboardEvent) {
|
||||
if (ev.key === 'Escape') onClose();
|
||||
if (ev.key === 'ArrowLeft') prev();
|
||||
if (ev.key === 'ArrowRight') next();
|
||||
}
|
||||
|
||||
function onTouchStart(ev: TouchEvent) {
|
||||
touchX = ev.changedTouches[0].clientX;
|
||||
}
|
||||
function onTouchEnd(ev: TouchEvent) {
|
||||
const dx = ev.changedTouches[0].clientX - touchX;
|
||||
if (dx > 50) prev();
|
||||
else if (dx < -50) next();
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKey} />
|
||||
|
||||
<div
|
||||
class="bg-bg/95 fixed inset-0 z-50 flex flex-col"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
ontouchstart={onTouchStart}
|
||||
ontouchend={onTouchEnd}
|
||||
>
|
||||
<div class="flex items-center justify-between p-3">
|
||||
<span class="text-text-muted text-sm">{index + 1} / {photos.length}</span>
|
||||
<div class="flex gap-2">
|
||||
{#if fresh?.download_url}
|
||||
<a
|
||||
href={fresh.download_url}
|
||||
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm"
|
||||
target="_blank"
|
||||
rel="noreferrer">Скачать</a
|
||||
>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={onClose}
|
||||
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm">✕</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center justify-center overflow-hidden px-2 pb-2">
|
||||
<button type="button" class="text-text-muted px-2 text-3xl" onclick={prev} disabled={index === 0}
|
||||
>‹</button
|
||||
>
|
||||
{#if current}
|
||||
<img
|
||||
src={fresh?.preview_url ?? fresh?.original_url ?? current.preview_url ?? current.original_url}
|
||||
alt={current.original_filename}
|
||||
class="max-h-[75vh] max-w-full rounded-lg object-contain"
|
||||
/>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-muted px-2 text-3xl"
|
||||
onclick={next}
|
||||
disabled={index === photos.length - 1}>›</button
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if current}
|
||||
<div class="border-border bg-bg-elevated max-h-56 overflow-y-auto border-t p-3">
|
||||
<p class="text-text text-sm">
|
||||
{current.uploader.name} · {current.original_filename}
|
||||
</p>
|
||||
<Comments photoId={current.id} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,45 @@
|
||||
<script lang="ts">
|
||||
import type { Photo } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
photos: Photo[];
|
||||
onOpen?: (index: number) => void;
|
||||
}
|
||||
|
||||
let { photos, onOpen }: Props = $props();
|
||||
</script>
|
||||
|
||||
{#if photos.length === 0}
|
||||
<p class="text-text-muted p-8 text-center">Пока нет фотографий.</p>
|
||||
{:else}
|
||||
<ul class="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
||||
{#each photos as photo, i (photo.id)}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
class="border-border bg-bg-muted group relative block aspect-square w-full overflow-hidden rounded-lg border"
|
||||
onclick={() => onOpen?.(i)}
|
||||
>
|
||||
{#if photo.thumb_url}
|
||||
<img
|
||||
src={photo.thumb_url}
|
||||
alt={photo.original_filename}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
class="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
|
||||
/>
|
||||
{:else}
|
||||
<span class="text-text-subtle flex h-full w-full items-center justify-center text-xs">
|
||||
обработка…
|
||||
</span>
|
||||
{/if}
|
||||
<span
|
||||
class="bg-bg/70 text-text absolute right-1 bottom-1 rounded px-1.5 py-0.5 text-xs"
|
||||
>
|
||||
♥ {photo.likes_count} · 💬 {photo.comments_count}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
@@ -0,0 +1,27 @@
|
||||
<script lang="ts">
|
||||
import { theme, type Theme } from '$lib/stores/theme.svelte';
|
||||
|
||||
const options: { value: Theme; label: string; icon: string }[] = [
|
||||
{ value: 'light', label: 'Light', icon: '☀️' },
|
||||
{ value: 'dark', label: 'Dark', icon: '🌙' },
|
||||
{ value: 'neutral', label: 'Neutral', icon: '🌾' },
|
||||
{ value: 'system', label: 'System', icon: '💻' }
|
||||
];
|
||||
</script>
|
||||
|
||||
<div class="border-border bg-bg-elevated inline-flex gap-1 rounded-lg border p-1" role="group" aria-label="Theme">
|
||||
{#each options as option (option.value)}
|
||||
<button
|
||||
type="button"
|
||||
title={option.label}
|
||||
aria-label={option.label}
|
||||
aria-pressed={theme.current === option.value}
|
||||
onclick={() => theme.set(option.value)}
|
||||
class="rounded-md px-2 py-1 text-sm transition-colors {theme.current === option.value
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-text-muted hover:bg-bg-muted'}"
|
||||
>
|
||||
{option.icon}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -0,0 +1,117 @@
|
||||
<script lang="ts">
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Photo } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
albumId: string;
|
||||
onUploaded?: (photos: Photo[]) => void;
|
||||
}
|
||||
|
||||
let { albumId, onUploaded }: Props = $props();
|
||||
|
||||
let dragging = $state(false);
|
||||
let progress = $state(0);
|
||||
let busy = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
function pick() {
|
||||
fileInput?.click();
|
||||
}
|
||||
|
||||
let fileInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
function onDrop(ev: DragEvent) {
|
||||
ev.preventDefault();
|
||||
dragging = false;
|
||||
if (ev.dataTransfer?.files?.length) {
|
||||
upload(ev.dataTransfer.files);
|
||||
}
|
||||
}
|
||||
|
||||
function onChange(ev: Event) {
|
||||
const target = ev.target as HTMLInputElement;
|
||||
if (target.files?.length) upload(target.files);
|
||||
target.value = '';
|
||||
}
|
||||
|
||||
function upload(files: FileList) {
|
||||
error = '';
|
||||
busy = true;
|
||||
progress = 0;
|
||||
const form = new FormData();
|
||||
for (const file of Array.from(files)) {
|
||||
form.append('files', file);
|
||||
}
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', `/api/albums/${albumId}/photos`);
|
||||
if (auth.access) xhr.setRequestHeader('Authorization', `Bearer ${auth.access}`);
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) progress = Math.round((e.loaded / e.total) * 100);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
busy = false;
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
onUploaded?.(data.photos ?? []);
|
||||
} catch {
|
||||
onUploaded?.([]);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
error = JSON.parse(xhr.responseText)?.error?.message ?? 'Ошибка загрузки';
|
||||
} catch {
|
||||
error = 'Ошибка загрузки';
|
||||
}
|
||||
}
|
||||
};
|
||||
xhr.onerror = () => {
|
||||
busy = false;
|
||||
error = 'Сетевая ошибка';
|
||||
};
|
||||
xhr.send(form);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="border-border rounded-xl border-2 border-dashed p-6 text-center transition-colors {dragging
|
||||
? 'bg-bg-muted border-primary'
|
||||
: 'bg-bg-elevated'}"
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
dragging = true;
|
||||
}}
|
||||
ondragleave={() => (dragging = false)}
|
||||
ondrop={onDrop}
|
||||
ondragenter={(e) => e.preventDefault()}
|
||||
role="region"
|
||||
aria-label="Загрузка фотографий"
|
||||
>
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
class="hidden"
|
||||
onchange={onChange}
|
||||
/>
|
||||
<p class="text-text mb-3 text-sm">Перетащите фото сюда или</p>
|
||||
<button
|
||||
type="button"
|
||||
onclick={pick}
|
||||
disabled={busy}
|
||||
class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{busy ? 'Загрузка…' : 'Выбрать файлы'}
|
||||
</button>
|
||||
|
||||
{#if busy}
|
||||
<div class="bg-bg-muted mt-4 h-2 w-full overflow-hidden rounded">
|
||||
<div class="bg-primary h-full transition-all" style="width: {progress}%"></div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if error}
|
||||
<p class="text-danger mt-3 text-sm">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,77 @@
|
||||
export interface SSEEvent {
|
||||
type: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface SSEClientOptions {
|
||||
path: string;
|
||||
onEvent: (event: SSEEvent) => void;
|
||||
onReconnect?: () => void;
|
||||
}
|
||||
|
||||
// Wrapper над EventSource с экспоненциальным backoff и догоном через REST.
|
||||
export class SSEClient {
|
||||
private es: EventSource | null = null;
|
||||
private stopped = false;
|
||||
private attempt = 0;
|
||||
private readonly knownEvents = [
|
||||
'photo.created',
|
||||
'photo.deleted',
|
||||
'comment.created',
|
||||
'like.added',
|
||||
'like.removed',
|
||||
'member.joined',
|
||||
'member.left',
|
||||
'member.updated',
|
||||
'album.updated',
|
||||
'album.deleted',
|
||||
'notification'
|
||||
];
|
||||
|
||||
constructor(private opts: SSEClientOptions) {}
|
||||
|
||||
connect(token: string) {
|
||||
this.stopped = false;
|
||||
this.open(token);
|
||||
}
|
||||
|
||||
private open(token: string) {
|
||||
if (this.stopped) return;
|
||||
const url = `${this.opts.path}?token=${encodeURIComponent(token)}`;
|
||||
this.es = new EventSource(url);
|
||||
|
||||
this.es.onopen = () => {
|
||||
if (this.attempt > 0) {
|
||||
this.opts.onReconnect?.();
|
||||
}
|
||||
this.attempt = 0;
|
||||
};
|
||||
|
||||
for (const name of this.knownEvents) {
|
||||
this.es.addEventListener(name, (ev) => {
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = JSON.parse((ev as MessageEvent).data);
|
||||
} catch {
|
||||
data = (ev as MessageEvent).data;
|
||||
}
|
||||
this.opts.onEvent({ type: name, data });
|
||||
});
|
||||
}
|
||||
|
||||
this.es.onerror = () => {
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
if (this.stopped) return;
|
||||
const delay = Math.min(1000 * 2 ** this.attempt, 30000);
|
||||
this.attempt += 1;
|
||||
setTimeout(() => this.open(token), delay);
|
||||
};
|
||||
}
|
||||
|
||||
close() {
|
||||
this.stopped = true;
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
export interface Tokens {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
const ACCESS_KEY = 'galo.access';
|
||||
const REFRESH_KEY = 'galo.refresh';
|
||||
const USER_KEY = 'galo.user';
|
||||
|
||||
class AuthStore {
|
||||
access = $state<string | null>(null);
|
||||
refresh = $state<string | null>(null);
|
||||
user = $state<User | null>(null);
|
||||
|
||||
constructor() {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
this.access = localStorage.getItem(ACCESS_KEY);
|
||||
this.refresh = localStorage.getItem(REFRESH_KEY);
|
||||
const raw = localStorage.getItem(USER_KEY);
|
||||
if (raw) {
|
||||
try {
|
||||
this.user = JSON.parse(raw);
|
||||
} catch {
|
||||
this.user = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get isAuthenticated(): boolean {
|
||||
return !!this.access;
|
||||
}
|
||||
|
||||
setTokens(tokens: Tokens) {
|
||||
this.access = tokens.access_token;
|
||||
this.refresh = tokens.refresh_token;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(ACCESS_KEY, tokens.access_token);
|
||||
localStorage.setItem(REFRESH_KEY, tokens.refresh_token);
|
||||
}
|
||||
}
|
||||
|
||||
setUser(user: User) {
|
||||
this.user = user;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
}
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.access = null;
|
||||
this.refresh = null;
|
||||
this.user = null;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const auth = new AuthStore();
|
||||
@@ -0,0 +1,44 @@
|
||||
export type Theme = 'light' | 'dark' | 'neutral' | 'system';
|
||||
type Resolved = 'light' | 'dark' | 'neutral';
|
||||
|
||||
const KEY = 'theme';
|
||||
|
||||
function resolve(theme: Theme): Resolved {
|
||||
if (theme === 'system') {
|
||||
if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
return 'dark';
|
||||
}
|
||||
return 'light';
|
||||
}
|
||||
return theme;
|
||||
}
|
||||
|
||||
class ThemeStore {
|
||||
current = $state<Theme>('system');
|
||||
resolved = $state<Resolved>('light');
|
||||
private media: MediaQueryList | null = null;
|
||||
|
||||
init() {
|
||||
if (typeof window === 'undefined') return;
|
||||
const stored = (localStorage.getItem(KEY) as Theme | null) ?? 'system';
|
||||
this.current = stored;
|
||||
this.apply();
|
||||
this.media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
this.media.addEventListener('change', () => {
|
||||
if (this.current === 'system') this.apply();
|
||||
});
|
||||
}
|
||||
|
||||
set(theme: Theme) {
|
||||
this.current = theme;
|
||||
localStorage.setItem(KEY, theme);
|
||||
this.apply();
|
||||
}
|
||||
|
||||
private apply() {
|
||||
this.resolved = resolve(this.current);
|
||||
document.documentElement.setAttribute('data-theme', this.resolved);
|
||||
}
|
||||
}
|
||||
|
||||
export const theme = new ThemeStore();
|
||||
@@ -0,0 +1,88 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email?: string;
|
||||
name: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
export interface Album {
|
||||
id: string;
|
||||
owner_id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
cover_photo_id?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AlbumMember {
|
||||
album_id: string;
|
||||
user_id: string;
|
||||
role: string;
|
||||
joined_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface Photo {
|
||||
id: string;
|
||||
album_id: string;
|
||||
uploader_id: string;
|
||||
original_filename: string;
|
||||
size: number;
|
||||
width: number;
|
||||
height: number;
|
||||
mime_type: string;
|
||||
taken_at?: string | null;
|
||||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
caption: string;
|
||||
created_at: string;
|
||||
uploader: User;
|
||||
likes_count: number;
|
||||
comments_count: number;
|
||||
liked_by_me: boolean;
|
||||
thumb_url?: string;
|
||||
preview_url?: string;
|
||||
original_url?: string;
|
||||
download_url?: string;
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: string;
|
||||
photo_id: string;
|
||||
user_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface Invite {
|
||||
id: string;
|
||||
album_id: string;
|
||||
token: string;
|
||||
role: string;
|
||||
expires_at: string;
|
||||
max_uses: number;
|
||||
uses: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ShareLink {
|
||||
id: string;
|
||||
album_id: string;
|
||||
token: string;
|
||||
created_by: string;
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
revoked_at?: string | null;
|
||||
}
|
||||
|
||||
export interface Notification {
|
||||
id: string;
|
||||
user_id: string;
|
||||
type: string;
|
||||
payload: Record<string, unknown>;
|
||||
read_at?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import '../app.css';
|
||||
import ThemeSwitcher from '$lib/components/ThemeSwitcher.svelte';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import { theme } from '$lib/stores/theme.svelte';
|
||||
import { authApi } from '$lib/api';
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
onMount(() => {
|
||||
theme.init();
|
||||
if (auth.isAuthenticated && !auth.user) {
|
||||
authApi
|
||||
.me()
|
||||
.then((data) => auth.setUser(data.user))
|
||||
.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
async function logout() {
|
||||
if (auth.refresh) {
|
||||
await authApi.logout(auth.refresh).catch(() => {});
|
||||
}
|
||||
auth.clear();
|
||||
goto('/login');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="bg-bg text-text min-h-screen">
|
||||
<header class="border-border bg-bg-elevated border-b">
|
||||
<div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-3">
|
||||
<a href="/" class="text-lg font-semibold">📷 Galo</a>
|
||||
<div class="flex items-center gap-3">
|
||||
{#if auth.isAuthenticated}
|
||||
<span class="text-text-muted hidden text-sm sm:inline">{auth.user?.name ?? ''}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-muted hover:text-text text-sm"
|
||||
onclick={logout}>Выйти</button
|
||||
>
|
||||
{:else}
|
||||
<a href="/login" class="text-text-muted hover:text-text text-sm">Войти</a>
|
||||
{/if}
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="mx-auto max-w-6xl px-4 py-6">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
@@ -0,0 +1,2 @@
|
||||
export const ssr = false;
|
||||
export const prerender = false;
|
||||
@@ -0,0 +1,91 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Album } from '$lib/types';
|
||||
|
||||
let albums = $state<Album[]>([]);
|
||||
let loading = $state(true);
|
||||
let title = $state('');
|
||||
let error = $state('');
|
||||
|
||||
async function load() {
|
||||
if (!auth.isAuthenticated) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await api<{ albums: Album[] }>('/albums');
|
||||
albums = data.albums;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function create(ev: Event) {
|
||||
ev.preventDefault();
|
||||
if (!title.trim()) return;
|
||||
try {
|
||||
const data = await api<{ album: Album }>('/albums', {
|
||||
method: 'POST',
|
||||
body: { title }
|
||||
});
|
||||
albums = [data.album, ...albums];
|
||||
title = '';
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !auth.isAuthenticated}
|
||||
<div class="py-16 text-center">
|
||||
<h1 class="mb-2 text-2xl font-bold">Общие фотоальбомы</h1>
|
||||
<p class="text-text-muted mb-6">Войдите, чтобы создавать альбомы и делиться фотографиями.</p>
|
||||
<a href="/login" class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium">Войти</a>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="mb-6 flex items-center justify-between gap-4">
|
||||
<h1 class="text-2xl font-bold">Мои альбомы</h1>
|
||||
<form class="flex gap-2" onsubmit={create}>
|
||||
<input
|
||||
bind:value={title}
|
||||
placeholder="Название альбома"
|
||||
class="border-border bg-bg-elevated text-text rounded-lg border px-3 py-2 text-sm"
|
||||
/>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать</button
|
||||
>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
{#if loading}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{:else if albums.length === 0}
|
||||
<p class="text-text-muted">Альбомов пока нет. Создайте первый.</p>
|
||||
{:else}
|
||||
<ul class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{#each albums as album (album.id)}
|
||||
<li>
|
||||
<a
|
||||
href="/albums/{album.id}"
|
||||
class="border-border bg-bg-elevated hover:border-primary block overflow-hidden rounded-xl border transition-colors"
|
||||
>
|
||||
<div class="bg-bg-muted flex aspect-video items-center justify-center text-4xl">🖼️</div>
|
||||
<div class="p-4">
|
||||
<h2 class="text-text font-semibold">{album.title}</h2>
|
||||
<p class="text-text-muted line-clamp-2 text-sm">{album.description}</p>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -0,0 +1,176 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import PhotoGrid from '$lib/components/PhotoGrid.svelte';
|
||||
import Lightbox from '$lib/components/Lightbox.svelte';
|
||||
import Uploader from '$lib/components/Uploader.svelte';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import { SSEClient, type SSEEvent } from '$lib/sse';
|
||||
import type { Album, Photo } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let role = $state('');
|
||||
let photos = $state<Photo[]>([]);
|
||||
let nextCursor = $state('');
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let lightboxIndex = $state(-1);
|
||||
|
||||
let canUpload = $derived(['owner', 'admin', 'editor', 'member'].includes(role));
|
||||
|
||||
async function loadAlbum() {
|
||||
const data = await api<{ album: Album; role: string }>(`/albums/${albumId}`);
|
||||
album = data.album;
|
||||
role = data.role;
|
||||
}
|
||||
|
||||
async function loadPhotos() {
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/albums/${albumId}/photos`
|
||||
);
|
||||
photos = data.photos;
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!nextCursor) return;
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/albums/${albumId}/photos?cursor=${encodeURIComponent(nextCursor)}`
|
||||
);
|
||||
photos = [...photos, ...data.photos];
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const id = albumId;
|
||||
loading = true;
|
||||
error = '';
|
||||
Promise.all([loadAlbum(), loadPhotos()])
|
||||
.catch((e) => (error = (e as Error).message))
|
||||
.finally(() => (loading = false));
|
||||
});
|
||||
|
||||
let client: SSEClient | null = null;
|
||||
|
||||
$effect(() => {
|
||||
const id = albumId;
|
||||
if (!auth.access) return;
|
||||
client = new SSEClient({
|
||||
path: `/api/sse/albums/${id}`,
|
||||
onEvent: handleEvent,
|
||||
onReconnect: () => loadPhotos()
|
||||
});
|
||||
client.connect(auth.access);
|
||||
return () => {
|
||||
client?.close();
|
||||
client = null;
|
||||
};
|
||||
});
|
||||
|
||||
function handleEvent(ev: SSEEvent) {
|
||||
const data = ev.data as Record<string, unknown>;
|
||||
switch (ev.type) {
|
||||
case 'photo.created': {
|
||||
const photo = data as unknown as Photo;
|
||||
if (photos.some((p) => p.id === photo.id)) {
|
||||
photos = photos.map((p) => (p.id === photo.id ? photo : p));
|
||||
} else {
|
||||
photos = [photo, ...photos];
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'photo.deleted': {
|
||||
photos = photos.filter((p) => p.id !== data.id);
|
||||
break;
|
||||
}
|
||||
case 'like.added': {
|
||||
photos = photos.map((p) =>
|
||||
p.id === data.photo_id
|
||||
? { ...p, likes_count: p.likes_count + 1, liked_by_me: data.user_id === auth.user?.id || p.liked_by_me }
|
||||
: p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'like.removed': {
|
||||
photos = photos.map((p) =>
|
||||
p.id === data.photo_id
|
||||
? { ...p, likes_count: Math.max(0, p.likes_count - 1), liked_by_me: false }
|
||||
: p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'comment.created': {
|
||||
const comment = data as unknown as { photo_id: string };
|
||||
photos = photos.map((p) =>
|
||||
p.id === comment.photo_id ? { ...p, comments_count: p.comments_count + 1 } : p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'album.updated': {
|
||||
loadAlbum().catch(() => {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if loading}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{:else if error}
|
||||
<p class="text-danger">{error}</p>
|
||||
{:else if album}
|
||||
<div class="mb-6 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold">{album.title}</h1>
|
||||
<p class="text-text-muted">{album.description}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<a
|
||||
href="/albums/{albumId}/members"
|
||||
class="border-border text-text rounded-lg border px-3 py-2 text-sm">Участники</a
|
||||
>
|
||||
{#if role === 'owner' || role === 'admin'}
|
||||
<a
|
||||
href="/albums/{albumId}/settings"
|
||||
class="border-border text-text rounded-lg border px-3 py-2 text-sm">Настройки</a
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if canUpload}
|
||||
<div class="mb-6">
|
||||
<Uploader
|
||||
{albumId}
|
||||
onUploaded={(created) => {
|
||||
for (const p of created) {
|
||||
if (!photos.some((x) => x.id === p.id)) photos = [p, ...photos];
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<PhotoGrid {photos} onOpen={(i) => (lightboxIndex = i)} />
|
||||
|
||||
{#if nextCursor}
|
||||
<div class="mt-6 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="border-border text-text rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={loadMore}>Показать ещё</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if lightboxIndex >= 0}
|
||||
<Lightbox
|
||||
{photos}
|
||||
index={lightboxIndex}
|
||||
onClose={() => (lightboxIndex = -1)}
|
||||
onIndexChange={(i) => (lightboxIndex = i)}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Album, AlbumMember } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let members = $state<AlbumMember[]>([]);
|
||||
let role = $state('');
|
||||
let inviteRole = $state('member');
|
||||
let inviteUses = $state(1);
|
||||
let inviteExpires = $state('168h');
|
||||
let inviteUrl = $state('');
|
||||
let error = $state('');
|
||||
|
||||
const assignableRoles = $derived(
|
||||
role === 'owner'
|
||||
? ['admin', 'editor', 'member', 'viewer']
|
||||
: role === 'admin'
|
||||
? ['editor', 'member', 'viewer']
|
||||
: []
|
||||
);
|
||||
const inviteRoles = $derived(role === 'owner' ? ['admin', 'editor', 'member', 'viewer'] : ['member', 'viewer']);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [membersData, albumData] = await Promise.all([
|
||||
api<{ members: AlbumMember[] }>(`/albums/${albumId}/members`),
|
||||
api<{ album: Album; role: string }>(`/albums/${albumId}`)
|
||||
]);
|
||||
members = membersData.members;
|
||||
role = albumData.role;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function invite(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
try {
|
||||
const data = await api<{ invite: { token: string } }>(`/albums/${albumId}/invites`, {
|
||||
method: 'POST',
|
||||
body: { role: inviteRole, expires_in: inviteExpires, max_uses: inviteUses }
|
||||
});
|
||||
inviteUrl = `${location.origin}/invites/${data.invite.token}`;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function changeRole(userId: string, newRole: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/members/${userId}`, {
|
||||
method: 'PATCH',
|
||||
body: { role: newRole }
|
||||
});
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMember(userId: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/members/${userId}`, { method: 'DELETE' });
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mb-6 flex items-center justify-between">
|
||||
<h1 class="text-2xl font-bold">Участники</h1>
|
||||
<a href="/albums/{albumId}" class="text-primary text-sm">← К альбому</a>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
<ul class="mb-8 divide-y divide-border border-border rounded-xl border">
|
||||
<li class="bg-bg-muted flex items-center justify-between px-4 py-3">
|
||||
<span class="font-medium">Владелец</span>
|
||||
</li>
|
||||
{#each members as member (member.user_id)}
|
||||
<li class="flex items-center justify-between gap-4 px-4 py-3">
|
||||
<span class="text-text"
|
||||
>{member.user.name} <span class="text-text-muted text-sm">({member.user.email})</span></span
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
{#if assignableRoles.length > 0}
|
||||
<select
|
||||
value={member.role}
|
||||
onchange={(e) => changeRole(member.user_id, e.currentTarget.value)}
|
||||
class="border-border bg-bg-elevated text-text rounded-lg border px-2 py-1 text-sm"
|
||||
>
|
||||
{#each Array.from(new Set([member.role, ...assignableRoles])) as r}
|
||||
<option value={r}>{r}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
class="text-danger text-sm"
|
||||
onclick={() => removeMember(member.user_id)}>Удалить</button
|
||||
>
|
||||
{:else}
|
||||
<span class="text-text-muted text-sm">{member.role}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if assignableRoles.length > 0}
|
||||
<form class="border-border bg-bg-elevated space-y-3 rounded-xl border p-4" onsubmit={invite}>
|
||||
<h2 class="font-semibold">Пригласить</h2>
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Роль</span>
|
||||
<select
|
||||
bind:value={inviteRole}
|
||||
class="border-border bg-bg text-text rounded-lg border px-2 py-1.5"
|
||||
>
|
||||
{#each inviteRoles as r}
|
||||
<option value={r}>{r}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Использований</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
bind:value={inviteUses}
|
||||
class="border-border bg-bg text-text w-24 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Срок</span>
|
||||
<input
|
||||
bind:value={inviteExpires}
|
||||
class="border-border bg-bg text-text w-32 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать ссылку</button
|
||||
>
|
||||
{#if inviteUrl}
|
||||
<p class="text-text-muted break-all text-sm">Ссылка: <a class="text-primary" href={inviteUrl}>{inviteUrl}</a></p>
|
||||
{/if}
|
||||
</form>
|
||||
{/if}
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { api } from '$lib/api';
|
||||
import type { Album, ShareLink } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let shareLinks = $state<ShareLink[]>([]);
|
||||
let title = $state('');
|
||||
let description = $state('');
|
||||
let expiresIn = $state('168h');
|
||||
let error = $state('');
|
||||
let saved = $state(false);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [albumData, linksData] = await Promise.all([
|
||||
api<{ album: Album }>(`/albums/${albumId}`),
|
||||
api<{ share_links: ShareLink[] }>(`/albums/${albumId}/share`)
|
||||
]);
|
||||
album = albumData.album;
|
||||
title = album.title;
|
||||
description = album.description;
|
||||
shareLinks = linksData.share_links;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function save(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
saved = false;
|
||||
try {
|
||||
const data = await api<{ album: Album }>(`/albums/${albumId}`, {
|
||||
method: 'PATCH',
|
||||
body: { title, description }
|
||||
});
|
||||
album = data.album;
|
||||
saved = true;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function createLink(ev: Event) {
|
||||
ev.preventDefault();
|
||||
try {
|
||||
await api(`/albums/${albumId}/share`, { method: 'POST', body: { expires_in: expiresIn } });
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(id: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/share/${id}`, { method: 'DELETE' });
|
||||
shareLinks = shareLinks.filter((l) => l.id !== id);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAlbum() {
|
||||
if (!confirm('Удалить альбом вместе с фото?')) return;
|
||||
try {
|
||||
await api(`/albums/${albumId}`, { method: 'DELETE' });
|
||||
goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mb-6 flex items-center justify-between">
|
||||
<h1 class="text-2xl font-bold">Настройки</h1>
|
||||
<a href="/albums/{albumId}" class="text-primary text-sm">← К альбому</a>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
<form class="border-border bg-bg-elevated mb-6 space-y-3 rounded-xl border p-4" onsubmit={save}>
|
||||
<h2 class="font-semibold">Альбом</h2>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Название</span>
|
||||
<input
|
||||
bind:value={title}
|
||||
class="border-border bg-bg text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Описание</span>
|
||||
<textarea
|
||||
bind:value={description}
|
||||
rows="3"
|
||||
class="border-border bg-bg text-text w-full rounded-lg border px-3 py-2"
|
||||
></textarea>
|
||||
</label>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit">Сохранить</button>
|
||||
{#if saved}<span class="text-success ml-3 text-sm">Сохранено</span>{/if}
|
||||
</form>
|
||||
|
||||
<div class="border-border bg-bg-elevated mb-6 space-y-3 rounded-xl border p-4">
|
||||
<h2 class="font-semibold">Ссылки для просмотра</h2>
|
||||
<form class="flex items-end gap-2" onsubmit={createLink}>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Срок действия</span>
|
||||
<input
|
||||
bind:value={expiresIn}
|
||||
class="border-border bg-bg text-text w-32 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать ссылку</button
|
||||
>
|
||||
</form>
|
||||
<ul class="divide-border divide-y">
|
||||
{#each shareLinks as link (link.id)}
|
||||
<li class="flex items-center justify-between gap-2 py-2 text-sm">
|
||||
<span class="text-text-muted truncate">
|
||||
{link.revoked_at ? 'отозвана' : 'до ' + new Date(link.expires_at).toLocaleString()}
|
||||
· <a class="text-primary" href="/share/{link.token}">/share/{link.token}</a>
|
||||
</span>
|
||||
{#if !link.revoked_at}
|
||||
<button type="button" class="text-danger" onclick={() => revoke(link.id)}>Отозвать</button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="border-danger text-danger rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={removeAlbum}>Удалить альбом</button
|
||||
>
|
||||
@@ -0,0 +1,57 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
|
||||
const token = $derived($page.params.token);
|
||||
|
||||
let info = $state<{ album_id: string; role: string; expires_at: string } | null>(null);
|
||||
let error = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
api<{ invite: typeof info }>(`/invites/${token}`)
|
||||
.then((data) => (info = data.invite))
|
||||
.catch((e) => (error = (e as Error).message));
|
||||
});
|
||||
|
||||
async function accept() {
|
||||
busy = true;
|
||||
error = '';
|
||||
try {
|
||||
const data = await api<{ album_id: string }>(`/invites/${token}/accept`, {
|
||||
method: 'POST'
|
||||
});
|
||||
goto(`/albums/${data.album_id}`);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-md py-12 text-center">
|
||||
<h1 class="mb-4 text-2xl font-bold">Приглашение в альбом</h1>
|
||||
{#if error}
|
||||
<p class="text-danger">{error}</p>
|
||||
{:else if info}
|
||||
<p class="text-text-muted mb-6">Вас приглашают с ролью <strong>{info.role}</strong>.</p>
|
||||
{#if auth.isAuthenticated}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onclick={accept}
|
||||
class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium"
|
||||
>
|
||||
{busy ? 'Принятие…' : 'Принять приглашение'}
|
||||
</button>
|
||||
{:else}
|
||||
<p class="mb-4 text-sm">Войдите или зарегистрируйтесь, чтобы принять приглашение.</p>
|
||||
<a href="/login" class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium">Войти</a>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { authApi } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
|
||||
let mode = $state<'login' | 'register'>('login');
|
||||
let email = $state('');
|
||||
let password = $state('');
|
||||
let name = $state('');
|
||||
let error = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
async function submit(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
busy = true;
|
||||
try {
|
||||
const data =
|
||||
mode === 'login'
|
||||
? await authApi.login(email, password)
|
||||
: await authApi.register(email, password, name);
|
||||
auth.setTokens(data.tokens);
|
||||
auth.setUser(data.user);
|
||||
goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-sm py-10">
|
||||
<h1 class="mb-6 text-2xl font-bold">{mode === 'login' ? 'Вход' : 'Регистрация'}</h1>
|
||||
|
||||
<form class="space-y-4" onsubmit={submit}>
|
||||
{#if mode === 'register'}
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Имя</span>
|
||||
<input
|
||||
bind:value={name}
|
||||
required
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
{/if}
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Email</span>
|
||||
<input
|
||||
bind:value={email}
|
||||
type="email"
|
||||
required
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Пароль</span>
|
||||
<input
|
||||
bind:value={password}
|
||||
type="password"
|
||||
required
|
||||
minlength="8"
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if error}<p class="text-danger text-sm">{error}</p>{/if}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
class="bg-primary text-primary-fg w-full rounded-lg px-4 py-2.5 font-medium disabled:opacity-50"
|
||||
>
|
||||
{busy ? 'Подождите…' : mode === 'login' ? 'Войти' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="text-primary mt-4 text-sm"
|
||||
onclick={() => (mode = mode === 'login' ? 'register' : 'login')}
|
||||
>
|
||||
{mode === 'login' ? 'Нет аккаунта? Зарегистрироваться' : 'Уже есть аккаунт? Войти'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import PhotoGrid from '$lib/components/PhotoGrid.svelte';
|
||||
import type { Album, Photo } from '$lib/types';
|
||||
|
||||
const token = $derived($page.params.token);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let photos = $state<Photo[]>([]);
|
||||
let nextCursor = $state('');
|
||||
let error = $state('');
|
||||
let active = $state(-1);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [albumData, photosData] = await Promise.all([
|
||||
api<{ album: Album }>(`/share/${token}`),
|
||||
api<{ photos: Photo[]; next_cursor: string }>(`/share/${token}/photos`)
|
||||
]);
|
||||
album = albumData.album;
|
||||
photos = photosData.photos;
|
||||
nextCursor = photosData.next_cursor;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!nextCursor) return;
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/share/${token}/photos?cursor=${encodeURIComponent(nextCursor)}`
|
||||
);
|
||||
photos = [...photos, ...data.photos];
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
token;
|
||||
load();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if error}
|
||||
<div class="py-16 text-center">
|
||||
<h1 class="mb-2 text-2xl font-bold">Доступ недоступен</h1>
|
||||
<p class="text-danger">{error}</p>
|
||||
</div>
|
||||
{:else if album}
|
||||
<h1 class="mb-2 text-2xl font-bold">{album.title}</h1>
|
||||
<p class="text-text-muted mb-6">Доступ только для просмотра · {album.description}</p>
|
||||
<PhotoGrid {photos} onOpen={(i) => (active = i)} />
|
||||
{#if nextCursor}
|
||||
<div class="mt-6 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="border-border text-text rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={loadMore}>Показать ещё</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if active >= 0}
|
||||
<div
|
||||
class="bg-bg/95 fixed inset-0 z-50 flex items-center justify-center"
|
||||
role="dialog"
|
||||
onclick={() => (active = -1)}
|
||||
>
|
||||
<img
|
||||
src={photos[active].preview_url ?? photos[active].original_url}
|
||||
alt={photos[active].original_filename}
|
||||
class="max-h-[90vh] max-w-full object-contain"
|
||||
/>
|
||||
<a
|
||||
href={photos[active].download_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="border-border bg-bg-elevated text-text absolute top-4 right-4 rounded-lg border px-3 py-1.5 text-sm"
|
||||
onclick={(e) => e.stopPropagation()}>Скачать</a
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,14 @@
|
||||
import adapter from '@sveltejs/adapter-static';
|
||||
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
preprocess: vitePreprocess(),
|
||||
kit: {
|
||||
adapter: adapter({
|
||||
fallback: 'index.html'
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
export default {
|
||||
content: ['./src/**/*.{html,js,svelte,ts}'],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
bg: {
|
||||
DEFAULT: 'hsl(var(--bg) / <alpha-value>)',
|
||||
elevated: 'hsl(var(--bg-elevated) / <alpha-value>)',
|
||||
muted: 'hsl(var(--bg-muted) / <alpha-value>)'
|
||||
},
|
||||
border: 'hsl(var(--border) / <alpha-value>)',
|
||||
text: {
|
||||
DEFAULT: 'hsl(var(--text) / <alpha-value>)',
|
||||
muted: 'hsl(var(--text-muted) / <alpha-value>)',
|
||||
subtle: 'hsl(var(--text-subtle) / <alpha-value>)'
|
||||
},
|
||||
primary: {
|
||||
DEFAULT: 'hsl(var(--primary) / <alpha-value>)',
|
||||
fg: 'hsl(var(--primary-fg) / <alpha-value>)'
|
||||
},
|
||||
danger: 'hsl(var(--danger) / <alpha-value>)',
|
||||
success: 'hsl(var(--success) / <alpha-value>)'
|
||||
}
|
||||
}
|
||||
}
|
||||
} satisfies Config;
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080'
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-10-10
|
||||
@@ -0,0 +1,89 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
Greenfield-сервис «многопользовательский фотоальбом». Существующая инфраструктура:
|
||||
PostgreSQL (`pg.localnet:5432`) и Garage S3 (`s3.localnet`, path-style, регион `garage`,
|
||||
ключ `GK...`). Жёсткое ограничение — без Docker: один статичный Go-бинарник со вшитой
|
||||
статикой SvelteKit через `go:embed`, запуск через systemd. Мотивация — в proposal.md.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Один артефакт (Go-бинарник), `CGO_ENABLED=0`, self-hosted поверх Garage + PostgreSQL.
|
||||
- Чёткая модель прав, проверяемая на уровне сервиса, а не только UI.
|
||||
- Live-обновления через SSE без внешних зависимостей.
|
||||
|
||||
**Non-Goals:**
|
||||
- Горизонтальное масштабирование (один инстанс, in-memory SSE-хаб).
|
||||
- Web push (браузерные push) — отложено; уведомления только in-app через SSE.
|
||||
- Публичный каталог альбомов — доступ вне состава только по share-ссылке.
|
||||
- Zip-скачивание альбомов.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Обработка изображений: `imaging` + `gen2brain/webp` + `goexif`
|
||||
Resize — `disintegration/imaging`, WebP-кодирование — `gen2brain/webp` (libwebp,
|
||||
транспилированный в чистый Go/WASM; `kolesa-team/go-webp` отклонён, т.к. это cgo-биндинг,
|
||||
несовместимый с `CGO_ENABLED=0`), EXIF — `rwcarlsen/goexif`. Всё чистый Go, совместимо с `CGO_ENABLED=0`.
|
||||
- **Альтернатива (отклонена):** `bimg`/libvips — быстрее и нативный WebP/EXIF, но требует
|
||||
CGO и libvips на сборочной и прод-машинах, ломает «статичный бинарник».
|
||||
- **Альтернатива (запасная):** `imaging` + JPEG-превью — проще, но превью тяжелее ~25–35%.
|
||||
- Конвейер: stream original в S3 → EXIF+resize → encode WebP → thumb/preview в S3.
|
||||
|
||||
### 2. Аутентификация: JWT access + refresh с хранением refresh-токена
|
||||
Access 15 мин, refresh 30 дней. Refresh-токены хранятся в отдельной таблице
|
||||
`refresh_tokens` (хэшированными) — это даёт отзыв при logout и ротацию при refresh.
|
||||
- **Альтернатива:** stateless refresh-JWT без хранения — проще, но logout не может
|
||||
отозвать токен (противоречит спец `auth`).
|
||||
- SSE: `EventSource` не умеет заголовки, поэтому access-токен в `?token=`; короткий TTL
|
||||
компенсирует риск. (Cookie+CSRF — отложено.)
|
||||
|
||||
### 3. Права: «нет эскалации», владелец из `albums.owner_id`
|
||||
Роли `admin/editor/member/viewer` хранятся в `album_members`. Владелец — создатель,
|
||||
выводится из `albums.owner_id`, не дублируется в составе. Правило: никто не может выдать
|
||||
роль выше своей; админ управляет `editor/member/viewer`, владелец — админами; редактор
|
||||
приглашает только `member/viewer`. Проверка на уровне сервиса.
|
||||
|
||||
### 4. Скачивание: только одиночное фото
|
||||
`GET /api/photos/:id/download` — presigned URL оригинала. Zip альбома исключён из MVP.
|
||||
|
||||
### 5. Доступ по ссылке: таблица `share_links` вместо `privacy`
|
||||
`privacy` на `albums` убран. `share_links` (id, album_id, token, created_by, created_at,
|
||||
expires_at, revoked_at) — несколько ссылок, срок при создании, точечный отзыв. Доступ по
|
||||
токену — view-only (сетка, лайтбокс, одиночное скачивание), без комментариев/лайков/загрузки.
|
||||
Публичные эндпоинты `/api/share/:token/*` отдают свежие presigned URL.
|
||||
|
||||
### 6. Presigned URL: TTL 1 час + выдача по требованию
|
||||
Клиент не хранит URL надолго: сетка получает свежие thumb/preview при каждом запросе списка,
|
||||
лайтбокс дёргает `GET /api/photos/:id` перед показом оригинала. SSE-событие несёт `thumb_url`
|
||||
только для мгновенного рендера. Короткий TTL сохраняет малое окно утечки для приватных фото.
|
||||
|
||||
### 7. SSE: in-memory hub на каналах
|
||||
`map[albumID]map[clientID]chan Event`, неблокирующая публикация, отключение при переполнении
|
||||
буфера, heartbeat 25 сек, отдельная горутина на клиента. Догон пропущенного — REST
|
||||
(`photos?since=`). Один инстанс (см. Non-Goals); на рестарте клиенты переподключаются.
|
||||
|
||||
### 8. Фреймворк и структура
|
||||
Backend — Gin + pgx + AWS SDK v2 (path-style, регион `garage`). Frontend — SvelteKit 2 +
|
||||
Svelte 5, adapter-static, статика в `backend/static` через `go:embed`. Миграции —
|
||||
golang-migrate. Логи — slog. Конфиг — env (12-factor).
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **[Чистый Go медленнее libvips]** → Приемлемо для MVP; превью генерируются асинхронно,
|
||||
не в пути запроса. При росте нагрузки — миграция на bimg с отказом от `CGO_ENABLED=0`.
|
||||
- **[In-memory SSE-хаб теряет события при рестарте]** → Клиенты переподключаются и догоняют
|
||||
через REST; окно потери ограничено.
|
||||
- **[Токен в query-параметре]** → Короткий TTL access-токена и refresh в httpOnly-хранилище
|
||||
на фронте; Cookie+CSRF как дальнейшее улучшение.
|
||||
- **[Presigned URL в 1 час]** → Может «протухать» на долгоживущих вкладках → компенсируется
|
||||
выдачей по требованию (лайтбокс, свежий список).
|
||||
- **[Несколько share-ссылок]** → Небольшой оверхед на управление, но даёт точечный отзыв
|
||||
(важно для сценария «фотограф ↔ несколько клиентов»).
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Greenfield: golang-migrate применяет `up` к `pg.localnet` при деплое. Таблицы: users,
|
||||
albums (без `privacy`), album_members, invites, photos, comments, likes, notifications,
|
||||
share_links, refresh_tokens. Откат — `down`-миграции или переустановка предыдущего бинарника.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Фото участников разбросаны по мессенджерам и галереям — теряется авторство, контекст
|
||||
и разграничение прав. Нужно единое многопользовательское пространство (семьи и друзья,
|
||||
рабочие команды, фотограф ↔ клиент) с понятными ролями, live-обновлениями и self-hosted
|
||||
хранением поверх уже существующих Garage (S3) и PostgreSQL, без контейнеров.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Новый backend на Go 1.22+ (Gin, pgx, AWS SDK v2, нативный SSE) — один статичный
|
||||
бинарник (`CGO_ENABLED=0`) со вшитой статикой SvelteKit через `go:embed`.
|
||||
- Новый frontend на SvelteKit 2 + Svelte 5 (adapter-static, TypeScript, TailwindCSS).
|
||||
- Аутентификация: регистрация, вход, JWT (access 15 мин + refresh 30 дней), logout.
|
||||
- Альбомы: создание / редактирование / удаление / список, владение альбомом.
|
||||
- Участники и роли: инвайт по токену, роли `admin` / `editor` / `member` / `viewer`,
|
||||
владелец выводится из `albums.owner_id`, правило «нет эскалации прав».
|
||||
- Фото: загрузка (одиночно и массово), три варианта (thumb 200px / preview 1200px /
|
||||
original), WebP-превью, EXIF, cursor-пагинация, просмотр, скачивание одиночного фото.
|
||||
- Социальное: лайки и комментарии к фото.
|
||||
- Real-time через SSE: события фото / комментариев / лайков / участников.
|
||||
- Уведомления: персональный поток в приложении (in-app через SSE).
|
||||
- Ссылки для просмотра: view-only доступ к альбому без аккаунта (несколько ссылок,
|
||||
срок действия, отзыв).
|
||||
- Деплой без Docker: systemd-юнит, статика вшита в бинарник, один артефакт.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `auth`: регистрация и вход по email/паролю, JWT-токены, refresh, logout.
|
||||
- `albums`: жизненный цикл альбома (создание, просмотр, редактирование, удаление,
|
||||
список) и владение им.
|
||||
- `members`: состав альбома, роли и права доступа, инвайт по токену, смена ролей.
|
||||
- `photos`: загрузка и хранение фото в S3, генерация вариантов и EXIF, листинг с
|
||||
пагинацией, просмотр, скачивание одиночного фото.
|
||||
- `social`: лайки и комментарии к фотографиям.
|
||||
- `realtime`: поток событий альбома через SSE (фото, комментарии, лайки, участники).
|
||||
- `notifications`: персональные уведомления пользователя и их статус прочитано.
|
||||
- `share-links`: view-only доступ к альбому по ссылке без авторизации.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
_Нет — проект новый, существующих спец нет._
|
||||
|
||||
## Impact
|
||||
|
||||
- **Код:** новый `backend/` (Go) и `frontend/` (SvelteKit), `deploy/` (systemd, nginx),
|
||||
`Makefile`, `.env.example`.
|
||||
- **Зависимости:** `gin`, `pgx`, `aws-sdk-go-v2`, `golang-migrate`, `imaging`,
|
||||
`gen2brain/webp` (чистый Go), `rwcarlsen/goexif`, `golang-jwt`, `bcrypt`.
|
||||
- **Системы:** подключение к существующим `pg.localnet:5432` (PostgreSQL) и
|
||||
Garage на `s3.localnet` (path-style, регион `garage`, ключ `GK...`).
|
||||
- **Права:** все эндпоинты за JWT, кроме `/api/auth/*` и публичных share-эндпоинтов;
|
||||
проверка прав на уровне сервиса, не только UI.
|
||||
- **Не входит в MVP (осознанно отложено):** web push (браузерные push-уведомления),
|
||||
распознавание лиц/ML-теги, мобильные приложения, биллинг, публичный API, печать.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Управление фотоальбомами: создание, просмотр, редактирование, удаление и владение.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Создание альбома
|
||||
Зарегистрированный пользователь SHALL иметь возможность создать альбом и стать его владельцем.
|
||||
|
||||
#### Scenario: Создание альбома
|
||||
- **WHEN** пользователь создаёт альбом с названием
|
||||
- **THEN** система создаёт альбом и назначает пользователя владельцем
|
||||
|
||||
### Requirement: Список альбомов пользователя
|
||||
Пользователь SHALL иметь возможность получить список альбомов, к которым у него есть доступ.
|
||||
|
||||
#### Scenario: Список альбомов
|
||||
- **WHEN** пользователь запрашивает список альбомов
|
||||
- **THEN** система возвращает альбомы, где он владелец или участник
|
||||
|
||||
### Requirement: Получение альбома
|
||||
Участник SHALL иметь возможность получить данные альбома по id.
|
||||
|
||||
#### Scenario: Просмотр альбома
|
||||
- **WHEN** участник запрашивает альбом по id
|
||||
- **THEN** система возвращает данные альбома
|
||||
|
||||
### Requirement: Редактирование альбома
|
||||
Владелец и админ SHALL иметь возможность редактировать название, описание и обложку альбома.
|
||||
|
||||
#### Scenario: Редактирование альбома
|
||||
- **WHEN** админ изменяет описание альбома
|
||||
- **THEN** система сохраняет изменения
|
||||
|
||||
### Requirement: Удаление альбома
|
||||
Владелец SHALL иметь возможность удалить альбом вместе с содержимым.
|
||||
|
||||
#### Scenario: Удаление альбома
|
||||
- **WHEN** владелец удаляет альбом
|
||||
- **THEN** система удаляет альбом, его фото, участников и share-ссылки
|
||||
@@ -0,0 +1,47 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Регистрация и аутентификация пользователей по email и паролю с выдачей краткоживущих и долгоживущих JWT-токенов.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Регистрация пользователя
|
||||
Пользователь SHALL иметь возможность зарегистрироваться, указав email, пароль и имя. Пароль SHALL храниться в виде bcrypt-хэша.
|
||||
|
||||
#### Scenario: Успешная регистрация
|
||||
- **WHEN** пользователь отправляет уникальный email, пароль и имя
|
||||
- **THEN** система создаёт учётную запись и возвращает access- и refresh-токены
|
||||
|
||||
#### Scenario: Повторный email
|
||||
- **WHEN** пользователь регистрируется с уже занятым email
|
||||
- **THEN** система возвращает ошибку конфликта и не создаёт вторую запись
|
||||
|
||||
### Requirement: Вход по email и паролю
|
||||
Пользователь SHALL иметь возможность войти, указав email и пароль.
|
||||
|
||||
#### Scenario: Успешный вход
|
||||
- **WHEN** пользователь вводит верные email и пароль
|
||||
- **THEN** система возвращает access- и refresh-токены
|
||||
|
||||
#### Scenario: Неверные учётные данные
|
||||
- **WHEN** пользователь вводит неверный email или пароль
|
||||
- **THEN** система возвращает 401, не раскрывая, какое именно поле неверно
|
||||
|
||||
### Requirement: Обновление access-токена
|
||||
Пользователь SHALL иметь возможность обменять refresh-токен на новую пару токенов. Access-токен живёт 15 минут, refresh-токен — 30 дней.
|
||||
|
||||
#### Scenario: Валидный refresh-токен
|
||||
- **WHEN** пользователь предоставляет действующий refresh-токен
|
||||
- **THEN** система выдаёт новый access-токен и ротирует refresh-токен
|
||||
|
||||
#### Scenario: Недействительный refresh-токен
|
||||
- **WHEN** пользователь предоставляет истёкший или отозванный refresh-токен
|
||||
- **THEN** система возвращает 401
|
||||
|
||||
### Requirement: Выход из системы
|
||||
Пользователь SHALL иметь возможность выйти, отозвав refresh-токен.
|
||||
|
||||
#### Scenario: Выход
|
||||
- **WHEN** пользователь вызывает logout с действующим refresh-токеном
|
||||
- **THEN** система отзывает refresh-токен, и его дальнейшее использование отклоняется
|
||||
@@ -0,0 +1,65 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Управление составом альбома, ролями и правами доступа, включая приглашения по токену.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Роли участников
|
||||
Участник альбома SHALL иметь одну из ролей: admin, editor, member, viewer. Владелец выводится из albums.owner_id и не хранится как роль участника.
|
||||
|
||||
#### Scenario: Создатель становится владельцем
|
||||
- **WHEN** пользователь создаёт альбом
|
||||
- **THEN** система делает его владельцем альбома
|
||||
|
||||
### Requirement: Матрица прав
|
||||
Система SHALL ограничивать действия по ролям: загружать фото могут owner/admin/editor/member; удалять чужие фото — owner/admin; удалять свои — owner/admin/editor/member; комментировать — owner/admin/editor/member; скачивать одиночное фото и просматривать — все участники, включая viewer.
|
||||
|
||||
#### Scenario: Наблюдатель не может загружать
|
||||
- **WHEN** участник с ролью viewer пытается загрузить фото
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
#### Scenario: Участник не может удалять чужие фото
|
||||
- **WHEN** участник с ролью member пытается удалить фото другого автора
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Приглашение участников
|
||||
Владелец и админ SHALL иметь возможность создавать инвайт-ссылку с токеном. Редактор SHALL иметь возможность приглашать только на роли member и viewer. Никто не может приглашать на роль выше своей.
|
||||
|
||||
#### Scenario: Админ приглашает участника
|
||||
- **WHEN** админ создаёт инвайт на роль member
|
||||
- **THEN** система создаёт инвайт с токеном и сроком действия
|
||||
|
||||
#### Scenario: Редактор не может приглашать админа
|
||||
- **WHEN** редактор пытается создать инвайт на роль admin или editor
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Принятие инвайта
|
||||
Пользователь SHALL иметь возможность стать участником, перейдя по токену инвайта.
|
||||
|
||||
#### Scenario: Принятие действующего инвайта
|
||||
- **WHEN** пользователь принимает неистёкший инвайт с неисчерпанным лимитом использования
|
||||
- **THEN** система добавляет его в состав альбома с ролью из инвайта
|
||||
|
||||
#### Scenario: Принятие истёкшего инвайта
|
||||
- **WHEN** пользователь принимает истёкший инвайт
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Смена ролей
|
||||
Админ SHALL иметь возможность менять роли editor/member/viewer. Владелец SHALL управлять ролями админов. Никто не может менять роль выше своей и не может трогать владельца.
|
||||
|
||||
#### Scenario: Админ меняет роль участника
|
||||
- **WHEN** админ повышает участника до editor
|
||||
- **THEN** система обновляет роль
|
||||
|
||||
#### Scenario: Админ не может назначить админа
|
||||
- **WHEN** админ пытается назначить другому участнику роль admin
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Удаление участника
|
||||
Владелец и админ SHALL иметь возможность удалять участников, кроме владельца и других админов.
|
||||
|
||||
#### Scenario: Удаление участника
|
||||
- **WHEN** админ удаляет участника с ролью member/viewer/editor
|
||||
- **THEN** система убирает его из состава альбома
|
||||
@@ -0,0 +1,28 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Персональные уведомления пользователя о событиях (комментарии, лайки, участники) и их статус прочитано.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Создание уведомления
|
||||
Система SHALL создавать уведомление пользователю при наступлении события (комментарий к его фото, лайк, добавление в альбом).
|
||||
|
||||
#### Scenario: Комментарий к моему фото
|
||||
- **WHEN** другой пользователь комментирует фото пользователя
|
||||
- **THEN** система создаёт уведомление этому пользователю
|
||||
|
||||
### Requirement: Список уведомлений
|
||||
Пользователь SHALL иметь возможность получить свои уведомления.
|
||||
|
||||
#### Scenario: Получение уведомлений
|
||||
- **WHEN** пользователь запрашивает уведомления
|
||||
- **THEN** система возвращает список с признаком прочитано
|
||||
|
||||
### Requirement: Отметка прочитанным
|
||||
Пользователь SHALL иметь возможность отметить уведомление прочитанным.
|
||||
|
||||
#### Scenario: Отметить прочитанным
|
||||
- **WHEN** пользователь отмечает уведомление прочитанным
|
||||
- **THEN** система фиксирует время прочтения
|
||||
@@ -0,0 +1,57 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Загрузка, хранение в S3 и просмотр фотографий с генерацией вариантов и извлечением EXIF.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Загрузка фото
|
||||
Пользователь с правом загрузки SHALL иметь возможность загружать фото по одному и массово.
|
||||
|
||||
#### Scenario: Успешная загрузка
|
||||
- **WHEN** участник с правом загрузки отправляет файл изображения
|
||||
- **THEN** система сохраняет оригинал и создаёт запись фото с метаданными
|
||||
|
||||
#### Scenario: Загрузка без права
|
||||
- **WHEN** наблюдатель пытается загрузить фото
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Варианты изображений
|
||||
Система SHALL генерировать три варианта: thumb (200px), preview (1200px) и оригинал, с WebP для превью, и извлекать EXIF (дата, координаты, размеры).
|
||||
|
||||
#### Scenario: Генерация вариантов
|
||||
- **WHEN** фото загружено
|
||||
- **THEN** система асинхронно генерирует thumb и preview и заполняет EXIF-поля
|
||||
|
||||
### Requirement: Листинг фото с пагинацией
|
||||
Система SHALL возвращать фото альбома с cursor-пагинацией.
|
||||
|
||||
#### Scenario: Пагинация по курсору
|
||||
- **WHEN** клиент запрашивает список с курсором и лимитом
|
||||
- **THEN** система возвращает не более лимита фото и курсор следующей страницы
|
||||
|
||||
### Requirement: Получение фото по требованию
|
||||
Клиент SHALL иметь возможность получить актуальные данные фото с presigned URL.
|
||||
|
||||
#### Scenario: Выдача свежего URL
|
||||
- **WHEN** клиент запрашивает фото по id
|
||||
- **THEN** система возвращает свежий presigned URL (срок до 1 часа) для просмотра
|
||||
|
||||
### Requirement: Скачивание одиночного фото
|
||||
Любой участник, включая viewer, SHALL иметь возможность скачать одиночное фото.
|
||||
|
||||
#### Scenario: Скачивание фото
|
||||
- **WHEN** участник запрашивает скачивание фото
|
||||
- **THEN** система возвращает presigned URL оригинала
|
||||
|
||||
### Requirement: Удаление фото
|
||||
Автор SHALL иметь возможность удалить своё фото; владелец и админ SHALL иметь возможность удалить любое фото.
|
||||
|
||||
#### Scenario: Удаление своего фото
|
||||
- **WHEN** автор удаляет своё фото
|
||||
- **THEN** система удаляет запись и файлы в S3
|
||||
|
||||
#### Scenario: Удаление чужого фото участником
|
||||
- **WHEN** участник с ролью member пытается удалить чужое фото
|
||||
- **THEN** система отклоняет запрос
|
||||
@@ -0,0 +1,49 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Поток событий альбома и персональный поток через Server-Sent Events.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Подписка на события альбома
|
||||
Клиент SHALL иметь возможность подписаться на события конкретного альбома через SSE.
|
||||
|
||||
#### Scenario: Подписка на альбом
|
||||
- **WHEN** участник подключается к SSE-потоку альбома
|
||||
- **THEN** система устанавливает text/event-stream и отправляет heartbeat
|
||||
|
||||
### Requirement: События альбома
|
||||
Система SHALL публиковать события photo.created, photo.deleted, comment.created, like.added, like.removed, member.joined, member.left, album.updated.
|
||||
|
||||
#### Scenario: Новое фото
|
||||
- **WHEN** в альбоме появляется фото
|
||||
- **THEN** подписчики получают событие photo.created с метаданными и URL превью
|
||||
|
||||
### Requirement: Персональный поток
|
||||
Клиент SHALL иметь возможность подписаться на персональный поток (приглашения, уведомления).
|
||||
|
||||
#### Scenario: Подписка на персональный поток
|
||||
- **WHEN** пользователь подключается к персональному потоку
|
||||
- **THEN** система отправляет ему персональные события
|
||||
|
||||
### Requirement: Авторизация и область доступа
|
||||
Клиент SHALL подписываться только на доступные ему альбомы; токен передаётся в query-параметре.
|
||||
|
||||
#### Scenario: Подписка на недоступный альбом
|
||||
- **WHEN** пользователь подписывается на альбом, к которому нет доступа
|
||||
- **THEN** система отклоняет подключение
|
||||
|
||||
### Requirement: Устойчивость соединения
|
||||
Система SHALL отправлять heartbeat каждые 25 секунд и отключать медленных клиентов при переполнении буфера.
|
||||
|
||||
#### Scenario: Переполнение буфера клиента
|
||||
- **WHEN** буфер клиента переполняется
|
||||
- **THEN** система отключает клиента
|
||||
|
||||
### Requirement: Догон пропущенного
|
||||
Клиент SHALL иметь возможность догнать пропущенные события через REST.
|
||||
|
||||
#### Scenario: Переподключение
|
||||
- **WHEN** клиент переподключается после разрыва
|
||||
- **THEN** клиент догоняет события через запрос фото с параметром since
|
||||
@@ -0,0 +1,46 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
View-only доступ к альбому по ссылке без авторизации, с несколькими ссылками, сроком действия и отзывом.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Создание ссылки для просмотра
|
||||
Владелец и админ SHALL иметь возможность создать ссылку для просмотра альбома с заданным сроком действия.
|
||||
|
||||
#### Scenario: Создание ссылки
|
||||
- **WHEN** админ создаёт share-ссылку со сроком действия
|
||||
- **THEN** система создаёт токен и возвращает URL для просмотра
|
||||
|
||||
### Requirement: Несколько ссылок
|
||||
Альбом SHALL поддерживать несколько независимых share-ссылок.
|
||||
|
||||
#### Scenario: Отзыв одной ссылки не затрагивает другие
|
||||
- **WHEN** владелец отзывает одну ссылку
|
||||
- **THEN** остальные ссылки остаются действующими
|
||||
|
||||
### Requirement: Просмотр альбома по ссылке
|
||||
Пользователь без авторизации SHALL иметь возможность просматривать альбом по действующему токену (сетка, лайтбокс, скачивание одиночного фото).
|
||||
|
||||
#### Scenario: Просмотр по действующей ссылке
|
||||
- **WHEN** аноним открывает ссылку с действующим токеном
|
||||
- **THEN** система возвращает фото альбома со свежими presigned URL
|
||||
|
||||
#### Scenario: Истёкшая или отозванная ссылка
|
||||
- **WHEN** аноним открывает ссылку с истёкшим или отозванным токеном
|
||||
- **THEN** система отклоняет доступ
|
||||
|
||||
### Requirement: Ограничения по ссылке
|
||||
Доступ по ссылке SHALL быть только на просмотр: без комментариев, лайков, загрузки и управления участниками.
|
||||
|
||||
#### Scenario: Аноним не может комментировать
|
||||
- **WHEN** аноним по ссылке пытается добавить комментарий
|
||||
- **THEN** система отклоняет запрос
|
||||
|
||||
### Requirement: Отзыв ссылки
|
||||
Владелец и админ SHALL иметь возможность отозвать ссылку.
|
||||
|
||||
#### Scenario: Отзыв ссылки
|
||||
- **WHEN** владелец отзывает share-ссылку
|
||||
- **THEN** система прекращает доступ по этому токену
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user