Compare commits
1
Commits
next
..
4c397786e6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c397786e6 |
No files matched your search
@@ -1,73 +1,55 @@
|
|||||||
# Rules for coding agents
|
# AGENTS.md — Rules for AI Agents
|
||||||
|
|
||||||
This file holds the rules for coding agents working in this repository.
|
## Before Every Commit
|
||||||
`CONVENTIONS.md` defines the architecture. `REPO_POLICIES.md` defines the
|
|
||||||
repository standards. Both are copies of shared documents. Do not edit them
|
|
||||||
here.
|
|
||||||
|
|
||||||
## Before every commit
|
1. **Format**: `make fmt`
|
||||||
|
2. **Check**: `make check` — the tests and the linter, which run in Docker, and
|
||||||
|
the format check: all passing, zero issues
|
||||||
|
|
||||||
1. Run `make fmt`.
|
Never run `go test`, `golangci-lint` or `gofmt` directly; use the `make`
|
||||||
2. Run `make check`. It runs the tests and the linter in Docker, then the format
|
targets.
|
||||||
check. All three must pass with no findings.
|
|
||||||
|
|
||||||
Never run `go test`, `golangci-lint` or `gofmt` directly. Use the `make` targets
|
No commit lands on main with lint errors, test failures, or formatting issues.
|
||||||
instead, such as `make test` and `make lint`.
|
|
||||||
|
|
||||||
## Branches and pull requests
|
## Code Style
|
||||||
|
|
||||||
- Never commit to `main` or `next` directly. Every change is a pull request from
|
- Follow CONVENTIONS.md exactly — it defines the architecture
|
||||||
a feature branch into `next`.
|
- All exported types, functions, methods, and vars must have doc comments
|
||||||
- Only the owner merges `next` into `main`.
|
- All packages must have a package doc comment
|
||||||
- A pull request that closes an issue has the title `Description (closes #N)`.
|
- JSON tags use camelCase (not snake_case)
|
||||||
- One logical change per commit.
|
- No magic numbers — use named constants
|
||||||
- Commit messages are in the imperative mood and short.
|
- No inline error handling (`if err := ...; err != nil`) — use plain assignment
|
||||||
|
- Blank line before every `return` statement
|
||||||
|
- Blank line separating embedded fields from regular fields in structs
|
||||||
|
- Blank imports must have a justification comment
|
||||||
|
|
||||||
## Code style
|
## Git Workflow
|
||||||
|
|
||||||
- Follow `CONVENTIONS.md`.
|
- **Never commit directly to main** — all changes go on feature branches
|
||||||
- Every package has a package doc comment. Test files need none.
|
- Merge to main only when ready and passing all checks
|
||||||
- Every exported type, function and variable has a doc comment. Test files need
|
- PR titles: `Description (closes #N)` when closing an issue
|
||||||
none.
|
- One logical change per commit
|
||||||
- JSON tags are camelCase. The HTTP API's `last_id`, `pow_token` and
|
- Commit messages: imperative mood, concise
|
||||||
`hashcash_bits` stay as they are, each with a `//nolint:tagliatelle` comment.
|
|
||||||
- Prefer named constants to magic numbers. The `mnd` linter checks for them
|
|
||||||
outside test files.
|
|
||||||
- No inline error handling such as `if err := f(); err != nil`. Assign the error
|
|
||||||
on its own line, then test it.
|
|
||||||
- A `return` that follows another statement in its block has a blank line before
|
|
||||||
it.
|
|
||||||
- A blank line between the embedded fields of a struct and its other fields.
|
|
||||||
- Every blank import has a comment saying why it is there. Test files need none.
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
- The server uses `go.uber.org/fx` for dependency injection.
|
- Dependency injection via Uber fx — all components are fx providers
|
||||||
`cmd/neoircd/main.go` lists its `fx` providers, such as `db.New` and
|
- `internal/` for all application packages — one package per concern
|
||||||
`handlers.New`.
|
- Handlers return `http.HandlerFunc` using the closure pattern
|
||||||
- Application packages live under `internal/`, one package per concern.
|
- Request/response structs defined inside handler closures
|
||||||
- `pkg/irc` holds the IRC command names and numeric reply codes.
|
- Models embed `models.Base` for database access to relation methods
|
||||||
- The `web` package embeds the built web client.
|
- Database migrations in `internal/db/schema/` — embedded via `go:embed`
|
||||||
- Each exported `Handle…` method of `Handlers` returns an `http.HandlerFunc`.
|
- SQLite by default (pure Go driver: modernc.org/sqlite)
|
||||||
- A request struct is defined inside the method that decodes it.
|
|
||||||
- The server uses the database only through the methods of `db.Database`.
|
|
||||||
- The database migrations live in `internal/db/schema/` and are embedded with
|
|
||||||
`go:embed`.
|
|
||||||
- The database is SQLite, through the pure Go driver `modernc.org/sqlite`.
|
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
- Prefer table-driven tests.
|
- Table-driven tests preferred
|
||||||
- Use `testing.T` helpers, not assertion libraries.
|
- Use `testing.T` helpers, not assertion libraries
|
||||||
- A test file lives next to the code it tests and ends in `_test.go`.
|
- Test files live next to the code they test
|
||||||
- The linter requires each test file to be in the package's external test
|
- `_test.go` suffix, same package for white-box testing
|
||||||
package, such as `handlers_test`. It allows `export_test.go` and files ending
|
|
||||||
in `_internal_test.go` in the package itself.
|
|
||||||
- An `export_test.go` file gives the external tests access to the package's
|
|
||||||
unexported code.
|
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
- The required libraries are listed in `CONVENTIONS.md` §1.
|
- Required libraries are listed in CONVENTIONS.md §1
|
||||||
- No new dependency without a reason given in the pull request.
|
- No new dependencies without justification
|
||||||
- Prefer dependencies written in pure Go, which build without cgo.
|
- Pure Go preferred (no CGO)
|
||||||
+10
-15
@@ -33,18 +33,14 @@ RUN golangci-lint run --config .golangci.yml ./...
|
|||||||
# golang:1.24.13-bookworm, 2026-10-06
|
# golang:1.24.13-bookworm, 2026-10-06
|
||||||
FROM golang@sha256:1a6d4452c65dea36aac2e2d606b01b4a029ec90cc1ae53890540ce6173ea77ac AS test
|
FROM golang@sha256:1a6d4452c65dea36aac2e2d606b01b4a029ec90cc1ae53890540ce6173ea77ac AS test
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css web/dist/app.js
|
RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css web/dist/app.js
|
||||||
# -p 4 because test runs on a shared build host cap their parallelism.
|
# -p 4 because test runs on a shared build host cap their parallelism.
|
||||||
# The modules download in this RUN rather than a layer of their own, because
|
RUN go test -p 4 -timeout 90s -race -cover ./... || \
|
||||||
# exporting a layer that holds them is slow. Nothing reads them or the build
|
|
||||||
# cache afterwards, so go clean removes both.
|
|
||||||
RUN set -e; \
|
|
||||||
go mod download; \
|
|
||||||
go test -p 4 -timeout 90s -race -cover ./... || \
|
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
go test -p 4 -timeout 90s -race -v ./...; exit 1; }; \
|
go test -p 4 -timeout 90s -race -v ./...; exit 1; }
|
||||||
go clean -cache -modcache
|
|
||||||
|
|
||||||
# Build stage. Nothing is wanted from either phase above; the copies
|
# Build stage. Nothing is wanted from either phase above; the copies
|
||||||
# are what make BuildKit build them first, so this stage cannot run
|
# are what make BuildKit build them first, so this stage cannot run
|
||||||
@@ -83,15 +79,14 @@ RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /neoirc-cli ./cmd/neoir
|
|||||||
# stage's chain and nothing else.
|
# stage's chain and nothing else.
|
||||||
# alpine:3.21, 2026-02-26
|
# alpine:3.21, 2026-02-26
|
||||||
FROM alpine@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709
|
FROM alpine@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709
|
||||||
# su-exec 0.2-r3, 2026-11-10
|
RUN apk add --no-cache ca-certificates \
|
||||||
RUN apk add --no-cache ca-certificates su-exec=0.2-r3 \
|
&& addgroup -S neoirc && adduser -S neoirc -G neoirc \
|
||||||
&& addgroup -S neoirc && adduser -S neoirc -G neoirc
|
&& mkdir -p /var/lib/neoirc \
|
||||||
|
&& chown neoirc:neoirc /var/lib/neoirc
|
||||||
COPY --from=builder /neoircd /usr/local/bin/neoircd
|
COPY --from=builder /neoircd /usr/local/bin/neoircd
|
||||||
COPY deploy/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
|
||||||
|
|
||||||
# No USER: the entrypoint starts as root to give /var/lib/neoirc to neoirc,
|
USER neoirc
|
||||||
# then runs neoircd as neoirc.
|
|
||||||
EXPOSE 8080 6667
|
EXPOSE 8080 6667
|
||||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
CMD wget -qO- http://localhost:8080/.well-known/healthcheck.json || exit 1
|
CMD wget -qO- http://localhost:8080/.well-known/healthcheck.json || exit 1
|
||||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
ENTRYPOINT ["neoircd"]
|
||||||
@@ -128,8 +128,8 @@ Three kinds of message reach a queue:
|
|||||||
- **Events**: `JOIN`, `PART`, `NICK`, `QUIT`, `TOPIC`, `MODE`, `KICK`, `INVITE`
|
- **Events**: `JOIN`, `PART`, `NICK`, `QUIT`, `TOPIC`, `MODE`, `KICK`, `INVITE`
|
||||||
and `WALLOPS`, telling the client what other users did. When a client's own
|
and `WALLOPS`, telling the client what other users did. When a client's own
|
||||||
`JOIN`, `PART`, `NICK`, `TOPIC`, `MODE` or `KICK` causes an event, every HTTP
|
`JOIN`, `PART`, `NICK`, `TOPIC`, `MODE` or `KICK` causes an event, every HTTP
|
||||||
client of its session receives it too. The IRC connection that sent the
|
client of its session receives it too; an IRC connection that sent the command
|
||||||
command gets it as an IRC line instead.
|
gets the IRC echo instead.
|
||||||
- **Numeric replies**: the server's answers to commands, such as `RPL_TOPIC` or
|
- **Numeric replies**: the server's answers to commands, such as `RPL_TOPIC` or
|
||||||
`ERR_NOSUCHNICK`. A numeric reply goes only to the client that sent the
|
`ERR_NOSUCHNICK`. A numeric reply goes only to the client that sent the
|
||||||
command.
|
command.
|
||||||
@@ -168,10 +168,8 @@ either.
|
|||||||
- Request bodies for `POST /api/v1/session`, `POST /api/v1/login` and
|
- Request bodies for `POST /api/v1/session`, `POST /api/v1/login` and
|
||||||
`POST /api/v1/messages` are limited to `MAX_MESSAGE_SIZE` bytes (default
|
`POST /api/v1/messages` are limited to `MAX_MESSAGE_SIZE` bytes (default
|
||||||
`4096`). A larger body gets `400` `invalid request body`.
|
`4096`). A larger body gets `400` `invalid request body`.
|
||||||
- `GET /api/v1/server` and `GET /.well-known/healthcheck.json` answer a request
|
- The server allows cross-origin requests from any origin, with credentials. The
|
||||||
from any origin with `Access-Control-Allow-Origin: *`. Every other route sends
|
cookie is `SameSite=Strict`, so a browser sends it only from the same site.
|
||||||
no `Access-Control-Allow-*` header, so a page on another origin cannot read
|
|
||||||
its responses.
|
|
||||||
|
|
||||||
### The auth cookie
|
### The auth cookie
|
||||||
|
|
||||||
@@ -188,8 +186,8 @@ of the response does not repeat it. A browser sends the cookie by itself. Any
|
|||||||
other client must save it and send it back, as `curl -c` and `curl -b` do.
|
other client must save it and send it back, as `curl -c` and `curl -b` do.
|
||||||
|
|
||||||
The cookie is `Secure`. Chrome, Firefox, `curl` and `neoirc-cli` send it to a
|
The cookie is `Secure`. Chrome, Firefox, `curl` and `neoirc-cli` send it to a
|
||||||
server on `localhost` over plain HTTP too; Python's `requests` does not. To a
|
server on `localhost` over plain HTTP too; Python's `requests` does not. To any
|
||||||
remote host they send it only over HTTPS, which a reverse proxy provides.
|
other host they send it only over HTTPS, which a reverse proxy provides.
|
||||||
|
|
||||||
`QUIT`, `POST /api/v1/logout`, `KILL` and the idle cleanup invalidate the
|
`QUIT`, `POST /api/v1/logout`, `KILL` and the idle cleanup invalidate the
|
||||||
cookie. After that, every request with it gets `401`.
|
cookie. After that, every request with it gets `401`.
|
||||||
@@ -358,9 +356,7 @@ gets `ERR_UNKNOWNCOMMAND` (`421`) in the queue and `{"status": "error"}`.
|
|||||||
|
|
||||||
Errors at the HTTP level:
|
Errors at the HTTP level:
|
||||||
|
|
||||||
- `400` `invalid request body`: not JSON, or too large. A `PRIVMSG` or `NOTICE`
|
- `400` `invalid request body`: not JSON, or too large.
|
||||||
also gets it when `body` is not an array of strings or `meta` is not an
|
|
||||||
object.
|
|
||||||
- `400` `command required`.
|
- `400` `command required`.
|
||||||
- `401` `not registered`.
|
- `401` `not registered`.
|
||||||
- `500` `internal error`.
|
- `500` `internal error`.
|
||||||
@@ -378,9 +374,6 @@ Needs auth. Query parameters:
|
|||||||
Response `200`: an array of `PRIVMSG` messages, oldest first. History holds only
|
Response `200`: an array of `PRIVMSG` messages, oldest first. History holds only
|
||||||
`PRIVMSG`; events and `NOTICE` are left out.
|
`PRIVMSG`; events and `NOTICE` are left out.
|
||||||
|
|
||||||
Without `before`, the answer holds the newest `limit` messages. With `before`,
|
|
||||||
it holds the newest `limit` messages older than that one.
|
|
||||||
|
|
||||||
For a channel, the caller must be a member. For a nick, only the caller's own
|
For a channel, the caller must be a member. For a nick, only the caller's own
|
||||||
nick is allowed. The result is then the direct messages sent to the caller's
|
nick is allowed. The result is then the direct messages sent to the caller's
|
||||||
session, under any nick it has held. It does not hold the direct messages the
|
session, under any nick it has held. It does not hold the direct messages the
|
||||||
@@ -537,10 +530,9 @@ with these fields:
|
|||||||
- `params`: an array of strings with further parameters. `KICK` events and many
|
- `params`: an array of strings with further parameters. `KICK` events and many
|
||||||
numeric replies have it. The server ignores one sent by a client.
|
numeric replies have it. The server ignores one sent by a client.
|
||||||
- `body`: an array of strings. For chat it is the lines of text, one string per
|
- `body`: an array of strings. For chat it is the lines of text, one string per
|
||||||
line. A `body` is never a bare string. On a command other than `PRIVMSG` and
|
line. A `body` is never a bare string; a client's `body` that is not an array
|
||||||
`NOTICE`, a `body` that is not an array of strings counts as missing. Every
|
of strings counts as missing. Every numeric reply has a `body`; a few, such as
|
||||||
numeric reply has a `body`; a few, such as `RPL_CHANNELMODEIS`, carry one
|
`RPL_CHANNELMODEIS`, carry one empty string.
|
||||||
empty string.
|
|
||||||
- `ts`: when the server stored the message: UTC, RFC 3339 with fractional
|
- `ts`: when the server stored the message: UTC, RFC 3339 with fractional
|
||||||
seconds, such as `2026-02-10T20:00:00.123456789Z`; trailing zeros are dropped.
|
seconds, such as `2026-02-10T20:00:00.123456789Z`; trailing zeros are dropped.
|
||||||
The server assigns it.
|
The server assigns it.
|
||||||
@@ -602,23 +594,18 @@ Replies and errors:
|
|||||||
- `ERR_NORECIPIENT` (`411`): no `to`.
|
- `ERR_NORECIPIENT` (`411`): no `to`.
|
||||||
- `ERR_NOTEXTTOSEND` (`412`): no `body`, or an empty one.
|
- `ERR_NOTEXTTOSEND` (`412`): no `body`, or an empty one.
|
||||||
- `ERR_NOSUCHCHANNEL` (`403`): the channel does not exist.
|
- `ERR_NOSUCHCHANNEL` (`403`): the channel does not exist.
|
||||||
- `ERR_CANNOTSENDTOCHAN` (`404`): the message is not allowed:
|
- `ERR_CANNOTSENDTOCHAN` (`404`): the message is not allowed. The `body` says
|
||||||
|
why:
|
||||||
- the sender is not a member;
|
- the sender is not a member;
|
||||||
- the sender is banned (`+b`);
|
- the sender is banned (`+b`);
|
||||||
- the channel is moderated (`+m`) and the sender has neither `+o` nor `+v`;
|
- the channel is moderated (`+m`) and the sender has neither `+o` nor `+v`;
|
||||||
- the channel is `+H` and the message has no valid hashcash stamp.
|
- the channel is `+H` and the message has no valid hashcash stamp.
|
||||||
|
|
||||||
The `body` names the reason in the last three cases.
|
|
||||||
|
|
||||||
- `ERR_NOSUCHNICK` (`401`): no session has the target nick.
|
- `ERR_NOSUCHNICK` (`401`): no session has the target nick.
|
||||||
- `RPL_AWAY` (`301`): the target of a direct message is away. The message is
|
- `RPL_AWAY` (`301`): the target of a direct message is away. The message is
|
||||||
still delivered. `params` holds the nick and `body` the away message.
|
still delivered. `params` holds the nick and `body` the away message.
|
||||||
|
|
||||||
HTTP response: `{"id": "<message id>", "status": "sent"}`.
|
HTTP response: `{"id": "<message id>", "status": "sent"}`.
|
||||||
|
|
||||||
A `body` or `meta` of the wrong type gets `400` `invalid request body`, and
|
|
||||||
nothing is relayed.
|
|
||||||
|
|
||||||
#### `NOTICE`: send a notice
|
#### `NOTICE`: send a notice
|
||||||
|
|
||||||
The same as `PRIVMSG`, with three differences:
|
The same as `PRIVMSG`, with three differences:
|
||||||
@@ -986,9 +973,9 @@ HTTP response: `{"status": "ok"}`.
|
|||||||
|
|
||||||
The server adds a missing `#`. The reply is `RPL_NAMREPLY` (`353`), when the
|
The server adds a missing `#`. The reply is `RPL_NAMREPLY` (`353`), when the
|
||||||
channel has members, then `RPL_ENDOFNAMES` (`366`). `RPL_NAMREPLY` has `params`
|
channel has members, then `RPL_ENDOFNAMES` (`366`). `RPL_NAMREPLY` has `params`
|
||||||
`["=", channel]` and a `body` with one string. That string holds the members'
|
`["=", channel]` and a `body` with one string: the members' hostmasks in nick
|
||||||
hostmasks in nick order, separated by spaces. A `@` before a hostmask marks a
|
order, separated by spaces, each with `@` before a channel operator and `+`
|
||||||
channel operator, and a `+` marks a voiced member:
|
before a voiced member:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -1200,7 +1187,7 @@ out when the message of the day is empty (see the `MOTD` setting under
|
|||||||
- `002` `RPL_YOURHOST`: `Your host is <server name>, running version <version>`.
|
- `002` `RPL_YOURHOST`: `Your host is <server name>, running version <version>`.
|
||||||
`<version>` is `dev` in a binary built without one.
|
`<version>` is `dev` in a binary built without one.
|
||||||
- `003` `RPL_CREATED`: `This server was created <date the server started>`.
|
- `003` `RPL_CREATED`: `This server was created <date the server started>`.
|
||||||
- `004` `RPL_MYINFO`: `params` `[server name, version, "ow", "Hbiklmnostv"]`.
|
- `004` `RPL_MYINFO`: `params` `[server name, version, "", "ikmnostl"]`.
|
||||||
- `005` `RPL_BOUNCE`: `params`
|
- `005` `RPL_BOUNCE`: `params`
|
||||||
`["CHANTYPES=#", "NICKLEN=32", "PREFIX=(ov)@+", "CHANMODES=b,k,Hl,imnst", "NETWORK=neoirc", "CASEMAPPING=ascii"]`,
|
`["CHANTYPES=#", "NICKLEN=32", "PREFIX=(ov)@+", "CHANMODES=b,k,Hl,imnst", "NETWORK=neoirc", "CASEMAPPING=ascii"]`,
|
||||||
`body` `["are supported by this server"]`.
|
`body` `["are supported by this server"]`.
|
||||||
@@ -1341,9 +1328,8 @@ Every session has a hostmask in IRC's form, `nick!username@hostname`:
|
|||||||
from, or that IP address when the lookup gives no name. The lookup waits up to
|
from, or that IP address when the lookup gives no name. The lookup waits up to
|
||||||
three seconds.
|
three seconds.
|
||||||
|
|
||||||
Over the HTTP API, the client's IP address is the address of the TCP connection.
|
Over the HTTP API, the server takes the client's IP address from the first entry
|
||||||
When that connection comes from a trusted proxy, the server reads the address
|
of the `X-Forwarded-For` header, then `X-Real-IP`, then the TCP connection (see
|
||||||
from `X-Forwarded-For` or `X-Real-IP` instead (see
|
|
||||||
[Reverse proxy](#reverse-proxy)).
|
[Reverse proxy](#reverse-proxy)).
|
||||||
|
|
||||||
Every user can see a hostmask: in `RPL_WHOISUSER` (`311`), `RPL_WHOREPLY`
|
Every user can see a hostmask: in `RPL_WHOISUSER` (`311`), `RPL_WHOREPLY`
|
||||||
@@ -1453,9 +1439,10 @@ over the limit gets `429` `too many login attempts, try again later` with
|
|||||||
attempt is more than 15 minutes old. Session creation has no rate limit; the
|
attempt is more than 15 minutes old. Session creation has no rate limit; the
|
||||||
hashcash stamp is its cost.
|
hashcash stamp is its cost.
|
||||||
|
|
||||||
The IP address is the client's address as described in
|
The IP address comes from the first entry of `X-Forwarded-For`, else from
|
||||||
[Reverse proxy](#reverse-proxy). A client outside the trusted proxies cannot
|
`X-Real-IP`, else from the TCP connection. Without a reverse proxy that
|
||||||
change it with `X-Forwarded-For` or `X-Real-IP`.
|
overwrites those headers, a client can set them itself and so pick any address
|
||||||
|
(see [Reverse proxy](#reverse-proxy)).
|
||||||
|
|
||||||
### Writing a client
|
### Writing a client
|
||||||
|
|
||||||
@@ -1584,9 +1571,8 @@ completes.
|
|||||||
|
|
||||||
After registration the client receives `001` to `005`, the `LUSERS` replies and
|
After registration the client receives `001` to `005`, the `LUSERS` replies and
|
||||||
the message of the day, or `ERR_NOMOTD` (`422`) when that is empty. The `004`
|
the message of the day, or `ERR_NOMOTD` (`422`) when that is empty. The `004`
|
||||||
user modes are `ow` and its channel modes are `Himnostv`. The `005` tokens are
|
modes are `mnst` and the `005` tokens `CHANTYPES=#`, `NICKLEN=32`,
|
||||||
`CHANTYPES=#`, `NICKLEN=32`, `PREFIX=(ov)@+`, `CHANMODES=,,H,imnst` and
|
`PREFIX=(ov)@+`, `CHANMODES=,,H,imnst` and `NETWORK=<server name>`.
|
||||||
`NETWORK=<server name>`.
|
|
||||||
|
|
||||||
`CAP LS` is answered with an empty capability list; other `CAP` subcommands are
|
`CAP LS` is answered with an empty capability list; other `CAP` subcommands are
|
||||||
ignored.
|
ignored.
|
||||||
@@ -1595,10 +1581,10 @@ When a connection has sent nothing for 90 seconds, the server sends `PING`. When
|
|||||||
nothing arrives in the 30 seconds after that, the server closes the connection.
|
nothing arrives in the 30 seconds after that, the server closes the connection.
|
||||||
Any line, such as the client's `PONG`, starts both waits again.
|
Any line, such as the client's `PONG`, starts both waits again.
|
||||||
|
|
||||||
Closing the connection ends the session, as `QUIT` does over the HTTP API. After
|
Closing the connection, with or without `QUIT`, ends the session, as `QUIT` does
|
||||||
a `QUIT`, channel peers see the reason the client gave, or `Client quit` when it
|
over the HTTP API. Its channel peers see a `QUIT` with the reason
|
||||||
gave none. Without a `QUIT`, they see `Connection closed`. Every command after
|
`Connection closed`; the reason given to `QUIT` is not relayed. Every command
|
||||||
registration counts as activity for the idle cleanup.
|
after registration counts as activity for the idle cleanup.
|
||||||
|
|
||||||
### Commands
|
### Commands
|
||||||
|
|
||||||
@@ -1639,9 +1625,9 @@ They behave as over the HTTP API, with the IRC syntax and these differences:
|
|||||||
- `KICK` without a reason uses the kicked user's nick as the reason.
|
- `KICK` without a reason uses the kicked user's nick as the reason.
|
||||||
- `MOTD` sends only `375` to `376`, or `ERR_NOMOTD` (`422`) when the message of
|
- `MOTD` sends only `375` to `376`, or `ERR_NOMOTD` (`422`) when the message of
|
||||||
the day is empty, without the welcome and `LUSERS` replies.
|
the day is empty, without the welcome and `LUSERS` replies.
|
||||||
- `PASS` after registration answers with a `NOTICE` when it stores the password.
|
- `PASS` after registration answers a password of the wrong length with a
|
||||||
A password of the wrong length also gets a `NOTICE`, not `ERR_NEEDMOREPARAMS`
|
`NOTICE`, not `ERR_NEEDMOREPARAMS` (`461`), and a stored password with a
|
||||||
(`461`).
|
`NOTICE` too.
|
||||||
|
|
||||||
### What IRC clients see
|
### What IRC clients see
|
||||||
|
|
||||||
@@ -1699,9 +1685,10 @@ It starts disconnected. Commands start with `/`:
|
|||||||
- `/quit`: send `QUIT` and exit. `/help`: the command list.
|
- `/quit`: send `QUIT` and exit. `/help`: the command list.
|
||||||
|
|
||||||
Text without a `/` goes as a `PRIVMSG` to the current target. `/join` and
|
Text without a `/` goes as a `PRIVMSG` to the current target. `/join` and
|
||||||
`/query` set the target to the channel or user they open. `/window`, `/w` and
|
`/query` set the target to the channel or user they open. `/window` and `/w` set
|
||||||
Alt with a digit set it to the channel or user of the window they switch to. A
|
it to the channel or user of the window they switch to; a switch to window `0`
|
||||||
switch to window `0` clears it, and so does `/part` of the target's channel.
|
leaves it as it was. Alt and a digit switches the window shown and leaves the
|
||||||
|
target as it was. `/part` of the target's channel clears it.
|
||||||
|
|
||||||
The client reads its queue with `timeout=15` and retries after two seconds on an
|
The client reads its queue with `timeout=15` and retries after two seconds on an
|
||||||
error. It sends no hashcash stamps for `+H` channels. It sends the auth cookie
|
error. It sends no hashcash stamps for `+H` channels. It sends the auth cookie
|
||||||
@@ -1716,18 +1703,12 @@ Every setting is an environment variable. The server also reads a `.env` file in
|
|||||||
its working directory, and a YAML file `neoirc.yaml` in `/etc/neoirc/` or
|
its working directory, and a YAML file `neoirc.yaml` in `/etc/neoirc/` or
|
||||||
`$HOME/.config/neoirc/` with the same names as keys. A variable from the
|
`$HOME/.config/neoirc/` with the same names as keys. A variable from the
|
||||||
environment wins over one in `.env`, and both win over `neoirc.yaml`. An
|
environment wins over one in `.env`, and both win over `neoirc.yaml`. An
|
||||||
environment variable set to the empty string counts as unset, with two
|
environment variable set to the empty string counts as unset, except
|
||||||
exceptions:
|
`IRC_LISTEN_ADDR`, where the empty string turns the IRC listener off. A
|
||||||
|
`neoirc.yaml` that is not valid YAML stops the server at startup.
|
||||||
|
|
||||||
- For `IRC_LISTEN_ADDR`, the empty string turns the IRC listener off.
|
- `PORT` (default `8080`): the HTTP port. A value that is not a whole number
|
||||||
- For `TRUSTED_PROXIES`, the empty string trusts no proxy.
|
counts as `0`, and the system then picks a free port.
|
||||||
|
|
||||||
A `neoirc.yaml` that is not valid YAML stops the server at startup. A setting
|
|
||||||
that does not parse or is out of range also stops the server at startup, and the
|
|
||||||
error names the setting. The same holds for a setting given a list or a map in
|
|
||||||
`neoirc.yaml`.
|
|
||||||
|
|
||||||
- `PORT` (default `8080`): the HTTP port. `0` lets the system pick a free port.
|
|
||||||
- `IRC_LISTEN_ADDR` (default `:6667`): the address of the IRC listener. The
|
- `IRC_LISTEN_ADDR` (default `:6667`): the address of the IRC listener. The
|
||||||
empty string turns the listener off.
|
empty string turns the listener off.
|
||||||
- `DBURL` (default
|
- `DBURL` (default
|
||||||
@@ -1744,29 +1725,28 @@ error names the setting. The same holds for a setting given a list or a map in
|
|||||||
separated by newlines. An empty environment variable counts as unset and gives
|
separated by newlines. An empty environment variable counts as unset and gives
|
||||||
the banner. To send no message of the day, put `MOTD: ""` in `neoirc.yaml`.
|
the banner. To send no message of the day, put `MOTD: ""` in `neoirc.yaml`.
|
||||||
- `NEOIRC_HASHCASH_BITS` (default `20`): the difficulty of the stamp
|
- `NEOIRC_HASHCASH_BITS` (default `20`): the difficulty of the stamp
|
||||||
`POST /api/v1/session` needs. `0` turns the requirement off.
|
`POST /api/v1/session` needs. `0` turns the requirement off, and so does a
|
||||||
|
value that is not a whole number.
|
||||||
- `NEOIRC_OPER_NAME` and `NEOIRC_OPER_PASSWORD` (default empty): the name and
|
- `NEOIRC_OPER_NAME` and `NEOIRC_OPER_PASSWORD` (default empty): the name and
|
||||||
password `OPER` accepts. `OPER` fails while either is empty.
|
password `OPER` accepts. `OPER` fails while either is empty.
|
||||||
- `MAX_MESSAGE_SIZE` (default `4096`): the largest request body, in bytes, for
|
- `MAX_MESSAGE_SIZE` (default `4096`): the largest request body, in bytes, for
|
||||||
`POST /api/v1/session`, `POST /api/v1/login` and `POST /api/v1/messages`. It
|
`POST /api/v1/session`, `POST /api/v1/login` and `POST /api/v1/messages`. A
|
||||||
must be at least `1`.
|
value of `0` or less, or one that is not a whole number, means the default.
|
||||||
- `LOGIN_RATE_LIMIT` (default `1`): login attempts allowed per second per IP
|
- `LOGIN_RATE_LIMIT` (default `1`): login attempts allowed per second per IP
|
||||||
address. A fraction such as `0.5` is allowed. It must be above `0`.
|
address. A fraction such as `0.5` is allowed. A value of `0` or less, or one
|
||||||
|
that is not a number, means the default.
|
||||||
- `LOGIN_RATE_BURST` (default `5`): how many attempts an address may make at
|
- `LOGIN_RATE_BURST` (default `5`): how many attempts an address may make at
|
||||||
once before the rate applies. It must be at least `1`.
|
once before the rate applies. A value of `0` or less, or one that is not a
|
||||||
- `TRUSTED_PROXIES` (default `10.0.0.0/8,172.16.0.0/12,192.168.0.0/16`): the
|
whole number, means the default.
|
||||||
reverse proxies whose `X-Forwarded-For` and `X-Real-IP` headers the server
|
|
||||||
believes. It is a comma-separated list of networks, such as `10.0.0.0/8`, and
|
|
||||||
single addresses, such as `192.0.2.1`. A list replaces the default entirely.
|
|
||||||
The empty string trusts nothing. See [Reverse proxy](#reverse-proxy).
|
|
||||||
- `SESSION_IDLE_TIMEOUT` (default `720h`, 30 days): a duration with a unit, `h`
|
- `SESSION_IDLE_TIMEOUT` (default `720h`, 30 days): a duration with a unit, `h`
|
||||||
for hours, `m` for minutes or `s` for seconds, such as `720h` or `36h30m`. A
|
for hours, `m` for minutes or `s` for seconds, such as `720h` or `36h30m`. A
|
||||||
client with no request for this long is removed, and a session left with no
|
client with no request for this long is removed, and a session left with no
|
||||||
client ends. See [Data lifecycle](#data-lifecycle). It must be above zero.
|
client ends. See [Data lifecycle](#data-lifecycle). A value that is not a
|
||||||
|
duration is logged, and the default applies.
|
||||||
- `MESSAGE_MAX_AGE` (default `720h`): messages older than this duration are
|
- `MESSAGE_MAX_AGE` (default `720h`): messages older than this duration are
|
||||||
deleted. It must be above zero.
|
deleted. A value that is not a duration is logged, and no message is deleted.
|
||||||
- `QUEUE_MAX_AGE` (default `720h`): queue entries older than this duration are
|
- `QUEUE_MAX_AGE` (default `720h`): queue entries older than this duration are
|
||||||
deleted. It must be above zero.
|
deleted. A value that is not a duration is logged, and no entry is deleted.
|
||||||
- `DEBUG` (default `false`): `true` turns on debug logging.
|
- `DEBUG` (default `false`): `true` turns on debug logging.
|
||||||
- `SENTRY_DSN` (default empty): when set, panics in HTTP requests are reported
|
- `SENTRY_DSN` (default empty): when set, panics in HTTP requests are reported
|
||||||
to Sentry. A value that is not a valid DSN stops the server at startup.
|
to Sentry. A value that is not a valid DSN stops the server at startup.
|
||||||
@@ -1793,17 +1773,13 @@ NEOIRC_HASHCASH_BITS=20
|
|||||||
the linter first and stops when either fails. The image:
|
the linter first and stops when either fails. The image:
|
||||||
|
|
||||||
- is Alpine with the `neoircd` binary and CA certificates;
|
- is Alpine with the `neoircd` binary and CA certificates;
|
||||||
- runs `neoircd` as the user `neoirc`;
|
- runs as the user `neoirc`;
|
||||||
- exposes ports 8080 and 6667;
|
- exposes ports 8080 and 6667;
|
||||||
- keeps its database in `/var/lib/neoirc`;
|
- keeps its database in `/var/lib/neoirc`;
|
||||||
- has a `HEALTHCHECK` that calls `/.well-known/healthcheck.json` every 30
|
- has a `HEALTHCHECK` that calls `/.well-known/healthcheck.json` every 30
|
||||||
seconds.
|
seconds.
|
||||||
|
|
||||||
The image prepares `/var/lib/neoirc` itself on every start. It creates the
|
Run it with a volume for the database and the settings as environment variables:
|
||||||
directory, gives it to `neoirc` and then runs `neoircd` as `neoirc`.
|
|
||||||
|
|
||||||
Run it with a named volume for the database and the settings as environment
|
|
||||||
variables:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -d --name neoirc \
|
docker run -d --name neoirc \
|
||||||
@@ -1814,51 +1790,20 @@ docker run -d --name neoirc \
|
|||||||
neoirc
|
neoirc
|
||||||
```
|
```
|
||||||
|
|
||||||
A host directory works the same way in place of the named volume:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run -d --name neoirc \
|
|
||||||
-p 8080:8080 -p 6667:6667 \
|
|
||||||
-v /srv/neoirc:/var/lib/neoirc \
|
|
||||||
-e SERVER_NAME="My Server" \
|
|
||||||
-e MOTD="Welcome!" \
|
|
||||||
neoirc
|
|
||||||
```
|
|
||||||
|
|
||||||
### Reverse proxy
|
### Reverse proxy
|
||||||
|
|
||||||
Run the server behind a reverse proxy that terminates TLS. The server itself
|
Run the server behind a reverse proxy that terminates TLS. The server itself
|
||||||
speaks plain HTTP, and the auth cookie is `Secure`, so browsers send it only
|
speaks plain HTTP, and the auth cookie is `Secure`, so browsers send it only
|
||||||
over HTTPS. The proxy must:
|
over HTTPS. The proxy must:
|
||||||
|
|
||||||
- Connect from an address in `TRUSTED_PROXIES`. The default trusts the private
|
- Set `X-Forwarded-For` to the client's address, replacing any value the client
|
||||||
ranges `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`. The setting must
|
sent. The server reads that header first and trusts it from anyone; it reads
|
||||||
hold the address the server sees the proxy connect from. For a proxy on the
|
`X-Real-IP` only when `X-Forwarded-For` is absent. Without a proxy that
|
||||||
same host:
|
overwrites the header, a client can choose its own address, which sets its
|
||||||
- With the server outside Docker, that address is `127.0.0.1` or `::1`. The
|
hostname and lets it dodge the login rate limit.
|
||||||
default does not trust them, so set `TRUSTED_PROXIES=127.0.0.1,::1`.
|
|
||||||
- Through a published Docker port, that address is the Docker bridge
|
|
||||||
gateway, such as `172.17.0.1`. The default trusts it.
|
|
||||||
- Add the client's address to `X-Forwarded-For`.
|
|
||||||
- Wait at least 60 seconds for a response. A long poll can take 30 seconds, and
|
- Wait at least 60 seconds for a response. A long poll can take 30 seconds, and
|
||||||
the server's own write timeout is 60 seconds.
|
the server's own write timeout is 60 seconds.
|
||||||
|
|
||||||
The server finds the client's address in these steps:
|
|
||||||
|
|
||||||
- A connection from outside `TRUSTED_PROXIES` is the client. The server ignores
|
|
||||||
its `X-Forwarded-For` and `X-Real-IP` headers.
|
|
||||||
- For a connection from a trusted proxy, the server reads `X-Forwarded-For` from
|
|
||||||
right to left. It skips trusted addresses and takes the first untrusted one.
|
|
||||||
When every entry is trusted, it takes the leftmost.
|
|
||||||
- Without `X-Forwarded-For`, the server takes `X-Real-IP`.
|
|
||||||
- When an entry it reads is not an IP address, the server uses the proxy's
|
|
||||||
address.
|
|
||||||
|
|
||||||
The client's address sets the session's hostname and counts toward the login
|
|
||||||
rate limit. Any connection from a trusted address can choose its client address
|
|
||||||
through `X-Forwarded-For`. If clients connect directly from private addresses,
|
|
||||||
set `TRUSTED_PROXIES` to the proxy's address alone.
|
|
||||||
|
|
||||||
Caddy:
|
Caddy:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -1895,34 +1840,22 @@ The IRC listener has no TLS.
|
|||||||
seconds. A request still running after 60 seconds is cancelled, and the
|
seconds. A request still running after 60 seconds is cancelled, and the
|
||||||
connection closes without a response. Headers may be up to 1 MiB.
|
connection closes without a response. Headers may be up to 1 MiB.
|
||||||
- A long poll waits at most 30 seconds.
|
- A long poll waits at most 30 seconds.
|
||||||
- Every response to a well-formed request carries a `Content-Security-Policy`
|
- Every response to a well-formed request, except to a cross-origin preflight,
|
||||||
header:
|
carries a `Content-Security-Policy` header:
|
||||||
`default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'`.
|
`default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'`.
|
||||||
The web client works within it.
|
The web client works within it.
|
||||||
- `GET /api/v1/server` and `GET /.well-known/healthcheck.json` answer a request
|
- Cross-origin requests are allowed from any origin, with credentials. The
|
||||||
from any origin with `Access-Control-Allow-Origin: *`. Every other route sends
|
allowed methods are `GET`, `POST`, `PUT`, `DELETE` and `OPTIONS`. The allowed
|
||||||
no `Access-Control-Allow-*` header, so a page on another origin cannot read
|
request headers are `Accept`, `Content-Type` and `X-CSRF-Token`. The cookie's
|
||||||
its responses.
|
`SameSite=Strict` still keeps it to the same site.
|
||||||
|
|
||||||
### Logging
|
### Logging
|
||||||
|
|
||||||
The server logs with Go's `slog`, one line per event, to standard output. The
|
The server logs with Go's `slog`, one line per event, to standard output. The
|
||||||
lines are JSON, or plain text when standard output is a terminal. Every HTTP
|
lines are JSON, or plain text when standard output is a terminal. Every HTTP
|
||||||
request is logged with:
|
request is logged with its method, URL, protocol, status, latency, remote
|
||||||
|
address, user agent, referrer and request ID. `DEBUG=true` adds debug-level
|
||||||
- start time
|
lines.
|
||||||
- method
|
|
||||||
- URL
|
|
||||||
- protocol
|
|
||||||
- status
|
|
||||||
- latency
|
|
||||||
- client address
|
|
||||||
- user agent
|
|
||||||
- referrer
|
|
||||||
- request ID
|
|
||||||
|
|
||||||
The client address is the one found as described in
|
|
||||||
[Reverse proxy](#reverse-proxy). `DEBUG=true` adds debug-level lines.
|
|
||||||
|
|
||||||
### The database
|
### The database
|
||||||
|
|
||||||
@@ -2005,8 +1938,8 @@ and their sessions to end. Then it closes the database.
|
|||||||
gets a message.
|
gets a message.
|
||||||
- `internal/hashcash/`: stamp checking and minting.
|
- `internal/hashcash/`: stamp checking and minting.
|
||||||
- `internal/ratelimit/`: the per-address login rate limiter.
|
- `internal/ratelimit/`: the per-address login rate limiter.
|
||||||
- `internal/middleware/`: finding the client's address, request logging,
|
- `internal/middleware/`: request logging, cross-origin requests, the
|
||||||
cross-origin requests, the `Content-Security-Policy` header and metrics.
|
`Content-Security-Policy` header and metrics.
|
||||||
- `internal/healthcheck/` and `internal/stats/`: the health check and its
|
- `internal/healthcheck/` and `internal/stats/`: the health check and its
|
||||||
counters.
|
counters.
|
||||||
- `internal/logger/` and `internal/globals/`: logging setup and build
|
- `internal/logger/` and `internal/globals/`: logging setup and build
|
||||||
@@ -2018,8 +1951,6 @@ and their sessions to end. Then it closes the database.
|
|||||||
- `schema/`: JSON Schema files for the message envelope, with their own
|
- `schema/`: JSON Schema files for the message envelope, with their own
|
||||||
`README.md`.
|
`README.md`.
|
||||||
- `script/`: the entrypoints below.
|
- `script/`: the entrypoints below.
|
||||||
- `deploy/`: `docker-entrypoint.sh`, the image's entrypoint, which prepares
|
|
||||||
`/var/lib/neoirc` and starts `neoircd` as `neoirc`.
|
|
||||||
- `CONVENTIONS.md`, `REPO_POLICIES.md` and `AGENTS.md`: the architecture
|
- `CONVENTIONS.md`, `REPO_POLICIES.md` and `AGENTS.md`: the architecture
|
||||||
conventions, the repository policies and the rules for coding agents.
|
conventions, the repository policies and the rules for coding agents.
|
||||||
|
|
||||||
@@ -2031,16 +1962,15 @@ standard. Each script has a `make` target of the same name, except
|
|||||||
`script/install-precommit`, which is `make hooks`, and `script/cibuild`,
|
`script/install-precommit`, which is `make hooks`, and `script/cibuild`,
|
||||||
`script/precommit` and `script/projectname`, which have none.
|
`script/precommit` and `script/projectname`, which have none.
|
||||||
|
|
||||||
- `script/bootstrap`: installs `make`, `git`, Go, Node and `yarn`, and
|
- `script/bootstrap`: installs `make`, `git`, Go, Node and `yarn`, and prettier
|
||||||
`prettier` through `yarn`. Docker must already be installed.
|
through `yarn`. Docker must already be installed.
|
||||||
- `script/setup`: makes a fresh clone ready: runs `script/bootstrap`, then
|
- `script/setup`: makes a fresh clone ready: runs `script/bootstrap`, then
|
||||||
`script/install-precommit`.
|
`script/install-precommit`.
|
||||||
- `script/test`: builds the `Dockerfile`'s `test` stage, which runs the tests
|
- `script/test`: builds the `Dockerfile`'s `test` stage, which runs the tests
|
||||||
with `-race`.
|
with `-race`.
|
||||||
- `script/lint`: builds the `Dockerfile`'s `lint` stage, which runs
|
- `script/lint`: builds the `Dockerfile`'s `lint` stage, which runs
|
||||||
`golangci-lint`.
|
golangci-lint.
|
||||||
- `script/fmt`: formats the Go code with `gofmt` and the Markdown with
|
- `script/fmt`: formats the Go code with `gofmt` and the Markdown with prettier.
|
||||||
`prettier`.
|
|
||||||
- `script/fmt-check`: the same, read-only; fails if anything would change.
|
- `script/fmt-check`: the same, read-only; fails if anything would change.
|
||||||
- `script/check`: runs `script/test`, `script/lint` and `script/fmt-check`.
|
- `script/check`: runs `script/test`, `script/lint` and `script/fmt-check`.
|
||||||
- `script/docker`: builds the image, tagged `neoirc`.
|
- `script/docker`: builds the image, tagged `neoirc`.
|
||||||
@@ -2058,9 +1988,7 @@ standard. Each script has a `make` target of the same name, except
|
|||||||
`/`. To include the web client, build it first: in `web/`, run
|
`/`. To include the web client, build it first: in `web/`, run
|
||||||
`yarn install --frozen-lockfile` and `sh build.sh`.
|
`yarn install --frozen-lockfile` and `sh build.sh`.
|
||||||
- `make run`: builds and starts the server. `make debug` does the same with
|
- `make run`: builds and starts the server. `make debug` does the same with
|
||||||
`DEBUG=1`. With the default `DBURL`, both stop at startup when
|
`DEBUG=1`.
|
||||||
`/var/lib/neoirc/` does not exist or is not writable. Set `DBURL` to a
|
|
||||||
writable path to avoid that.
|
|
||||||
- `make clean`: removes `bin/`.
|
- `make clean`: removes `bin/`.
|
||||||
- `make check`: runs `script/check`. `make test`, `make lint`, `make fmt` and
|
- `make check`: runs `script/check`. `make test`, `make lint`, `make fmt` and
|
||||||
`make fmt-check` run the script of the same name.
|
`make fmt-check` run the script of the same name.
|
||||||
@@ -2072,8 +2000,8 @@ standard. Each script has a `make` target of the same name, except
|
|||||||
The tests and the linter run inside Docker, as stages of the `Dockerfile`, so
|
The tests and the linter run inside Docker, as stages of the `Dockerfile`, so
|
||||||
every developer and the CI run the same toolchain. `make test` builds the `test`
|
every developer and the CI run the same toolchain. `make test` builds the `test`
|
||||||
stage: `go test -race` over every package, with a 90-second limit. `make lint`
|
stage: `go test -race` over every package, with a 90-second limit. `make lint`
|
||||||
builds the `lint` stage, which runs `golangci-lint` with the shared
|
builds the `lint` stage, which runs golangci-lint with the shared
|
||||||
`.golangci.yml`. `make fmt-check` runs `gofmt` and `prettier` on the host. Tests
|
`.golangci.yml`. `make fmt-check` runs `gofmt` and prettier on the host. Tests
|
||||||
live next to the code, most in `_test` packages. A test that needs a database
|
live next to the code, most in `_test` packages. A test that needs a database
|
||||||
gets an in-memory one of its own from `internal/dbtest`, which holds a second
|
gets an in-memory one of its own from `internal/dbtest`, which holds a second
|
||||||
connection open to keep it.
|
connection open to keep it.
|
||||||
@@ -2081,9 +2009,9 @@ connection open to keep it.
|
|||||||
The `Dockerfile` has five stages:
|
The `Dockerfile` has five stages:
|
||||||
|
|
||||||
1. `web-builder`: installs the web client's Node dependencies and bundles
|
1. `web-builder`: installs the web client's Node dependencies and bundles
|
||||||
`web/src/app.jsx` with `esbuild` into `web/dist/`.
|
`web/src/app.jsx` with esbuild into `web/dist/`.
|
||||||
2. `lint`: runs `golangci-lint`, with placeholder files in `web/dist/` so that
|
2. `lint`: runs golangci-lint, with placeholder files in `web/dist/` so that it
|
||||||
it does not wait for the web build.
|
does not wait for the web build.
|
||||||
3. `test`: runs the tests, with the same placeholders.
|
3. `test`: runs the tests, with the same placeholders.
|
||||||
4. `builder`: runs only after `lint` and `test` have passed. It compiles
|
4. `builder`: runs only after `lint` and `test` have passed. It compiles
|
||||||
`neoircd` with the real web client, and compiles `neoirc-cli` to check that
|
`neoircd` with the real web client, and compiles `neoirc-cli` to check that
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# deploy/docker-entrypoint.sh: the image's ENTRYPOINT, run as root. A host
|
|
||||||
# directory mounted at /var/lib/neoirc keeps the host's owner, so this gives
|
|
||||||
# it to neoirc before running neoircd as neoirc.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
main() {
|
|
||||||
mkdir -p /var/lib/neoirc
|
|
||||||
chown -R neoirc:neoirc /var/lib/neoirc
|
|
||||||
chmod 0700 /var/lib/neoirc
|
|
||||||
exec su-exec neoirc neoircd "$@"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -13,10 +13,8 @@ require (
|
|||||||
github.com/prometheus/client_golang v1.23.2
|
github.com/prometheus/client_golang v1.23.2
|
||||||
github.com/rivo/tview v0.42.0
|
github.com/rivo/tview v0.42.0
|
||||||
github.com/slok/go-http-metrics v0.13.0
|
github.com/slok/go-http-metrics v0.13.0
|
||||||
github.com/spf13/cast v1.10.0
|
|
||||||
github.com/spf13/viper v1.21.0
|
github.com/spf13/viper v1.21.0
|
||||||
go.uber.org/fx v1.24.0
|
go.uber.org/fx v1.24.0
|
||||||
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb
|
|
||||||
golang.org/x/crypto v0.48.0
|
golang.org/x/crypto v0.48.0
|
||||||
golang.org/x/time v0.6.0
|
golang.org/x/time v0.6.0
|
||||||
modernc.org/sqlite v1.45.0
|
modernc.org/sqlite v1.45.0
|
||||||
@@ -42,6 +40,7 @@ require (
|
|||||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||||
github.com/spf13/afero v1.15.0 // indirect
|
github.com/spf13/afero v1.15.0 // indirect
|
||||||
|
github.com/spf13/cast v1.10.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.10 // indirect
|
github.com/spf13/pflag v1.0.10 // indirect
|
||||||
github.com/subosito/gotenv v1.6.0 // indirect
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
go.uber.org/dig v1.19.0 // indirect
|
go.uber.org/dig v1.19.0 // indirect
|
||||||
|
|||||||
@@ -111,8 +111,6 @@ go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
|||||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs=
|
|
||||||
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||||
|
|||||||
+85
-147
@@ -34,42 +34,28 @@ type App struct {
|
|||||||
|
|
||||||
// Run creates and runs the CLI application.
|
// Run creates and runs the CLI application.
|
||||||
func Run() {
|
func Run() {
|
||||||
err := run(NewUI())
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// run starts the client on ui and returns when ui stops. Tests
|
|
||||||
// call it with ui on a simulation screen.
|
|
||||||
func run(ui *UI) error {
|
|
||||||
app := &App{ //nolint:exhaustruct
|
app := &App{ //nolint:exhaustruct
|
||||||
ui: ui,
|
ui: NewUI(),
|
||||||
nick: "guest",
|
nick: "guest",
|
||||||
}
|
}
|
||||||
|
|
||||||
app.ui.OnInput(app.handleInput)
|
app.ui.OnInput(app.handleInput)
|
||||||
|
app.ui.SetStatus(app.nick, "", "disconnected")
|
||||||
|
|
||||||
// SetStatus and AddStatus wait for the event loop, which
|
app.ui.AddStatus(
|
||||||
// app.ui.Run starts below, so they run on a goroutine. The
|
"Welcome to neoirc-cli — an IRC-style client",
|
||||||
// nick is read first, as a typed /nick may change app.nick.
|
)
|
||||||
nick := app.nick
|
app.ui.AddStatus(
|
||||||
|
"Type [yellow]/connect <server-url>" +
|
||||||
|
"[white] to begin, " +
|
||||||
|
"or [yellow]/help[white] for commands",
|
||||||
|
)
|
||||||
|
|
||||||
go func() {
|
err := app.ui.Run()
|
||||||
app.ui.SetStatus(nick, "", "disconnected")
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
app.ui.AddStatus(
|
os.Exit(1)
|
||||||
"Welcome to neoirc-cli — an IRC-style client",
|
}
|
||||||
)
|
|
||||||
app.ui.AddStatus(
|
|
||||||
"Type [yellow]/connect <server-url>" +
|
|
||||||
"[white] to begin, " +
|
|
||||||
"or [yellow]/help[white] for commands",
|
|
||||||
)
|
|
||||||
}()
|
|
||||||
|
|
||||||
return app.ui.Run()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) handleInput(text string) {
|
func (a *App) handleInput(text string) {
|
||||||
@@ -108,7 +94,7 @@ func (a *App) handleInput(text string) {
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(
|
||||||
"[red]Send error: " + escape(err.Error()),
|
"[red]Send error: " + err.Error(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,7 +152,7 @@ func (a *App) dispatchInfoCommand(cmd, args string) {
|
|||||||
a.cmdWhois(args)
|
a.cmdWhois(args)
|
||||||
default:
|
default:
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(
|
||||||
"[red]Unknown command: " + escape(cmd),
|
"[red]Unknown command: " + cmd,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,7 +168,7 @@ func (a *App) cmdConnect(serverURL string) {
|
|||||||
|
|
||||||
serverURL = strings.TrimRight(serverURL, "/")
|
serverURL = strings.TrimRight(serverURL, "/")
|
||||||
|
|
||||||
a.ui.AddStatus("Connecting to " + escape(serverURL) + "...")
|
a.ui.AddStatus("Connecting to " + serverURL + "...")
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
@@ -192,37 +178,29 @@ func (a *App) cmdConnect(serverURL string) {
|
|||||||
|
|
||||||
resp, err := client.CreateSession(nick)
|
resp, err := client.CreateSession(nick)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Connection failed: " + escape(err.Error()),
|
"[red]Connection failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The poll loop of an earlier connection is stopped in the same
|
|
||||||
// step that replaces the client, so it never polls with the new
|
|
||||||
// one.
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.client = client
|
a.client = client
|
||||||
a.nick = resp.Nick
|
a.nick = resp.Nick
|
||||||
a.connected = true
|
a.connected = true
|
||||||
a.lastQID = 0
|
a.lastQID = 0
|
||||||
|
|
||||||
if a.stopPoll != nil {
|
|
||||||
close(a.stopPoll)
|
|
||||||
}
|
|
||||||
|
|
||||||
stop := make(chan struct{})
|
|
||||||
a.stopPoll = stop
|
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[green]Connected! Nick: %s, Session: %d",
|
"[green]Connected! Nick: %s, Session: %d",
|
||||||
escape(resp.Nick), resp.ID,
|
resp.Nick, resp.ID,
|
||||||
))
|
))
|
||||||
a.ui.SetStatus(resp.Nick, "", "connected")
|
a.ui.SetStatus(resp.Nick, "", "connected")
|
||||||
|
|
||||||
go a.pollLoop(stop)
|
a.stopPoll = make(chan struct{})
|
||||||
|
|
||||||
|
go a.pollLoop()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdNick(nick string) {
|
func (a *App) cmdNick(nick string) {
|
||||||
@@ -244,7 +222,7 @@ func (a *App) cmdNick(nick string) {
|
|||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(
|
||||||
"Nick set to " + escape(nick) +
|
"Nick set to " + nick +
|
||||||
" (will be used on connect)",
|
" (will be used on connect)",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -256,9 +234,9 @@ func (a *App) cmdNick(nick string) {
|
|||||||
Body: []string{nick},
|
Body: []string{nick},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Nick change failed: " + escape(err.Error()),
|
"[red]Nick change failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -269,7 +247,7 @@ func (a *App) cmdNick(nick string) {
|
|||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.SetStatus(nick, target, "connected")
|
a.ui.SetStatus(nick, target, "connected")
|
||||||
a.ui.AddStatus("Nick changed to " + escape(nick))
|
a.ui.AddStatus("Nick changed to " + nick)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdJoin(channel string) {
|
func (a *App) cmdJoin(channel string) {
|
||||||
@@ -297,9 +275,9 @@ func (a *App) cmdJoin(channel string) {
|
|||||||
|
|
||||||
err := a.client.JoinChannel(channel)
|
err := a.client.JoinChannel(channel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Join failed: " + escape(err.Error()),
|
"[red]Join failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -337,9 +315,9 @@ func (a *App) cmdPart(channel string) {
|
|||||||
|
|
||||||
err := a.client.PartChannel(channel)
|
err := a.client.PartChannel(channel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Part failed: " + escape(err.Error()),
|
"[red]Part failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -384,9 +362,9 @@ func (a *App) cmdMsg(args string) {
|
|||||||
Body: []string{text},
|
Body: []string{text},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Send failed: " + escape(err.Error()),
|
"[red]Send failed: %v", err,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,16 +380,10 @@ func (a *App) cmdQuery(nick string) {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.target = nick
|
a.target = nick
|
||||||
myNick := a.nick
|
myNick := a.nick
|
||||||
connected := a.connected
|
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
connStatus := "disconnected"
|
|
||||||
if connected {
|
|
||||||
connStatus = "connected"
|
|
||||||
}
|
|
||||||
|
|
||||||
a.ui.SwitchToBuffer(nick)
|
a.ui.SwitchToBuffer(nick)
|
||||||
a.ui.SetStatus(myNick, nick, connStatus)
|
a.ui.SetStatus(myNick, nick, "connected")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdTopic(args string) {
|
func (a *App) cmdTopic(args string) {
|
||||||
@@ -445,9 +417,9 @@ func (a *App) cmdTopic(args string) {
|
|||||||
Body: []string{args},
|
Body: []string{args},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Topic set failed: " + escape(err.Error()),
|
"[red]Topic set failed: %v", err,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -471,9 +443,9 @@ func (a *App) cmdNames() {
|
|||||||
|
|
||||||
members, err := a.client.GetMembers(target)
|
members, err := a.client.GetMembers(target)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]Names failed: " + escape(err.Error()),
|
"[red]Names failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -486,7 +458,7 @@ func (a *App) cmdNames() {
|
|||||||
|
|
||||||
a.ui.AddLine(target, fmt.Sprintf(
|
a.ui.AddLine(target, fmt.Sprintf(
|
||||||
"[cyan]*** Members of %s: %s",
|
"[cyan]*** Members of %s: %s",
|
||||||
escape(target), escape(strings.Join(nicks, " ")),
|
target, strings.Join(nicks, " "),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -517,9 +489,9 @@ func (a *App) cmdList() {
|
|||||||
|
|
||||||
channels, err := a.client.ListChannels()
|
channels, err := a.client.ListChannels()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]List failed: " + escape(err.Error()),
|
"[red]List failed: %v", err,
|
||||||
)
|
))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -528,7 +500,7 @@ func (a *App) cmdList() {
|
|||||||
|
|
||||||
for _, ch := range channels {
|
for _, ch := range channels {
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
" %s %s", escape(ch.Name), escape(ch.Topic),
|
" %s %s", ch.Name, ch.Topic,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -550,9 +522,9 @@ func (a *App) cmdMotd() {
|
|||||||
&api.Message{Command: irc.CmdMotd}, //nolint:exhaustruct
|
&api.Message{Command: irc.CmdMotd}, //nolint:exhaustruct
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]MOTD failed: " + escape(err.Error()),
|
"[red]MOTD failed: %v", err,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -588,9 +560,9 @@ func (a *App) cmdWho(args string) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]WHO failed: " + escape(err.Error()),
|
"[red]WHO failed: %v", err,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -619,9 +591,9 @@ func (a *App) cmdWhois(args string) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[red]WHOIS failed: " + escape(err.Error()),
|
"[red]WHOIS failed: %v", err,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,37 +610,24 @@ func (a *App) cmdWindow(args string) {
|
|||||||
|
|
||||||
_, _ = fmt.Sscanf(args, "%d", &bufIndex)
|
_, _ = fmt.Sscanf(args, "%d", &bufIndex)
|
||||||
|
|
||||||
|
a.ui.SwitchBuffer(bufIndex)
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
connected := a.connected
|
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
connStatus := "disconnected"
|
if bufIndex >= 0 && bufIndex < a.ui.BufferCount() {
|
||||||
if connected {
|
buf := a.ui.buffers[bufIndex]
|
||||||
connStatus = "connected"
|
if buf.Name != "(status)" {
|
||||||
}
|
|
||||||
|
|
||||||
// Read the name before switching. A message from the server can
|
|
||||||
// add a buffer at any time, but only at the end, so bufIndex
|
|
||||||
// still names this buffer when SwitchBuffer runs.
|
|
||||||
name, found := a.ui.BufferName(bufIndex)
|
|
||||||
if found {
|
|
||||||
a.ui.SwitchBuffer(bufIndex)
|
|
||||||
|
|
||||||
if name != "(status)" {
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.target = name
|
a.target = buf.Name
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.SetStatus(
|
a.ui.SetStatus(
|
||||||
nick, name, connStatus,
|
nick, buf.Name, "connected",
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
a.mu.Lock()
|
a.ui.SetStatus(nick, "", "connected")
|
||||||
a.target = ""
|
|
||||||
a.mu.Unlock()
|
|
||||||
|
|
||||||
a.ui.SetStatus(nick, "", connStatus)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -716,23 +675,16 @@ func (a *App) cmdHelp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pollLoop long-polls for messages in the background until stop is
|
// pollLoop long-polls for messages in the background.
|
||||||
// closed. A later /connect closes stop under a.mu as it replaces the
|
func (a *App) pollLoop() {
|
||||||
// client and the cursor, so the loop checks stop under a.mu too. A
|
|
||||||
// stopped loop then neither polls with the new client nor moves the
|
|
||||||
// new cursor.
|
|
||||||
func (a *App) pollLoop(stop <-chan struct{}) {
|
|
||||||
for {
|
for {
|
||||||
a.mu.Lock()
|
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-stop:
|
case <-a.stopPoll:
|
||||||
a.mu.Unlock()
|
|
||||||
|
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
a.mu.Lock()
|
||||||
client := a.client
|
client := a.client
|
||||||
lastQID := a.lastQID
|
lastQID := a.lastQID
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
@@ -750,24 +702,12 @@ func (a *App) pollLoop(stop <-chan struct{}) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// A poll sent before stop was closed answers for the earlier
|
|
||||||
// connection.
|
|
||||||
a.mu.Lock()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-stop:
|
|
||||||
a.mu.Unlock()
|
|
||||||
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.LastID > 0 {
|
if result.LastID > 0 {
|
||||||
|
a.mu.Lock()
|
||||||
a.lastQID = result.LastID
|
a.lastQID = result.LastID
|
||||||
|
a.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
a.mu.Unlock()
|
|
||||||
|
|
||||||
for i := range result.Messages {
|
for i := range result.Messages {
|
||||||
a.handleServerMessage(&result.Messages[i])
|
a.handleServerMessage(&result.Messages[i])
|
||||||
}
|
}
|
||||||
@@ -824,7 +764,7 @@ func (a *App) handlePrivmsgEvent(
|
|||||||
|
|
||||||
a.ui.AddLine(target, fmt.Sprintf(
|
a.ui.AddLine(target, fmt.Sprintf(
|
||||||
"[gray]%s [green]<%s>[white] %s",
|
"[gray]%s [green]<%s>[white] %s",
|
||||||
timestamp, escape(msg.From), escape(text),
|
timestamp, msg.From, text,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -837,7 +777,7 @@ func (a *App) handleJoinEvent(
|
|||||||
|
|
||||||
a.ui.AddLine(msg.To, fmt.Sprintf(
|
a.ui.AddLine(msg.To, fmt.Sprintf(
|
||||||
"[gray]%s [yellow]*** %s has joined %s",
|
"[gray]%s [yellow]*** %s has joined %s",
|
||||||
timestamp, escape(msg.From), escape(msg.To),
|
timestamp, msg.From, msg.To,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -856,11 +796,11 @@ func (a *App) handlePartEvent(
|
|||||||
|
|
||||||
line := fmt.Sprintf(
|
line := fmt.Sprintf(
|
||||||
"[gray]%s [yellow]*** %s has left %s",
|
"[gray]%s [yellow]*** %s has left %s",
|
||||||
timestamp, escape(msg.From), escape(msg.To),
|
timestamp, msg.From, msg.To,
|
||||||
)
|
)
|
||||||
|
|
||||||
if reason != "" {
|
if reason != "" {
|
||||||
line += " (" + escape(reason) + ")"
|
line += " (" + reason + ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg.From == myNick {
|
if msg.From == myNick {
|
||||||
@@ -881,12 +821,12 @@ func (a *App) handleQuitEvent(
|
|||||||
if reason != "" {
|
if reason != "" {
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[gray]%s [yellow]*** %s has quit (%s)",
|
"[gray]%s [yellow]*** %s has quit (%s)",
|
||||||
timestamp, escape(msg.From), escape(reason),
|
timestamp, msg.From, reason,
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[gray]%s [yellow]*** %s has quit",
|
"[gray]%s [yellow]*** %s has quit",
|
||||||
timestamp, escape(msg.From),
|
timestamp, msg.From,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -913,7 +853,7 @@ func (a *App) handleNickEvent(
|
|||||||
|
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[gray]%s [yellow]*** %s is now known as %s",
|
"[gray]%s [yellow]*** %s is now known as %s",
|
||||||
timestamp, escape(msg.From), escape(newNick),
|
timestamp, msg.From, newNick,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -925,7 +865,7 @@ func (a *App) handleNoticeEvent(
|
|||||||
|
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[gray]%s [magenta]--%s-- %s",
|
"[gray]%s [magenta]--%s-- %s",
|
||||||
timestamp, escape(msg.From), escape(text),
|
timestamp, msg.From, text,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -941,7 +881,7 @@ func (a *App) handleTopicEvent(
|
|||||||
|
|
||||||
a.ui.AddLine(msg.To, fmt.Sprintf(
|
a.ui.AddLine(msg.To, fmt.Sprintf(
|
||||||
"[gray]%s [cyan]*** %s set topic: %s",
|
"[gray]%s [cyan]*** %s set topic: %s",
|
||||||
timestamp, escape(msg.From), escape(text),
|
timestamp, msg.From, text,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -951,12 +891,10 @@ func (a *App) handleDefaultEvent(
|
|||||||
lines := msg.BodyLines()
|
lines := msg.BodyLines()
|
||||||
text := strings.Join(lines, " ")
|
text := strings.Join(lines, " ")
|
||||||
|
|
||||||
// The brackets around the command are escaped with it, as tview
|
|
||||||
// reads a command such as "[MODE]" as a tag.
|
|
||||||
if text != "" {
|
if text != "" {
|
||||||
a.ui.AddStatus(fmt.Sprintf(
|
a.ui.AddStatus(fmt.Sprintf(
|
||||||
"[gray]%s [white]%s %s",
|
"[gray]%s [white][%s] %s",
|
||||||
timestamp, escape("["+msg.Command+"]"), escape(text),
|
timestamp, msg.Command, text,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
+14
-83
@@ -16,10 +16,7 @@ type Buffer struct {
|
|||||||
Unread int
|
Unread int
|
||||||
}
|
}
|
||||||
|
|
||||||
// UI manages the terminal interface. Most of its methods wait for
|
// UI manages the terminal interface.
|
||||||
// the tview event loop to run their update. Code that runs on that
|
|
||||||
// loop, such as a key handler, must not call them: it would wait
|
|
||||||
// for itself.
|
|
||||||
type UI struct {
|
type UI struct {
|
||||||
app *tview.Application
|
app *tview.Application
|
||||||
messages *tview.TextView
|
messages *tview.TextView
|
||||||
@@ -30,17 +27,7 @@ type UI struct {
|
|||||||
buffers []*Buffer
|
buffers []*Buffer
|
||||||
currentBuffer int
|
currentBuffer int
|
||||||
|
|
||||||
// The nick, target and connection state last passed to
|
|
||||||
// SetStatus.
|
|
||||||
nick string
|
|
||||||
target string
|
|
||||||
connStatus string
|
|
||||||
|
|
||||||
onInput func(string)
|
onInput func(string)
|
||||||
// inputDone is closed once the line last passed to onInput
|
|
||||||
// has been handled. Only callOnInput, on the event loop, uses
|
|
||||||
// it.
|
|
||||||
inputDone chan struct{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewUI creates the tview-based IRC-like UI.
|
// NewUI creates the tview-based IRC-like UI.
|
||||||
@@ -185,32 +172,13 @@ func (ui *UI) SetStatus(
|
|||||||
nick, target, connStatus string,
|
nick, target, connStatus string,
|
||||||
) {
|
) {
|
||||||
ui.app.QueueUpdateDraw(func() {
|
ui.app.QueueUpdateDraw(func() {
|
||||||
ui.nick = nick
|
ui.renderStatusBar(nick, target, connStatus)
|
||||||
ui.target = target
|
|
||||||
ui.connStatus = connStatus
|
|
||||||
|
|
||||||
ui.refreshStatusBar()
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// BufferName returns the name of the buffer at index bufIndex,
|
// BufferCount returns the number of buffers.
|
||||||
// and whether there is such a buffer.
|
func (ui *UI) BufferCount() int {
|
||||||
func (ui *UI) BufferName(bufIndex int) (string, bool) {
|
return len(ui.buffers)
|
||||||
var (
|
|
||||||
name string
|
|
||||||
found bool
|
|
||||||
)
|
|
||||||
|
|
||||||
ui.app.QueueUpdate(func() {
|
|
||||||
if bufIndex < 0 || bufIndex >= len(ui.buffers) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
name = ui.buffers[bufIndex].Name
|
|
||||||
found = true
|
|
||||||
})
|
|
||||||
|
|
||||||
return name, found
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BufferIndex returns the index of a named buffer.
|
// BufferIndex returns the index of a named buffer.
|
||||||
@@ -235,21 +203,9 @@ func (ui *UI) initMessages() {
|
|||||||
ui.messages.SetBorder(false)
|
ui.messages.SetBorder(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// escape returns text so that the message window shows it exactly
|
|
||||||
// as written. It writes each "[" as "[[:]": a "[" followed by
|
|
||||||
// another "[" never starts a tag, and the tag "[:]" changes
|
|
||||||
// nothing. tview.Escape is not enough: it does not escape a bracket
|
|
||||||
// pair holding a symbol such as "|" or "^", and nothing it adds
|
|
||||||
// stops a tag with a URL, such as "[:::y|z]".
|
|
||||||
func escape(text string) string {
|
|
||||||
return strings.ReplaceAll(text, "[", "[[:]")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ui *UI) initStatusBar() {
|
func (ui *UI) initStatusBar() {
|
||||||
// Colour tags stay off. With them on, tview reads text in
|
ui.statusBar = tview.NewTextView().
|
||||||
// square brackets, such as "[connected]" or part of a nick,
|
SetDynamicColors(true)
|
||||||
// as a tag and drops it.
|
|
||||||
ui.statusBar = tview.NewTextView()
|
|
||||||
ui.statusBar.SetBackgroundColor(tcell.ColorNavy)
|
ui.statusBar.SetBackgroundColor(tcell.ColorNavy)
|
||||||
ui.statusBar.SetTextColor(tcell.ColorWhite)
|
ui.statusBar.SetTextColor(tcell.ColorWhite)
|
||||||
}
|
}
|
||||||
@@ -270,7 +226,10 @@ func (ui *UI) initInput() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ui.input.SetText("")
|
ui.input.SetText("")
|
||||||
ui.callOnInput(text)
|
|
||||||
|
if ui.onInput != nil {
|
||||||
|
ui.onInput(text)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,11 +240,10 @@ func (ui *UI) initKeyCapture() {
|
|||||||
return event
|
return event
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alt and a digit runs /window with that digit.
|
|
||||||
// SwitchBuffer alone would leave the target as it was.
|
|
||||||
r := event.Rune()
|
r := event.Rune()
|
||||||
if r >= '0' && r <= '9' {
|
if r >= '0' && r <= '9' {
|
||||||
ui.callOnInput("/window " + string(r))
|
idx := int(r - '0')
|
||||||
|
ui.SwitchBuffer(idx)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -295,35 +253,8 @@ func (ui *UI) initKeyCapture() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// callOnInput passes text to the input callback on a new
|
|
||||||
// goroutine. The key handlers call it on the event loop, and the
|
|
||||||
// callback waits for that loop to update the screen, so they must
|
|
||||||
// not wait for the callback. The goroutine first waits for the
|
|
||||||
// line before it to be handled, which keeps lines in the order
|
|
||||||
// they were typed.
|
|
||||||
func (ui *UI) callOnInput(text string) {
|
|
||||||
if ui.onInput == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
previous := ui.inputDone
|
|
||||||
done := make(chan struct{})
|
|
||||||
ui.inputDone = done
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
if previous != nil {
|
|
||||||
<-previous
|
|
||||||
}
|
|
||||||
|
|
||||||
ui.onInput(text)
|
|
||||||
close(done)
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// refreshStatusBar redraws the status bar with the nick, target
|
|
||||||
// and connection state last passed to SetStatus.
|
|
||||||
func (ui *UI) refreshStatusBar() {
|
func (ui *UI) refreshStatusBar() {
|
||||||
ui.renderStatusBar(ui.nick, ui.target, ui.connStatus)
|
// Placeholder; full refresh needs nick/target context.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ui *UI) renderStatusBar(
|
func (ui *UI) renderStatusBar(
|
||||||
|
|||||||
+29
-266
@@ -3,19 +3,11 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/cast"
|
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"go4.org/netipx"
|
|
||||||
"sneak.berlin/go/neoirc/internal/globals"
|
"sneak.berlin/go/neoirc/internal/globals"
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
"sneak.berlin/go/neoirc/internal/logger"
|
||||||
|
|
||||||
@@ -36,16 +28,6 @@ Type /help for available commands.`
|
|||||||
const DefaultDBURL = "file:///var/lib/neoirc/state.db" +
|
const DefaultDBURL = "file:///var/lib/neoirc/state.db" +
|
||||||
"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
|
"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
|
||||||
|
|
||||||
// DefaultTrustedProxies is TRUSTED_PROXIES when it is not set: the
|
|
||||||
// private address ranges of RFC 1918.
|
|
||||||
const DefaultTrustedProxies = "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
|
|
||||||
|
|
||||||
var errOutOfRange = errors.New("setting out of range")
|
|
||||||
|
|
||||||
var errNeverMatches = errors.New("entry can never match a connection")
|
|
||||||
|
|
||||||
var errListOrMap = errors.New("a list or a map")
|
|
||||||
|
|
||||||
// Params defines the dependencies for creating a Config.
|
// Params defines the dependencies for creating a Config.
|
||||||
type Params struct {
|
type Params struct {
|
||||||
fx.In
|
fx.In
|
||||||
@@ -76,15 +58,11 @@ type Config struct {
|
|||||||
LoginRateLimit float64
|
LoginRateLimit float64
|
||||||
LoginRateBurst int
|
LoginRateBurst int
|
||||||
IRCListenAddr string
|
IRCListenAddr string
|
||||||
TrustedProxies *netipx.IPSet
|
|
||||||
params *Params
|
params *Params
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Config by reading from files and environment variables.
|
// New creates a new Config by reading from files and environment variables.
|
||||||
// It returns an error when the config file does not parse, when the file
|
|
||||||
// gives a setting a list or a map, and when a number, true/false,
|
|
||||||
// duration or address setting does not parse or is out of range.
|
|
||||||
func New(
|
func New(
|
||||||
_ fx.Lifecycle, params Params,
|
_ fx.Lifecycle, params Params,
|
||||||
) (*Config, error) {
|
) (*Config, error) {
|
||||||
@@ -117,25 +95,46 @@ func New(
|
|||||||
viper.SetDefault("LOGIN_RATE_LIMIT", "1")
|
viper.SetDefault("LOGIN_RATE_LIMIT", "1")
|
||||||
viper.SetDefault("LOGIN_RATE_BURST", "5")
|
viper.SetDefault("LOGIN_RATE_BURST", "5")
|
||||||
viper.SetDefault("IRC_LISTEN_ADDR", ":6667")
|
viper.SetDefault("IRC_LISTEN_ADDR", ":6667")
|
||||||
viper.SetDefault("TRUSTED_PROXIES", DefaultTrustedProxies)
|
|
||||||
|
|
||||||
err := viper.ReadInConfig()
|
err := viper.ReadInConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var notFound viper.ConfigFileNotFoundError
|
var notFound viper.ConfigFileNotFoundError
|
||||||
if !errors.As(err, ¬Found) {
|
if !errors.As(err, ¬Found) {
|
||||||
return nil, fmt.Errorf("cannot read %s: %w",
|
log.Error("config file malformed", "error", err)
|
||||||
viper.ConfigFileUsed(), err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := &Config{
|
cfg := &Config{
|
||||||
log: log,
|
DBURL: viper.GetString("DBURL"),
|
||||||
params: ¶ms,
|
Debug: viper.GetBool("DEBUG"),
|
||||||
|
Port: viper.GetInt("PORT"),
|
||||||
|
SentryDSN: viper.GetString("SENTRY_DSN"),
|
||||||
|
MaintenanceMode: viper.GetBool("MAINTENANCE_MODE"),
|
||||||
|
MetricsUsername: viper.GetString("METRICS_USERNAME"),
|
||||||
|
MetricsPassword: viper.GetString("METRICS_PASSWORD"),
|
||||||
|
MessageMaxAge: viper.GetString("MESSAGE_MAX_AGE"),
|
||||||
|
MaxMessageSize: viper.GetInt("MAX_MESSAGE_SIZE"),
|
||||||
|
QueueMaxAge: viper.GetString("QUEUE_MAX_AGE"),
|
||||||
|
MOTD: viper.GetString("MOTD"),
|
||||||
|
ServerName: viper.GetString("SERVER_NAME"),
|
||||||
|
FederationKey: viper.GetString("FEDERATION_KEY"),
|
||||||
|
SessionIdleTimeout: viper.GetString("SESSION_IDLE_TIMEOUT"),
|
||||||
|
HashcashBits: viper.GetInt("NEOIRC_HASHCASH_BITS"),
|
||||||
|
OperName: viper.GetString("NEOIRC_OPER_NAME"),
|
||||||
|
OperPassword: viper.GetString("NEOIRC_OPER_PASSWORD"),
|
||||||
|
LoginRateLimit: viper.GetFloat64("LOGIN_RATE_LIMIT"),
|
||||||
|
LoginRateBurst: viper.GetInt("LOGIN_RATE_BURST"),
|
||||||
|
IRCListenAddr: viper.GetString("IRC_LISTEN_ADDR"),
|
||||||
|
log: log,
|
||||||
|
params: ¶ms,
|
||||||
}
|
}
|
||||||
|
|
||||||
err = parseSettings(cfg)
|
// Viper counts an empty environment variable as unset, but an
|
||||||
if err != nil {
|
// empty IRC_LISTEN_ADDR must turn the IRC listener off.
|
||||||
return nil, err
|
ircListenAddr, set := os.LookupEnv("IRC_LISTEN_ADDR")
|
||||||
|
if set {
|
||||||
|
cfg.IRCListenAddr = ircListenAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Debug {
|
if cfg.Debug {
|
||||||
@@ -145,239 +144,3 @@ func New(
|
|||||||
|
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseSettings reads every setting into cfg. Each number and duration
|
|
||||||
// must be above zero. PORT and NEOIRC_HASHCASH_BITS may also be zero:
|
|
||||||
// port 0 lets the system pick a port, and 0 bits turns proof of work off.
|
|
||||||
// The error names each setting that is a list or a map, does not parse or
|
|
||||||
// is out of range.
|
|
||||||
func parseSettings(cfg *Config) error {
|
|
||||||
return errors.Join(
|
|
||||||
parseString("DBURL", &cfg.DBURL),
|
|
||||||
parseString("SENTRY_DSN", &cfg.SentryDSN),
|
|
||||||
parseString("METRICS_USERNAME", &cfg.MetricsUsername),
|
|
||||||
parseString("METRICS_PASSWORD", &cfg.MetricsPassword),
|
|
||||||
parseString("MOTD", &cfg.MOTD),
|
|
||||||
parseString("SERVER_NAME", &cfg.ServerName),
|
|
||||||
parseString("FEDERATION_KEY", &cfg.FederationKey),
|
|
||||||
parseString("NEOIRC_OPER_NAME", &cfg.OperName),
|
|
||||||
parseString("NEOIRC_OPER_PASSWORD", &cfg.OperPassword),
|
|
||||||
// The empty string turns the IRC listener off.
|
|
||||||
parseStringAllowEmptyEnv("IRC_LISTEN_ADDR", &cfg.IRCListenAddr),
|
|
||||||
parseInt("PORT", 0, &cfg.Port),
|
|
||||||
parseInt("MAX_MESSAGE_SIZE", 1, &cfg.MaxMessageSize),
|
|
||||||
parseInt("NEOIRC_HASHCASH_BITS", 0, &cfg.HashcashBits),
|
|
||||||
parseInt("LOGIN_RATE_BURST", 1, &cfg.LoginRateBurst),
|
|
||||||
parseFloat("LOGIN_RATE_LIMIT", &cfg.LoginRateLimit),
|
|
||||||
parseBool("DEBUG", &cfg.Debug),
|
|
||||||
parseBool("MAINTENANCE_MODE", &cfg.MaintenanceMode),
|
|
||||||
parseDuration("MESSAGE_MAX_AGE", &cfg.MessageMaxAge),
|
|
||||||
parseDuration("QUEUE_MAX_AGE", &cfg.QueueMaxAge),
|
|
||||||
parseDuration("SESSION_IDLE_TIMEOUT", &cfg.SessionIdleTimeout),
|
|
||||||
parseTrustedProxies(&cfg.TrustedProxies),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getString returns the setting key as a string. A number or a true/false
|
|
||||||
// value in the config file becomes its text, as with viper.GetString. A
|
|
||||||
// list or a map in the config file is an error, where viper.GetString
|
|
||||||
// would return the empty string. The error leaves out the value, which
|
|
||||||
// may be a password.
|
|
||||||
func getString(key string) (string, error) {
|
|
||||||
raw, err := cast.ToStringE(viper.Get(key))
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("%s is %w", key, errListOrMap)
|
|
||||||
}
|
|
||||||
|
|
||||||
return raw, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseString sets *value to the setting key.
|
|
||||||
func parseString(key string, value *string) error {
|
|
||||||
raw, err := getString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = raw
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseStringAllowEmptyEnv sets *value to the setting key, as parseString
|
|
||||||
// does, but an environment variable set to the empty string counts as
|
|
||||||
// set. Viper counts such a variable as unset and uses the config file or
|
|
||||||
// the default instead.
|
|
||||||
func parseStringAllowEmptyEnv(key string, value *string) error {
|
|
||||||
fromEnv, set := os.LookupEnv(key)
|
|
||||||
if set {
|
|
||||||
*value = fromEnv
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return parseString(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseTrustedProxies sets *value to the addresses in TRUSTED_PROXIES.
|
|
||||||
func parseTrustedProxies(value **netipx.IPSet) error {
|
|
||||||
var raw string
|
|
||||||
|
|
||||||
err := parseStringAllowEmptyEnv("TRUSTED_PROXIES", &raw)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
ipSet, err := ParseTrustedProxies(raw)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot parse TRUSTED_PROXIES: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = ipSet
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseTrustedProxies returns the addresses in list, which has the form
|
|
||||||
// of TRUSTED_PROXIES: a comma-separated list of networks such as
|
|
||||||
// 10.0.0.0/8 and single addresses such as 192.0.2.1. The empty string
|
|
||||||
// trusts nothing.
|
|
||||||
func ParseTrustedProxies(list string) (*netipx.IPSet, error) {
|
|
||||||
var builder netipx.IPSetBuilder
|
|
||||||
|
|
||||||
if strings.TrimSpace(list) != "" {
|
|
||||||
for entry := range strings.SplitSeq(list, ",") {
|
|
||||||
err := addTrustedProxy(&builder, strings.TrimSpace(entry))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return builder.IPSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
// addTrustedProxy adds entry, a network with a slash or a single
|
|
||||||
// address, to builder. An IPv4 address written in IPv6 form, such as
|
|
||||||
// ::ffff:192.0.2.1, is added as IPv4. A network in that form and an
|
|
||||||
// address with a zone are errors, since no connection could match them.
|
|
||||||
func addTrustedProxy(builder *netipx.IPSetBuilder, entry string) error {
|
|
||||||
if strings.Contains(entry, "/") {
|
|
||||||
prefix, err := netip.ParsePrefix(entry)
|
|
||||||
if err != nil {
|
|
||||||
return err //nolint:wrapcheck // the caller names the setting
|
|
||||||
}
|
|
||||||
|
|
||||||
// A connection from an IPv4 address is checked in IPv4 form.
|
|
||||||
if prefix.Addr().Is4In6() {
|
|
||||||
return fmt.Errorf("%w: %s is an IPv4 network in IPv6 form",
|
|
||||||
errNeverMatches, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
builder.AddPrefix(prefix)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := netip.ParseAddr(entry)
|
|
||||||
if err != nil {
|
|
||||||
return err //nolint:wrapcheck // the caller names the setting
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSet.Contains is false for every address with a zone.
|
|
||||||
if addr.Zone() != "" {
|
|
||||||
return fmt.Errorf("%w: %s has a zone", errNeverMatches, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
builder.Add(addr.Unmap())
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseInt sets *value to the setting key read as a whole number. It
|
|
||||||
// returns an error when the value does not parse or is below minimum.
|
|
||||||
func parseInt(key string, minimum int, value *int) error {
|
|
||||||
raw, err := getString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed, err := strconv.Atoi(raw)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot parse %s: %w", key, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if parsed < minimum {
|
|
||||||
return fmt.Errorf("%w: %s is %s, but must be at least %d",
|
|
||||||
errOutOfRange, key, raw, minimum)
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = parsed
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseFloat sets *value to the setting key read as a floating-point
|
|
||||||
// number. It returns an error when the value does not parse or is not a
|
|
||||||
// finite number above zero.
|
|
||||||
func parseFloat(key string, value *float64) error {
|
|
||||||
raw, err := getString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed, err := strconv.ParseFloat(raw, 64)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot parse %s: %w", key, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if math.IsNaN(parsed) || math.IsInf(parsed, 0) || parsed <= 0 {
|
|
||||||
return fmt.Errorf(
|
|
||||||
"%w: %s is %s, but must be a finite number above zero",
|
|
||||||
errOutOfRange, key, raw)
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = parsed
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseBool sets *value to the setting key read as true or false.
|
|
||||||
func parseBool(key string, value *bool) error {
|
|
||||||
raw, err := getString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed, err := strconv.ParseBool(raw)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot parse %s: %w", key, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = parsed
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseDuration sets *value to the setting key. It returns an error when
|
|
||||||
// the value is not a Go duration above zero.
|
|
||||||
func parseDuration(key string, value *string) error {
|
|
||||||
raw, err := getString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
duration, err := time.ParseDuration(raw)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot parse %s: %w", key, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if duration <= 0 {
|
|
||||||
return fmt.Errorf("%w: %s is %s, but must be above zero",
|
|
||||||
errOutOfRange, key, raw)
|
|
||||||
}
|
|
||||||
|
|
||||||
*value = raw
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,16 @@
|
|||||||
package config_test
|
package config_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/netip"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/globals"
|
"sneak.berlin/go/neoirc/internal/globals"
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
"sneak.berlin/go/neoirc/internal/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
// loadConfig runs config.New and returns its result.
|
func newConfig(t *testing.T) *config.Config {
|
||||||
func loadConfig(t *testing.T) (*config.Config, error) {
|
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
globs := &globals.Globals{
|
globs := &globals.Globals{
|
||||||
@@ -29,15 +24,9 @@ func loadConfig(t *testing.T) (*config.Config, error) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return config.New(
|
cfg, err := config.New(
|
||||||
nil, config.Params{Globals: globs, Logger: log},
|
nil, config.Params{Globals: globs, Logger: log},
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
|
||||||
func newConfig(t *testing.T) *config.Config {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
cfg, err := loadConfig(t)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -45,148 +34,6 @@ func newConfig(t *testing.T) *config.Config {
|
|||||||
return cfg
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUnsetSettingsKeepDefaults(t *testing.T) {
|
|
||||||
// Viper counts an empty environment variable as unset.
|
|
||||||
t.Setenv("PORT", "")
|
|
||||||
t.Setenv("MAX_MESSAGE_SIZE", "")
|
|
||||||
t.Setenv("NEOIRC_HASHCASH_BITS", "")
|
|
||||||
t.Setenv("LOGIN_RATE_BURST", "")
|
|
||||||
t.Setenv("LOGIN_RATE_LIMIT", "")
|
|
||||||
t.Setenv("DEBUG", "")
|
|
||||||
t.Setenv("MAINTENANCE_MODE", "")
|
|
||||||
t.Setenv("MESSAGE_MAX_AGE", "")
|
|
||||||
t.Setenv("QUEUE_MAX_AGE", "")
|
|
||||||
t.Setenv("SESSION_IDLE_TIMEOUT", "")
|
|
||||||
|
|
||||||
// Each duration setting defaults to 30 days.
|
|
||||||
const thirtyDays = "720h"
|
|
||||||
|
|
||||||
want := settings{
|
|
||||||
Port: 8080,
|
|
||||||
MaxMessageSize: 4096,
|
|
||||||
HashcashBits: 20,
|
|
||||||
LoginRateBurst: 5,
|
|
||||||
LoginRateLimit: 1,
|
|
||||||
Debug: false,
|
|
||||||
MaintenanceMode: false,
|
|
||||||
MessageMaxAge: thirtyDays,
|
|
||||||
QueueMaxAge: thirtyDays,
|
|
||||||
SessionIdleTimeout: thirtyDays,
|
|
||||||
}
|
|
||||||
|
|
||||||
got := settingsOf(newConfig(t))
|
|
||||||
if got != want {
|
|
||||||
t.Errorf("settings = %+v, want %+v", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidSettingsAreUsed(t *testing.T) {
|
|
||||||
// Each whole number is the lowest value its setting allows, and 1ns
|
|
||||||
// is the shortest duration allowed.
|
|
||||||
t.Setenv("PORT", "0")
|
|
||||||
t.Setenv("MAX_MESSAGE_SIZE", "1")
|
|
||||||
t.Setenv("NEOIRC_HASHCASH_BITS", "0")
|
|
||||||
t.Setenv("LOGIN_RATE_BURST", "1")
|
|
||||||
t.Setenv("LOGIN_RATE_LIMIT", "0.5")
|
|
||||||
t.Setenv("DEBUG", "true")
|
|
||||||
t.Setenv("MAINTENANCE_MODE", "true")
|
|
||||||
t.Setenv("MESSAGE_MAX_AGE", "1ns")
|
|
||||||
t.Setenv("QUEUE_MAX_AGE", "1h30m")
|
|
||||||
t.Setenv("SESSION_IDLE_TIMEOUT", "45m")
|
|
||||||
|
|
||||||
want := settings{
|
|
||||||
Port: 0,
|
|
||||||
MaxMessageSize: 1,
|
|
||||||
HashcashBits: 0,
|
|
||||||
LoginRateBurst: 1,
|
|
||||||
LoginRateLimit: 0.5,
|
|
||||||
Debug: true,
|
|
||||||
MaintenanceMode: true,
|
|
||||||
MessageMaxAge: "1ns",
|
|
||||||
QueueMaxAge: "1h30m",
|
|
||||||
SessionIdleTimeout: "45m",
|
|
||||||
}
|
|
||||||
|
|
||||||
got := settingsOf(newConfig(t))
|
|
||||||
if got != want {
|
|
||||||
t.Errorf("settings = %+v, want %+v", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// settings holds the Config fields whose settings config.New parses.
|
|
||||||
type settings struct {
|
|
||||||
Port int
|
|
||||||
MaxMessageSize int
|
|
||||||
HashcashBits int
|
|
||||||
LoginRateBurst int
|
|
||||||
LoginRateLimit float64
|
|
||||||
Debug bool
|
|
||||||
MaintenanceMode bool
|
|
||||||
MessageMaxAge string
|
|
||||||
QueueMaxAge string
|
|
||||||
SessionIdleTimeout string
|
|
||||||
}
|
|
||||||
|
|
||||||
func settingsOf(cfg *config.Config) settings {
|
|
||||||
return settings{
|
|
||||||
Port: cfg.Port,
|
|
||||||
MaxMessageSize: cfg.MaxMessageSize,
|
|
||||||
HashcashBits: cfg.HashcashBits,
|
|
||||||
LoginRateBurst: cfg.LoginRateBurst,
|
|
||||||
LoginRateLimit: cfg.LoginRateLimit,
|
|
||||||
Debug: cfg.Debug,
|
|
||||||
MaintenanceMode: cfg.MaintenanceMode,
|
|
||||||
MessageMaxAge: cfg.MessageMaxAge,
|
|
||||||
QueueMaxAge: cfg.QueueMaxAge,
|
|
||||||
SessionIdleTimeout: cfg.SessionIdleTimeout,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBadSettingStopsStartup(t *testing.T) {
|
|
||||||
// Each value is invalid for its setting.
|
|
||||||
tests := []struct {
|
|
||||||
key string
|
|
||||||
values []string
|
|
||||||
}{
|
|
||||||
{key: "PORT", values: []string{"80a", "-1"}},
|
|
||||||
{key: "MAX_MESSAGE_SIZE", values: []string{"4k", "0", "-4096"}},
|
|
||||||
{key: "NEOIRC_HASHCASH_BITS", values: []string{"twenty", "-1"}},
|
|
||||||
{key: "LOGIN_RATE_BURST", values: []string{"five", "0", "-5"}},
|
|
||||||
{key: "LOGIN_RATE_LIMIT", values: []string{
|
|
||||||
"fast", "0", "-1", "NaN", "Inf", "-Inf",
|
|
||||||
}},
|
|
||||||
{key: "DEBUG", values: []string{"yes"}},
|
|
||||||
{key: "MAINTENANCE_MODE", values: []string{"on"}},
|
|
||||||
{key: "MESSAGE_MAX_AGE", values: []string{"30d", "0", "-1h"}},
|
|
||||||
{key: "QUEUE_MAX_AGE", values: []string{"720", "0s", "-24h"}},
|
|
||||||
{key: "SESSION_IDLE_TIMEOUT", values: []string{"a month", "0", "-1m"}},
|
|
||||||
{key: "TRUSTED_PROXIES", values: []string{
|
|
||||||
"proxy.example.com", "10.0.0.0/33", "192.0.2.1:8080",
|
|
||||||
"::ffff:10.0.0.0/104", "fe80::1%eth0",
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
for _, value := range test.values {
|
|
||||||
t.Run(test.key+"="+value, func(t *testing.T) {
|
|
||||||
t.Setenv(test.key, value)
|
|
||||||
|
|
||||||
_, err := loadConfig(t)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("%s=%q: got no error", test.key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := err.Error()
|
|
||||||
if !strings.Contains(msg, test.key) ||
|
|
||||||
!strings.Contains(msg, value) {
|
|
||||||
t.Errorf("error %q does not name %s and %q",
|
|
||||||
msg, test.key, value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIRCListenAddrUnsetKeepsDefault(t *testing.T) {
|
func TestIRCListenAddrUnsetKeepsDefault(t *testing.T) {
|
||||||
// t.Setenv puts back whatever value was there after the test.
|
// t.Setenv puts back whatever value was there after the test.
|
||||||
t.Setenv("IRC_LISTEN_ADDR", "")
|
t.Setenv("IRC_LISTEN_ADDR", "")
|
||||||
@@ -212,228 +59,3 @@ func TestIRCListenAddrEmptyTurnsListenerOff(t *testing.T) {
|
|||||||
t.Errorf("IRCListenAddr = %q, want empty", cfg.IRCListenAddr)
|
t.Errorf("IRCListenAddr = %q, want empty", cfg.IRCListenAddr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTrustedProxies(t *testing.T) {
|
|
||||||
// Each case lists addresses that must be in the trusted set and
|
|
||||||
// addresses that must not.
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
set bool
|
|
||||||
value string
|
|
||||||
trusted []string
|
|
||||||
untrusted []string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "unset trusts the RFC 1918 ranges",
|
|
||||||
set: false,
|
|
||||||
value: "",
|
|
||||||
trusted: []string{
|
|
||||||
"10.1.2.3", "172.16.0.1", "172.31.255.254", "192.168.1.1",
|
|
||||||
},
|
|
||||||
untrusted: []string{
|
|
||||||
"127.0.0.1", "172.32.0.1", "192.0.2.1", "2001:db8::1",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "a value replaces the default",
|
|
||||||
set: true,
|
|
||||||
value: "198.51.100.0/24, 192.0.2.7,2001:db8::/32",
|
|
||||||
trusted: []string{"198.51.100.200", "192.0.2.7", "2001:db8::5"},
|
|
||||||
untrusted: []string{"10.4.5.6", "192.168.4.4", "192.0.2.8"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "a mapped IPv6 address is trusted as IPv4",
|
|
||||||
set: true,
|
|
||||||
value: "::ffff:192.0.2.7",
|
|
||||||
trusted: []string{"192.0.2.7"},
|
|
||||||
untrusted: []string{"10.7.8.9"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "the empty string trusts nothing",
|
|
||||||
set: true,
|
|
||||||
value: "",
|
|
||||||
trusted: nil,
|
|
||||||
untrusted: []string{"10.0.0.1", "192.168.0.1", "::1"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
// t.Setenv puts back whatever value was there after the
|
|
||||||
// test, including when Unsetenv removes it.
|
|
||||||
t.Setenv("TRUSTED_PROXIES", test.value)
|
|
||||||
|
|
||||||
if !test.set {
|
|
||||||
err := os.Unsetenv("TRUSTED_PROXIES")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies := newConfig(t).TrustedProxies
|
|
||||||
|
|
||||||
for _, addr := range test.trusted {
|
|
||||||
if !proxies.Contains(netip.MustParseAddr(addr)) {
|
|
||||||
t.Errorf("%s is not trusted", addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, addr := range test.untrusted {
|
|
||||||
if proxies.Contains(netip.MustParseAddr(addr)) {
|
|
||||||
t.Errorf("%s is trusted", addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// unsetEnv removes the environment variable key for the rest of the
|
|
||||||
// test, so that config.New reads key from the config file.
|
|
||||||
func unsetEnv(t *testing.T, key string) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
// t.Setenv puts back whatever value was there after the test,
|
|
||||||
// including when Unsetenv removes it.
|
|
||||||
t.Setenv(key, "")
|
|
||||||
|
|
||||||
err := os.Unsetenv(key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeConfigFile writes content to the config file config.New reads
|
|
||||||
// when HOME is home, and returns the file's path.
|
|
||||||
func writeConfigFile(t *testing.T, home, content string) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
// loadConfig names the app neoirc-test, so config.New reads
|
|
||||||
// $HOME/.config/neoirc-test/neoirc-test.yaml.
|
|
||||||
dir := filepath.Join(home, ".config", "neoirc-test")
|
|
||||||
|
|
||||||
err := os.MkdirAll(dir, 0o700)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
path := filepath.Join(dir, "neoirc-test.yaml")
|
|
||||||
|
|
||||||
err = os.WriteFile(path, []byte(content), 0o600)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Viper keeps the file and the values it read from it after the
|
|
||||||
// file is gone. Reset clears them for later tests.
|
|
||||||
t.Cleanup(viper.Reset)
|
|
||||||
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListOrMapInConfigFileStopsStartup(t *testing.T) {
|
|
||||||
// YAML reads the first value as a list and the second as a map.
|
|
||||||
values := []string{`[":6667"]`, `{addr: ":6667"}`}
|
|
||||||
keys := []string{"IRC_LISTEN_ADDR", "MOTD", "TRUSTED_PROXIES"}
|
|
||||||
|
|
||||||
for _, key := range keys {
|
|
||||||
for _, value := range values {
|
|
||||||
t.Run(key+"="+value, func(t *testing.T) {
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
unsetEnv(t, key)
|
|
||||||
writeConfigFile(t, home, key+": "+value+"\n")
|
|
||||||
|
|
||||||
_, err := loadConfig(t)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), key) {
|
|
||||||
t.Errorf("error = %v, want one naming %s", err, key)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListOrMapErrorLeavesOutValue(t *testing.T) {
|
|
||||||
const key = "NEOIRC_OPER_PASSWORD"
|
|
||||||
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
unsetEnv(t, key)
|
|
||||||
// YAML reads an unquoted {hunter2} as a map.
|
|
||||||
writeConfigFile(t, home, key+": {hunter2}\n")
|
|
||||||
|
|
||||||
_, err := loadConfig(t)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), key) {
|
|
||||||
t.Fatalf("error = %v, want one naming %s", err, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.Contains(err.Error(), "hunter2") {
|
|
||||||
t.Errorf("error %q shows the password", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEmptyEnvironmentValueWinsOverConfigFile(t *testing.T) {
|
|
||||||
const (
|
|
||||||
ircListenAddr = "IRC_LISTEN_ADDR"
|
|
||||||
trustedProxies = "TRUSTED_PROXIES"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Each setting is the empty string in the environment and a list in
|
|
||||||
// the config file. The environment wins, so the list is never read.
|
|
||||||
tests := []struct {
|
|
||||||
key string
|
|
||||||
empty func(cfg *config.Config) bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
key: ircListenAddr,
|
|
||||||
empty: func(cfg *config.Config) bool {
|
|
||||||
return cfg.IRCListenAddr == ""
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: trustedProxies,
|
|
||||||
empty: func(cfg *config.Config) bool {
|
|
||||||
return len(cfg.TrustedProxies.Prefixes()) == 0
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.key, func(t *testing.T) {
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
t.Setenv(test.key, "")
|
|
||||||
writeConfigFile(t, home, test.key+": [\":6667\"]\n")
|
|
||||||
|
|
||||||
cfg := newConfig(t)
|
|
||||||
if !test.empty(cfg) {
|
|
||||||
t.Errorf("%s is not the empty string", test.key)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSingleValuesInConfigFileAreUsed(t *testing.T) {
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
unsetEnv(t, "PORT")
|
|
||||||
unsetEnv(t, "DEBUG")
|
|
||||||
unsetEnv(t, "MOTD")
|
|
||||||
writeConfigFile(t, home, "PORT: 9000\nDEBUG: true\nMOTD: hello\n")
|
|
||||||
|
|
||||||
cfg := newConfig(t)
|
|
||||||
if cfg.Port != 9000 || !cfg.Debug || cfg.MOTD != "hello" {
|
|
||||||
t.Errorf("Port, Debug, MOTD = %d, %t, %q, want 9000, true, %q",
|
|
||||||
cfg.Port, cfg.Debug, cfg.MOTD, "hello")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConfigFileThatDoesNotParseStopsStartup(t *testing.T) {
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
path := writeConfigFile(t, home, "MOTD: [unclosed\n")
|
|
||||||
|
|
||||||
_, err := loadConfig(t)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), path) {
|
|
||||||
t.Errorf("error = %v, want one naming %s", err, path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+8
-1
@@ -10,6 +10,13 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//nolint:gochecknoglobals // var so tests can override via SetBcryptCost
|
||||||
|
var bcryptCost = bcrypt.DefaultCost
|
||||||
|
|
||||||
|
// SetBcryptCost overrides the bcrypt cost.
|
||||||
|
// Use bcrypt.MinCost in tests to avoid slow hashing.
|
||||||
|
func SetBcryptCost(cost int) { bcryptCost = cost }
|
||||||
|
|
||||||
var errNoPassword = errors.New(
|
var errNoPassword = errors.New(
|
||||||
"account has no password set",
|
"account has no password set",
|
||||||
)
|
)
|
||||||
@@ -22,7 +29,7 @@ func (database *Database) SetPassword(
|
|||||||
password string,
|
password string,
|
||||||
) error {
|
) error {
|
||||||
hash, err := bcrypt.GenerateFromPassword(
|
hash, err := bcrypt.GenerateFromPassword(
|
||||||
[]byte(password), database.passwordCost,
|
[]byte(password), bcryptCost,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("hash password: %w", err)
|
return fmt.Errorf("hash password: %w", err)
|
||||||
|
|||||||
+10
-18
@@ -15,7 +15,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
"sneak.berlin/go/neoirc/internal/logger"
|
||||||
|
|
||||||
@@ -40,19 +39,13 @@ type Params struct {
|
|||||||
|
|
||||||
Logger *logger.Logger
|
Logger *logger.Logger
|
||||||
Config *config.Config
|
Config *config.Config
|
||||||
|
|
||||||
// PasswordCost is the bcrypt cost at which SetPassword hashes
|
|
||||||
// a password. The server leaves it unset, which means
|
|
||||||
// bcrypt.DefaultCost. Tests set a lower cost to save time.
|
|
||||||
PasswordCost int `optional:"true"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Database manages the SQLite connection and migrations.
|
// Database manages the SQLite connection and migrations.
|
||||||
type Database struct {
|
type Database struct {
|
||||||
conn *sql.DB
|
conn *sql.DB
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
params *Params
|
params *Params
|
||||||
passwordCost int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Database and registers lifecycle hooks.
|
// New creates a new Database and registers lifecycle hooks.
|
||||||
@@ -60,15 +53,9 @@ func New(
|
|||||||
lifecycle fx.Lifecycle,
|
lifecycle fx.Lifecycle,
|
||||||
params Params,
|
params Params,
|
||||||
) (*Database, error) {
|
) (*Database, error) {
|
||||||
passwordCost := params.PasswordCost
|
|
||||||
if passwordCost == 0 {
|
|
||||||
passwordCost = bcrypt.DefaultCost
|
|
||||||
}
|
|
||||||
|
|
||||||
database := &Database{ //nolint:exhaustruct // conn set in OnStart
|
database := &Database{ //nolint:exhaustruct // conn set in OnStart
|
||||||
params: ¶ms,
|
params: ¶ms,
|
||||||
log: params.Logger.Get(),
|
log: params.Logger.Get(),
|
||||||
passwordCost: passwordCost,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
database.log.Info("Database instantiated")
|
database.log.Info("Database instantiated")
|
||||||
@@ -98,6 +85,11 @@ func New(
|
|||||||
return database, nil
|
return database, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDB returns the underlying sql.DB connection.
|
||||||
|
func (database *Database) GetDB() *sql.DB {
|
||||||
|
return database.conn
|
||||||
|
}
|
||||||
|
|
||||||
func (database *Database) connect(ctx context.Context) error {
|
func (database *Database) connect(ctx context.Context) error {
|
||||||
dbURL := database.params.Config.DBURL
|
dbURL := database.params.Config.DBURL
|
||||||
if dbURL == "" {
|
if dbURL == "" {
|
||||||
|
|||||||
+1
-85
@@ -10,7 +10,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.uber.org/fx/fxtest"
|
"go.uber.org/fx/fxtest"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/db"
|
"sneak.berlin/go/neoirc/internal/db"
|
||||||
"sneak.berlin/go/neoirc/internal/dbtest"
|
"sneak.berlin/go/neoirc/internal/dbtest"
|
||||||
@@ -27,11 +26,7 @@ const (
|
|||||||
(SELECT 1 UNION ALL SELECT x + 1 FROM n)
|
(SELECT 1 UNION ALL SELECT x + 1 FROM n)
|
||||||
SELECT COUNT(*) FROM n`
|
SELECT COUNT(*) FROM n`
|
||||||
|
|
||||||
// endlessQueryTimeout is how long the endless query runs
|
endlessQueryTimeout = 100 * time.Millisecond
|
||||||
// before its context ends. A query whose context ends before
|
|
||||||
// it starts is never run, and the pool keeps its connection,
|
|
||||||
// so the timeout leaves a loaded host time to start it.
|
|
||||||
endlessQueryTimeout = 2 * time.Second
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestDefaultDBURLSetsWALAndBusyTimeout opens a file database
|
// TestDefaultDBURLSetsWALAndBusyTimeout opens a file database
|
||||||
@@ -241,85 +236,6 @@ func TestDBURLSettingForeignKeysFailsStartup(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestPasswordCost checks the bcrypt cost of the hash that SetPassword
|
|
||||||
// stores: bcrypt.DefaultCost when db.Params leaves PasswordCost unset,
|
|
||||||
// as the server does, and PasswordCost when it is set.
|
|
||||||
func TestPasswordCost(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
passwordCost int
|
|
||||||
wantCost int
|
|
||||||
}{
|
|
||||||
{name: "unset", wantCost: bcrypt.DefaultCost},
|
|
||||||
{
|
|
||||||
name: "bcrypt.MinCost",
|
|
||||||
passwordCost: bcrypt.MinCost,
|
|
||||||
wantCost: bcrypt.MinCost,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
lifecycle := fxtest.NewLifecycle(t)
|
|
||||||
|
|
||||||
log, err := logger.New(lifecycle, logger.Params{
|
|
||||||
Globals: &globals.Globals{},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
database, err := db.New(lifecycle, db.Params{
|
|
||||||
Logger: log,
|
|
||||||
Config: &config.Config{DBURL: dbtest.NewURL(t)},
|
|
||||||
PasswordCost: test.passwordCost,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
lifecycle.RequireStart()
|
|
||||||
t.Cleanup(lifecycle.RequireStop)
|
|
||||||
|
|
||||||
sessionID, _, _, err := database.CreateSession(
|
|
||||||
t.Context(), "costuser", "", "", "",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = database.SetPassword(t.Context(), sessionID, "password123")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var hash string
|
|
||||||
|
|
||||||
err = database.GetDB().QueryRowContext(
|
|
||||||
t.Context(),
|
|
||||||
"SELECT password_hash FROM sessions WHERE id = ?",
|
|
||||||
sessionID,
|
|
||||||
).Scan(&hash)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cost, err := bcrypt.Cost([]byte(hash))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if cost != test.wantCost {
|
|
||||||
t.Errorf("cost = %d, want %d", cost, test.wantCost)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// startDatabase starts a Database for dbURL the way the server does.
|
// startDatabase starts a Database for dbURL the way the server does.
|
||||||
// It returns the error that stopped it from starting, if any.
|
// It returns the error that stopped it from starting, if any.
|
||||||
func startDatabase(t *testing.T, dbURL string) (*db.Database, error) {
|
func startDatabase(t *testing.T, dbURL string) (*db.Database, error) {
|
||||||
|
|||||||
@@ -6,14 +6,11 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"sneak.berlin/go/neoirc/internal/dbtest"
|
"sneak.berlin/go/neoirc/internal/dbtest"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewTestDatabase creates an in-memory database for testing. It
|
// NewTestDatabase creates an in-memory database for testing.
|
||||||
// hashes passwords at bcrypt.MinCost.
|
|
||||||
func NewTestDatabase(tb testing.TB) (*Database, error) {
|
func NewTestDatabase(tb testing.TB) (*Database, error) {
|
||||||
tb.Helper()
|
tb.Helper()
|
||||||
|
|
||||||
@@ -25,9 +22,8 @@ func NewTestDatabase(tb testing.TB) (*Database, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
database := &Database{ //nolint:exhaustruct // test helper, params not needed
|
database := &Database{ //nolint:exhaustruct // test helper, params not needed
|
||||||
conn: conn,
|
conn: conn,
|
||||||
log: slog.Default(),
|
log: slog.Default(),
|
||||||
passwordCost: bcrypt.MinCost,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err = database.runMigrations(context.Background())
|
err = database.runMigrations(context.Background())
|
||||||
@@ -71,78 +67,3 @@ func (database *Database) ExecForTest(
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDB returns the underlying sql.DB connection.
|
|
||||||
func (database *Database) GetDB() *sql.DB {
|
|
||||||
return database.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetOrCreateChannel returns channel id, creating if needed.
|
|
||||||
// Uses INSERT OR IGNORE to avoid TOCTOU races.
|
|
||||||
func (database *Database) GetOrCreateChannel(
|
|
||||||
ctx context.Context,
|
|
||||||
name string,
|
|
||||||
) (int64, error) {
|
|
||||||
now := time.Now()
|
|
||||||
|
|
||||||
_, err := database.conn.ExecContext(ctx,
|
|
||||||
`INSERT OR IGNORE INTO channels
|
|
||||||
(name, created_at, updated_at)
|
|
||||||
VALUES (?, ?, ?)`,
|
|
||||||
name, now, now)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("create channel: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var channelID int64
|
|
||||||
|
|
||||||
err = database.conn.QueryRowContext(
|
|
||||||
ctx,
|
|
||||||
"SELECT id FROM channels WHERE name = ?",
|
|
||||||
name,
|
|
||||||
).Scan(&channelID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("get channel: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return channelID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JoinChannel adds a session to a channel.
|
|
||||||
func (database *Database) JoinChannel(
|
|
||||||
ctx context.Context,
|
|
||||||
channelID, sessionID int64,
|
|
||||||
) error {
|
|
||||||
_, err := database.conn.ExecContext(ctx,
|
|
||||||
`INSERT OR IGNORE INTO channel_members
|
|
||||||
(channel_id, session_id, joined_at)
|
|
||||||
VALUES (?, ?, ?)`,
|
|
||||||
channelID, sessionID, time.Now())
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("join channel: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasChannelInvite checks if a session has been invited
|
|
||||||
// to a channel.
|
|
||||||
func (database *Database) HasChannelInvite(
|
|
||||||
ctx context.Context,
|
|
||||||
channelID, sessionID int64,
|
|
||||||
) (bool, error) {
|
|
||||||
var count int
|
|
||||||
|
|
||||||
err := database.conn.QueryRowContext(ctx,
|
|
||||||
`SELECT COUNT(*) FROM channel_invites
|
|
||||||
WHERE channel_id = ? AND session_id = ?`,
|
|
||||||
channelID, sessionID,
|
|
||||||
).Scan(&count)
|
|
||||||
if err != nil {
|
|
||||||
return false, fmt.Errorf(
|
|
||||||
"check invite: %w", err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return count > 0, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package db_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"sneak.berlin/go/neoirc/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
db.SetBcryptCost(bcrypt.MinCost)
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
@@ -320,6 +320,29 @@ type ClientHostInfo struct {
|
|||||||
Hostname string
|
Hostname string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetClientHostInfo returns the IP and hostname for a
|
||||||
|
// client.
|
||||||
|
func (database *Database) GetClientHostInfo(
|
||||||
|
ctx context.Context,
|
||||||
|
clientID int64,
|
||||||
|
) (*ClientHostInfo, error) {
|
||||||
|
var info ClientHostInfo
|
||||||
|
|
||||||
|
err := database.conn.QueryRowContext(
|
||||||
|
ctx,
|
||||||
|
`SELECT ip, hostname
|
||||||
|
FROM clients WHERE id = ?`,
|
||||||
|
clientID,
|
||||||
|
).Scan(&info.IP, &info.Hostname)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"get client host info: %w", err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SetSessionOper sets the is_oper flag on a session.
|
// SetSessionOper sets the is_oper flag on a session.
|
||||||
func (database *Database) SetSessionOper(
|
func (database *Database) SetSessionOper(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
@@ -410,6 +433,54 @@ func (database *Database) GetChannelByName(
|
|||||||
return channelID, nil
|
return channelID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrCreateChannel returns channel id, creating if needed.
|
||||||
|
// Uses INSERT OR IGNORE to avoid TOCTOU races.
|
||||||
|
func (database *Database) GetOrCreateChannel(
|
||||||
|
ctx context.Context,
|
||||||
|
name string,
|
||||||
|
) (int64, error) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
_, err := database.conn.ExecContext(ctx,
|
||||||
|
`INSERT OR IGNORE INTO channels
|
||||||
|
(name, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?)`,
|
||||||
|
name, now, now)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("create channel: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var channelID int64
|
||||||
|
|
||||||
|
err = database.conn.QueryRowContext(
|
||||||
|
ctx,
|
||||||
|
"SELECT id FROM channels WHERE name = ?",
|
||||||
|
name,
|
||||||
|
).Scan(&channelID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("get channel: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return channelID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinChannel adds a session to a channel.
|
||||||
|
func (database *Database) JoinChannel(
|
||||||
|
ctx context.Context,
|
||||||
|
channelID, sessionID int64,
|
||||||
|
) error {
|
||||||
|
_, err := database.conn.ExecContext(ctx,
|
||||||
|
`INSERT OR IGNORE INTO channel_members
|
||||||
|
(channel_id, session_id, joined_at)
|
||||||
|
VALUES (?, ?, ?)`,
|
||||||
|
channelID, sessionID, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("join channel: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Errors that CreateOrJoinChannel refuses a join with.
|
// Errors that CreateOrJoinChannel refuses a join with.
|
||||||
var (
|
var (
|
||||||
ErrBannedFromChannel = errors.New("banned from channel")
|
ErrBannedFromChannel = errors.New("banned from channel")
|
||||||
@@ -1056,6 +1127,23 @@ func (database *Database) GetChannelMemberIDs(
|
|||||||
return scanInt64s(rows)
|
return scanInt64s(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetSessionChannelIDs returns channel IDs for a session.
|
||||||
|
func (database *Database) GetSessionChannelIDs(
|
||||||
|
ctx context.Context,
|
||||||
|
sessionID int64,
|
||||||
|
) ([]int64, error) {
|
||||||
|
rows, err := database.conn.QueryContext(ctx,
|
||||||
|
`SELECT channel_id FROM channel_members
|
||||||
|
WHERE session_id = ?`, sessionID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"get session channel ids: %w", err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return scanInt64s(rows)
|
||||||
|
}
|
||||||
|
|
||||||
// InsertMessage stores a message and returns its DB ID.
|
// InsertMessage stores a message and returns its DB ID.
|
||||||
// toSessionID is the session a DM or INVITE is sent to and
|
// toSessionID is the session a DM or INVITE is sent to and
|
||||||
// toChannelID the channel a channel message is sent to;
|
// toChannelID the channel a channel message is sent to;
|
||||||
@@ -2372,6 +2460,28 @@ func (database *Database) AddChannelInvite(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasChannelInvite checks if a session has been invited
|
||||||
|
// to a channel.
|
||||||
|
func (database *Database) HasChannelInvite(
|
||||||
|
ctx context.Context,
|
||||||
|
channelID, sessionID int64,
|
||||||
|
) (bool, error) {
|
||||||
|
var count int
|
||||||
|
|
||||||
|
err := database.conn.QueryRowContext(ctx,
|
||||||
|
`SELECT COUNT(*) FROM channel_invites
|
||||||
|
WHERE channel_id = ? AND session_id = ?`,
|
||||||
|
channelID, sessionID,
|
||||||
|
).Scan(&count)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf(
|
||||||
|
"check invite: %w", err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return count > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
// --- Tier 2: Secret (+s) ---
|
// --- Tier 2: Secret (+s) ---
|
||||||
|
|
||||||
// IsChannelSecret checks if a channel has +s mode.
|
// IsChannelSecret checks if a channel has +s mode.
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ func TestCreateSessionStoresIP(t *testing.T) {
|
|||||||
database := setupTestDB(t)
|
database := setupTestDB(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
sessionID, _, _, err := database.CreateSession(
|
sessionID, clientID, _, err := database.CreateSession(
|
||||||
ctx, "ipuser", "ident", "host.example.com",
|
ctx, "ipuser", "ident", "host.example.com",
|
||||||
"192.168.1.42",
|
"192.168.1.42",
|
||||||
)
|
)
|
||||||
@@ -147,8 +147,8 @@ func TestCreateSessionStoresIP(t *testing.T) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
clientInfo, err := database.GetLatestClientForSession(
|
clientInfo, err := database.GetClientHostInfo(
|
||||||
ctx, sessionID,
|
ctx, clientID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -169,6 +169,19 @@ func TestCreateSessionStoresIP(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetClientHostInfoNotFound(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
database := setupTestDB(t)
|
||||||
|
|
||||||
|
_, err := database.GetClientHostInfo(
|
||||||
|
t.Context(), 99999,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for nonexistent client")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetSessionHostInfoNotFound(t *testing.T) {
|
func TestGetSessionHostInfoNotFound(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewTestDatabaseFromConn creates a Database wrapping an
|
||||||
|
// existing *sql.DB connection. Intended for integration
|
||||||
|
// tests in other packages.
|
||||||
|
func NewTestDatabaseFromConn(conn *sql.DB) *Database {
|
||||||
|
return &Database{ //nolint:exhaustruct
|
||||||
|
conn: conn,
|
||||||
|
log: slog.Default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunMigrations applies all schema migrations. Exposed
|
||||||
|
// for integration tests in other packages.
|
||||||
|
func (database *Database) RunMigrations(
|
||||||
|
ctx context.Context,
|
||||||
|
) error {
|
||||||
|
return database.runMigrations(ctx)
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// Package dbtest gives each test a database of its own and runs raw
|
// Package dbtest gives each test a database of its own. Only tests
|
||||||
// SQL on it. Only tests may import it.
|
// may import it.
|
||||||
package dbtest
|
package dbtest
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -37,23 +37,3 @@ func NewURL(tb testing.TB) string {
|
|||||||
|
|
||||||
return dbURL
|
return dbURL
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exec runs one raw SQL statement on the database at dbURL, over a
|
|
||||||
// connection of its own. A test uses it for what the methods of
|
|
||||||
// db.Database cannot do, such as creating a trigger that makes a
|
|
||||||
// write fail.
|
|
||||||
func Exec(tb testing.TB, dbURL, statement string) {
|
|
||||||
tb.Helper()
|
|
||||||
|
|
||||||
pool, err := sql.Open("sqlite", dbURL)
|
|
||||||
if err != nil {
|
|
||||||
tb.Fatalf("open test database: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() { _ = pool.Close() }()
|
|
||||||
|
|
||||||
_, err = pool.ExecContext(tb.Context(), statement)
|
|
||||||
if err != nil {
|
|
||||||
tb.Fatalf("run %q: %v", statement, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+25
-56
@@ -42,9 +42,25 @@ func (hdlr *Handlers) maxBodySize() int64 {
|
|||||||
return defaultMaxBodySize
|
return defaultMaxBodySize
|
||||||
}
|
}
|
||||||
|
|
||||||
// clientIP returns the IP address in request.RemoteAddr, which the
|
// clientIP extracts the connecting client's IP address
|
||||||
// ClientIP middleware has set to the client's address.
|
// from the request, checking X-Forwarded-For and
|
||||||
|
// X-Real-IP headers before falling back to RemoteAddr.
|
||||||
func clientIP(request *http.Request) string {
|
func clientIP(request *http.Request) string {
|
||||||
|
if forwarded := request.Header.Get("X-Forwarded-For"); forwarded != "" {
|
||||||
|
// X-Forwarded-For can contain a comma-separated list;
|
||||||
|
// the first entry is the original client.
|
||||||
|
parts := strings.SplitN(forwarded, ",", 2) //nolint:mnd
|
||||||
|
ip := strings.TrimSpace(parts[0])
|
||||||
|
|
||||||
|
if ip != "" {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if realIP := request.Header.Get("X-Real-IP"); realIP != "" {
|
||||||
|
return strings.TrimSpace(realIP)
|
||||||
|
}
|
||||||
|
|
||||||
host, _, err := net.SplitHostPort(request.RemoteAddr)
|
host, _, err := net.SplitHostPort(request.RemoteAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return request.RemoteAddr
|
return request.RemoteAddr
|
||||||
@@ -172,7 +188,7 @@ func (hdlr *Handlers) handleCreateSession(
|
|||||||
|
|
||||||
var payload createRequest
|
var payload createRequest
|
||||||
|
|
||||||
err := decodeJSON(request, &payload)
|
err := json.NewDecoder(request.Body).Decode(&payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hdlr.respondError(
|
hdlr.respondError(
|
||||||
writer, request,
|
writer, request,
|
||||||
@@ -396,7 +412,7 @@ func (hdlr *Handlers) deliverWelcome(
|
|||||||
// 004 RPL_MYINFO
|
// 004 RPL_MYINFO
|
||||||
hdlr.enqueueNumeric(
|
hdlr.enqueueNumeric(
|
||||||
ctx, clientID, irc.RplMyInfo, nick,
|
ctx, clientID, irc.RplMyInfo, nick,
|
||||||
[]string{srvName, version, service.UserModes, "Hbiklmnostv"},
|
[]string{srvName, version, "", "ikmnostl"},
|
||||||
"",
|
"",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -909,7 +925,7 @@ func (hdlr *Handlers) HandleSendCommand() http.HandlerFunc {
|
|||||||
|
|
||||||
var payload commandRequest
|
var payload commandRequest
|
||||||
|
|
||||||
err := decodeJSON(request, &payload)
|
err := json.NewDecoder(request.Body).Decode(&payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hdlr.respondError(
|
hdlr.respondError(
|
||||||
writer, request,
|
writer, request,
|
||||||
@@ -978,7 +994,7 @@ func (hdlr *Handlers) dispatchCommand(
|
|||||||
hdlr.handlePrivmsg(
|
hdlr.handlePrivmsg(
|
||||||
writer, request,
|
writer, request,
|
||||||
sessionID, clientID, nick,
|
sessionID, clientID, nick,
|
||||||
command, target, body, meta,
|
command, target, body, meta, bodyLines,
|
||||||
)
|
)
|
||||||
case irc.CmdJoin:
|
case irc.CmdJoin:
|
||||||
hdlr.handleJoin(
|
hdlr.handleJoin(
|
||||||
@@ -1123,18 +1139,8 @@ func (hdlr *Handlers) handlePrivmsg(
|
|||||||
nick, command, target string,
|
nick, command, target string,
|
||||||
body json.RawMessage,
|
body json.RawMessage,
|
||||||
meta json.RawMessage,
|
meta json.RawMessage,
|
||||||
|
bodyLines func() []string,
|
||||||
) {
|
) {
|
||||||
lines, ok := checkBodyAndMeta(body, meta)
|
|
||||||
if !ok {
|
|
||||||
hdlr.respondError(
|
|
||||||
writer, request,
|
|
||||||
"invalid request body",
|
|
||||||
http.StatusBadRequest,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if target == "" {
|
if target == "" {
|
||||||
hdlr.enqueueNumeric(
|
hdlr.enqueueNumeric(
|
||||||
request.Context(), clientID,
|
request.Context(), clientID,
|
||||||
@@ -1149,6 +1155,7 @@ func (hdlr *Handlers) handlePrivmsg(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lines := bodyLines()
|
||||||
if len(lines) == 0 {
|
if len(lines) == 0 {
|
||||||
hdlr.enqueueNumeric(
|
hdlr.enqueueNumeric(
|
||||||
request.Context(), clientID,
|
request.Context(), clientID,
|
||||||
@@ -1182,44 +1189,6 @@ func (hdlr *Handlers) handlePrivmsg(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkBodyAndMeta returns the lines in body. It returns false
|
|
||||||
// when body is present and is not an array of strings, or meta
|
|
||||||
// is present and is not an object. Each line is decoded as any
|
|
||||||
// because decoding into []string turns a null line into "". A
|
|
||||||
// null body or meta decodes without an error into nil.
|
|
||||||
func checkBodyAndMeta(body, meta json.RawMessage) ([]string, bool) {
|
|
||||||
var lines []string
|
|
||||||
|
|
||||||
if body != nil {
|
|
||||||
var values []any
|
|
||||||
|
|
||||||
err := json.Unmarshal(body, &values)
|
|
||||||
if err != nil || values == nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, value := range values {
|
|
||||||
line, isString := value.(string)
|
|
||||||
if !isString {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
lines = append(lines, line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if meta != nil {
|
|
||||||
var fields map[string]any
|
|
||||||
|
|
||||||
err := json.Unmarshal(meta, &fields)
|
|
||||||
if err != nil || fields == nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// respondIRCError enqueues a numeric error reply, notifies
|
// respondIRCError enqueues a numeric error reply, notifies
|
||||||
// the broker, and sends HTTP 200 with {"status":"error"}.
|
// the broker, and sends HTTP 200 with {"status":"error"}.
|
||||||
func (hdlr *Handlers) respondIRCError(
|
func (hdlr *Handlers) respondIRCError(
|
||||||
@@ -3222,7 +3191,7 @@ func (hdlr *Handlers) handleWho(
|
|||||||
// 315 RPL_ENDOFWHO (empty result)
|
// 315 RPL_ENDOFWHO (empty result)
|
||||||
hdlr.enqueueNumeric(
|
hdlr.enqueueNumeric(
|
||||||
ctx, clientID, irc.RplEndOfWho, nick,
|
ctx, clientID, irc.RplEndOfWho, nick,
|
||||||
[]string{channel},
|
[]string{target},
|
||||||
"End of /WHO list",
|
"End of /WHO list",
|
||||||
)
|
)
|
||||||
hdlr.broker.Notify(sessionID)
|
hdlr.broker.Notify(sessionID)
|
||||||
|
|||||||
+154
-612
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -54,7 +55,7 @@ func (hdlr *Handlers) handleLogin(
|
|||||||
|
|
||||||
var payload loginRequest
|
var payload loginRequest
|
||||||
|
|
||||||
err := decodeJSON(request, &payload)
|
err := json.NewDecoder(request.Body).Decode(&payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hdlr.respondError(
|
hdlr.respondError(
|
||||||
writer, request,
|
writer, request,
|
||||||
|
|||||||
@@ -6,10 +6,6 @@ import (
|
|||||||
"sneak.berlin/go/neoirc/internal/db"
|
"sneak.berlin/go/neoirc/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MaxLongPollTimeout is the longest HandleGetMessages waits, in
|
|
||||||
// seconds.
|
|
||||||
const MaxLongPollTimeout = maxLongPollTimeout
|
|
||||||
|
|
||||||
// SetPollMessages makes HandleGetMessages read the client
|
// SetPollMessages makes HandleGetMessages read the client
|
||||||
// output queue with poll in place of Database.PollMessages.
|
// output queue with poll in place of Database.PollMessages.
|
||||||
func (hdlr *Handlers) SetPollMessages(
|
func (hdlr *Handlers) SetPollMessages(
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
@@ -160,18 +159,6 @@ func (hdlr *Handlers) respondError(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// decodeJSON reads the whole request body and decodes it into dest.
|
|
||||||
// It fails if the body is larger than the http.MaxBytesReader limit,
|
|
||||||
// or holds anything other than one JSON value and whitespace.
|
|
||||||
func decodeJSON(request *http.Request, dest any) error {
|
|
||||||
body, err := io.ReadAll(request.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Unmarshal(body, dest)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hdlr *Handlers) idleTimeout() time.Duration {
|
func (hdlr *Handlers) idleTimeout() time.Duration {
|
||||||
raw := hdlr.params.Config.SessionIdleTimeout
|
raw := hdlr.params.Config.SessionIdleTimeout
|
||||||
if raw == "" {
|
if raw == "" {
|
||||||
|
|||||||
@@ -371,7 +371,6 @@ func (c *Conn) handleQuit(msg *Message) {
|
|||||||
|
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
c.closed = true
|
c.closed = true
|
||||||
c.quitReason = reason
|
|
||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1227,12 +1226,9 @@ func (c *Conn) handlePassPostReg(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The IRC listener cannot add a connection to an existing
|
|
||||||
// session; only the HTTP API login can.
|
|
||||||
c.sendFromServer("NOTICE", c.currentNick(),
|
c.sendFromServer("NOTICE", c.currentNick(),
|
||||||
"Password set. Another client can log in to this "+
|
"Password set. You can reconnect using "+
|
||||||
"session over the HTTP API: POST /api/v1/login "+
|
"PASS <password> with your nick.",
|
||||||
"with your nick and this password.",
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-24
@@ -69,15 +69,6 @@ type Conn struct {
|
|||||||
lastQueueID int64
|
lastQueueID int64
|
||||||
closed bool
|
closed bool
|
||||||
killed bool
|
killed bool
|
||||||
|
|
||||||
// pollInterval is how often the relay checks the client
|
|
||||||
// output queue when no broker notification arrives.
|
|
||||||
pollInterval time.Duration
|
|
||||||
|
|
||||||
// quitReason is the reason in the QUIT that peers are
|
|
||||||
// sent when the connection ends. The client's QUIT
|
|
||||||
// replaces it.
|
|
||||||
quitReason string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newConn(
|
func newConn(
|
||||||
@@ -87,7 +78,6 @@ func newConn(
|
|||||||
brk *broker.Broker,
|
brk *broker.Broker,
|
||||||
cfg *config.Config,
|
cfg *config.Config,
|
||||||
svc *service.Service,
|
svc *service.Service,
|
||||||
poll time.Duration,
|
|
||||||
) *Conn {
|
) *Conn {
|
||||||
host, _, _ := net.SplitHostPort(tcpConn.RemoteAddr().String())
|
host, _, _ := net.SplitHostPort(tcpConn.RemoteAddr().String())
|
||||||
|
|
||||||
@@ -97,17 +87,14 @@ func newConn(
|
|||||||
}
|
}
|
||||||
|
|
||||||
conn := &Conn{ //nolint:exhaustruct // zero-value defaults
|
conn := &Conn{ //nolint:exhaustruct // zero-value defaults
|
||||||
conn: tcpConn,
|
conn: tcpConn,
|
||||||
log: log,
|
log: log,
|
||||||
database: database,
|
database: database,
|
||||||
brk: brk,
|
brk: brk,
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
svc: svc,
|
svc: svc,
|
||||||
serverSfx: srvName,
|
serverSfx: srvName,
|
||||||
remoteIP: host,
|
remoteIP: host,
|
||||||
quitReason: "Connection closed",
|
|
||||||
|
|
||||||
pollInterval: poll,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
conn.commands = conn.buildCommandMap()
|
conn.commands = conn.buildCommandMap()
|
||||||
@@ -291,7 +278,6 @@ func (c *Conn) cleanup(ctx context.Context) {
|
|||||||
wasKilled := c.killed
|
wasKilled := c.killed
|
||||||
sessID := c.sessionID
|
sessID := c.sessionID
|
||||||
nick := c.nick
|
nick := c.nick
|
||||||
quitReason := c.quitReason
|
|
||||||
c.closed = true
|
c.closed = true
|
||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
|
|
||||||
@@ -301,7 +287,9 @@ func (c *Conn) cleanup(ctx context.Context) {
|
|||||||
// KILL has already sent the QUIT and deleted the
|
// KILL has already sent the QUIT and deleted the
|
||||||
// session.
|
// session.
|
||||||
if !wasKilled {
|
if !wasKilled {
|
||||||
c.svc.BroadcastQuit(ctx, sessID, nick, quitReason)
|
c.svc.BroadcastQuit(
|
||||||
|
ctx, sessID, nick, "Connection closed",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -617,7 +605,7 @@ func (c *Conn) deliverWelcome() {
|
|||||||
)
|
)
|
||||||
c.sendNumeric(
|
c.sendNumeric(
|
||||||
irc.RplMyInfo,
|
irc.RplMyInfo,
|
||||||
c.serverSfx, "neoirc", service.UserModes, "Himnostv",
|
c.serverSfx, "neoirc", "", "mnst",
|
||||||
)
|
)
|
||||||
c.sendNumeric(
|
c.sendNumeric(
|
||||||
irc.RplIsupport,
|
irc.RplIsupport,
|
||||||
|
|||||||
@@ -14,16 +14,16 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewTestServer creates a Server suitable for testing, whose
|
// NewTestServer creates a Server suitable for testing, whose
|
||||||
// connections use interval, deadline and poll in place of
|
// connections use interval and deadline in place of
|
||||||
// pingInterval, pongDeadline and pollInterval, and resolve in
|
// pingInterval and pongDeadline, and resolve in place of
|
||||||
// place of resolveHost.
|
// resolveHost.
|
||||||
// The caller must call Stop() when finished.
|
// The caller must call Stop() when finished.
|
||||||
func NewTestServer(
|
func NewTestServer(
|
||||||
log *slog.Logger,
|
log *slog.Logger,
|
||||||
cfg *config.Config,
|
cfg *config.Config,
|
||||||
database *db.Database,
|
database *db.Database,
|
||||||
brk *broker.Broker,
|
brk *broker.Broker,
|
||||||
interval, deadline, poll time.Duration,
|
interval, deadline time.Duration,
|
||||||
resolve func(ctx context.Context, addr string) string,
|
resolve func(ctx context.Context, addr string) string,
|
||||||
) *Server {
|
) *Server {
|
||||||
globs := &globals.Globals{
|
globs := &globals.Globals{
|
||||||
@@ -46,18 +46,10 @@ func NewTestServer(
|
|||||||
|
|
||||||
pingInterval: interval,
|
pingInterval: interval,
|
||||||
pongDeadline: deadline,
|
pongDeadline: deadline,
|
||||||
pollInterval: poll,
|
|
||||||
stopTimeout: stopTimeout,
|
|
||||||
resolveHost: resolve,
|
resolveHost: resolve,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetStopTimeout makes Stop wait at most timeout for the
|
|
||||||
// connections' cleanup.
|
|
||||||
func (s *Server) SetStopTimeout(timeout time.Duration) {
|
|
||||||
s.stopTimeout = timeout
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolveHost is the reverse DNS lookup that a server made by
|
// ResolveHost is the reverse DNS lookup that a server made by
|
||||||
// New does for each client.
|
// New does for each client.
|
||||||
func ResolveHost(ctx context.Context, addr string) string {
|
func ResolveHost(ctx context.Context, addr string) string {
|
||||||
@@ -107,6 +99,10 @@ const PingInterval = pingInterval
|
|||||||
// for a line before it closes the connection.
|
// for a line before it closes the connection.
|
||||||
const PongDeadline = pongDeadline
|
const PongDeadline = pongDeadline
|
||||||
|
|
||||||
|
// StopTimeout is the longest Stop waits for the connections'
|
||||||
|
// cleanup.
|
||||||
|
const StopTimeout = stopTimeout
|
||||||
|
|
||||||
// NewTestConn returns a Conn for nick on tcpConn, without a
|
// NewTestConn returns a Conn for nick on tcpConn, without a
|
||||||
// server, database or service behind it.
|
// server, database or service behind it.
|
||||||
func NewTestConn(
|
func NewTestConn(
|
||||||
@@ -115,7 +111,7 @@ func NewTestConn(
|
|||||||
tcpConn net.Conn,
|
tcpConn net.Conn,
|
||||||
nick string,
|
nick string,
|
||||||
) *Conn {
|
) *Conn {
|
||||||
conn := newConn(tcpConn, log, nil, nil, cfg, nil, pollInterval)
|
conn := newConn(tcpConn, log, nil, nil, cfg, nil)
|
||||||
conn.nick = nick
|
conn.nick = nick
|
||||||
|
|
||||||
return conn
|
return conn
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package ircserver_test
|
|||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
)
|
)
|
||||||
@@ -1507,6 +1508,9 @@ func TestIntegrationThirdClientObserver(t *testing.T) {
|
|||||||
bob.joinAndDrain("#trio")
|
bob.joinAndDrain("#trio")
|
||||||
carol.joinAndDrain("#trio")
|
carol.joinAndDrain("#trio")
|
||||||
|
|
||||||
|
// Drain join notifications.
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
// alice sends; both bob and carol should receive.
|
// alice sends; both bob and carol should receive.
|
||||||
alice.send("PRIVMSG #trio :hello trio")
|
alice.send("PRIVMSG #trio :hello trio")
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
func (c *Conn) relayMessages(ctx context.Context) {
|
func (c *Conn) relayMessages(ctx context.Context) {
|
||||||
// Use a ticker as a fallback; primary wakeup is via
|
// Use a ticker as a fallback; primary wakeup is via
|
||||||
// broker notification.
|
// broker notification.
|
||||||
ticker := time.NewTicker(c.pollInterval)
|
ticker := time.NewTicker(pollInterval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
|||||||
@@ -8,9 +8,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
|
||||||
"sneak.berlin/go/neoirc/internal/dbtest"
|
|
||||||
"sneak.berlin/go/neoirc/internal/ircserver"
|
"sneak.berlin/go/neoirc/internal/ircserver"
|
||||||
"sneak.berlin/go/neoirc/internal/service"
|
"sneak.berlin/go/neoirc/internal/service"
|
||||||
)
|
)
|
||||||
@@ -59,11 +56,7 @@ func (env *testEnv) queueMessage(
|
|||||||
func TestRelayKeepsOneWaitChannel(t *testing.T) {
|
func TestRelayKeepsOneWaitChannel(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
env := newTestEnvWithResolver(
|
env := newTestEnv(t)
|
||||||
t, &config.Config{ServerName: testServerName},
|
|
||||||
ircserver.PingInterval, ircserver.PongDeadline,
|
|
||||||
ircserver.PollInterval, ircserver.ResolveHost,
|
|
||||||
)
|
|
||||||
|
|
||||||
client := env.dial(t)
|
client := env.dial(t)
|
||||||
client.register("idle")
|
client.register("idle")
|
||||||
@@ -124,63 +117,6 @@ func (env *testEnv) checkOneWaitChannel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRelayDeliversAfterFailedRead checks that when the relay
|
|
||||||
// cannot read the client output queue, it waits for the next
|
|
||||||
// notification, and delivers once the queue can be read again.
|
|
||||||
func TestRelayDeliversAfterFailedRead(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
|
||||||
client := env.dial(t)
|
|
||||||
client.register("reader")
|
|
||||||
|
|
||||||
sessionID, err := env.database.GetSessionByNick(t.Context(), "reader")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get session of reader: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
|
||||||
"ALTER TABLE client_queues RENAME TO hidden_queues")
|
|
||||||
|
|
||||||
// Each pass of the relay takes a wait channel and then reads
|
|
||||||
// the queue. Once it holds a channel after the second
|
|
||||||
// notification, the read after the first one has failed.
|
|
||||||
for range 2 {
|
|
||||||
env.waitForWaitChannel(t, sessionID)
|
|
||||||
env.brk.Notify(sessionID)
|
|
||||||
}
|
|
||||||
|
|
||||||
env.waitForWaitChannel(t, sessionID)
|
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
|
||||||
"ALTER TABLE hidden_queues RENAME TO client_queues")
|
|
||||||
|
|
||||||
env.queueMessage(
|
|
||||||
t, "reader", "PRIVMSG", "carol", "reader", []string{"readable"},
|
|
||||||
)
|
|
||||||
|
|
||||||
client.readUntil(func(l string) bool {
|
|
||||||
return strings.Contains(l, "readable")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// waitForWaitChannel waits until the session sessionID holds a
|
|
||||||
// broker wait channel, and fails the test if it does not
|
|
||||||
// within testTimeout.
|
|
||||||
func (env *testEnv) waitForWaitChannel(t *testing.T, sessionID int64) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
deadline := time.Now().Add(testTimeout)
|
|
||||||
|
|
||||||
for env.brk.ListenerCount(sessionID) == 0 {
|
|
||||||
if time.Now().After(deadline) {
|
|
||||||
t.Fatal("the relay is not waiting for a notification")
|
|
||||||
}
|
|
||||||
|
|
||||||
time.Sleep(relayCheckStep)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRelayMultiLineBody checks that each line of a PRIVMSG
|
// TestRelayMultiLineBody checks that each line of a PRIVMSG
|
||||||
// or NOTICE body sent over the HTTP API reaches an IRC
|
// or NOTICE body sent over the HTTP API reaches an IRC
|
||||||
// listener user as its own line.
|
// listener user as its own line.
|
||||||
@@ -380,7 +316,7 @@ func TestRelayNickDiffersOnlyInCase(t *testing.T) {
|
|||||||
{"JOIN #case", ":Alice!Alice@* JOIN #case"},
|
{"JOIN #case", ":Alice!Alice@* JOIN #case"},
|
||||||
{"NICK Alicia", ":Alice!Alice@* NICK Alicia"},
|
{"NICK Alicia", ":Alice!Alice@* NICK Alicia"},
|
||||||
{"NICK Alice", ":Alicia!Alicia@* NICK Alice"}, // back for QUIT
|
{"NICK Alice", ":Alicia!Alicia@* NICK Alice"}, // back for QUIT
|
||||||
{"QUIT", ":Alice!Alice@* QUIT :Quit: Client quit"},
|
{"QUIT", ":Alice!Alice@* QUIT :Quit: Connection closed"},
|
||||||
} {
|
} {
|
||||||
capitalAlice.send(step.line)
|
capitalAlice.send(step.line)
|
||||||
|
|
||||||
@@ -647,10 +583,8 @@ func ownSessionCopies(
|
|||||||
|
|
||||||
// aliceWithHTTPClient connects alice to the IRC listener and
|
// aliceWithHTTPClient connects alice to the IRC listener and
|
||||||
// has her join #chan, which bob is on too, then adds an HTTP API
|
// has her join #chan, which bob is on too, then adds an HTTP API
|
||||||
// client to her session with a password, as POST /api/v1/login
|
// client to her session with the password her connection set,
|
||||||
// does. It stores that password without sending PASS. It hashes
|
// as POST /api/v1/login does. It returns her connection, bob's
|
||||||
// at bcrypt.MinCost, and a login compares at the cost stored in
|
|
||||||
// the hash, so both are fast. It returns her connection, bob's
|
|
||||||
// connection, her session and her HTTP API client.
|
// connection, her session and her HTTP API client.
|
||||||
func aliceWithHTTPClient(
|
func aliceWithHTTPClient(
|
||||||
t *testing.T, env *testEnv,
|
t *testing.T, env *testEnv,
|
||||||
@@ -660,24 +594,15 @@ func aliceWithHTTPClient(
|
|||||||
const password = "alicepass"
|
const password = "alicepass"
|
||||||
|
|
||||||
alice := env.dial(t)
|
alice := env.dial(t)
|
||||||
|
alice.send("PASS " + password)
|
||||||
alice.register("alice")
|
alice.register("alice")
|
||||||
|
// Registration stores the password before the JOIN runs.
|
||||||
alice.joinAndDrain("#chan")
|
alice.joinAndDrain("#chan")
|
||||||
|
|
||||||
bob := env.dial(t)
|
bob := env.dial(t)
|
||||||
bob.register("bob")
|
bob.register("bob")
|
||||||
bob.joinAndDrain("#chan")
|
bob.joinAndDrain("#chan")
|
||||||
|
|
||||||
hash, err := bcrypt.GenerateFromPassword(
|
|
||||||
[]byte(password), bcrypt.MinCost,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash password: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
|
||||||
"UPDATE sessions SET password_hash = '"+string(hash)+
|
|
||||||
"' WHERE nick = 'alice'")
|
|
||||||
|
|
||||||
sessionID, httpClientID, _, err := env.database.LoginUser(
|
sessionID, httpClientID, _, err := env.database.LoginUser(
|
||||||
t.Context(), "alice", password, "127.0.0.1", "localhost",
|
t.Context(), "alice", password, "127.0.0.1", "localhost",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -53,11 +53,6 @@ type Server struct {
|
|||||||
pingInterval time.Duration
|
pingInterval time.Duration
|
||||||
pongDeadline time.Duration
|
pongDeadline time.Duration
|
||||||
|
|
||||||
// pollInterval and stopTimeout are the constants of the
|
|
||||||
// same names, except in tests, which change them.
|
|
||||||
pollInterval time.Duration
|
|
||||||
stopTimeout time.Duration
|
|
||||||
|
|
||||||
// resolveHost is the function of the same name, except in
|
// resolveHost is the function of the same name, except in
|
||||||
// tests, which replace it with one that blocks.
|
// tests, which replace it with one that blocks.
|
||||||
resolveHost func(ctx context.Context, addr string) string
|
resolveHost func(ctx context.Context, addr string) string
|
||||||
@@ -84,8 +79,6 @@ func New(
|
|||||||
|
|
||||||
pingInterval: pingInterval,
|
pingInterval: pingInterval,
|
||||||
pongDeadline: pongDeadline,
|
pongDeadline: pongDeadline,
|
||||||
pollInterval: pollInterval,
|
|
||||||
stopTimeout: stopTimeout,
|
|
||||||
resolveHost: resolveHost,
|
resolveHost: resolveHost,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,10 +154,10 @@ func (s *Server) stop() {
|
|||||||
|
|
||||||
select {
|
select {
|
||||||
case <-done:
|
case <-done:
|
||||||
case <-time.After(s.stopTimeout):
|
case <-time.After(stopTimeout):
|
||||||
s.log.Error(
|
s.log.Error(
|
||||||
"irc connections not cleaned up before stop timeout",
|
"irc connections not cleaned up before stop timeout",
|
||||||
"timeout", s.stopTimeout,
|
"timeout", stopTimeout,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,7 +181,7 @@ func (s *Server) acceptLoop(ctx context.Context) {
|
|||||||
|
|
||||||
client := newConn(
|
client := newConn(
|
||||||
tcpConn, s.log,
|
tcpConn, s.log,
|
||||||
s.database, s.brk, s.cfg, s.svc, s.pollInterval,
|
s.database, s.brk, s.cfg, s.svc,
|
||||||
)
|
)
|
||||||
|
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
|
|||||||
@@ -4,21 +4,18 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
"slices"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.uber.org/fx/fxtest"
|
"go.uber.org/fx/fxtest"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"sneak.berlin/go/neoirc/internal/broker"
|
"sneak.berlin/go/neoirc/internal/broker"
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/db"
|
"sneak.berlin/go/neoirc/internal/db"
|
||||||
@@ -26,25 +23,20 @@ import (
|
|||||||
"sneak.berlin/go/neoirc/internal/globals"
|
"sneak.berlin/go/neoirc/internal/globals"
|
||||||
"sneak.berlin/go/neoirc/internal/ircserver"
|
"sneak.berlin/go/neoirc/internal/ircserver"
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
"sneak.berlin/go/neoirc/internal/logger"
|
||||||
"sneak.berlin/go/neoirc/pkg/irc"
|
|
||||||
|
|
||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testTimeout is how long a test waits for something before it
|
const testTimeout = 5 * time.Second
|
||||||
// fails. A passing test never waits this long, so it is generous
|
|
||||||
// enough for a heavily loaded host.
|
|
||||||
const testTimeout = 30 * time.Second
|
|
||||||
|
|
||||||
// testPollInterval is how often the relay of a test server
|
func TestMain(m *testing.M) {
|
||||||
// checks the client output queue without a broker
|
db.SetBcryptCost(4)
|
||||||
// notification. It is so long that the relay delivers only on
|
|
||||||
// notification, and a test fails when one is missing.
|
os.Exit(m.Run())
|
||||||
const testPollInterval = time.Hour
|
}
|
||||||
|
|
||||||
// testEnv holds the shared test infrastructure.
|
// testEnv holds the shared test infrastructure.
|
||||||
type testEnv struct {
|
type testEnv struct {
|
||||||
dbURL string
|
|
||||||
database *db.Database
|
database *db.Database
|
||||||
brk *broker.Broker
|
brk *broker.Broker
|
||||||
cfg *config.Config
|
cfg *config.Config
|
||||||
@@ -101,44 +93,47 @@ func newTestEnvWithPingTimes(
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
return newTestEnvWithResolver(
|
return newTestEnvWithResolver(
|
||||||
t, cfg, interval, deadline, testPollInterval,
|
t, cfg, interval, deadline, ircserver.ResolveHost,
|
||||||
ircserver.ResolveHost,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newTestEnvWithResolver is newTestEnvWithPingTimes, except
|
// newTestEnvWithResolver is newTestEnvWithPingTimes, except
|
||||||
// that the relay checks the client output queue every poll
|
// that the server looks up a client's hostname with resolve.
|
||||||
// without a broker notification, and the server looks up a
|
|
||||||
// client's hostname with resolve.
|
|
||||||
func newTestEnvWithResolver(
|
func newTestEnvWithResolver(
|
||||||
t *testing.T,
|
t *testing.T,
|
||||||
cfg *config.Config,
|
cfg *config.Config,
|
||||||
interval, deadline, poll time.Duration,
|
interval, deadline time.Duration,
|
||||||
resolve func(ctx context.Context, addr string) string,
|
resolve func(ctx context.Context, addr string) string,
|
||||||
) *testEnv {
|
) *testEnv {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
dbURL := dbtest.NewURL(t)
|
conn, err := sql.Open("sqlite", dbtest.NewURL(t))
|
||||||
lifecycle := fxtest.NewLifecycle(t)
|
|
||||||
|
|
||||||
dbLog, err := logger.New(lifecycle, logger.Params{
|
|
||||||
Globals: &globals.Globals{},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("new logger: %v", err)
|
t.Fatalf("open db: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
database, err := db.New(lifecycle, db.Params{
|
t.Cleanup(func() {
|
||||||
Logger: dbLog,
|
err := conn.Close()
|
||||||
Config: &config.Config{DBURL: dbURL},
|
if err != nil {
|
||||||
PasswordCost: bcrypt.MinCost,
|
t.Logf("close db: %v", err)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
conn.SetMaxOpenConns(1)
|
||||||
|
|
||||||
|
_, err = conn.ExecContext(
|
||||||
|
t.Context(), "PRAGMA foreign_keys = ON",
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("new database: %v", err)
|
t.Fatalf("pragma: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
lifecycle.RequireStart()
|
database := db.NewTestDatabaseFromConn(conn)
|
||||||
t.Cleanup(lifecycle.RequireStop)
|
|
||||||
|
err = database.RunMigrations(t.Context())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
brk := broker.New()
|
brk := broker.New()
|
||||||
|
|
||||||
@@ -148,7 +143,7 @@ func newTestEnvWithResolver(
|
|||||||
))
|
))
|
||||||
|
|
||||||
srv := ircserver.NewTestServer(
|
srv := ircserver.NewTestServer(
|
||||||
log, cfg, database, brk, interval, deadline, poll, resolve,
|
log, cfg, database, brk, interval, deadline, resolve,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Port 0 makes the system pick a free port. dial reads it
|
// Port 0 makes the system pick a free port. dial reads it
|
||||||
@@ -163,7 +158,6 @@ func newTestEnvWithResolver(
|
|||||||
t.Cleanup(srv.Stop)
|
t.Cleanup(srv.Stop)
|
||||||
|
|
||||||
return &testEnv{
|
return &testEnv{
|
||||||
dbURL: dbURL,
|
|
||||||
database: database,
|
database: database,
|
||||||
brk: brk,
|
brk: brk,
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
@@ -444,8 +438,7 @@ func TestRegistrationWhileAnotherLookupIsPending(t *testing.T) {
|
|||||||
|
|
||||||
env := newTestEnvWithResolver(
|
env := newTestEnvWithResolver(
|
||||||
t, &config.Config{ServerName: testServerName},
|
t, &config.Config{ServerName: testServerName},
|
||||||
ircserver.PingInterval, ircserver.PongDeadline,
|
ircserver.PingInterval, ircserver.PongDeadline, resolve,
|
||||||
testPollInterval, resolve,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
env.dial(t)
|
env.dial(t)
|
||||||
@@ -493,22 +486,6 @@ func TestWelcomeContainsNick(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMyInfoListsModes checks that RPL_MYINFO lists the user
|
|
||||||
// modes o and w, then the channel modes MODE accepts on the
|
|
||||||
// IRC listener. It compares the whole line, so a missing or
|
|
||||||
// extra mode fails it.
|
|
||||||
func TestMyInfoListsModes(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
|
||||||
lines := env.dial(t).register("carol")
|
|
||||||
|
|
||||||
want := ":test.irc 004 carol test.irc neoirc ow Himnostv"
|
|
||||||
if !slices.Contains(lines, want) {
|
|
||||||
t.Errorf("no line %q in %v", want, lines)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPingPong(t *testing.T) {
|
func TestPingPong(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -568,49 +545,27 @@ func TestQuietClientAnsweringPingStaysConnected(t *testing.T) {
|
|||||||
func TestQuietClientNotAnsweringPingIsClosed(t *testing.T) {
|
func TestQuietClientNotAnsweringPingIsClosed(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
// A read deadline of two ping intervals would close the
|
// latest leaves room for a loaded host, but is sooner than
|
||||||
// connection a second after latest. The ping interval is
|
// a read deadline of two ping intervals would close it.
|
||||||
// longer than testPingInterval, so that the time between
|
|
||||||
// the expected close and latest leaves room for a loaded
|
|
||||||
// host.
|
|
||||||
const (
|
const (
|
||||||
interval = 4 * time.Second
|
earliest = testPingInterval + testPongDeadline
|
||||||
earliest = interval + testPongDeadline
|
latest = 2 * testPingInterval
|
||||||
latest = 2*interval - time.Second
|
|
||||||
)
|
)
|
||||||
|
|
||||||
env := newTestEnvWithPingTimes(
|
env := newTestEnvWithShortPings(t)
|
||||||
t,
|
|
||||||
&config.Config{ServerName: testServerName},
|
|
||||||
interval, testPongDeadline,
|
|
||||||
)
|
|
||||||
client := env.dial(t)
|
client := env.dial(t)
|
||||||
|
|
||||||
lastSent := time.Now()
|
lastSent := time.Now()
|
||||||
|
|
||||||
client.register("silent")
|
client.register("silent")
|
||||||
|
client.readServerPing(lastSent)
|
||||||
// The server starts both waits once it has handled the
|
|
||||||
// registration, so the time registration took does not
|
|
||||||
// count against latest.
|
|
||||||
registered := time.Now()
|
|
||||||
|
|
||||||
client.readUntil(isServerPing)
|
|
||||||
client.readUntilClosed()
|
client.readUntilClosed()
|
||||||
|
|
||||||
waited := time.Since(lastSent)
|
waited := time.Since(lastSent)
|
||||||
if waited < earliest {
|
if waited < earliest || waited >= latest {
|
||||||
t.Errorf(
|
t.Errorf(
|
||||||
"closed %v after the client's last line, want at least %v",
|
"closed %v after the client's last line, want %v to %v",
|
||||||
waited, earliest,
|
waited, earliest, latest,
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
sinceRegistered := time.Since(registered)
|
|
||||||
if sinceRegistered >= latest {
|
|
||||||
t.Errorf(
|
|
||||||
"closed %v after registration, want less than %v",
|
|
||||||
sinceRegistered, latest,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -901,107 +856,6 @@ func TestQuit(t *testing.T) {
|
|||||||
assertContains(t, lines, "goodbye", "QUIT reason")
|
assertContains(t, lines, "goodbye", "QUIT reason")
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestQuitReasonReachesPeers checks the reason that an IRC
|
|
||||||
// listener user's channel peers see in its QUIT, on both the
|
|
||||||
// IRC listener and the HTTP API. It is the reason the user
|
|
||||||
// gave, Client quit for a QUIT without one, or Connection
|
|
||||||
// closed when the connection ends without a QUIT.
|
|
||||||
func TestQuitReasonReachesPeers(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
for _, step := range []struct {
|
|
||||||
name, quit, want string
|
|
||||||
}{
|
|
||||||
{"QUIT with a reason", "QUIT :gone home", "gone home"},
|
|
||||||
{"QUIT without a reason", irc.CmdQuit, "Client quit"},
|
|
||||||
{"connection closed without QUIT", "", "Connection closed"},
|
|
||||||
} {
|
|
||||||
t.Run(step.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ircLine, apiBody := quitSeenByPeers(t, step.quit)
|
|
||||||
|
|
||||||
want := ":quitter!quitter@* QUIT :Quit: " + step.want
|
|
||||||
if ircLine != want {
|
|
||||||
t.Errorf("IRC peer got %q, want %q", ircLine, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(apiBody) != 1 || apiBody[0] != step.want {
|
|
||||||
t.Errorf("HTTP API peer got %q, want [%q]", apiBody, step.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// quitSeenByPeers starts a server on which quitter, ircpeer on
|
|
||||||
// the IRC listener and apipeer on the HTTP API share a channel.
|
|
||||||
// quitter sends the line quit, or closes its connection when
|
|
||||||
// quit is empty. It returns the QUIT line ircpeer is sent and
|
|
||||||
// the body of the QUIT apipeer is sent.
|
|
||||||
func quitSeenByPeers(t *testing.T, quit string) (string, []string) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
|
||||||
ctx := t.Context()
|
|
||||||
|
|
||||||
ircPeer := env.dial(t)
|
|
||||||
ircPeer.register("ircpeer")
|
|
||||||
ircPeer.joinAndDrain("#bye")
|
|
||||||
|
|
||||||
apiPeerID, apiPeerClientID, _, err := env.database.CreateSession(
|
|
||||||
ctx, "apipeer", "apipeer", "", "",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create peer session: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _, err = env.database.CreateOrJoinChannel(ctx, "#bye", apiPeerID, "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("join peer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
quitter := env.dial(t)
|
|
||||||
quitter.register("quitter")
|
|
||||||
quitter.joinAndDrain("#bye")
|
|
||||||
|
|
||||||
if quit == "" {
|
|
||||||
err = quitter.conn.Close()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("close: %v", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
quitter.send(quit)
|
|
||||||
}
|
|
||||||
|
|
||||||
lines := ircPeer.readUntil(func(l string) bool {
|
|
||||||
return strings.Contains(l, " QUIT ")
|
|
||||||
})
|
|
||||||
|
|
||||||
// The QUIT is queued to both peers at once, so apipeer has
|
|
||||||
// it by now.
|
|
||||||
msgs, _, err := env.database.PollMessages(ctx, apiPeerClientID, 0, 0)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("poll peer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, msg := range msgs {
|
|
||||||
if msg.Command == irc.CmdQuit && msg.From == "quitter" {
|
|
||||||
var body []string
|
|
||||||
|
|
||||||
err = json.Unmarshal(msg.Body, &body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("decode QUIT body %s: %v", msg.Body, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines[len(lines)-1], body
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Fatalf("apipeer was not sent the QUIT: %v", msgs)
|
|
||||||
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestStopEndsSessions checks that stopping the server ends
|
// TestStopEndsSessions checks that stopping the server ends
|
||||||
// a registered connection's session before Stop returns, as
|
// a registered connection's session before Stop returns, as
|
||||||
// closing the connection does: the session, its client and
|
// closing the connection does: the session, its client and
|
||||||
@@ -1026,9 +880,12 @@ func TestStopEndsSessions(t *testing.T) {
|
|||||||
t.Fatalf("create peer session: %v", err)
|
t.Fatalf("create peer session: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
channelID, _, err := env.database.CreateOrJoinChannel(
|
channelID, err := env.database.GetChannelByName(ctx, "#shut")
|
||||||
ctx, "#shut", peerID, "",
|
if err != nil {
|
||||||
)
|
t.Fatalf("get channel: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = env.database.JoinChannel(ctx, channelID, peerID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("join peer: %v", err)
|
t.Fatalf("join peer: %v", err)
|
||||||
}
|
}
|
||||||
@@ -1076,30 +933,21 @@ func TestStopEndsSessions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TestStopReturnsWhileCleanupIsStuck checks that Stop stops
|
// TestStopReturnsWhileCleanupIsStuck checks that Stop stops
|
||||||
// waiting for a connection's cleanup after its stop timeout,
|
// waiting for a connection's cleanup after StopTimeout, so a
|
||||||
// so a cleanup that cannot finish does not hold up stopping.
|
// cleanup that cannot finish does not hold up stopping.
|
||||||
func TestStopReturnsWhileCleanupIsStuck(t *testing.T) {
|
func TestStopReturnsWhileCleanupIsStuck(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
const stopTimeout = 100 * time.Millisecond
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
env.srv.SetStopTimeout(stopTimeout)
|
|
||||||
|
|
||||||
client := env.dial(t)
|
client := env.dial(t)
|
||||||
|
|
||||||
client.register("stuck")
|
client.register("stuck")
|
||||||
|
|
||||||
// While a connection of the test's own holds a write
|
// The test database has one connection. While the test
|
||||||
// transaction, the cleanup's first write waits for it to end.
|
// holds it, the cleanup's first query waits for it.
|
||||||
holder, err := sql.Open("sqlite", env.dbURL)
|
held, err := env.database.GetDB().Conn(t.Context())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("open a second database connection: %v", err)
|
t.Fatalf("take the database connection: %v", err)
|
||||||
}
|
|
||||||
|
|
||||||
_, err = holder.ExecContext(t.Context(), "BEGIN IMMEDIATE")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("begin a write transaction: %v", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stopped := make(chan struct{})
|
stopped := make(chan struct{})
|
||||||
@@ -1111,15 +959,14 @@ func TestStopReturnsWhileCleanupIsStuck(t *testing.T) {
|
|||||||
|
|
||||||
select {
|
select {
|
||||||
case <-stopped:
|
case <-stopped:
|
||||||
case <-time.After(stopTimeout + testTimeout):
|
case <-time.After(ircserver.StopTimeout + testTimeout):
|
||||||
t.Error("Stop did not return while a cleanup was stuck")
|
t.Error("Stop did not return while a cleanup was stuck")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Closing ends the transaction, which lets the cleanup finish
|
// Lets the cleanup finish before the database is closed.
|
||||||
// before the database is closed.
|
err = held.Close()
|
||||||
err = holder.Close()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("close the second database connection: %v", err)
|
t.Errorf("release the database connection: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1163,6 +1010,9 @@ func TestDirectMessage(t *testing.T) {
|
|||||||
receiver := env.dial(t)
|
receiver := env.dial(t)
|
||||||
receiver.register("dmreceiver")
|
receiver.register("dmreceiver")
|
||||||
|
|
||||||
|
// Give relay goroutines time to start.
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
sender.send("PRIVMSG dmreceiver :hello privately")
|
sender.send("PRIVMSG dmreceiver :hello privately")
|
||||||
|
|
||||||
lines := receiver.readUntil(func(line string) bool {
|
lines := receiver.readUntil(func(line string) bool {
|
||||||
@@ -1275,9 +1125,6 @@ func TestAwaySetAndClear(t *testing.T) {
|
|||||||
assertContains(t, clearLines, " 305 ", "RPL_UNAWAY")
|
assertContains(t, clearLines, " 305 ", "RPL_UNAWAY")
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestHandlePassPostRegistration checks the NOTICE that
|
|
||||||
// confirms PASS after registration. It points to the HTTP API
|
|
||||||
// login, the only way to add a client to an existing session.
|
|
||||||
func TestHandlePassPostRegistration(t *testing.T) {
|
func TestHandlePassPostRegistration(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -1290,11 +1137,7 @@ func TestHandlePassPostRegistration(t *testing.T) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
assertContains(
|
assertContains(
|
||||||
t, lines,
|
t, lines, "Password set", "password confirmation",
|
||||||
" NOTICE passuser :Password set. Another client can log "+
|
|
||||||
"in to this session over the HTTP API: "+
|
|
||||||
"POST /api/v1/login with your nick and this password.",
|
|
||||||
"password confirmation",
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1395,11 +1238,14 @@ func TestPassPostRegistrationNotStored(t *testing.T) {
|
|||||||
|
|
||||||
client.register("failpass")
|
client.register("failpass")
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
_, err := env.database.GetDB().ExecContext(t.Context(),
|
||||||
`CREATE TRIGGER refuse_password
|
`CREATE TRIGGER refuse_password
|
||||||
BEFORE UPDATE OF password_hash ON sessions
|
BEFORE UPDATE OF password_hash ON sessions
|
||||||
BEGIN SELECT RAISE(ABORT, 'refused'); END`,
|
BEGIN SELECT RAISE(ABORT, 'refused'); END`,
|
||||||
)
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create trigger: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
client.send("PASS :mypassword123")
|
client.send("PASS :mypassword123")
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,6 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
basicauth "github.com/99designs/basicauth-go"
|
basicauth "github.com/99designs/basicauth-go"
|
||||||
@@ -18,7 +15,6 @@ import (
|
|||||||
"github.com/slok/go-http-metrics/middleware/std"
|
"github.com/slok/go-http-metrics/middleware/std"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"go4.org/netipx"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/globals"
|
"sneak.berlin/go/neoirc/internal/globals"
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
"sneak.berlin/go/neoirc/internal/logger"
|
||||||
@@ -66,77 +62,6 @@ func ipFromHostPort(hostPort string) string {
|
|||||||
return host
|
return host
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClientIP returns middleware that replaces request.RemoteAddr with the
|
|
||||||
// client's address and keeps the port of the TCP connection. The
|
|
||||||
// X-Forwarded-For and X-Real-IP headers count only when the connection
|
|
||||||
// comes from an address in TRUSTED_PROXIES.
|
|
||||||
func (mware *Middleware) ClientIP() func(http.Handler) http.Handler {
|
|
||||||
trusted := mware.params.Config.TrustedProxies
|
|
||||||
|
|
||||||
return func(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(
|
|
||||||
func(
|
|
||||||
writer http.ResponseWriter,
|
|
||||||
request *http.Request,
|
|
||||||
) {
|
|
||||||
peer, err := netip.ParseAddrPort(request.RemoteAddr)
|
|
||||||
if err == nil {
|
|
||||||
client := clientAddr(
|
|
||||||
peer.Addr().Unmap(), request.Header, trusted,
|
|
||||||
)
|
|
||||||
request.RemoteAddr = netip.AddrPortFrom(
|
|
||||||
client, peer.Port(),
|
|
||||||
).String()
|
|
||||||
}
|
|
||||||
|
|
||||||
next.ServeHTTP(writer, request)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// clientAddr returns the client's address for a request from peer. A
|
|
||||||
// peer outside trusted is the client, whatever its headers say. A
|
|
||||||
// trusted peer is a proxy. Its X-Forwarded-For list is read from the
|
|
||||||
// right, past the trusted addresses, to the first untrusted one; when
|
|
||||||
// all are trusted, the client is the leftmost. Without X-Forwarded-For,
|
|
||||||
// the client is X-Real-IP. An entry that is not an IP address gives
|
|
||||||
// peer.
|
|
||||||
func clientAddr(
|
|
||||||
peer netip.Addr, header http.Header, trusted *netipx.IPSet,
|
|
||||||
) netip.Addr {
|
|
||||||
if !trusted.Contains(peer) {
|
|
||||||
return peer
|
|
||||||
}
|
|
||||||
|
|
||||||
forwarded := strings.Join(header.Values("X-Forwarded-For"), ",")
|
|
||||||
if forwarded == "" {
|
|
||||||
realIP, err := netip.ParseAddr(
|
|
||||||
strings.TrimSpace(header.Get("X-Real-IP")),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return peer
|
|
||||||
}
|
|
||||||
|
|
||||||
return realIP.Unmap()
|
|
||||||
}
|
|
||||||
|
|
||||||
client := peer
|
|
||||||
|
|
||||||
for _, entry := range slices.Backward(strings.Split(forwarded, ",")) {
|
|
||||||
addr, err := netip.ParseAddr(strings.TrimSpace(entry))
|
|
||||||
if err != nil {
|
|
||||||
return peer
|
|
||||||
}
|
|
||||||
|
|
||||||
client = addr.Unmap()
|
|
||||||
if !trusted.Contains(client) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return client
|
|
||||||
}
|
|
||||||
|
|
||||||
type loggingResponseWriter struct {
|
type loggingResponseWriter struct {
|
||||||
http.ResponseWriter
|
http.ResponseWriter
|
||||||
|
|
||||||
@@ -200,19 +125,24 @@ func (mware *Middleware) Logging() func(http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// CORS returns middleware that lets a page on any origin read the
|
// CORS returns middleware that handles Cross-Origin Resource Sharing.
|
||||||
// response. Use it only on public, read-only routes.
|
// AllowCredentials is true so browsers include cookies in
|
||||||
|
// cross-origin API requests.
|
||||||
func (mware *Middleware) CORS() func(http.Handler) http.Handler {
|
func (mware *Middleware) CORS() func(http.Handler) http.Handler {
|
||||||
return cors.Handler(cors.Options{ //nolint:exhaustruct // optional fields
|
return cors.Handler(cors.Options{ //nolint:exhaustruct // optional fields
|
||||||
AllowedOrigins: []string{"*"},
|
AllowOriginFunc: func(
|
||||||
|
_ *http.Request, _ string,
|
||||||
|
) bool {
|
||||||
|
return true
|
||||||
|
},
|
||||||
AllowedMethods: []string{
|
AllowedMethods: []string{
|
||||||
"GET", "POST", "PUT", "DELETE", "OPTIONS",
|
"GET", "POST", "PUT", "DELETE", "OPTIONS",
|
||||||
},
|
},
|
||||||
AllowedHeaders: []string{
|
AllowedHeaders: []string{
|
||||||
"Accept", "Authorization", "Content-Type", "X-CSRF-Token",
|
"Accept", "Content-Type", "X-CSRF-Token",
|
||||||
},
|
},
|
||||||
ExposedHeaders: []string{"Link"},
|
ExposedHeaders: []string{"Link"},
|
||||||
AllowCredentials: false,
|
AllowCredentials: true,
|
||||||
MaxAge: corsMaxAge,
|
MaxAge: corsMaxAge,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,189 +0,0 @@
|
|||||||
package middleware_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"net/netip"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"go4.org/netipx"
|
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
|
||||||
"sneak.berlin/go/neoirc/internal/globals"
|
|
||||||
"sneak.berlin/go/neoirc/internal/logger"
|
|
||||||
"sneak.berlin/go/neoirc/internal/middleware"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The tests trust 10.0.0.0/8. Clients use the documentation ranges
|
|
||||||
// 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24.
|
|
||||||
const (
|
|
||||||
trustedNetwork = "10.0.0.0/8"
|
|
||||||
proxyPeer = "10.0.0.1:4000"
|
|
||||||
directPeer = "192.0.2.1:4000"
|
|
||||||
client = "203.0.113.7"
|
|
||||||
clientWithPort = "203.0.113.7:4000"
|
|
||||||
realIPClient = "203.0.113.8"
|
|
||||||
)
|
|
||||||
|
|
||||||
type clientIPTest struct {
|
|
||||||
name string
|
|
||||||
remoteAddr string
|
|
||||||
forwarded []string
|
|
||||||
realIP string
|
|
||||||
want string
|
|
||||||
}
|
|
||||||
|
|
||||||
func clientIPTests() []clientIPTest {
|
|
||||||
return []clientIPTest{
|
|
||||||
{
|
|
||||||
name: "untrusted peer ignores forged headers",
|
|
||||||
remoteAddr: directPeer,
|
|
||||||
forwarded: []string{client},
|
|
||||||
realIP: realIPClient,
|
|
||||||
want: directPeer,
|
|
||||||
},
|
|
||||||
{name: "trusted peer without headers", remoteAddr: proxyPeer, want: proxyPeer},
|
|
||||||
{
|
|
||||||
name: "trusted peer gives rightmost untrusted entry",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"198.51.100.9, 203.0.113.7, 10.0.0.2"},
|
|
||||||
want: clientWithPort,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "entries split over several headers",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"198.51.100.9", client, "10.0.0.2"},
|
|
||||||
want: clientWithPort,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "all-trusted chain gives leftmost entry",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"10.0.0.3, 10.0.0.2"},
|
|
||||||
want: "10.0.0.3:4000",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "X-Real-IP without X-Forwarded-For",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
realIP: realIPClient,
|
|
||||||
want: "203.0.113.8:4000",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "X-Forwarded-For wins over X-Real-IP",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{client},
|
|
||||||
realIP: realIPClient,
|
|
||||||
want: clientWithPort,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unparseable X-Forwarded-For entry gives peer",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"203.0.113.7, not-an-ip, 10.0.0.2"},
|
|
||||||
want: proxyPeer,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unparseable entry past the client is not read",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"not-an-ip, 203.0.113.7"},
|
|
||||||
want: clientWithPort,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unparseable X-Real-IP gives peer",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
realIP: "not-an-ip",
|
|
||||||
want: proxyPeer,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "mapped IPv6 peer is unmapped and trusted",
|
|
||||||
remoteAddr: "[::ffff:10.0.0.1]:4000",
|
|
||||||
forwarded: []string{client},
|
|
||||||
want: clientWithPort,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "mapped IPv6 peer outside the set",
|
|
||||||
remoteAddr: "[::ffff:192.0.2.1]:4000",
|
|
||||||
forwarded: []string{client},
|
|
||||||
want: directPeer,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "IPv6 client",
|
|
||||||
remoteAddr: proxyPeer,
|
|
||||||
forwarded: []string{"2001:db8::1"},
|
|
||||||
want: "[2001:db8::1]:4000",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClientIP(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mware := newMiddleware(t, trustedNetwork)
|
|
||||||
|
|
||||||
for _, test := range clientIPTests() {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var got string
|
|
||||||
|
|
||||||
handler := mware.ClientIP()(http.HandlerFunc(func(
|
|
||||||
_ http.ResponseWriter, request *http.Request,
|
|
||||||
) {
|
|
||||||
got = request.RemoteAddr
|
|
||||||
}))
|
|
||||||
|
|
||||||
request := httptest.NewRequestWithContext(
|
|
||||||
t.Context(), http.MethodGet, "/", nil,
|
|
||||||
)
|
|
||||||
request.RemoteAddr = test.remoteAddr
|
|
||||||
|
|
||||||
for _, value := range test.forwarded {
|
|
||||||
request.Header.Add("X-Forwarded-For", value)
|
|
||||||
}
|
|
||||||
|
|
||||||
if test.realIP != "" {
|
|
||||||
request.Header.Set("X-Real-IP", test.realIP)
|
|
||||||
}
|
|
||||||
|
|
||||||
handler.ServeHTTP(httptest.NewRecorder(), request)
|
|
||||||
|
|
||||||
if got != test.want {
|
|
||||||
t.Errorf("RemoteAddr = %q, want %q", got, test.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// newMiddleware returns a Middleware that trusts the network trusted.
|
|
||||||
func newMiddleware(t *testing.T, trusted string) *middleware.Middleware {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var builder netipx.IPSetBuilder
|
|
||||||
|
|
||||||
builder.AddPrefix(netip.MustParsePrefix(trusted))
|
|
||||||
|
|
||||||
trustedSet, err := builder.IPSet()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
globs := &globals.Globals{
|
|
||||||
Appname: "neoirc-test",
|
|
||||||
Version: "test",
|
|
||||||
StartTime: time.Now(),
|
|
||||||
}
|
|
||||||
|
|
||||||
log, err := logger.New(nil, logger.Params{Globals: globs})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
mware, err := middleware.New(nil, middleware.Params{
|
|
||||||
Logger: log,
|
|
||||||
Globals: globs,
|
|
||||||
Config: &config.Config{TrustedProxies: trustedSet},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return mware
|
|
||||||
}
|
|
||||||
@@ -23,13 +23,13 @@ func (srv *Server) SetupRoutes() {
|
|||||||
|
|
||||||
srv.router.Use(middleware.Recoverer)
|
srv.router.Use(middleware.Recoverer)
|
||||||
srv.router.Use(middleware.RequestID)
|
srv.router.Use(middleware.RequestID)
|
||||||
srv.router.Use(srv.mw.ClientIP())
|
|
||||||
srv.router.Use(srv.mw.Logging())
|
srv.router.Use(srv.mw.Logging())
|
||||||
|
|
||||||
if viper.GetString("METRICS_USERNAME") != "" {
|
if viper.GetString("METRICS_USERNAME") != "" {
|
||||||
srv.router.Use(srv.mw.Metrics())
|
srv.router.Use(srv.mw.Metrics())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
srv.router.Use(srv.mw.CORS())
|
||||||
srv.router.Use(srv.mw.CSP())
|
srv.router.Use(srv.mw.CSP())
|
||||||
srv.router.Use(middleware.Timeout(routeTimeout))
|
srv.router.Use(middleware.Timeout(routeTimeout))
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ func (srv *Server) SetupRoutes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Health check.
|
// Health check.
|
||||||
srv.router.With(srv.mw.CORS()).Get(
|
srv.router.Get(
|
||||||
"/.well-known/healthcheck.json",
|
"/.well-known/healthcheck.json",
|
||||||
srv.handlers.HandleHealthCheck(),
|
srv.handlers.HandleHealthCheck(),
|
||||||
)
|
)
|
||||||
@@ -68,7 +68,7 @@ func (srv *Server) SetupRoutes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (srv *Server) setupAPIv1(router chi.Router) {
|
func (srv *Server) setupAPIv1(router chi.Router) {
|
||||||
router.With(srv.mw.CORS()).Get(
|
router.Get(
|
||||||
"/server",
|
"/server",
|
||||||
srv.handlers.HandleServerInfo(),
|
srv.handlers.HandleServerInfo(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,10 +6,8 @@ package server_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"maps"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -190,88 +188,6 @@ func TestServeAfterStopDoesNotStopApp(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestCORSHeaders checks the Access-Control-Allow-* headers on the
|
|
||||||
// answers to requests from another origin. The public, read-only
|
|
||||||
// routes answer with Access-Control-Allow-Origin: * alone. Routes
|
|
||||||
// that need the cookie, and a preflight to one, answer with none.
|
|
||||||
func TestCORSHeaders(t *testing.T) {
|
|
||||||
var srv *server.Server
|
|
||||||
|
|
||||||
startApp(t, fx.Populate(&srv))
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
method string
|
|
||||||
path string
|
|
||||||
requestMethod string
|
|
||||||
wantHeaders map[string]string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "server information",
|
|
||||||
method: http.MethodGet,
|
|
||||||
path: "/api/v1/server",
|
|
||||||
wantHeaders: map[string]string{"Access-Control-Allow-Origin": "*"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "health check",
|
|
||||||
method: http.MethodGet,
|
|
||||||
path: "/.well-known/healthcheck.json",
|
|
||||||
wantHeaders: map[string]string{"Access-Control-Allow-Origin": "*"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "send",
|
|
||||||
method: http.MethodPost,
|
|
||||||
path: "/api/v1/messages",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "state",
|
|
||||||
method: http.MethodGet,
|
|
||||||
path: "/api/v1/state",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "preflight for send",
|
|
||||||
method: http.MethodOptions,
|
|
||||||
path: "/api/v1/messages",
|
|
||||||
requestMethod: http.MethodPost,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
request := httptest.NewRequestWithContext(
|
|
||||||
t.Context(), test.method,
|
|
||||||
"http://chat.example.com"+test.path, nil,
|
|
||||||
)
|
|
||||||
request.Header.Set("Origin", "http://blog.example.com")
|
|
||||||
|
|
||||||
if test.requestMethod != "" {
|
|
||||||
request.Header.Set(
|
|
||||||
"Access-Control-Request-Method", test.requestMethod,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
recorder := httptest.NewRecorder()
|
|
||||||
|
|
||||||
srv.ServeHTTP(recorder, request)
|
|
||||||
|
|
||||||
gotHeaders := map[string]string{}
|
|
||||||
|
|
||||||
for name := range recorder.Header() {
|
|
||||||
if strings.HasPrefix(name, "Access-Control-Allow-") {
|
|
||||||
gotHeaders[name] = recorder.Header().Get(name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !maps.Equal(gotHeaders, test.wantHeaders) {
|
|
||||||
t.Errorf(
|
|
||||||
"Access-Control-Allow-* headers are %v, want %v",
|
|
||||||
gotHeaders, test.wantHeaders,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// startApp starts the app newApp builds, with the HTTP port
|
// startApp starts the app newApp builds, with the HTTP port
|
||||||
// set to 0, so the system gives the server a free port.
|
// set to 0, so the system gives the server a free port.
|
||||||
func startApp(
|
func startApp(
|
||||||
|
|||||||
@@ -1169,12 +1169,6 @@ func (s *Service) ApplyUserMode(
|
|||||||
return s.QueryUserMode(ctx, sessionID)
|
return s.QueryUserMode(ctx, sessionID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserModes lists the user modes the server supports, as
|
|
||||||
// RPL_MYINFO sends them: o (server operator) and w
|
|
||||||
// (receives WALLOPS). parseUserModeString must accept the
|
|
||||||
// same letters.
|
|
||||||
const UserModes = "ow"
|
|
||||||
|
|
||||||
// parseUserModeString parses a user mode string such as
|
// parseUserModeString parses a user mode string such as
|
||||||
// "+w", "-o" or "+w-o" into the new value of each flag it
|
// "+w", "-o" or "+w-o" into the new value of each flag it
|
||||||
// names, or nil for a flag it does not name; a later letter
|
// names, or nil for a flag it does not name; a later letter
|
||||||
|
|||||||
+105
-134
@@ -1,3 +1,7 @@
|
|||||||
|
// Tests use a global viper instance for configuration,
|
||||||
|
// making parallel execution unsafe.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest
|
||||||
package service_test
|
package service_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,6 +9,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -13,6 +18,7 @@ import (
|
|||||||
|
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"go.uber.org/fx/fxtest"
|
"go.uber.org/fx/fxtest"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
"sneak.berlin/go/neoirc/internal/broker"
|
"sneak.berlin/go/neoirc/internal/broker"
|
||||||
"sneak.berlin/go/neoirc/internal/config"
|
"sneak.berlin/go/neoirc/internal/config"
|
||||||
"sneak.berlin/go/neoirc/internal/db"
|
"sneak.berlin/go/neoirc/internal/db"
|
||||||
@@ -24,10 +30,14 @@ import (
|
|||||||
"sneak.berlin/go/neoirc/pkg/irc"
|
"sneak.berlin/go/neoirc/pkg/irc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
db.SetBcryptCost(bcrypt.MinCost)
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
|
|
||||||
// testEnv holds all dependencies for a service test.
|
// testEnv holds all dependencies for a service test.
|
||||||
type testEnv struct {
|
type testEnv struct {
|
||||||
svc *service.Service
|
svc *service.Service
|
||||||
dbURL string
|
|
||||||
db *db.Database
|
db *db.Database
|
||||||
broker *broker.Broker
|
broker *broker.Broker
|
||||||
app *fxtest.App
|
app *fxtest.App
|
||||||
@@ -55,12 +65,28 @@ func newTestEnv(t *testing.T) *testEnv {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
logger.New,
|
logger.New,
|
||||||
func() *config.Config {
|
func(
|
||||||
return &config.Config{
|
lifecycle fx.Lifecycle,
|
||||||
DBURL: dbURL,
|
globs *globals.Globals,
|
||||||
OperName: "admin",
|
log *logger.Logger,
|
||||||
OperPassword: "secret",
|
) (*config.Config, error) {
|
||||||
|
cfg, err := config.New(
|
||||||
|
lifecycle, config.Params{ //nolint:exhaustruct
|
||||||
|
Globals: globs, Logger: log,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"test config: %w", err,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg.DBURL = dbURL
|
||||||
|
cfg.Port = 0
|
||||||
|
cfg.OperName = "admin"
|
||||||
|
cfg.OperPassword = "secret"
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
},
|
},
|
||||||
func(
|
func(
|
||||||
lifecycle fx.Lifecycle,
|
lifecycle fx.Lifecycle,
|
||||||
@@ -85,7 +111,6 @@ func newTestEnv(t *testing.T) *testEnv {
|
|||||||
|
|
||||||
return &testEnv{
|
return &testEnv{
|
||||||
svc: svc,
|
svc: svc,
|
||||||
dbURL: dbURL,
|
|
||||||
db: database,
|
db: database,
|
||||||
broker: brk,
|
broker: brk,
|
||||||
app: app,
|
app: app,
|
||||||
@@ -116,8 +141,6 @@ func createSession(
|
|||||||
// environment starts on an empty database while another one
|
// environment starts on an empty database while another one
|
||||||
// is still open.
|
// is still open.
|
||||||
func TestEachTestEnvHasItsOwnDatabase(t *testing.T) {
|
func TestEachTestEnvHasItsOwnDatabase(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
first := newTestEnv(t)
|
first := newTestEnv(t)
|
||||||
@@ -128,8 +151,6 @@ func TestEachTestEnvHasItsOwnDatabase(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestFanOut(t *testing.T) {
|
func TestFanOut(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -157,8 +178,6 @@ func TestFanOut(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestJoinChannel(t *testing.T) {
|
func TestJoinChannel(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -199,8 +218,6 @@ func TestJoinChannel(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPartChannel(t *testing.T) {
|
func TestPartChannel(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -301,8 +318,6 @@ func joinConcurrently(
|
|||||||
// concurrent JOINs of a +l 2 channel with one member, one
|
// concurrent JOINs of a +l 2 channel with one member, one
|
||||||
// gets in and the other gets ERR_CHANNELISFULL.
|
// gets in and the other gets ERR_CHANNELISFULL.
|
||||||
func TestConcurrentJoinsRespectUserLimit(t *testing.T) {
|
func TestConcurrentJoinsRespectUserLimit(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const userLimit = 2
|
const userLimit = 2
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
@@ -365,8 +380,6 @@ func TestConcurrentJoinsRespectUserLimit(t *testing.T) {
|
|||||||
// two concurrent JOINs that create a channel, exactly one
|
// two concurrent JOINs that create a channel, exactly one
|
||||||
// makes its session the operator.
|
// makes its session the operator.
|
||||||
func TestConcurrentFirstJoinsMakeOneOperator(t *testing.T) {
|
func TestConcurrentFirstJoinsMakeOneOperator(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -418,8 +431,6 @@ func TestConcurrentFirstJoinsMakeOneOperator(t *testing.T) {
|
|||||||
// either joins a channel that still exists or gets
|
// either joins a channel that still exists or gets
|
||||||
// ERR_NOSUCHCHANNEL, and never fails otherwise.
|
// ERR_NOSUCHCHANNEL, and never fails otherwise.
|
||||||
func TestJoinConcurrentWithLastPart(t *testing.T) {
|
func TestJoinConcurrentWithLastPart(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -485,8 +496,6 @@ func TestJoinConcurrentWithLastPart(t *testing.T) {
|
|||||||
// quits, gets in only once the channel is deleted, into a
|
// quits, gets in only once the channel is deleted, into a
|
||||||
// new channel of that name with no key.
|
// new channel of that name with no key.
|
||||||
func TestJoinConcurrentWithLastQuit(t *testing.T) {
|
func TestJoinConcurrentWithLastQuit(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -565,95 +574,81 @@ const quitCrowdSize = 10
|
|||||||
// ahead of that JOIN. The quitting session is also on a
|
// ahead of that JOIN. The quitting session is also on a
|
||||||
// channel with quitCrowdSize other sessions, made before the
|
// channel with quitCrowdSize other sessions, made before the
|
||||||
// watcher's channel, so that its QUIT reaches the watcher
|
// watcher's channel, so that its QUIT reaches the watcher
|
||||||
// last. Each trial runs on a database of its own.
|
// last.
|
||||||
func TestQuitQueuedAheadOfNewNickHoldersJoin(t *testing.T) {
|
func TestQuitQueuedAheadOfNewNickHoldersJoin(t *testing.T) {
|
||||||
t.Parallel()
|
env := newTestEnv(t)
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
for trial := range concurrentJoinTrials {
|
for trial := range concurrentJoinTrials {
|
||||||
t.Run(fmt.Sprintf("trial %d", trial), func(t *testing.T) {
|
nick := fmt.Sprintf("reused%d", trial)
|
||||||
t.Parallel()
|
crowd := fmt.Sprintf("#crowd%d", trial)
|
||||||
|
shared := fmt.Sprintf("#shared%d", trial)
|
||||||
|
quitterSID := createSession(ctx, t, env.db, nick)
|
||||||
|
|
||||||
checkQuitQueuedAheadOfJoin(t, newTestEnv(t))
|
for _, channel := range []string{crowd, shared} {
|
||||||
})
|
_, err := env.svc.JoinChannel(ctx, quitterSID, 0, nick, channel, "")
|
||||||
}
|
if err != nil {
|
||||||
}
|
t.Fatalf("join %s: %v", channel, err)
|
||||||
|
}
|
||||||
// checkQuitQueuedAheadOfJoin runs one trial of
|
|
||||||
// TestQuitQueuedAheadOfNewNickHoldersJoin on env.
|
|
||||||
func checkQuitQueuedAheadOfJoin(t *testing.T, env *testEnv) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
const (
|
|
||||||
nick = "reused"
|
|
||||||
crowd = "#crowd"
|
|
||||||
shared = "#shared"
|
|
||||||
watcherNick = "watcher"
|
|
||||||
)
|
|
||||||
|
|
||||||
ctx := t.Context()
|
|
||||||
quitterSID := createSession(ctx, t, env.db, nick)
|
|
||||||
|
|
||||||
for _, channel := range []string{crowd, shared} {
|
|
||||||
_, err := env.svc.JoinChannel(ctx, quitterSID, 0, nick, channel, "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("join %s: %v", channel, err)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
for member := range quitCrowdSize {
|
for member := range quitCrowdSize {
|
||||||
memberNick := fmt.Sprintf("crowd%d", member)
|
memberNick := fmt.Sprintf("crowd%dx%d", trial, member)
|
||||||
memberSID := createSession(ctx, t, env.db, memberNick)
|
memberSID := createSession(ctx, t, env.db, memberNick)
|
||||||
|
|
||||||
_, err := env.svc.JoinChannel(ctx, memberSID, 0, memberNick, crowd, "")
|
_, err := env.svc.JoinChannel(ctx, memberSID, 0, memberNick, crowd, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("join %s: %v", memberNick, err)
|
t.Fatalf("join %s: %v", memberNick, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
watcherSID, watcherClientID, _, err := env.db.CreateSession(
|
watcherNick := fmt.Sprintf("watcher%d", trial)
|
||||||
ctx, watcherNick, watcherNick, "localhost", "127.0.0.1",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create session %s: %v", watcherNick, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = env.svc.JoinChannel(ctx, watcherSID, 0, watcherNick, shared, "")
|
watcherSID, watcherClientID, _, err := env.db.CreateSession(
|
||||||
if err != nil {
|
ctx, watcherNick, watcherNick, "localhost", "127.0.0.1",
|
||||||
t.Fatalf("join %s: %v", watcherNick, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, lastQueueID, err := env.db.PollMessages(ctx, watcherClientID, 0, 0)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("poll: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
errs := runConcurrently(
|
|
||||||
func() error {
|
|
||||||
env.svc.BroadcastQuit(ctx, quitterSID, nick, "")
|
|
||||||
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
func() error {
|
|
||||||
return takeNickAndJoin(ctx, env, nick, shared)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if errs[1] != nil {
|
|
||||||
t.Fatalf("new session: %v", errs[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
msgs, _, err := env.db.PollMessages(
|
|
||||||
ctx, watcherClientID, lastQueueID, 0,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("poll: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
commands := commandsFrom(msgs, nick)
|
|
||||||
if !slices.Equal(commands, []string{irc.CmdQuit, irc.CmdJoin}) {
|
|
||||||
t.Errorf(
|
|
||||||
"watcher got %v from %s, want QUIT then JOIN",
|
|
||||||
commands, nick,
|
|
||||||
)
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create session %s: %v", watcherNick, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = env.svc.JoinChannel(ctx, watcherSID, 0, watcherNick, shared, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("join %s: %v", watcherNick, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, lastQueueID, err := env.db.PollMessages(ctx, watcherClientID, 0, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("poll: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
errs := runConcurrently(
|
||||||
|
func() error {
|
||||||
|
env.svc.BroadcastQuit(ctx, quitterSID, nick, "")
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
func() error {
|
||||||
|
return takeNickAndJoin(ctx, env, nick, shared)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if errs[1] != nil {
|
||||||
|
t.Fatalf("trial %d: new session: %v", trial, errs[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs, _, err := env.db.PollMessages(
|
||||||
|
ctx, watcherClientID, lastQueueID, 0,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("poll: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
commands := commandsFrom(msgs, nick)
|
||||||
|
if !slices.Equal(commands, []string{irc.CmdQuit, irc.CmdJoin}) {
|
||||||
|
t.Errorf(
|
||||||
|
"trial %d: watcher got %v from %s, want QUIT then JOIN",
|
||||||
|
trial, commands, nick,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -701,8 +696,6 @@ func commandsFrom(msgs []db.IRCMessage, nick string) []string {
|
|||||||
// into a +i channel uses the invite up, so that a JOIN
|
// into a +i channel uses the invite up, so that a JOIN
|
||||||
// after leaving gets ERR_INVITEONLYCHAN.
|
// after leaving gets ERR_INVITEONLYCHAN.
|
||||||
func TestJoinUsesUpInvite(t *testing.T) {
|
func TestJoinUsesUpInvite(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const channel = "#club"
|
const channel = "#club"
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
@@ -748,8 +741,6 @@ func TestJoinUsesUpInvite(t *testing.T) {
|
|||||||
// session's nick, username and hostname refuses its JOIN
|
// session's nick, username and hostname refuses its JOIN
|
||||||
// with ERR_BANNEDFROMCHAN.
|
// with ERR_BANNEDFROMCHAN.
|
||||||
func TestJoinRefusedByHostmaskBan(t *testing.T) {
|
func TestJoinRefusedByHostmaskBan(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const channel = "#club"
|
const channel = "#club"
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
@@ -788,8 +779,6 @@ func TestJoinRefusedByHostmaskBan(t *testing.T) {
|
|||||||
// keeps a channel other members are still on and deletes
|
// keeps a channel other members are still on and deletes
|
||||||
// the channel when its last member parts.
|
// the channel when its last member parts.
|
||||||
func TestPartDeletesChannelOnlyWhenEmpty(t *testing.T) {
|
func TestPartDeletesChannelOnlyWhenEmpty(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const channel = "#room"
|
const channel = "#room"
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
@@ -837,8 +826,6 @@ func TestPartDeletesChannelOnlyWhenEmpty(t *testing.T) {
|
|||||||
// TestKickOfLastMemberDeletesChannel checks that a KICK
|
// TestKickOfLastMemberDeletesChannel checks that a KICK
|
||||||
// that leaves a channel with no members deletes it.
|
// that leaves a channel with no members deletes it.
|
||||||
func TestKickOfLastMemberDeletesChannel(t *testing.T) {
|
func TestKickOfLastMemberDeletesChannel(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const channel = "#room"
|
const channel = "#room"
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
@@ -863,8 +850,6 @@ func TestKickOfLastMemberDeletesChannel(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSendChannelMessage(t *testing.T) {
|
func TestSendChannelMessage(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -912,8 +897,6 @@ func TestSendChannelMessage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestBroadcastQuit(t *testing.T) {
|
func TestBroadcastQuit(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -951,24 +934,25 @@ func TestBroadcastQuit(t *testing.T) {
|
|||||||
// error as a DM to an unknown nick. The trigger deletes the
|
// error as a DM to an unknown nick. The trigger deletes the
|
||||||
// target's session just before the DM is stored.
|
// target's session just before the DM is stored.
|
||||||
func TestSendDirectMessageTargetQuits(t *testing.T) {
|
func TestSendDirectMessageTargetQuits(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
sid := createSession(ctx, t, env.db, "alice")
|
sid := createSession(ctx, t, env.db, "alice")
|
||||||
createSession(ctx, t, env.db, "bob")
|
createSession(ctx, t, env.db, "bob")
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
_, err := env.db.GetDB().ExecContext(ctx,
|
||||||
`CREATE TRIGGER delete_recipient
|
`CREATE TRIGGER delete_recipient
|
||||||
BEFORE INSERT ON messages
|
BEFORE INSERT ON messages
|
||||||
BEGIN
|
BEGIN
|
||||||
DELETE FROM sessions WHERE id = NEW.to_session_id;
|
DELETE FROM sessions WHERE id = NEW.to_session_id;
|
||||||
END`)
|
END`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create trigger: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
body, _ := json.Marshal([]string{"hi"}) //nolint:errchkjson
|
body, _ := json.Marshal([]string{"hi"}) //nolint:errchkjson
|
||||||
|
|
||||||
_, err := env.svc.SendDirectMessage(
|
_, err = env.svc.SendDirectMessage(
|
||||||
ctx, sid, 0, "alice", irc.CmdPrivmsg, "bob", body, nil,
|
ctx, sid, 0, "alice", irc.CmdPrivmsg, "bob", body, nil,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -984,8 +968,6 @@ func TestSendDirectMessageTargetQuits(t *testing.T) {
|
|||||||
// trigger deletes the channel just before the message is
|
// trigger deletes the channel just before the message is
|
||||||
// stored.
|
// stored.
|
||||||
func TestSendChannelMessageChannelDeleted(t *testing.T) {
|
func TestSendChannelMessageChannelDeleted(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -996,12 +978,15 @@ func TestSendChannelMessageChannelDeleted(t *testing.T) {
|
|||||||
t.Fatalf("join alice: %v", err)
|
t.Fatalf("join alice: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
dbtest.Exec(t, env.dbURL,
|
_, err = env.db.GetDB().ExecContext(ctx,
|
||||||
`CREATE TRIGGER delete_recipient
|
`CREATE TRIGGER delete_recipient
|
||||||
BEFORE INSERT ON messages
|
BEFORE INSERT ON messages
|
||||||
BEGIN
|
BEGIN
|
||||||
DELETE FROM channels WHERE id = NEW.to_channel_id;
|
DELETE FROM channels WHERE id = NEW.to_channel_id;
|
||||||
END`)
|
END`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create trigger: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
body, _ := json.Marshal([]string{"hi"}) //nolint:errchkjson
|
body, _ := json.Marshal([]string{"hi"}) //nolint:errchkjson
|
||||||
|
|
||||||
@@ -1017,8 +1002,6 @@ func TestSendChannelMessageChannelDeleted(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSendChannelMessage_Moderated(t *testing.T) {
|
func TestSendChannelMessage_Moderated(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -1070,8 +1053,6 @@ func TestSendChannelMessage_Moderated(t *testing.T) {
|
|||||||
// not spend its hashcash stamp: the operator can then send
|
// not spend its hashcash stamp: the operator can then send
|
||||||
// the same message with it.
|
// the same message with it.
|
||||||
func TestRefusedChannelMessageLeavesStampUnspent(t *testing.T) {
|
func TestRefusedChannelMessageLeavesStampUnspent(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
channel = "#paid"
|
channel = "#paid"
|
||||||
bits = 2
|
bits = 2
|
||||||
@@ -1097,8 +1078,6 @@ func TestRefusedChannelMessageLeavesStampUnspent(t *testing.T) {
|
|||||||
|
|
||||||
for _, refusal := range refusals {
|
for _, refusal := range refusals {
|
||||||
t.Run(refusal.name, func(t *testing.T) {
|
t.Run(refusal.name, func(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -1151,8 +1130,6 @@ func TestRefusedChannelMessageLeavesStampUnspent(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestQueryUserMode(t *testing.T) {
|
func TestQueryUserMode(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -1203,8 +1180,6 @@ func TestQueryUserMode(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUserhostReply(t *testing.T) {
|
func TestUserhostReply(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
|
|
||||||
@@ -1310,14 +1285,10 @@ func applyUserModeTests() []applyUserModeTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyUserMode(t *testing.T) {
|
func TestApplyUserMode(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newTestEnv(t)
|
env := newTestEnv(t)
|
||||||
|
|
||||||
for i, test := range applyUserModeTests() {
|
for i, test := range applyUserModeTests() {
|
||||||
t.Run(test.modeStr, func(t *testing.T) {
|
t.Run(test.modeStr, func(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
sid := createSession(
|
sid := createSession(
|
||||||
ctx, t, env.db, fmt.Sprintf("user%d", i),
|
ctx, t, env.db, fmt.Sprintf("user%d", i),
|
||||||
|
|||||||
+82
-17
@@ -20,7 +20,7 @@ are the fields it can have:
|
|||||||
- `code`: the number of a numeric reply, such as `1` for `RPL_WELCOME`. Absent
|
- `code`: the number of a numeric reply, such as `1` for `RPL_WELCOME`. Absent
|
||||||
on other messages.
|
on other messages.
|
||||||
- `id`: the message's UUID, a unique ID that the server assigns.
|
- `id`: the message's UUID, a unique ID that the server assigns.
|
||||||
- `from`: the sender's nick, or the server name on a numeric reply or a `PONG`.
|
- `from`: the sender's nick, or the server name on a server message.
|
||||||
- `to`: the target, such as a channel name starting with `#` or a nick.
|
- `to`: the target, such as a channel name starting with `#` or a nick.
|
||||||
- `params`: an array of strings with the message's other parameters, in order.
|
- `params`: an array of strings with the message's other parameters, in order.
|
||||||
`KICK` events and many numeric replies have it. The HTTP API ignores `params`
|
`KICK` events and many numeric replies have it. The HTTP API ignores `params`
|
||||||
@@ -60,32 +60,29 @@ A `PRIVMSG` whose `body` has two strings is a two-line message:
|
|||||||
|
|
||||||
## Files
|
## Files
|
||||||
|
|
||||||
Most command files describe both the message a client sends and the message the
|
|
||||||
server sends. Their field descriptions say where the two differ. The examples in
|
|
||||||
the files leave out `id`, `ts` and `meta`.
|
|
||||||
|
|
||||||
Commands, in `commands/`:
|
Commands, in `commands/`:
|
||||||
|
|
||||||
- `PRIVMSG.json`: a message to a channel or a user.
|
- `PRIVMSG.json`: a message to a channel or a user.
|
||||||
- `NOTICE.json`: a notice, which is a message that a client must not answer
|
- `NOTICE.json`: a notice, which is a message that a client must not answer
|
||||||
automatically.
|
automatically.
|
||||||
- `JOIN.json`: joining a channel.
|
- `JOIN.json`: a user joined a channel.
|
||||||
- `PART.json`: leaving a channel.
|
- `PART.json`: a user left a channel.
|
||||||
- `QUIT.json`: leaving the server.
|
- `QUIT.json`: a user left the server.
|
||||||
- `NICK.json`: changing nick.
|
- `NICK.json`: a user changed nick.
|
||||||
- `TOPIC.json`: setting a channel's topic.
|
- `TOPIC.json`: a channel topic was set.
|
||||||
- `MODE.json`: querying or changing a channel's modes or the user's own modes.
|
- `MODE.json`: a channel mode was changed.
|
||||||
- `KICK.json`: a channel operator removing a user from a channel.
|
- `KICK.json`: a channel operator removed a user from a channel.
|
||||||
- `PING.json`: a check that the server still answers.
|
- `PING.json`: a check that the server still answers.
|
||||||
- `PONG.json`: the answer to a `PING`, which is the HTTP response to it.
|
- `PONG.json`: the answer to a `PING`.
|
||||||
|
- `PUBKEY.json`: an announcement of a user's public signing key. The server has
|
||||||
|
no such command. It answers a `PUBKEY` with `ERR_UNKNOWNCOMMAND` (`421`).
|
||||||
|
|
||||||
Numeric replies, in `numerics/`:
|
Numeric replies, in `numerics/`:
|
||||||
|
|
||||||
- `001.json`: `RPL_WELCOME`, which welcomes the user.
|
- `001.json`: `RPL_WELCOME`, which welcomes a new user.
|
||||||
- `002.json`: `RPL_YOURHOST`, the server's name and version.
|
- `002.json`: `RPL_YOURHOST`, the server's name and version.
|
||||||
- `003.json`: `RPL_CREATED`, the date the server last started.
|
- `003.json`: `RPL_CREATED`, which says when the server was created.
|
||||||
- `004.json`: `RPL_MYINFO`, the server's name, its version and its lists of
|
- `004.json`: `RPL_MYINFO`, the server's version and its lists of modes.
|
||||||
modes.
|
|
||||||
- `322.json`: `RPL_LIST`, one channel in the answer to `LIST`.
|
- `322.json`: `RPL_LIST`, one channel in the answer to `LIST`.
|
||||||
- `323.json`: `RPL_LISTEND`, the end of the answer to `LIST`.
|
- `323.json`: `RPL_LISTEND`, the end of the answer to `LIST`.
|
||||||
- `332.json`: `RPL_TOPIC`, a channel's topic.
|
- `332.json`: `RPL_TOPIC`, a channel's topic.
|
||||||
@@ -99,3 +96,71 @@ Numeric replies, in `numerics/`:
|
|||||||
- `433.json`: `ERR_NICKNAMEINUSE`, the nick is taken.
|
- `433.json`: `ERR_NICKNAMEINUSE`, the nick is taken.
|
||||||
- `442.json`: `ERR_NOTONCHANNEL`, the user is not on that channel.
|
- `442.json`: `ERR_NOTONCHANNEL`, the user is not on that channel.
|
||||||
- `482.json`: `ERR_CHANOPRIVSNEEDED`, the user is not a channel operator.
|
- `482.json`: `ERR_CHANOPRIVSNEEDED`, the user is not a channel operator.
|
||||||
|
|
||||||
|
## Where the files differ from the HTTP API
|
||||||
|
|
||||||
|
Where a schema file and the HTTP API disagree, the HTTP API is right:
|
||||||
|
|
||||||
|
- `message.json` and the files in `numerics/` put the three-digit code in
|
||||||
|
`command`. They have no `code` field. The HTTP API puts the reply's name in
|
||||||
|
`command` and its number in `code`.
|
||||||
|
- `message.json` allows an object as `body`. The HTTP API reads only arrays of
|
||||||
|
strings. A `PRIVMSG` with an object as `body` gets `ERR_NOTEXTTOSEND` (`412`).
|
||||||
|
- `message.json` says `to` is a channel or a nick. A `WALLOPS` message has `*`
|
||||||
|
there.
|
||||||
|
- `message.json` allows `meta` on every message. The HTTP API keeps a client's
|
||||||
|
`meta` only on a `PRIVMSG` or `NOTICE`.
|
||||||
|
- `message.json` describes signature fields in `meta`. The server never checks a
|
||||||
|
signature.
|
||||||
|
- `message.json` does not describe `meta.hashcash`. The HTTP API reads it in a
|
||||||
|
`PRIVMSG` to a channel with mode `+H`.
|
||||||
|
- `JOIN.json` has no `body`. A client's `JOIN` can carry the channel key in
|
||||||
|
`body`. When a user joins, the `JOIN` event repeats the channel name in
|
||||||
|
`body`.
|
||||||
|
- `JOIN.json` allows a channel name of any length. The server allows at most 63
|
||||||
|
characters after the `#`. It answers a longer name with `ERR_NOSUCHCHANNEL`
|
||||||
|
(`403`).
|
||||||
|
- `KICK.json` puts the kicked nick in `params`. The HTTP API reads a client's
|
||||||
|
`KICK` from `body`: the nick, then an optional reason.
|
||||||
|
- `MODE.json` puts the mode change in `params`. The HTTP API uses `body`
|
||||||
|
instead. A client sends the change and any value as separate strings, such as
|
||||||
|
`"+o"` and `"bob"`. In a `MODE` event, `body` holds the change as one string,
|
||||||
|
such as `"+o bob"`, or as two strings, such as `"+k"` and `"secret"`.
|
||||||
|
- `NOTICE.json` allows `*` as `to`. The server answers a `NOTICE` to `*` with
|
||||||
|
`ERR_NOSUCHNICK` (`401`).
|
||||||
|
- `NOTICE.json` has an example notice from the server to `*`. The server sends
|
||||||
|
no such notice.
|
||||||
|
- `PING.json` and `PONG.json` describe a token that the `PONG` repeats. The HTTP
|
||||||
|
API ignores the `body` of a `PING`. Its answer is the HTTP response
|
||||||
|
`{"command": "PONG", "from": "<server name>"}`.
|
||||||
|
- `PING.json` and `PONG.json` also describe messages between servers. The server
|
||||||
|
does not connect to other IRC servers.
|
||||||
|
- `PUBKEY.json` describes a command the server does not have.
|
||||||
|
- `QUIT.json` says that `QUIT` comes only from the server. A client can send it
|
||||||
|
too, to end its session. A client's `QUIT` can carry a reason in `body`.
|
||||||
|
- `TOPIC.json` says a `TOPIC` without a `body` queries the topic. The HTTP API
|
||||||
|
answers such a `TOPIC` with `ERR_NEEDMOREPARAMS` (`461`).
|
||||||
|
- `TOPIC.json` says an empty array clears the topic. The HTTP API answers `[]`
|
||||||
|
with `ERR_NEEDMOREPARAMS` (`461`). A `body` of `[""]` clears the topic.
|
||||||
|
- `003.json` describes the server's creation date. The HTTP API sends the date
|
||||||
|
the server last started.
|
||||||
|
- `004.json` has example mode lists. The HTTP API sends an empty string as the
|
||||||
|
user modes and `ikmnostl` as the channel modes.
|
||||||
|
- `322.json` says `LIST` gets one reply per channel. The server leaves out a
|
||||||
|
secret channel, one with mode `+s`, unless the user is on it.
|
||||||
|
- `332.json` says `RPL_TOPIC` answers a `TOPIC` query. The HTTP API has no such
|
||||||
|
query. It sends `RPL_TOPIC` after a client sets the topic, and after a `JOIN`
|
||||||
|
to a channel that has one.
|
||||||
|
- `353.json` says `body` lists nicks. The HTTP API lists `nick!user@host` in
|
||||||
|
place of each nick, such as `@op1!op1@host1`.
|
||||||
|
- `353.json` says the first parameter marks a channel as public, private or
|
||||||
|
secret. The server always sends `=`, the mark for a public channel.
|
||||||
|
- `376.json` gives the text as `End of /MOTD command`. The HTTP API adds a full
|
||||||
|
stop.
|
||||||
|
- `401.json` gives the text as `No such nick/channel`. The server sends
|
||||||
|
`No such nick` in answer to a `PRIVMSG` or `NOTICE` to an unknown nick.
|
||||||
|
- `433.json` has an example with `*` as `to`. The HTTP API sends `433` only in
|
||||||
|
answer to a `NICK`, with the user's nick as `to`.
|
||||||
|
|
||||||
|
The HTTP API also accepts some messages that the files do not allow, such as a
|
||||||
|
`JOIN` whose `to` has no `#`.
|
||||||
@@ -2,25 +2,15 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/JOIN.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/JOIN.json",
|
||||||
"title": "JOIN",
|
"title": "JOIN",
|
||||||
"description": "Join a channel. A client sends it to join a channel, which the server creates if it does not exist. The server sends it to every member of the channel when a user joins, the new member included. RFC 1459 §4.2.1.",
|
"description": "Join a channel. C2S: request to join. S2C: notification that a user joined. RFC 1459 §4.2.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "JOIN" },
|
"command": { "const": "JOIN" },
|
||||||
"from": { "type": "string", "description": "The nick that joined. The server sets it." },
|
"from": { "type": "string", "description": "Nick that joined (S2C)." },
|
||||||
"to": {
|
"to": { "type": "string", "description": "Channel name.", "pattern": "^#[a-zA-Z0-9_-]+$" }
|
||||||
"type": "string",
|
|
||||||
"description": "The channel name: # and then 1 to 63 of a-z, A-Z, 0-9, _ and -. The server adds the # if a client leaves it out.",
|
|
||||||
"pattern": "^#?[a-zA-Z0-9_-]{1,63}$"
|
|
||||||
},
|
|
||||||
"body": {
|
|
||||||
"type": "array",
|
|
||||||
"items": { "type": "string" },
|
|
||||||
"description": "From a client: the channel key as the first string, which a channel with mode +k needs. From the server: the channel name. After a login, and for GET /api/v1/state?initChannelState=1, the server queues a JOIN for each of the session's channels. That JOIN has an empty body."
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"required": ["command", "to"],
|
"required": ["command", "to"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "JOIN", "to": "#general" },
|
{ "command": "JOIN", "from": "alice", "to": "#general" }
|
||||||
{ "command": "JOIN", "from": "alice", "to": "#general", "body": ["#general"] }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,33 +2,28 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/KICK.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/KICK.json",
|
||||||
"title": "KICK",
|
"title": "KICK",
|
||||||
"description": "Remove a user from a channel. A client sends it, and only a channel operator may. The server sends it to every member of the channel, the removed user included. RFC 1459 §4.2.8.",
|
"description": "Kick a user from a channel. RFC 1459 §4.2.8.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "KICK" },
|
"command": { "const": "KICK" },
|
||||||
"from": { "type": "string", "description": "The nick that removed the user. The server sets it." },
|
"from": { "type": "string", "description": "Nick that performed the kick." },
|
||||||
"to": {
|
"to": { "type": "string", "description": "Channel name.", "pattern": "^#[a-zA-Z0-9_-]+$" },
|
||||||
"type": "string",
|
|
||||||
"description": "The channel name. The server adds the # if a client leaves it out.",
|
|
||||||
"pattern": "^#?[a-zA-Z0-9_-]{1,63}$"
|
|
||||||
},
|
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The removed nick. Only the server sends it.",
|
"description": "Kicked nick. e.g. [\"alice\"].",
|
||||||
"minItems": 1,
|
"minItems": 1,
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "From a client: the nick to remove, then an optional reason. From the server: the reason, as one string.",
|
"description": "Optional kick reason.",
|
||||||
"minItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "to", "body"],
|
"required": ["command", "to", "params"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "KICK", "to": "#general", "body": ["troll", "Behave"] },
|
|
||||||
{ "command": "KICK", "from": "op1", "to": "#general", "params": ["troll"], "body": ["Behave"] }
|
{ "command": "KICK", "from": "op1", "to": "#general", "params": ["troll"], "body": ["Behave"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,29 +2,28 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/MODE.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/MODE.json",
|
||||||
"title": "MODE",
|
"title": "MODE",
|
||||||
"description": "Query or change a channel's modes or the user's own modes. A client sends it. The server sends it to every member of the channel when a channel mode changes. A +H or -H sent over the HTTP API is the exception. The server answers it with RPL_CHANNELMODEIS (324) and sends no MODE. RFC 1459 §4.2.3.",
|
"description": "Set or query channel/user modes. RFC 1459 §4.2.3.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "MODE" },
|
"command": { "const": "MODE" },
|
||||||
"from": {
|
"from": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "The nick that changed the mode. The server sets it."
|
"description": "Nick that set the mode (S2C only)."
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "A channel name, which starts with #, or the user's own nick."
|
"description": "Channel name.",
|
||||||
|
"pattern": "^#[a-zA-Z0-9_-]+$"
|
||||||
},
|
},
|
||||||
"body": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "From a client: the mode change and then its value, as separate strings, such as \"+o\" and \"bob\". A MODE without a body is a query. From the server: the change and its value, as one string, such as \"+o bob\", or as separate strings, such as \"+k\" and \"secret\".",
|
"description": "Mode string and optional target nick. e.g. [\"+o\", \"alice\"].",
|
||||||
"examples": [["+o", "bob"], ["-m"], ["+o bob"], ["+k", "secret"]]
|
"examples": [["+o", "alice"], ["-m"], ["+v", "bob"]]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "to"],
|
"required": ["command", "to", "params"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "MODE", "to": "#general", "body": ["+o", "bob"] },
|
{ "command": "MODE", "from": "op1", "to": "#general", "params": ["+o", "alice"] }
|
||||||
{ "command": "MODE", "from": "op1", "to": "#general", "body": ["+o bob"] },
|
|
||||||
{ "command": "MODE", "from": "op1", "to": "#general", "body": ["+k", "secret"] }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,21 +2,21 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/NICK.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/NICK.json",
|
||||||
"title": "NICK",
|
"title": "NICK",
|
||||||
"description": "Change nick. A client sends it to change its nick. The server sends it to the user's own clients and to the users who share a channel with the user. RFC 1459 §4.1.2.",
|
"description": "Change nickname. C2S: request new nick. S2C: notification of nick change. RFC 1459 §4.1.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "NICK" },
|
"command": { "const": "NICK" },
|
||||||
"from": { "type": "string", "description": "The old nick. The server sets it." },
|
"from": { "type": "string", "description": "Old nick (S2C)." },
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The new nick, as the first string. The server sends one string.",
|
"description": "New nick (single-element array).",
|
||||||
"minItems": 1
|
"minItems": 1,
|
||||||
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "body"],
|
"required": ["command", "body"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "NICK", "body": ["newnick"] },
|
|
||||||
{ "command": "NICK", "from": "oldnick", "body": ["newnick"] }
|
{ "command": "NICK", "from": "oldnick", "body": ["newnick"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,21 +2,20 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/NOTICE.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/NOTICE.json",
|
||||||
"title": "NOTICE",
|
"title": "NOTICE",
|
||||||
"description": "A notice: a message to a channel or a user that a client must not answer automatically. The server relays it as it relays a PRIVMSG. A NOTICE to a channel with mode +H needs no hashcash stamp. RFC 1459 §4.4.2.",
|
"description": "Send a notice. Like PRIVMSG but must not trigger automatic replies. RFC 1459 §4.4.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "NOTICE" },
|
"command": { "const": "NOTICE" },
|
||||||
"from": { "type": "string", "description": "The sender's nick. The server sets it." },
|
"from": { "type": "string" },
|
||||||
"to": { "type": "string", "description": "A channel name, which starts with #, or a nick." },
|
"to": { "type": "string", "description": "Target: #channel, nick, or * (global)." },
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The lines of the notice, one string per line.",
|
"description": "Notice text lines."
|
||||||
"minItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "to", "body"],
|
"required": ["command", "to", "body"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "NOTICE", "from": "alice", "to": "#general", "body": ["Back in five minutes"] }
|
{ "command": "NOTICE", "from": "server.example.com", "to": "*", "body": ["Server restarting in 5 minutes"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,20 +2,17 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PART.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PART.json",
|
||||||
"title": "PART",
|
"title": "PART",
|
||||||
"description": "Leave a channel. A client sends it to leave. The server sends it to every member of the channel when a user leaves, the leaving user included. RFC 1459 §4.2.2.",
|
"description": "Leave a channel. C2S: request to leave. S2C: notification that a user left. RFC 1459 §4.2.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "PART" },
|
"command": { "const": "PART" },
|
||||||
"from": { "type": "string", "description": "The nick that left. The server sets it." },
|
"from": { "type": "string", "description": "Nick that left (S2C)." },
|
||||||
"to": {
|
"to": { "type": "string", "description": "Channel name.", "pattern": "^#[a-zA-Z0-9_-]+$" },
|
||||||
"type": "string",
|
|
||||||
"description": "The channel name. The server adds the # if a client leaves it out.",
|
|
||||||
"pattern": "^#?[a-zA-Z0-9_-]{1,63}$"
|
|
||||||
},
|
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The reason for leaving. A client may send one as the first string. The server always sends one string, which is empty when no reason was given."
|
"description": "Optional part reason.",
|
||||||
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "to"],
|
"required": ["command", "to"],
|
||||||
|
|||||||
@@ -2,13 +2,19 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PING.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PING.json",
|
||||||
"title": "PING",
|
"title": "PING",
|
||||||
"description": "A check that the server still answers. A client sends it. The server ignores every field but 'command'. Its answer is a PONG in the HTTP response. RFC 1459 §4.6.2.",
|
"description": "Keepalive. C2S or S2S. Server responds with PONG. RFC 1459 §4.6.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "PING" }
|
"command": { "const": "PING" },
|
||||||
|
"body": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Opaque token to be echoed in PONG (single-element array).",
|
||||||
|
"maxItems": 1
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"required": ["command"],
|
"required": ["command"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "PING" }
|
{ "command": "PING", "body": ["1707580000"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,14 +2,20 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PONG.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PONG.json",
|
||||||
"title": "PONG",
|
"title": "PONG",
|
||||||
"description": "The answer to a PING. The server sends it as the HTTP response to the PING, with only 'command' and 'from'. A client's PONG gets ERR_UNKNOWNCOMMAND (421). RFC 1459 §4.6.3.",
|
"description": "Keepalive response. S2C or S2S. RFC 1459 §4.6.3.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "PONG" },
|
"command": { "const": "PONG" },
|
||||||
"from": { "type": "string", "description": "The server name." }
|
"from": { "type": "string", "description": "Responding server name." },
|
||||||
|
"body": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Echoed token from PING (single-element array).",
|
||||||
|
"maxItems": 1
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "from"],
|
"required": ["command"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "PONG", "from": "neoirc" }
|
{ "command": "PONG", "from": "server.example.com", "body": ["1707580000"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,16 +2,16 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PRIVMSG.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PRIVMSG.json",
|
||||||
"title": "PRIVMSG",
|
"title": "PRIVMSG",
|
||||||
"description": "A message to a channel or a user. A client sends it. The server relays it to every member of the channel, or to the user, and to the sender's own clients. RFC 1459 §4.4.1.",
|
"description": "Send a message to a channel or user. C2S: client sends to server. S2C: server relays to recipients. RFC 1459 §4.4.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "PRIVMSG" },
|
"command": { "const": "PRIVMSG" },
|
||||||
"from": { "type": "string", "description": "The sender's nick. The server sets it." },
|
"from": { "type": "string", "description": "Sender nick (set by server on relay)." },
|
||||||
"to": { "type": "string", "description": "A channel name, which starts with #, or a nick.", "examples": ["#general", "alice"] },
|
"to": { "type": "string", "description": "Target: #channel or nick.", "examples": ["#general", "alice"] },
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The lines of the message, one string per line.",
|
"description": "Message lines. One string per line.",
|
||||||
"minItems": 1
|
"minItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -19,6 +19,6 @@
|
|||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "PRIVMSG", "from": "bob", "to": "#general", "body": ["hello world"] },
|
{ "command": "PRIVMSG", "from": "bob", "to": "#general", "body": ["hello world"] },
|
||||||
{ "command": "PRIVMSG", "from": "bob", "to": "#general", "body": ["line one", "line two"] },
|
{ "command": "PRIVMSG", "from": "bob", "to": "#general", "body": ["line one", "line two"] },
|
||||||
{ "command": "PRIVMSG", "from": "bob", "to": "alice", "body": ["hey"] }
|
{ "command": "PRIVMSG", "from": "bob", "to": "alice", "body": ["hey"], "meta": { "sig": "base64...", "alg": "ed25519" } }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/PUBKEY.json",
|
||||||
|
"title": "PUBKEY",
|
||||||
|
"description": "Announce or relay a user's public signing key. C2S: client announces key to channel or server. S2C: server relays to channel members. Protocol extension (not in RFC 1459). Body is a structured object (not an array) containing the key material.",
|
||||||
|
"$ref": "../message.json",
|
||||||
|
"properties": {
|
||||||
|
"command": { "const": "PUBKEY" },
|
||||||
|
"from": { "type": "string", "description": "Nick announcing the key (set by server on relay)." },
|
||||||
|
"to": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Target: #channel to announce to channel members, or omit for server-wide announcement."
|
||||||
|
},
|
||||||
|
"body": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Key material.",
|
||||||
|
"properties": {
|
||||||
|
"alg": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Key algorithm.",
|
||||||
|
"enum": ["ed25519"]
|
||||||
|
},
|
||||||
|
"key": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Base64-encoded public key."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["alg", "key"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["command", "body"],
|
||||||
|
"examples": [
|
||||||
|
{ "command": "PUBKEY", "from": "alice", "body": { "alg": "ed25519", "key": "base64-encoded-pubkey" } },
|
||||||
|
{ "command": "PUBKEY", "from": "alice", "to": "#general", "body": { "alg": "ed25519", "key": "base64-encoded-pubkey" } }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -2,20 +2,20 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/QUIT.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/QUIT.json",
|
||||||
"title": "QUIT",
|
"title": "QUIT",
|
||||||
"description": "A user left the server. A client sends it to end its session. The server sends it to the users who shared a channel with the user who left. RFC 1459 §4.1.6.",
|
"description": "User disconnected. S2C only. RFC 1459 §4.1.6.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "QUIT" },
|
"command": { "const": "QUIT" },
|
||||||
"from": { "type": "string", "description": "The nick that quit. The server sets it." },
|
"from": { "type": "string", "description": "Nick that quit." },
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The reason for leaving. A client may send one as the first string, and the server uses 'Client quit' when it does not. The server always sends one string."
|
"description": "Optional quit reason.",
|
||||||
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command"],
|
"required": ["command", "from"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "QUIT", "body": ["Gone for the day"] },
|
{ "command": "QUIT", "from": "alice", "body": ["Connection reset"] }
|
||||||
{ "command": "QUIT", "from": "alice", "body": ["Connection closed"] }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,24 +2,20 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/commands/TOPIC.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/commands/TOPIC.json",
|
||||||
"title": "TOPIC",
|
"title": "TOPIC",
|
||||||
"description": "Set a channel's topic. A client sends it to set the topic. The server sends it to every member of the channel when the topic changes. RFC 1459 §4.2.4.",
|
"description": "Get or set channel topic. C2S: set topic (body present) or query (body absent). S2C: topic change notification. RFC 1459 §4.2.4.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": { "const": "TOPIC" },
|
"command": { "const": "TOPIC" },
|
||||||
"from": { "type": "string", "description": "The nick that set the topic. The server sets it." },
|
"from": { "type": "string", "description": "Nick that changed the topic (S2C)." },
|
||||||
"to": {
|
"to": { "type": "string", "description": "Channel name.", "pattern": "^#[a-zA-Z0-9_-]+$" },
|
||||||
"type": "string",
|
|
||||||
"description": "The channel name. The server adds the # if a client leaves it out.",
|
|
||||||
"pattern": "^#?[a-zA-Z0-9_-]{1,63}$"
|
|
||||||
},
|
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The new topic. The server joins a client's strings with spaces, and sends the topic as one string. [\"\"] clears the topic.",
|
"description": "New topic text (single-element array). Empty array clears the topic.",
|
||||||
"minItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["command", "to", "body"],
|
"required": ["command", "to"],
|
||||||
"examples": [
|
"examples": [
|
||||||
{ "command": "TOPIC", "from": "alice", "to": "#general", "body": ["Welcome to the channel"] }
|
{ "command": "TOPIC", "from": "alice", "to": "#general", "body": ["Welcome to the channel"] }
|
||||||
]
|
]
|
||||||
|
|||||||
+32
-20
@@ -2,55 +2,67 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/message.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/message.json",
|
||||||
"title": "IRC Message Envelope",
|
"title": "IRC Message Envelope",
|
||||||
"description": "Every message in the HTTP API is one JSON object with these fields. Only 'command' is always present.",
|
"description": "Base envelope for all messages. Mirrors IRC wire format (RFC 1459/2812) encoded as JSON over HTTP. The 'command' field carries either an IRC command name (PRIVMSG, JOIN, etc.) or a three-digit numeric reply code (001, 353, 433, etc.).",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "uuid",
|
"format": "uuid",
|
||||||
"description": "The message's UUID, which the server assigns. Present on every message the server queues for a client."
|
"description": "Server-assigned message UUID. Present on all server-originated messages."
|
||||||
},
|
},
|
||||||
"command": {
|
"command": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "An IRC command name, such as PRIVMSG, or the name of a numeric reply, such as RPL_WELCOME. The server reads a client's command in any case and sends it in upper case.",
|
"description": "IRC command name (PRIVMSG, JOIN, NICK, etc.) or three-digit numeric reply code (001, 353, 433, etc.).",
|
||||||
"examples": ["PRIVMSG", "JOIN", "RPL_WELCOME", "ERR_NICKNAMEINUSE"]
|
"examples": ["PRIVMSG", "JOIN", "001", "353", "433"]
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"type": "integer",
|
|
||||||
"minimum": 1,
|
|
||||||
"maximum": 999,
|
|
||||||
"description": "The number of a numeric reply, such as 1 for RPL_WELCOME. Absent on other messages."
|
|
||||||
},
|
},
|
||||||
"from": {
|
"from": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "The sender's nick, or the server name on a numeric reply or a PONG. The server sets it and ignores it from a client."
|
"description": "Source — nick for user messages, server name for server messages. Equivalent to IRC prefix."
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "The target: a channel name, such as #general, or a nick. A WALLOPS has * here."
|
"description": "Target — channel (#name) or nick. Equivalent to first IRC parameter for most commands."
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": { "type": "string" },
|
"items": { "type": "string" },
|
||||||
"description": "The message's other parameters, in order. KICK events and many numeric replies have it. The server ignores it from a client."
|
"description": "Additional parameters (used primarily by numeric replies). Equivalent to IRC middle parameters."
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"oneOf": [
|
||||||
"items": { "type": "string" },
|
{
|
||||||
"description": "An array of strings, never a bare string. In a PRIVMSG or NOTICE, each string is one line of text."
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Array of strings (one per line for text messages)."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"description": "Structured data (e.g. PUBKEY key material).",
|
||||||
|
"additionalProperties": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Message body. MUST be an array or object, never a raw string. Arrays represent lines of text; objects carry structured data. This enables deterministic canonicalization (RFC 8785 JCS) for signing."
|
||||||
},
|
},
|
||||||
"ts": {
|
"ts": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "date-time",
|
"format": "date-time",
|
||||||
"description": "The time the server stored the message, as an RFC 3339 time in UTC."
|
"description": "Server-assigned timestamp (ISO 8601). Not present in original IRC; added for HTTP transport."
|
||||||
},
|
},
|
||||||
"meta": {
|
"meta": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"description": "An object of extra data. Every message the server queues for a client has meta, which is {} when there is none. The server keeps a client's meta only on a PRIVMSG or NOTICE, and relays it unchanged.",
|
"description": "Extensible metadata. Used for signatures (meta.sig, meta.alg), hashes (meta.hash), and client extensions.",
|
||||||
"properties": {
|
"properties": {
|
||||||
"hashcash": {
|
"sig": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "A hashcash stamp. A PRIVMSG to a channel with mode +H needs one."
|
"description": "Base64-encoded cryptographic signature over the canonical message form."
|
||||||
|
},
|
||||||
|
"alg": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Signature algorithm (e.g. 'ed25519')."
|
||||||
|
},
|
||||||
|
"hash": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Hash of the canonical message form (e.g. 'sha256:base64...')."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"additionalProperties": true
|
"additionalProperties": true
|
||||||
|
|||||||
@@ -2,45 +2,32 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/001.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/001.json",
|
||||||
"title": "001 RPL_WELCOME",
|
"title": "001 RPL_WELCOME",
|
||||||
"description": "Welcomes the user. Sent after a session is created, after a login, and in answer to MOTD. RFC 2812 §5.1.",
|
"description": "Welcome message sent after successful session creation. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_WELCOME"
|
"const": "001"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 1
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "The user's nick."
|
"description": "Target nick."
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'Welcome to the network, ' and the user's nick.",
|
"description": "Welcome text lines."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_WELCOME",
|
"command": "001",
|
||||||
"code": 1,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"body": [
|
"body": [
|
||||||
"Welcome to the network, alice"
|
"Welcome to the network, alice"
|
||||||
|
|||||||
@@ -2,48 +2,34 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/002.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/002.json",
|
||||||
"title": "002 RPL_YOURHOST",
|
"title": "002 RPL_YOURHOST",
|
||||||
"description": "The server's name and version. Sent right after RPL_WELCOME. RFC 2812 §5.1.",
|
"description": "Server host info sent after session creation. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_YOURHOST"
|
"const": "002"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 2
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'Your host is ', the server name, ', running version ' and the version.",
|
"description": "Host info lines."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_YOURHOST",
|
"command": "002",
|
||||||
"code": 2,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"body": [
|
"body": [
|
||||||
"Your host is neoirc, running version dev"
|
"Your host is neoirc.example.com, running version 0.1.0"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,45 +2,31 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/003.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/003.json",
|
||||||
"title": "003 RPL_CREATED",
|
"title": "003 RPL_CREATED",
|
||||||
"description": "The date the server last started. Sent right after RPL_YOURHOST. RFC 2812 §5.1.",
|
"description": "Server creation date. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_CREATED"
|
"const": "003"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 3
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'This server was created ' and the start date as YYYY-MM-DD.",
|
"description": "Text lines."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_CREATED",
|
"command": "003",
|
||||||
"code": 3,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"body": [
|
"body": [
|
||||||
"This server was created 2026-02-01"
|
"This server was created 2026-02-01"
|
||||||
|
|||||||
+10
-37
@@ -2,64 +2,37 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/004.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/004.json",
|
||||||
"title": "004 RPL_MYINFO",
|
"title": "004 RPL_MYINFO",
|
||||||
"description": "The server's name, its version, and its lists of user and channel modes. Sent right after RPL_CREATED. RFC 2812 §5.1.",
|
"description": "Server info (name, version, available modes). RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_MYINFO"
|
"const": "004"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 4
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The server name, the version, the user modes 'ow' and the channel modes 'Hbiklmnostv'.",
|
"description": "[server_name, version, user_modes, channel_modes]."
|
||||||
"minItems": 4,
|
|
||||||
"maxItems": 4
|
|
||||||
},
|
|
||||||
"body": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"description": "One empty string.",
|
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_MYINFO",
|
"command": "004",
|
||||||
"code": 4,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"neoirc",
|
"neoirc.example.com",
|
||||||
"dev",
|
"0.1.0",
|
||||||
"ow",
|
"o",
|
||||||
"Hbiklmnostv"
|
"imnst+ov"
|
||||||
],
|
|
||||||
"body": [
|
|
||||||
""
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,55 +2,38 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/322.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/322.json",
|
||||||
"title": "322 RPL_LIST",
|
"title": "322 RPL_LIST",
|
||||||
"description": "One channel in the answer to LIST. The answer has one per channel, except a secret channel, one with mode +s, that the user is not on. RFC 1459 §6.2.",
|
"description": "Channel list entry. One per channel in response to LIST. RFC 1459 \u00a76.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_LIST"
|
"const": "322"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 322
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name and its number of members.",
|
"description": "[channel, visible_count]."
|
||||||
"minItems": 2,
|
|
||||||
"maxItems": 2
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: the channel's topic, empty when it has none.",
|
"description": "Channel topic."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_LIST",
|
"command": "322",
|
||||||
"code": 322,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"#general",
|
"#general",
|
||||||
|
|||||||
@@ -2,49 +2,26 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/323.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/323.json",
|
||||||
"title": "323 RPL_LISTEND",
|
"title": "323 RPL_LISTEND",
|
||||||
"description": "The end of the answer to LIST. RFC 1459 §6.2.",
|
"description": "End of channel list. RFC 1459 \u00a76.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_LISTEND"
|
"const": "323"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 323
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'End of /LIST'.",
|
"description": "End of /LIST",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
"to"
|
||||||
"from",
|
|
||||||
"to",
|
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "RPL_LISTEND",
|
|
||||||
"code": 323,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"body": [
|
|
||||||
"End of /LIST"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,55 +2,39 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/332.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/332.json",
|
||||||
"title": "332 RPL_TOPIC",
|
"title": "332 RPL_TOPIC",
|
||||||
"description": "A channel's topic. Sent to a client after it sets the topic, and after it joins a channel that has one. Also sent for each of a session's channels that has one after a login, and for GET /api/v1/state?initChannelState=1. RFC 1459 §6.2.",
|
"description": "Channel topic (sent on JOIN or TOPIC query). RFC 1459 \u00a76.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_TOPIC"
|
"const": "332"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 332
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name.",
|
"description": "[channel]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: the topic.",
|
"description": "Topic text."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_TOPIC",
|
"command": "332",
|
||||||
"code": 332,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"#general"
|
"#general"
|
||||||
|
|||||||
@@ -2,62 +2,46 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/353.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/353.json",
|
||||||
"title": "353 RPL_NAMREPLY",
|
"title": "353 RPL_NAMREPLY",
|
||||||
"description": "A channel's members. Sent to a client after it joins a channel, and in answer to NAMES. Also sent for each of a session's channels after a login, and for GET /api/v1/state?initChannelState=1. RFC 1459 §6.2.",
|
"description": "Channel member list. Sent on JOIN or NAMES query. RFC 1459 \u00a76.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_NAMREPLY"
|
"const": "353"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 353
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "'=' and the channel name. The server always sends '='.",
|
"description": "[channel_type, channel]. channel_type: = (public), * (private), @ (secret)."
|
||||||
"minItems": 2,
|
|
||||||
"maxItems": 2
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: the members as nick!user@host, separated by spaces. '@' comes before a channel operator and '+' before a voiced member. The host is '*' when the server does not know it.",
|
"description": "Space-separated list of nicks. Prefixed with @ for ops, + for voiced."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_NAMREPLY",
|
"command": "353",
|
||||||
"code": 353,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"=",
|
"=",
|
||||||
"#general"
|
"#general"
|
||||||
],
|
],
|
||||||
"body": [
|
"body": [
|
||||||
"@op1!op1@host1 alice!alice@host2 +bob!bob@host3"
|
"@op1 alice bob +voiced1"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,62 +2,34 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/366.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/366.json",
|
||||||
"title": "366 RPL_ENDOFNAMES",
|
"title": "366 RPL_ENDOFNAMES",
|
||||||
"description": "The end of a channel's member list. It comes after the RPL_NAMREPLY for the channel. RFC 1459 §6.2.",
|
"description": "End of NAMES list. RFC 1459 \u00a76.2.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_ENDOFNAMES"
|
"const": "366"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 366
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name.",
|
"description": "[channel]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'End of /NAMES list'.",
|
"description": "End of /NAMES list",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "RPL_ENDOFNAMES",
|
|
||||||
"code": 366,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"params": [
|
|
||||||
"#general"
|
|
||||||
],
|
|
||||||
"body": [
|
|
||||||
"End of /NAMES list"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,45 +2,31 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/372.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/372.json",
|
||||||
"title": "372 RPL_MOTD",
|
"title": "372 RPL_MOTD",
|
||||||
"description": "One line of the message of the day. The server sends one per line, after RPL_MOTDSTART. RFC 2812 §5.1.",
|
"description": "MOTD line. One message per line of the MOTD. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_MOTD"
|
"const": "372"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 372
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: '- ' and the line.",
|
"description": "MOTD line text (prefixed with '- ')."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"body"
|
"body"
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "RPL_MOTD",
|
"command": "372",
|
||||||
"code": 372,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"body": [
|
"body": [
|
||||||
"- Welcome to our server!"
|
"- Welcome to our server!"
|
||||||
|
|||||||
@@ -2,49 +2,25 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/375.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/375.json",
|
||||||
"title": "375 RPL_MOTDSTART",
|
"title": "375 RPL_MOTDSTART",
|
||||||
"description": "The start of the message of the day. Sent after RPL_LUSERME (255) when the server has a message of the day. RFC 2812 §5.1.",
|
"description": "Start of MOTD. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_MOTDSTART"
|
"const": "375"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 375
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: '- ', the server name and ' Message of the Day -'.",
|
"description": "Text lines."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
"to"
|
||||||
"from",
|
|
||||||
"to",
|
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "RPL_MOTDSTART",
|
|
||||||
"code": 375,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"body": [
|
|
||||||
"- neoirc Message of the Day -"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,49 +2,26 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/376.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/376.json",
|
||||||
"title": "376 RPL_ENDOFMOTD",
|
"title": "376 RPL_ENDOFMOTD",
|
||||||
"description": "The end of the message of the day. RFC 2812 §5.1.",
|
"description": "End of MOTD. RFC 2812 \u00a75.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "RPL_ENDOFMOTD"
|
"const": "376"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 376
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'End of /MOTD command.'.",
|
"description": "End of /MOTD command",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
"to"
|
||||||
"from",
|
|
||||||
"to",
|
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "RPL_ENDOFMOTD",
|
|
||||||
"code": 376,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"body": [
|
|
||||||
"End of /MOTD command."
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,61 +2,45 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/401.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/401.json",
|
||||||
"title": "401 ERR_NOSUCHNICK",
|
"title": "401 ERR_NOSUCHNICK",
|
||||||
"description": "No user has that nick. RFC 1459 §6.1.",
|
"description": "No such nick/channel. RFC 1459 \u00a76.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "ERR_NOSUCHNICK"
|
"const": "401"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 401
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The nick that was not found.",
|
"description": "[target_nick]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'No such nick' in answer to a PRIVMSG or NOTICE, and 'No such nick/channel' in answer to anything else.",
|
"description": "No such nick/channel",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "ERR_NOSUCHNICK",
|
"command": "401",
|
||||||
"code": 401,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"bob"
|
"bob"
|
||||||
],
|
],
|
||||||
"body": [
|
"body": [
|
||||||
"No such nick"
|
"No such nick/channel"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,55 +2,39 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/403.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/403.json",
|
||||||
"title": "403 ERR_NOSUCHCHANNEL",
|
"title": "403 ERR_NOSUCHCHANNEL",
|
||||||
"description": "No channel has that name. A JOIN with a channel name that the server does not allow gets it too. RFC 1459 §6.1.",
|
"description": "No such channel. RFC 1459 \u00a76.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "ERR_NOSUCHCHANNEL"
|
"const": "403"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 403
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name.",
|
"description": "[channel_name]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'No such channel'.",
|
"description": "No such channel",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "ERR_NOSUCHCHANNEL",
|
"command": "403",
|
||||||
"code": 403,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
"to": "alice",
|
||||||
"params": [
|
"params": [
|
||||||
"#nonexistent"
|
"#nonexistent"
|
||||||
|
|||||||
@@ -2,58 +2,42 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/433.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/433.json",
|
||||||
"title": "433 ERR_NICKNAMEINUSE",
|
"title": "433 ERR_NICKNAMEINUSE",
|
||||||
"description": "Another user has the nick. Sent in answer to a NICK. RFC 1459 §6.1.",
|
"description": "Nickname is already in use. RFC 1459 \u00a76.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "ERR_NICKNAMEINUSE"
|
"const": "433"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 433
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick, which has not changed."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The nick that was asked for.",
|
"description": "[requested_nick]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'Nickname is already in use'.",
|
"description": "Nickname is already in use",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
],
|
||||||
"examples": [
|
"examples": [
|
||||||
{
|
{
|
||||||
"command": "ERR_NICKNAMEINUSE",
|
"command": "433",
|
||||||
"code": 433,
|
"to": "*",
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"params": [
|
"params": [
|
||||||
"bob"
|
"alice"
|
||||||
],
|
],
|
||||||
"body": [
|
"body": [
|
||||||
"Nickname is already in use"
|
"Nickname is already in use"
|
||||||
|
|||||||
@@ -2,62 +2,34 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/442.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/442.json",
|
||||||
"title": "442 ERR_NOTONCHANNEL",
|
"title": "442 ERR_NOTONCHANNEL",
|
||||||
"description": "The user is not on that channel. RFC 1459 §6.1.",
|
"description": "You're not on that channel. RFC 1459 \u00a76.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "ERR_NOTONCHANNEL"
|
"const": "442"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 442
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name.",
|
"description": "[channel]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'You're not on that channel'.",
|
"description": "You're not on that channel",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "ERR_NOTONCHANNEL",
|
|
||||||
"code": 442,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"params": [
|
|
||||||
"#general"
|
|
||||||
],
|
|
||||||
"body": [
|
|
||||||
"You're not on that channel"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,62 +2,34 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/482.json",
|
"$id": "https://sneak.berlin/go/neoirc/schema/numerics/482.json",
|
||||||
"title": "482 ERR_CHANOPRIVSNEEDED",
|
"title": "482 ERR_CHANOPRIVSNEEDED",
|
||||||
"description": "The user is not a channel operator, and the command needs one. RFC 1459 §6.1.",
|
"description": "You're not channel operator. RFC 1459 \u00a76.1.",
|
||||||
"$ref": "../message.json",
|
"$ref": "../message.json",
|
||||||
"properties": {
|
"properties": {
|
||||||
"command": {
|
"command": {
|
||||||
"const": "ERR_CHANOPRIVSNEEDED"
|
"const": "482"
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"const": 482
|
|
||||||
},
|
|
||||||
"from": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "The server name."
|
|
||||||
},
|
},
|
||||||
"to": {
|
"to": {
|
||||||
"type": "string",
|
"type": "string"
|
||||||
"description": "The user's nick."
|
|
||||||
},
|
},
|
||||||
"params": {
|
"params": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "The channel name.",
|
"description": "[channel]."
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
|
||||||
},
|
},
|
||||||
"body": {
|
"body": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"description": "One string: 'You're not channel operator'.",
|
"description": "You're not channel operator",
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 1
|
"maxItems": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"command",
|
"command",
|
||||||
"code",
|
|
||||||
"from",
|
|
||||||
"to",
|
"to",
|
||||||
"params",
|
"params"
|
||||||
"body"
|
|
||||||
],
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"command": "ERR_CHANOPRIVSNEEDED",
|
|
||||||
"code": 482,
|
|
||||||
"from": "neoirc",
|
|
||||||
"to": "alice",
|
|
||||||
"params": [
|
|
||||||
"#general"
|
|
||||||
],
|
|
||||||
"body": [
|
|
||||||
"You're not channel operator"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user