Page MenuHomePhorge

No OneTemporary

Size
64 KB
Referenced Files
None
Subscribers
None
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000..3de57a3603
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,12 @@
+node_modules/
+dist/
+logs/
+.DS_Store
+.git/
+config/local.json
+pleroma-backend/
+test/e2e/reports/
+test/e2e-playwright/test-results/
+test/e2e-playwright/playwright-report/
+__screenshots__/
+
diff --git a/.gitignore b/.gitignore
index 01ffda9a8f..c4a96ee1ed 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,15 @@
.DS_Store
node_modules/
dist/
npm-debug.log
test/unit/coverage
test/e2e/reports
+test/e2e-playwright/test-results
+test/e2e-playwright/playwright-report
selenium-debug.log
.idea/
+.gitlab-ci-local/
config/local.json
src/assets/emoji.json
logs/
__screenshots__/
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index b711c7fc94..5e1dfdb25e 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,94 +1,223 @@
# This file is a template, and might need editing before it works on your project.
# Official framework image. Look for the different tagged releases at:
# https://hub.docker.com/r/library/node/tags/
image: node:18
stages:
- check-changelog
- lint
- build
- test
- deploy
# https://git.pleroma.social/help/ci/yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
check-changelog:
stage: check-changelog
image: alpine
rules:
- if: $CI_MERGE_REQUEST_SOURCE_PROJECT_PATH == 'pleroma/pleroma-fe' && $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^renovate/
when: never
- if: $CI_MERGE_REQUEST_SOURCE_PROJECT_PATH == 'pleroma/pleroma-fe' && $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME == 'weblate'
when: never
- if: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop"
before_script: ''
after_script: ''
cache: {}
script:
- apk add git
- sh ./tools/check-changelog
lint-eslint:
stage: lint
script:
- yarn
- yarn ci-eslint
lint-biome:
stage: lint
script:
- yarn
- yarn ci-biome
lint-stylelint:
stage: lint
script:
- yarn
- yarn ci-stylelint
test:
stage: test
tags:
- amd64
- himem
variables:
APT_CACHE_DIR: apt-cache
script:
- mkdir -pv $APT_CACHE_DIR && apt-get -qq update
- yarn
- yarn playwright install firefox
- yarn playwright install-deps
- yarn unit-ci
artifacts:
# When the test fails, upload screenshots for better context on why it fails
paths:
- test/**/__screenshots__
when: on_failure
+e2e-pleroma:
+ stage: test
+ image: mcr.microsoft.com/playwright:v1.55.0-jammy
+ services:
+ - name: postgres:15-alpine
+ alias: db
+ - name: $PLEROMA_IMAGE
+ alias: pleroma
+ entrypoint: ["/bin/ash", "-c"]
+ command:
+ - |
+ set -eu
+
+ SEED_SENTINEL_PATH=/var/lib/pleroma/.e2e_seeded
+ CONFIG_OVERRIDE_PATH=/var/lib/pleroma/config.exs
+
+ echo '-- Waiting for database...'
+ while ! pg_isready -U ${DB_USER:-pleroma} -d postgres://${DB_HOST:-db}:${DB_PORT:-5432}/${DB_NAME:-pleroma} -t 1; do
+ sleep 1s
+ done
+
+ echo '-- Writing E2E config overrides...'
+ cat > $CONFIG_OVERRIDE_PATH <<EOF
+ import Config
+
+ config :pleroma, Pleroma.Captcha,
+ enabled: false
+
+ config :pleroma, :instance,
+ registrations_open: true,
+ account_activation_required: false,
+ approval_required: false
+ EOF
+
+ echo '-- Running migrations...'
+ /opt/pleroma/bin/pleroma_ctl migrate
+
+ echo '-- Starting!'
+ /opt/pleroma/bin/pleroma start &
+ PLEROMA_PID=$!
+
+ cleanup() {
+ if kill -0 $PLEROMA_PID 2>/dev/null; then
+ kill -TERM $PLEROMA_PID
+ wait $PLEROMA_PID || true
+ fi
+ }
+
+ trap cleanup INT TERM
+
+ echo '-- Waiting for API...'
+ api_ok=false
+ for _i in $(seq 1 120); do
+ if wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null 2>&1; then
+ api_ok=true
+ break
+ fi
+ sleep 1s
+ done
+
+ if [ $api_ok != true ]; then
+ echo 'Timed out waiting for Pleroma API to become available'
+ exit 1
+ fi
+
+ if [ ! -f $SEED_SENTINEL_PATH ]; then
+ if [ -n ${E2E_ADMIN_USERNAME:-} ] && [ -n ${E2E_ADMIN_PASSWORD:-} ] && [ -n ${E2E_ADMIN_EMAIL:-} ]; then
+ echo '-- Seeding admin user' $E2E_ADMIN_USERNAME '...'
+ if ! /opt/pleroma/bin/pleroma_ctl user new $E2E_ADMIN_USERNAME $E2E_ADMIN_EMAIL --admin --password $E2E_ADMIN_PASSWORD -y; then
+ echo '-- User already exists or creation failed, ensuring admin + confirmed...'
+ /opt/pleroma/bin/pleroma_ctl user set $E2E_ADMIN_USERNAME --admin --confirmed
+ fi
+ else
+ echo '-- Skipping admin seeding (missing E2E_ADMIN_* env)'
+ fi
+
+ touch $SEED_SENTINEL_PATH
+ fi
+
+ wait $PLEROMA_PID
+ tags:
+ - amd64
+ - himem
+ variables:
+ PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
+ FF_NETWORK_PER_BUILD: "true"
+ PLEROMA_IMAGE: git.pleroma.social:5050/pleroma/pleroma:stable
+ POSTGRES_USER: pleroma
+ POSTGRES_PASSWORD: pleroma
+ POSTGRES_DB: pleroma
+ DB_USER: pleroma
+ DB_PASS: pleroma
+ DB_NAME: pleroma
+ DB_HOST: db
+ DB_PORT: 5432
+ DOMAIN: localhost
+ INSTANCE_NAME: Pleroma E2E
+ E2E_ADMIN_USERNAME: admin
+ E2E_ADMIN_PASSWORD: adminadmin
+ E2E_ADMIN_EMAIL: admin@example.com
+ ADMIN_EMAIL: $E2E_ADMIN_EMAIL
+ NOTIFY_EMAIL: $E2E_ADMIN_EMAIL
+ VITE_PROXY_TARGET: http://pleroma:4000
+ VITE_PROXY_ORIGIN: http://localhost:4000
+ E2E_BASE_URL: http://localhost:8080
+ script:
+ - npm install -g yarn@1.22.22
+ - yarn --frozen-lockfile
+ - |
+ echo "-- Waiting for Pleroma API..."
+ api_ok="false"
+ for _i in $(seq 1 120); do
+ if wget -qO- http://pleroma:4000/api/v1/instance >/dev/null 2>&1; then
+ api_ok="true"
+ break
+ fi
+ sleep 1s
+ done
+ if [ "$api_ok" != "true" ]; then
+ echo "Timed out waiting for Pleroma API to become available"
+ exit 1
+ fi
+ - yarn e2e:pw
+ artifacts:
+ when: on_failure
+ paths:
+ - test/e2e-playwright/test-results
+ - test/e2e-playwright/playwright-report
+
build:
stage: build
tags:
- amd64
- himem
script:
- yarn
- yarn build
artifacts:
paths:
- dist/
docs-deploy:
stage: deploy
image: alpine:latest
only:
- develop@pleroma/pleroma-fe
before_script:
- apk add curl
script:
- curl -X POST -F"token=$DOCS_PIPELINE_TRIGGER" -F'ref=master' https://git.pleroma.social/api/v4/projects/673/trigger/pipeline
diff --git a/changelog.d/e2e-tests.add b/changelog.d/e2e-tests.add
new file mode 100644
index 0000000000..ba62b25ac6
--- /dev/null
+++ b/changelog.d/e2e-tests.add
@@ -0,0 +1 @@
+Add playwright E2E-tests with an optional docker-based backend
diff --git a/docker-compose.e2e.yml b/docker-compose.e2e.yml
new file mode 100644
index 0000000000..75a4979a14
--- /dev/null
+++ b/docker-compose.e2e.yml
@@ -0,0 +1,57 @@
+services:
+ db:
+ image: postgres:15-alpine
+ environment:
+ POSTGRES_USER: pleroma
+ POSTGRES_PASSWORD: pleroma
+ POSTGRES_DB: pleroma
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U pleroma -d pleroma"]
+ interval: 2s
+ timeout: 2s
+ retries: 30
+
+ pleroma:
+ image: ${PLEROMA_IMAGE:-git.pleroma.social:5050/pleroma/pleroma:stable}
+ environment:
+ DB_USER: pleroma
+ DB_PASS: pleroma
+ DB_NAME: pleroma
+ DB_HOST: db
+ DB_PORT: 5432
+ DOMAIN: localhost
+ INSTANCE_NAME: Pleroma E2E
+ ADMIN_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com}
+ NOTIFY_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com}
+ E2E_ADMIN_USERNAME: ${E2E_ADMIN_USERNAME:-admin}
+ E2E_ADMIN_PASSWORD: ${E2E_ADMIN_PASSWORD:-adminadmin}
+ E2E_ADMIN_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com}
+ depends_on:
+ db:
+ condition: service_healthy
+ volumes:
+ - ./docker/pleroma/entrypoint.e2e.sh:/opt/pleroma/entrypoint.e2e.sh:ro
+ entrypoint: ["/bin/ash", "/opt/pleroma/entrypoint.e2e.sh"]
+ healthcheck:
+ # NOTE: "localhost" may resolve to ::1 in some images (IPv6) while Pleroma only
+ # listens on IPv4 in this container. Use 127.0.0.1 to avoid false negatives.
+ test: ["CMD-SHELL", "test -f /var/lib/pleroma/.e2e_seeded && wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null || exit 1"]
+ interval: 5s
+ timeout: 3s
+ retries: 60
+
+ e2e:
+ build:
+ context: .
+ dockerfile: docker/e2e/Dockerfile.e2e
+ depends_on:
+ pleroma:
+ condition: service_healthy
+ environment:
+ CI: "1"
+ VITE_PROXY_TARGET: http://pleroma:4000
+ VITE_PROXY_ORIGIN: http://localhost:4000
+ E2E_BASE_URL: http://localhost:8080
+ E2E_ADMIN_USERNAME: ${E2E_ADMIN_USERNAME:-admin}
+ E2E_ADMIN_PASSWORD: ${E2E_ADMIN_PASSWORD:-adminadmin}
+ command: ["yarn", "e2e:pw"]
diff --git a/docker/e2e/Dockerfile.e2e b/docker/e2e/Dockerfile.e2e
new file mode 100644
index 0000000000..ec780e894c
--- /dev/null
+++ b/docker/e2e/Dockerfile.e2e
@@ -0,0 +1,17 @@
+FROM mcr.microsoft.com/playwright:v1.55.0-jammy
+
+WORKDIR /app
+
+ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
+
+RUN npm install -g yarn@1.22.22
+
+COPY package.json yarn.lock ./
+RUN yarn --frozen-lockfile
+
+COPY . .
+
+ENV CI=1
+
+CMD ["yarn", "e2e:pw"]
+
diff --git a/docker/pleroma/entrypoint.e2e.sh b/docker/pleroma/entrypoint.e2e.sh
new file mode 100644
index 0000000000..96920eeaef
--- /dev/null
+++ b/docker/pleroma/entrypoint.e2e.sh
@@ -0,0 +1,71 @@
+#!/bin/ash
+
+set -eu
+
+SEED_SENTINEL_PATH="/var/lib/pleroma/.e2e_seeded"
+CONFIG_OVERRIDE_PATH="/var/lib/pleroma/config.exs"
+
+echo "-- Waiting for database..."
+while ! pg_isready -U "${DB_USER:-pleroma}" -d "postgres://${DB_HOST:-db}:${DB_PORT:-5432}/${DB_NAME:-pleroma}" -t 1; do
+ sleep 1s
+done
+
+echo "-- Writing E2E config overrides..."
+cat > "$CONFIG_OVERRIDE_PATH" <<'EOF'
+import Config
+
+config :pleroma, Pleroma.Captcha,
+ enabled: false
+
+config :pleroma, :instance,
+ registrations_open: true,
+ account_activation_required: false,
+ approval_required: false
+EOF
+
+echo "-- Running migrations..."
+/opt/pleroma/bin/pleroma_ctl migrate
+
+echo "-- Starting!"
+/opt/pleroma/bin/pleroma start &
+PLEROMA_PID="$!"
+
+cleanup() {
+ if [ -n "${PLEROMA_PID:-}" ] && kill -0 "$PLEROMA_PID" 2>/dev/null; then
+ kill -TERM "$PLEROMA_PID"
+ wait "$PLEROMA_PID" || true
+ fi
+}
+
+trap cleanup INT TERM
+
+echo "-- Waiting for API..."
+api_ok="false"
+for _i in $(seq 1 120); do
+ if wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null 2>&1; then
+ api_ok="true"
+ break
+ fi
+ sleep 1s
+done
+
+if [ "$api_ok" != "true" ]; then
+ echo "Timed out waiting for Pleroma API to become available"
+ exit 1
+fi
+
+if [ ! -f "$SEED_SENTINEL_PATH" ]; then
+ if [ -n "${E2E_ADMIN_USERNAME:-}" ] && [ -n "${E2E_ADMIN_PASSWORD:-}" ] && [ -n "${E2E_ADMIN_EMAIL:-}" ]; then
+ echo "-- Seeding admin user (${E2E_ADMIN_USERNAME})..."
+ if ! /opt/pleroma/bin/pleroma_ctl user new "$E2E_ADMIN_USERNAME" "$E2E_ADMIN_EMAIL" --admin --password "$E2E_ADMIN_PASSWORD" -y; then
+ echo "-- User already exists (or creation failed), ensuring admin + confirmed..."
+ /opt/pleroma/bin/pleroma_ctl user set "$E2E_ADMIN_USERNAME" --admin --confirmed
+ fi
+ else
+ echo "-- Skipping admin seeding (missing E2E_ADMIN_* env)"
+ fi
+
+ touch "$SEED_SENTINEL_PATH"
+fi
+
+wait "$PLEROMA_PID"
diff --git a/package.json b/package.json
index 33a1d719fb..b00ed545ac 100644
--- a/package.json
+++ b/package.json
@@ -1,125 +1,126 @@
{
"name": "pleroma_fe",
"version": "2.10.0",
"description": "Pleroma frontend, the default frontend of Pleroma social network server",
"author": "Pleroma contributors <https://git.pleroma.social/pleroma/pleroma-fe/-/blob/develop/CONTRIBUTORS.md>",
"private": false,
"scripts": {
"dev": "node build/update-emoji.js && vite dev",
"build": "node build/update-emoji.js && vite build",
"unit": "node build/update-emoji.js && vitest --run",
"unit-ci": "node build/update-emoji.js && vitest --run --browser.headless",
"unit:watch": "node build/update-emoji.js && vitest",
- "e2e": "node test/e2e/runner.js",
+ "e2e:pw": "playwright test --config test/e2e-playwright/playwright.config.mjs",
+ "e2e": "sh ./tools/e2e/run.sh",
"test": "yarn run unit && yarn run e2e",
"ci-biome": "yarn exec biome check",
"ci-eslint": "yarn exec eslint",
"ci-stylelint": "yarn exec stylelint '**/*.scss' '**/*.vue'",
"lint": "yarn ci-biome; yarn ci-eslint; yarn ci-stylelint",
"lint-fix": "yarn exec eslint --fix; yarn exec stylelint '**/*.scss' '**/*.vue' --fix; biome check --write"
},
"dependencies": {
"@babel/runtime": "7.28.4",
"@chenfengyuan/vue-qrcode": "2.0.0",
"@fortawesome/fontawesome-svg-core": "7.1.0",
"@fortawesome/free-regular-svg-icons": "7.1.0",
"@fortawesome/free-solid-svg-icons": "7.1.0",
"@fortawesome/vue-fontawesome": "3.1.2",
"@kazvmoe-infra/pinch-zoom-element": "1.3.0",
"@kazvmoe-infra/unicode-emoji-json": "0.4.0",
"@ruffle-rs/ruffle": "0.1.0-nightly.2025.6.22",
"@vuelidate/core": "2.0.3",
"@vuelidate/validators": "2.0.4",
"@web3-storage/parse-link-header": "^3.1.0",
"body-scroll-lock": "3.1.5",
"chromatism": "3.0.0",
"click-outside-vue3": "4.0.1",
"cropperjs": "2.0.1",
"escape-html": "1.0.3",
"globals": "^16.0.0",
"hash-sum": "^2.0.0",
"js-cookie": "3.0.5",
"localforage": "1.10.0",
"parse-link-header": "2.0.0",
"phoenix": "1.8.1",
"pinia": "^3.0.0",
"punycode.js": "2.3.1",
"qrcode": "1.5.4",
"querystring-es3": "0.2.1",
"url": "0.11.4",
"utf8": "3.0.0",
"uuid": "11.1.0",
"vue": "3.5.22",
"vue-i18n": "11",
"vue-router": "4.6.4",
"vue-virtual-scroller": "^2.0.0-beta.7",
"vuex": "4.1.0"
},
"devDependencies": {
"@babel/core": "7.28.5",
"@babel/eslint-parser": "7.28.5",
"@babel/plugin-transform-runtime": "7.28.5",
"@babel/preset-env": "7.28.5",
"@babel/register": "7.28.3",
"@biomejs/biome": "2.3.11",
"@ungap/event-target": "0.2.4",
"@vitejs/plugin-vue": "^5.2.1",
"@vitejs/plugin-vue-jsx": "^4.1.1",
"@vitest/browser": "^3.0.7",
"@vitest/ui": "^3.0.7",
"@vue/babel-helper-vue-jsx-merge-props": "1.4.0",
"@vue/babel-plugin-jsx": "1.5.0",
"@vue/compiler-sfc": "3.5.22",
"@vue/test-utils": "2.4.6",
"autoprefixer": "10.4.21",
"babel-plugin-lodash": "3.3.4",
"chai": "5.3.3",
"chalk": "5.6.2",
"chromedriver": "135.0.4",
"connect-history-api-fallback": "2.0.0",
"cross-spawn": "7.0.6",
"custom-event-polyfill": "1.0.7",
"eslint": "9.39.2",
"eslint-config-standard": "17.1.0",
"eslint-formatter-friendly": "7.0.0",
"eslint-plugin-import": "2.32.0",
"eslint-plugin-n": "17.23.1",
"eslint-plugin-promise": "7.2.1",
"eslint-plugin-vue": "10.6.2",
"eventsource-polyfill": "0.9.6",
"express": "5.1.0",
"function-bind": "1.1.2",
"http-proxy-middleware": "3.0.5",
"iso-639-1": "3.1.5",
"lodash": "4.17.21",
"msw": "2.10.5",
"nightwatch": "3.12.2",
"playwright": "1.57.0",
"postcss": "8.5.6",
"postcss-html": "^1.5.0",
"postcss-scss": "^4.0.6",
"sass": "1.93.2",
"selenium-server": "3.141.59",
"semver": "7.7.3",
"serve-static": "2.2.0",
"shelljs": "0.10.0",
"sinon": "20.0.0",
"sinon-chai": "4.0.1",
"stylelint": "16.25.0",
"stylelint-config-html": "^1.1.0",
"stylelint-config-recommended": "^16.0.0",
"stylelint-config-recommended-scss": "^14.0.0",
"stylelint-config-recommended-vue": "^1.6.0",
"stylelint-config-standard": "38.0.0",
"vite": "^6.1.0",
"vite-plugin-eslint2": "^5.0.3",
"vite-plugin-stylelint": "^6.0.0",
"vitest": "^3.0.7",
"vue-eslint-parser": "10.2.0"
},
"type": "module",
"engines": {
"node": ">= 16.0.0"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
diff --git a/src/components/settings_modal/helpers/rate_setting.vue b/src/components/settings_modal/helpers/rate_setting.vue
index f6216223c7..49e09e046e 100644
--- a/src/components/settings_modal/helpers/rate_setting.vue
+++ b/src/components/settings_modal/helpers/rate_setting.vue
@@ -1,139 +1,140 @@
<template>
<div
v-if="matchesExpertLevel"
class="RateSetting setting-item"
>
<label
class="setting-label"
:class="{ 'faint': shouldBeDisabled }"
>
<ModifiedIndicator
:changed="isChanged"
:onclick="reset"
/>
<ProfileSettingIndicator :is-profile="isProfileSetting" />
{{ ' ' }}
<template v-if="backendDescriptionLabel">
{{ backendDescriptionLabel + ' ' }}
</template>
<template v-else-if="source === 'admin'">
MISSING LABEL FOR {{ path }}
</template>
<slot v-else />
</label>
<p
v-if="backendDescriptionDescription"
class="setting-description"
:class="{ 'faint': shouldBeDisabled }"
>
{{ backendDescriptionDescription + ' ' }}
</p>
<div class="setting-control">
<table>
- <tr>
- <th>&nbsp;</th>
- <th>
- {{ $t('admin_dash.rate_limit.period') }}
- </th>
- <th>
- {{ $t('admin_dash.rate_limit.amount') }}
- </th>
- </tr>
- <tr>
- <td v-if="isSeparate">
- {{ $t('admin_dash.rate_limit.unauthenticated') }}
- </td>
- <td v-else>
- {{ $t('admin_dash.rate_limit.rate_limit') }}
- </td>
- <td>
- <input
- class="input string-input"
- type="number"
- :value="normalizedState[0][0]"
- @change="e => update({ event: e, index: 0, side: 0, eventType: 'edit' })"
- >
- </td>
- <td>
- <input
- class="input string-input"
- type="number"
- :value="normalizedState[0][1]"
- @change="e => update({ event: e, index: 1, side: 0, eventType: 'edit' })"
- >
- </td>
- </tr>
- <tr v-if="isSeparate">
- <td>
- {{ $t('admin_dash.rate_limit.authenticated') }}
- </td>
- <td>
- <input
- class="input string-input"
- type="number"
- :value="normalizedState[1][0]"
- @change="e => update({ event: e, index: 0, side: 1, eventType: 'edit' })"
- >
- </td>
- <td>
- <input
- class="input string-input"
- type="number"
- :value="normalizedState[1][1]"
- @change="e => update({ event: e, index: 1, side: 1, eventType: 'edit' })"
- >
- </td>
- </tr>
+ <thead>
+ <tr>
+ <th>&nbsp;</th>
+ <th>
+ {{ $t('admin_dash.rate_limit.period') }}
+ </th>
+ <th>
+ {{ $t('admin_dash.rate_limit.amount') }}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ {{ isSeparate ? $t('admin_dash.rate_limit.unauthenticated') : $t('admin_dash.rate_limit.rate_limit') }}
+ </td>
+ <td>
+ <input
+ class="input string-input"
+ type="number"
+ :value="normalizedState[0][0]"
+ @change="e => update({ event: e, index: 0, side: 0, eventType: 'edit' })"
+ >
+ </td>
+ <td>
+ <input
+ class="input string-input"
+ type="number"
+ :value="normalizedState[0][1]"
+ @change="e => update({ event: e, index: 1, side: 0, eventType: 'edit' })"
+ >
+ </td>
+ </tr>
+ <tr v-if="isSeparate">
+ <td>
+ {{ $t('admin_dash.rate_limit.authenticated') }}
+ </td>
+ <td>
+ <input
+ class="input string-input"
+ type="number"
+ :value="normalizedState[1][0]"
+ @change="e => update({ event: e, index: 0, side: 1, eventType: 'edit' })"
+ >
+ </td>
+ <td>
+ <input
+ class="input string-input"
+ type="number"
+ :value="normalizedState[1][1]"
+ @change="e => update({ event: e, index: 1, side: 1, eventType: 'edit' })"
+ >
+ </td>
+ </tr>
+ </tbody>
</table>
<Checkbox
:model-value="isSeparate"
@update:model-value="event => update({ event: event ? 'join' : 'split', eventType: 'toggleMode' })"
>
{{ $t('admin_dash.rate_limit.separate') }}
</Checkbox>
</div>
<DraftButtons />
</div>
</template>
<script src="./rate_setting.js"></script>
<style lang="scss">
.RateSetting {
&.setting-item {
display: grid;
grid-template-areas:
"label control"
"desc control"
". draft";
.setting-label {
text-align: right;
align-self: center;
}
.setting-description {
text-align: right;
}
.setting-control {
align-self: end;
}
}
table {
margin-top: 0.5em;
}
th {
font-weight: normal;
}
td {
input {
width: 15ch;
}
}
margin-bottom: 2em;
}
</style>
diff --git a/src/modules/users.js b/src/modules/users.js
index 53e9ccf471..beea85260c 100644
--- a/src/modules/users.js
+++ b/src/modules/users.js
@@ -1,838 +1,838 @@
import {
compact,
concat,
each,
isArray,
last,
map,
mergeWith,
uniq,
} from 'lodash'
import { declarations } from 'src/modules/config_declaration'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useServerSideStorageStore } from 'src/stores/serverSideStorage'
import apiService from '../services/api/api.service.js'
import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js'
import oauthApi from '../services/new_api/oauth.js'
import {
registerPushNotifications,
unregisterPushNotifications,
} from '../services/sw/sw.js'
import {
windowHeight,
windowWidth,
} from '../services/window_utils/window_utils'
// TODO: Unify with mergeOrAdd in statuses.js
export const mergeOrAdd = (arr, obj, item) => {
if (!item) {
return false
}
const oldItem = obj[item.id]
if (oldItem) {
// We already have this, so only merge the new info.
mergeWith(oldItem, item, mergeArrayLength)
return { item: oldItem, new: false }
} else {
// This is a new item, prepare it
arr.push(item)
obj[item.id] = item
return { item, new: true }
}
}
const mergeArrayLength = (oldValue, newValue) => {
if (isArray(oldValue) && isArray(newValue)) {
oldValue.length = newValue.length
return mergeWith(oldValue, newValue, mergeArrayLength)
}
}
const getNotificationPermission = () => {
const Notification = window.Notification
if (!Notification) return Promise.resolve(null)
if (Notification.permission === 'default')
return Notification.requestPermission()
return Promise.resolve(Notification.permission)
}
const blockUser = (store, args) => {
const id = args.id
const expiresIn = typeof args === 'object' ? args.expiresIn : 0
const predictedRelationship = store.state.relationships[id] || { id }
store.commit('updateUserRelationship', [predictedRelationship])
store.commit('addBlockId', id)
return store.rootState.api.backendInteractor
.blockUser({ id, expiresIn })
.then((relationship) => {
store.commit('updateUserRelationship', [relationship])
store.commit('addBlockId', id)
store.commit('removeStatus', { timeline: 'friends', userId: id })
store.commit('removeStatus', { timeline: 'public', userId: id })
store.commit('removeStatus', {
timeline: 'publicAndExternal',
userId: id,
})
})
}
const unblockUser = (store, id) => {
return store.rootState.api.backendInteractor
.unblockUser({ id })
.then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const removeUserFromFollowers = (store, id) => {
return store.rootState.api.backendInteractor
.removeUserFromFollowers({ id })
.then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const editUserNote = (store, { id, comment }) => {
return store.rootState.api.backendInteractor
.editUserNote({ id, comment })
.then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const muteUser = (store, args) => {
const id = typeof args === 'object' ? args.id : args
const expiresIn = typeof args === 'object' ? args.expiresIn : 0
const predictedRelationship = store.state.relationships[id] || { id }
store.commit('updateUserRelationship', [predictedRelationship])
store.commit('addMuteId', id)
return store.rootState.api.backendInteractor
.muteUser({ id, expiresIn })
.then((relationship) => {
store.commit('updateUserRelationship', [relationship])
store.commit('addMuteId', id)
})
}
const unmuteUser = (store, id) => {
const predictedRelationship = store.state.relationships[id] || { id }
predictedRelationship.muting = false
store.commit('updateUserRelationship', [predictedRelationship])
return store.rootState.api.backendInteractor
.unmuteUser({ id })
.then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const hideReblogs = (store, userId) => {
return store.rootState.api.backendInteractor
.followUser({ id: userId, reblogs: false })
.then((relationship) => {
store.commit('updateUserRelationship', [relationship])
})
}
const showReblogs = (store, userId) => {
return store.rootState.api.backendInteractor
.followUser({ id: userId, reblogs: true })
.then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const muteDomain = (store, domain) => {
return store.rootState.api.backendInteractor
.muteDomain({ domain })
.then(() => store.commit('addDomainMute', domain))
}
const unmuteDomain = (store, domain) => {
return store.rootState.api.backendInteractor
.unmuteDomain({ domain })
.then(() => store.commit('removeDomainMute', domain))
}
export const mutations = {
tagUser(state, { user: { id }, tag }) {
const user = state.usersObject[id]
const tags = user.tags || []
const newTags = tags.concat([tag])
user.tags = newTags
},
untagUser(state, { user: { id }, tag }) {
const user = state.usersObject[id]
const tags = user.tags || []
const newTags = tags.filter((t) => t !== tag)
user.tags = newTags
},
updateRight(state, { user: { id }, right, value }) {
const user = state.usersObject[id]
const newRights = user.rights
newRights[right] = value
user.rights = newRights
},
updateActivationStatus(state, { user: { id }, deactivated }) {
const user = state.usersObject[id]
user.deactivated = deactivated
},
setCurrentUser(state, user) {
state.lastLoginName = user.screen_name
state.currentUser = mergeWith(
state.currentUser || {},
user,
mergeArrayLength,
)
},
clearCurrentUser(state) {
state.currentUser = false
state.lastLoginName = false
},
beginLogin(state) {
state.loggingIn = true
},
endLogin(state) {
state.loggingIn = false
},
saveFriendIds(state, { id, friendIds }) {
const user = state.usersObject[id]
user.friendIds = uniq(concat(user.friendIds || [], friendIds))
},
saveFollowerIds(state, { id, followerIds }) {
const user = state.usersObject[id]
user.followerIds = uniq(concat(user.followerIds || [], followerIds))
},
// Because frontend doesn't have a reason to keep these stuff in memory
// outside of viewing someones user profile.
clearFriends(state, userId) {
const user = state.usersObject[userId]
if (user) {
user.friendIds = []
}
},
clearFollowers(state, userId) {
const user = state.usersObject[userId]
if (user) {
user.followerIds = []
}
},
addNewUsers(state, users) {
each(users, (user) => {
if (user.relationship) {
state.relationships[user.relationship.id] = user.relationship
}
const res = mergeOrAdd(state.users, state.usersObject, user)
const item = res.item
if (res.new && item.screen_name && !item.screen_name.includes('@')) {
state.usersByNameObject[item.screen_name.toLowerCase()] = item
}
})
},
updateUserRelationship(state, relationships) {
relationships.forEach((relationship) => {
state.relationships[relationship.id] = relationship
})
},
updateUserInLists(state, { id, inLists }) {
state.usersObject[id].inLists = inLists
},
saveBlockIds(state, blockIds) {
state.currentUser.blockIds = blockIds
},
addBlockId(state, blockId) {
if (state.currentUser.blockIds.indexOf(blockId) === -1) {
state.currentUser.blockIds.push(blockId)
}
},
setBlockIdsMaxId(state, blockIdsMaxId) {
state.currentUser.blockIdsMaxId = blockIdsMaxId
},
saveMuteIds(state, muteIds) {
state.currentUser.muteIds = muteIds
},
setMuteIdsMaxId(state, muteIdsMaxId) {
state.currentUser.muteIdsMaxId = muteIdsMaxId
},
addMuteId(state, muteId) {
if (state.currentUser.muteIds.indexOf(muteId) === -1) {
state.currentUser.muteIds.push(muteId)
}
},
saveDomainMutes(state, domainMutes) {
state.currentUser.domainMutes = domainMutes
},
addDomainMute(state, domain) {
if (state.currentUser.domainMutes.indexOf(domain) === -1) {
state.currentUser.domainMutes.push(domain)
}
},
removeDomainMute(state, domain) {
const index = state.currentUser.domainMutes.indexOf(domain)
if (index !== -1) {
state.currentUser.domainMutes.splice(index, 1)
}
},
setPinnedToUser(state, status) {
const user = state.usersObject[status.user.id]
user.pinnedStatusIds = user.pinnedStatusIds || []
const index = user.pinnedStatusIds.indexOf(status.id)
if (status.pinned && index === -1) {
user.pinnedStatusIds.push(status.id)
} else if (!status.pinned && index !== -1) {
user.pinnedStatusIds.splice(index, 1)
}
},
setUserForStatus(state, status) {
status.user = state.usersObject[status.user.id]
},
setUserForNotification(state, notification) {
if (notification.type !== 'follow') {
notification.action.user = state.usersObject[notification.action.user.id]
}
notification.from_profile = state.usersObject[notification.from_profile.id]
},
setColor(state, { user: { id }, highlighted }) {
const user = state.usersObject[id]
user.highlight = highlighted
},
signUpPending(state) {
state.signUpPending = true
state.signUpErrors = []
state.signUpNotice = {}
},
signUpSuccess(state) {
state.signUpPending = false
},
signUpFailure(state, errors) {
state.signUpPending = false
state.signUpErrors = errors
state.signUpNotice = {}
},
signUpNotice(state, notice) {
state.signUpPending = false
state.signUpErrors = []
state.signUpNotice = notice
},
}
export const getters = {
findUser: (state) => (query) => {
return state.usersObject[query]
},
findUserByName: (state) => (query) => {
return state.usersByNameObject[query.toLowerCase()]
},
findUserByUrl: (state) => (query) => {
return state.users.find(
(u) =>
u.statusnet_profile_url &&
u.statusnet_profile_url.toLowerCase() === query.toLowerCase(),
)
},
relationship: (state) => (id) => {
const rel = id && state.relationships[id]
return rel || { id, loading: true }
},
}
export const defaultState = {
loggingIn: false,
lastLoginName: false,
currentUser: false,
users: [],
usersObject: {},
usersByNameObject: {},
signUpPending: false,
signUpErrors: [],
signUpNotice: {},
relationships: {},
}
const users = {
state: defaultState,
mutations,
getters,
actions: {
fetchUserIfMissing(store, id) {
if (!store.getters.findUser(id)) {
store.dispatch('fetchUser', id)
}
},
fetchUser(store, id) {
return store.rootState.api.backendInteractor
.fetchUser({ id })
.then((user) => {
store.commit('addNewUsers', [user])
return user
})
},
fetchUserByName(store, name) {
return store.rootState.api.backendInteractor
.fetchUserByName({ name })
.then((user) => {
store.commit('addNewUsers', [user])
return user
})
},
fetchUserRelationship(store, id) {
if (store.state.currentUser) {
store.rootState.api.backendInteractor
.fetchUserRelationship({ id })
.then((relationships) =>
store.commit('updateUserRelationship', relationships),
)
}
},
fetchUserInLists(store, id) {
if (store.state.currentUser) {
store.rootState.api.backendInteractor
.fetchUserInLists({ id })
.then((inLists) => store.commit('updateUserInLists', { id, inLists }))
}
},
fetchBlocks(store, args) {
const { reset } = args || {}
const maxId = store.state.currentUser.blockIdsMaxId
return store.rootState.api.backendInteractor
.fetchBlocks({ maxId })
.then((blocks) => {
if (reset) {
store.commit('saveBlockIds', map(blocks, 'id'))
} else {
map(blocks, 'id').map((id) => store.commit('addBlockId', id))
}
if (blocks.length) {
store.commit('setBlockIdsMaxId', last(blocks).id)
}
store.commit('addNewUsers', blocks)
return blocks
})
},
blockUser(store, data) {
return blockUser(store, data)
},
unblockUser(store, data) {
return unblockUser(store, data)
},
removeUserFromFollowers(store, id) {
return removeUserFromFollowers(store, id)
},
blockUsers(store, data = []) {
return Promise.all(data.map((d) => blockUser(store, d)))
},
unblockUsers(store, data = []) {
return Promise.all(data.map((d) => unblockUser(store, d)))
},
editUserNote(store, args) {
return editUserNote(store, args)
},
fetchMutes(store, args) {
const { reset } = args || {}
const maxId = store.state.currentUser.muteIdsMaxId
return store.rootState.api.backendInteractor
.fetchMutes({ maxId })
.then((mutes) => {
if (reset) {
store.commit('saveMuteIds', map(mutes, 'id'))
} else {
map(mutes, 'id').map((id) => store.commit('addMuteId', id))
}
if (mutes.length) {
store.commit('setMuteIdsMaxId', last(mutes).id)
}
store.commit('addNewUsers', mutes)
return mutes
})
},
muteUser(store, data) {
return muteUser(store, data)
},
unmuteUser(store, id) {
return unmuteUser(store, id)
},
hideReblogs(store, id) {
return hideReblogs(store, id)
},
showReblogs(store, id) {
return showReblogs(store, id)
},
muteUsers(store, data = []) {
return Promise.all(data.map((d) => muteUser(store, d)))
},
unmuteUsers(store, ids = []) {
return Promise.all(ids.map((d) => unmuteUser(store, d)))
},
fetchDomainMutes(store) {
return store.rootState.api.backendInteractor
.fetchDomainMutes()
.then((domainMutes) => {
store.commit('saveDomainMutes', domainMutes)
return domainMutes
})
},
muteDomain(store, domain) {
return muteDomain(store, domain)
},
unmuteDomain(store, domain) {
return unmuteDomain(store, domain)
},
muteDomains(store, domains = []) {
return Promise.all(domains.map((domain) => muteDomain(store, domain)))
},
unmuteDomains(store, domain = []) {
return Promise.all(domain.map((domain) => unmuteDomain(store, domain)))
},
fetchFriends({ rootState, commit }, id) {
const user = rootState.users.usersObject[id]
const maxId = last(user.friendIds)
return rootState.api.backendInteractor
.fetchFriends({ id, maxId })
.then((friends) => {
commit('addNewUsers', friends)
commit('saveFriendIds', { id, friendIds: map(friends, 'id') })
return friends
})
},
fetchFollowers({ rootState, commit }, id) {
const user = rootState.users.usersObject[id]
const maxId = last(user.followerIds)
return rootState.api.backendInteractor
.fetchFollowers({ id, maxId })
.then((followers) => {
commit('addNewUsers', followers)
commit('saveFollowerIds', { id, followerIds: map(followers, 'id') })
return followers
})
},
clearFriends({ commit }, userId) {
commit('clearFriends', userId)
},
clearFollowers({ commit }, userId) {
commit('clearFollowers', userId)
},
subscribeUser({ rootState, commit }, id) {
return rootState.api.backendInteractor
.followUser({ id, notify: true })
.then((relationship) =>
commit('updateUserRelationship', [relationship]),
)
},
unsubscribeUser({ rootState, commit }, id) {
return rootState.api.backendInteractor
.followUser({ id, notify: false })
.then((relationship) =>
commit('updateUserRelationship', [relationship]),
)
},
toggleActivationStatus({ rootState, commit }, { user }) {
const api = user.deactivated
? rootState.api.backendInteractor.activateUser
: rootState.api.backendInteractor.deactivateUser
api({ user }).then((user) => {
const deactivated = !user.is_active
commit('updateActivationStatus', { user, deactivated })
})
},
registerPushNotifications(store) {
const token = store.state.currentUser.credentials
const vapidPublicKey = store.rootState.instance.vapidPublicKey
const isEnabled = store.rootState.config.webPushNotifications
const notificationVisibility =
store.rootState.config.notificationVisibility
registerPushNotifications(
isEnabled,
vapidPublicKey,
token,
notificationVisibility,
)
},
unregisterPushNotifications(store) {
const token = store.state.currentUser.credentials
unregisterPushNotifications(token)
},
addNewUsers({ commit }, users) {
commit('addNewUsers', users)
},
addNewStatuses(store, { statuses }) {
const users = map(statuses, 'user')
const retweetedUsers = compact(map(statuses, 'retweeted_status.user'))
store.commit('addNewUsers', users)
store.commit('addNewUsers', retweetedUsers)
each(statuses, (status) => {
// Reconnect users to statuses
store.commit('setUserForStatus', status)
// Set pinned statuses to user
store.commit('setPinnedToUser', status)
})
each(compact(map(statuses, 'retweeted_status')), (status) => {
// Reconnect users to retweets
store.commit('setUserForStatus', status)
// Set pinned retweets to user
store.commit('setPinnedToUser', status)
})
},
addNewNotifications(store, { notifications }) {
const users = map(notifications, 'from_profile')
const targetUsers = map(notifications, 'target').filter((_) => _)
const notificationIds = notifications.map((_) => _.id)
store.commit('addNewUsers', users)
store.commit('addNewUsers', targetUsers)
const notificationsObject = store.rootState.notifications.idStore
const relevantNotifications = Object.entries(notificationsObject)
.filter(([k]) => notificationIds.includes(k))
.map(([, val]) => val)
// Reconnect users to notifications
each(relevantNotifications, (notification) => {
store.commit('setUserForNotification', notification)
})
},
searchUsers({ rootState, commit }, { query }) {
return rootState.api.backendInteractor
.searchUsers({ query })
.then((users) => {
commit('addNewUsers', users)
return users
})
},
async signUp(store, userInfo) {
const oauthStore = useOAuthStore()
store.commit('signUpPending')
try {
const token = await oauthStore.ensureAppToken()
const data = await apiService.register({
credentials: token,
params: { ...userInfo },
})
if (data.access_token) {
store.commit('signUpSuccess')
oauthStore.setToken(data.access_token)
- store.dispatch('loginUser', data.access_token)
+ await store.dispatch('loginUser', data.access_token)
return 'ok'
} else {
// Request succeeded, but user cannot login yet.
store.commit('signUpNotice', data)
return 'request_sent'
}
} catch (e) {
const errors = e.message
store.commit('signUpFailure', errors)
throw e
}
},
async getCaptcha(store) {
return store.rootState.api.backendInteractor.getCaptcha()
},
logout(store) {
const oauth = useOAuthStore()
const { instance } = store.rootState
// NOTE: No need to verify the app still exists, because if it doesn't,
// the token will be invalid too
return oauth
.ensureApp()
.then((app) => {
const params = {
app,
instance: instance.server,
token: oauth.userToken,
}
return oauthApi.revokeToken(params)
})
.then(() => {
store.commit('clearCurrentUser')
store.dispatch('disconnectFromSocket')
oauth.clearToken()
store.dispatch('stopFetchingTimeline', 'friends')
store.commit(
'setBackendInteractor',
backendInteractorService(oauth.getToken),
)
store.dispatch('stopFetchingNotifications')
store.dispatch('stopFetchingLists')
store.dispatch('stopFetchingBookmarkFolders')
store.dispatch('stopFetchingFollowRequests')
store.commit('clearNotifications')
store.commit('resetStatuses')
store.dispatch('resetChats')
useInterfaceStore().setLastTimeline('public-timeline')
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
store.commit('clearServerSideStorage')
})
},
loginUser(store, accessToken) {
return new Promise((resolve, reject) => {
const commit = store.commit
const dispatch = store.dispatch
const rootState = store.rootState
commit('beginLogin')
store.rootState.api.backendInteractor
.verifyCredentials(accessToken)
.then((data) => {
if (!data.error) {
const user = data
// user.credentials = userCredentials
user.credentials = accessToken
user.blockIds = []
user.muteIds = []
user.domainMutes = []
commit('setCurrentUser', user)
useServerSideStorageStore().setServerSideStorage(user)
commit('addNewUsers', [user])
dispatch('fetchEmoji')
getNotificationPermission().then((permission) =>
useInterfaceStore().setNotificationPermission(permission),
)
// Set our new backend interactor
commit(
'setBackendInteractor',
backendInteractorService(accessToken),
)
// Do server-side storage migrations
// Debug snippet to clean up storage and reset migrations
/*
// Reset wordfilter
Object.keys(
useServerSideStorageStore().prefsStorage.simple.muteFilters
).forEach(key => {
useServerSideStorageStore().unsetPreference({ path: 'simple.muteFilters.' + key, value: null })
})
// Reset flag to 0 to re-run migrations
useServerSideStorageStore().setFlag({ flag: 'configMigration', value: 0 })
/**/
const { configMigration } =
useServerSideStorageStore().flagStorage
declarations
.filter((x) => {
return (
x.store === 'server-side' &&
x.migrationNum > 0 &&
x.migrationNum > configMigration
)
})
.toSorted((a, b) => a.configMigration - b.configMigration)
.forEach((value) => {
value.migration(useServerSideStorageStore(), store.rootState)
useServerSideStorageStore().setFlag({
flag: 'configMigration',
value: value.migrationNum,
})
useServerSideStorageStore().pushServerSideStorage()
})
if (user.token) {
dispatch('setWsToken', user.token)
// Initialize the shout socket.
dispatch('initializeSocket')
}
const startPolling = () => {
// Start getting fresh posts.
dispatch('startFetchingTimeline', { timeline: 'friends' })
// Start fetching notifications
dispatch('startFetchingNotifications')
if (rootState.instance.pleromaChatMessagesAvailable) {
// Start fetching chats
dispatch('startFetchingChats')
}
}
dispatch('startFetchingLists')
dispatch('startFetchingBookmarkFolders')
if (user.locked) {
dispatch('startFetchingFollowRequests')
}
if (store.getters.mergedConfig.useStreamingApi) {
dispatch('fetchTimeline', { timeline: 'friends', since: null })
dispatch('fetchNotifications', { since: null })
dispatch('enableMastoSockets', true)
.catch((error) => {
console.error(
'Failed initializing MastoAPI Streaming socket',
error,
)
})
.then(() => {
dispatch('fetchChats', { latest: true })
setTimeout(
() => dispatch('setNotificationsSilence', false),
10000,
)
})
} else {
startPolling()
}
// Get user mutes
dispatch('fetchMutes')
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
// Fetch our friends
store.rootState.api.backendInteractor
.fetchFriends({ id: user.id })
.then((friends) => commit('addNewUsers', friends))
} else {
const response = data.error
// Authentication failed
commit('endLogin')
// remove authentication token on client/authentication errors
if ([400, 401, 403, 422].includes(response.status)) {
useOAuthStore().clearToken()
}
if (response.status === 401) {
reject(new Error('Wrong username or password'))
} else {
reject(new Error('An error occurred, please try again'))
}
}
commit('endLogin')
resolve()
})
.catch((error) => {
console.error(error)
commit('endLogin')
reject(new Error('Failed to connect to server, try again'))
})
})
},
},
}
export default users
diff --git a/test/e2e-playwright/playwright.config.mjs b/test/e2e-playwright/playwright.config.mjs
new file mode 100644
index 0000000000..04747ee776
--- /dev/null
+++ b/test/e2e-playwright/playwright.config.mjs
@@ -0,0 +1,50 @@
+/* global process */
+import { defineConfig, devices } from 'playwright/test'
+
+const baseURL = process.env.E2E_BASE_URL || 'http://localhost:8080'
+
+export default defineConfig({
+ testDir: './specs',
+ // Paths are resolved relative to this config file directory.
+ outputDir: 'test-results',
+ timeout: 60_000,
+ expect: {
+ timeout: 10_000,
+ },
+ retries: process.env.CI ? 1 : 0,
+ reporter: process.env.CI
+ ? [['line'], ['html', { outputFolder: 'playwright-report', open: 'never' }]]
+ : [
+ ['list'],
+ ['html', { outputFolder: 'playwright-report', open: 'never' }],
+ ],
+ use: {
+ baseURL,
+ screenshot: 'only-on-failure',
+ trace: 'on-first-retry',
+ video: 'retain-on-failure',
+ },
+ webServer: {
+ command: 'yarn dev -- --host 0.0.0.0 --port 8080 --strictPort',
+ url: baseURL,
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ env: {
+ ...process.env,
+ VITE_PROXY_TARGET:
+ process.env.VITE_PROXY_TARGET || 'http://localhost:4000',
+ VITE_PROXY_ORIGIN:
+ process.env.VITE_PROXY_ORIGIN ||
+ process.env.VITE_PROXY_TARGET ||
+ 'http://localhost:4000',
+ },
+ },
+ projects: [
+ {
+ name: 'firefox',
+ use: {
+ ...devices['Desktop Firefox'],
+ },
+ },
+ ],
+})
diff --git a/test/e2e-playwright/specs/admin_smoke.spec.js b/test/e2e-playwright/specs/admin_smoke.spec.js
new file mode 100644
index 0000000000..01fd38b295
--- /dev/null
+++ b/test/e2e-playwright/specs/admin_smoke.spec.js
@@ -0,0 +1,27 @@
+/* global process */
+import { expect, test } from 'playwright/test'
+
+const adminUsername = process.env.E2E_ADMIN_USERNAME || 'admin'
+const adminPassword = process.env.E2E_ADMIN_PASSWORD || 'adminadmin'
+
+test('admin can open the admin settings modal', async ({ page }) => {
+ await page.goto('/login')
+
+ const loginForm = page.locator('#main-scroller form.login-form')
+ await loginForm.locator('#username').fill(adminUsername)
+ await loginForm.locator('#password').fill(adminPassword)
+ await loginForm.getByRole('button', { name: 'Log in' }).click()
+
+ await page.waitForURL(/\/main\/friends/)
+
+ await expect(page.getByTitle('Administration')).toBeVisible()
+ await page.getByTitle('Administration').click()
+
+ const modal = page.locator('.settings-modal-panel')
+ await expect(
+ modal.getByRole('heading', { name: 'Administration' }),
+ ).toBeVisible()
+
+ await modal.getByRole('tab', { name: 'Emoji' }).click()
+ await expect(modal.getByText('Emoji packs')).toBeVisible()
+})
diff --git a/test/e2e-playwright/specs/user_smoke.spec.js b/test/e2e-playwright/specs/user_smoke.spec.js
new file mode 100644
index 0000000000..a71378c066
--- /dev/null
+++ b/test/e2e-playwright/specs/user_smoke.spec.js
@@ -0,0 +1,90 @@
+import { randomUUID } from 'node:crypto'
+import { expect, test } from 'playwright/test'
+
+const createTestUser = () => {
+ const id = randomUUID().slice(0, 8)
+ return {
+ username: `e2e_${id}`,
+ fullname: `E2E ${id}`,
+ email: `e2e_${id}@example.com`,
+ password: 'e2e-password',
+ }
+}
+
+const register = async (page, user) => {
+ await page.goto('/registration')
+
+ const registrationForm = page.locator('#main-scroller form.registration-form')
+ await registrationForm.locator('#sign-up-username').fill(user.username)
+ await registrationForm.locator('#sign-up-fullname').fill(user.fullname)
+ await registrationForm.locator('#email').fill(user.email)
+ await registrationForm.locator('#sign-up-password').fill(user.password)
+ await registrationForm
+ .locator('#sign-up-password-confirmation')
+ .fill(user.password)
+ await Promise.all([
+ page.waitForURL(/\/main\/friends/),
+ registrationForm.getByRole('button', { name: 'Register' }).click(),
+ ])
+}
+
+const logout = async (page) => {
+ await page.getByTitle('Log out').click()
+ const confirmLogout = page.getByRole('button', {
+ name: 'Logout',
+ exact: true,
+ })
+ if (await confirmLogout.isVisible()) {
+ await Promise.all([
+ page.waitForURL(/\/main\/(public|all)/),
+ confirmLogout.click(),
+ ])
+ } else {
+ await page.waitForURL(/\/main\/(public|all)/)
+ }
+
+ await expect(page.locator('#sidebar form.login-form')).toBeVisible()
+}
+
+const login = async (page, user) => {
+ await page.goto('/login')
+
+ const loginForm = page.locator('#main-scroller form.login-form')
+ await loginForm.locator('#username').fill(user.username)
+ await loginForm.locator('#password').fill(user.password)
+ await loginForm.getByRole('button', { name: 'Log in' }).click()
+
+ await page.waitForURL(/\/main\/friends/)
+}
+
+test('user can register, log out, and log back in', async ({ page }) => {
+ const user = createTestUser()
+ await register(page, user)
+ await expect(page.getByTitle('Log out')).toBeVisible()
+
+ await logout(page)
+
+ await login(page, user)
+ await expect(page.getByTitle('Log out')).toBeVisible()
+})
+
+test('user can post a status', async ({ page }) => {
+ const user = createTestUser()
+ await register(page, user)
+
+ const statusText = `Hello from ${user.username} (${randomUUID().slice(0, 8)})`
+ const composer = page.locator('#sidebar .user-panel .post-status-form')
+ await composer.locator('textarea.form-post-body').fill(statusText)
+ await Promise.all([
+ page.waitForResponse(
+ (resp) =>
+ resp.request().method() === 'POST' &&
+ resp.url().includes('/api/v1/statuses') &&
+ resp.ok(),
+ ),
+ composer.getByRole('button', { name: 'Post', exact: true }).click(),
+ ])
+
+ await page.goto(`/users/${user.username}`)
+ await expect(page.getByText(statusText)).toBeVisible()
+})
diff --git a/tools/e2e/run.sh b/tools/e2e/run.sh
new file mode 100644
index 0000000000..3c0ba8a362
--- /dev/null
+++ b/tools/e2e/run.sh
@@ -0,0 +1,35 @@
+#!/bin/sh
+
+set -u
+
+COMPOSE_FILE="docker-compose.e2e.yml"
+
+: "${COMPOSE_MENU:=false}"
+: "${PLEROMA_IMAGE:=git.pleroma.social:5050/pleroma/pleroma:stable}"
+: "${E2E_ADMIN_USERNAME:=admin}"
+: "${E2E_ADMIN_PASSWORD:=adminadmin}"
+: "${E2E_ADMIN_EMAIL:=admin@example.com}"
+
+cleanup() {
+ docker compose -f "$COMPOSE_FILE" down -v --remove-orphans >/dev/null 2>&1 || true
+}
+
+cleanup
+
+trap 'cleanup; exit 130' INT TERM
+
+set +e
+COMPOSE_MENU="$COMPOSE_MENU" docker compose -f "$COMPOSE_FILE" up --build --remove-orphans --attach e2e --no-log-prefix --abort-on-container-exit --exit-code-from e2e
+result="$?"
+set -e
+
+if [ "$result" -ne 0 ]; then
+ docker compose -f "$COMPOSE_FILE" cp e2e:/app/test/e2e-playwright/test-results test/e2e-playwright >/dev/null 2>&1 || true
+ docker compose -f "$COMPOSE_FILE" cp e2e:/app/test/e2e-playwright/playwright-report test/e2e-playwright >/dev/null 2>&1 || true
+ mkdir -p test/e2e-playwright/test-results
+ docker compose -f "$COMPOSE_FILE" logs --no-color pleroma db > test/e2e-playwright/test-results/docker-compose.log 2>/dev/null || true
+fi
+
+cleanup
+
+exit "$result"
diff --git a/vite.config.js b/vite.config.js
index 41468a089a..3632ba3c1f 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,235 +1,252 @@
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { defineConfig } from 'vite'
import eslint from 'vite-plugin-eslint2'
import stylelint from 'vite-plugin-stylelint'
+import { configDefaults } from 'vitest/config'
import { getCommitHash } from './build/commit_hash.js'
import copyPlugin from './build/copy_plugin.js'
import emojisPlugin from './build/emojis_plugin.js'
import mswPlugin from './build/msw_plugin.js'
import {
buildSwPlugin,
devSwPlugin,
swMessagesPlugin,
} from './build/sw_plugin.js'
const localConfigPath = '<projectRoot>/config/local.json'
+const normalizeTarget = (target) => {
+ if (!target || typeof target !== 'string') return target
+ return target.endsWith('/') ? target.replace(/\/$/, '') : target
+}
+
const getLocalDevSettings = async () => {
+ const envTarget = normalizeTarget(process.env.VITE_PROXY_TARGET)
+ const envOrigin = normalizeTarget(process.env.VITE_PROXY_ORIGIN)
try {
const settings = (await import('./config/local.json')).default
- if (settings.target && settings.target.endsWith('/')) {
- // replacing trailing slash since it can conflict with some apis
- // and that's how actual BE reports its url
- settings.target = settings.target.replace(/\/$/, '')
- }
+ settings.target = normalizeTarget(settings.target)
+ settings.origin = normalizeTarget(settings.origin)
+ if (envTarget) settings.target = envTarget
+ if (envOrigin) settings.origin = envOrigin
console.info(`Using local dev server settings (${localConfigPath}):`)
console.info(JSON.stringify(settings, null, 2))
return settings
} catch (e) {
+ if (!envTarget && !envOrigin) {
+ console.info(
+ `Local dev server settings not found (${localConfigPath}), using default`,
+ e,
+ )
+ return {}
+ }
+ const settings = { target: envTarget, origin: envOrigin }
console.info(
- `Local dev server settings not found (${localConfigPath}), using default`,
- e,
+ 'Using dev server settings from VITE_PROXY_TARGET/VITE_PROXY_ORIGIN:',
)
- return {}
+ console.info(JSON.stringify(settings, null, 2))
+ return settings
}
}
const projectRoot = dirname(fileURLToPath(import.meta.url))
const getTransformSWSettings = (settings) => {
if ('transformSW' in settings) {
return settings.transformSW
} else {
console.info(
'`transformSW` is not present in your local settings.\n' +
'This option controls whether the service worker should be bundled and transformed into iife (immediately-invoked function expression) during development.\n' +
'If set to false, the service worker will be served as-is, as an ES Module.\n' +
'Some browsers (e.g. Firefox) does not support ESM service workers.\n' +
'To avoid surprises, it is defaulted to true, but this can be slow.\n' +
'If you are using a browser that supports ESM service workers, you can set this option to false.\n' +
`No matter your choice, you can set the transformSW option in ${localConfigPath} in to disable this message.`,
)
return true
}
}
export default defineConfig(async ({ mode, command }) => {
const settings = await getLocalDevSettings()
const target = settings.target || 'http://localhost:4000/'
+ const origin = settings.origin || target
const transformSW = getTransformSWSettings(settings)
const proxy = {
'/api': {
target,
changeOrigin: true,
cookieDomainRewrite: 'localhost',
ws: true,
},
'/nodeinfo': {
target,
changeOrigin: true,
cookieDomainRewrite: 'localhost',
},
'/socket': {
target,
changeOrigin: true,
cookieDomainRewrite: 'localhost',
ws: true,
headers: {
- Origin: target,
+ Origin: origin,
},
},
'/oauth': {
target,
changeOrigin: true,
cookieDomainRewrite: 'localhost',
},
}
const swSrc = 'src/sw.js'
const swDest = 'sw-pleroma.js'
const alias = {
src: '/src',
components: '/src/components',
...(mode === 'test' ? { vue: 'vue/dist/vue.esm-bundler.js' } : {}),
}
return {
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement(tag) {
if (tag === 'pinch-zoom') {
return true
}
if (tag.startsWith('cropper-')) {
return true
}
return false
},
},
},
}),
vueJsx(),
devSwPlugin({ swSrc, swDest, transformSW, alias }),
buildSwPlugin({ swSrc, swDest }),
swMessagesPlugin(),
emojisPlugin(),
copyPlugin({
inUrl: '/static/ruffle',
inFs: resolve(projectRoot, 'node_modules/@ruffle-rs/ruffle'),
}),
eslint({
lintInWorker: true,
lintOnStart: true,
cacheLocation: resolve(projectRoot, 'node_modules/.cache/eslintcache'),
}),
stylelint({
lintInWorker: true,
lintOnStart: true,
cacheLocation: resolve(
projectRoot,
'node_modules/.cache/stylelintcache',
),
}),
...(mode === 'test' ? [mswPlugin()] : []),
],
optimizeDeps: {
// For unknown reasons, during vitest, vite will re-optimize the following
// deps, causing the test to reload, so add them here so that it will not
// reload during tests
include: [
'custom-event-polyfill',
'vue-i18n',
'@ungap/event-target',
'lodash.merge',
'body-scroll-lock',
'@kazvmoe-infra/pinch-zoom-element',
],
},
css: {
devSourcemap: true,
},
resolve: {
alias,
},
define: {
'process.env': JSON.stringify({
NODE_ENV:
mode === 'test'
? 'testing'
: command === 'serve'
? 'development'
: 'production',
HAS_MODULE_SERVICE_WORKER: command === 'serve' && !transformSW,
}),
COMMIT_HASH: JSON.stringify(
command === 'serve' ? 'DEV' : getCommitHash(),
),
DEV_OVERRIDES: JSON.stringify(command === 'serve' ? settings : undefined),
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false,
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false,
},
build: {
sourcemap: true,
rollupOptions: {
input: {
main: 'index.html',
},
output: {
inlineDynamicImports: false,
entryFileNames(chunkInfo) {
const id = chunkInfo.facadeModuleId
if (id.endsWith(swSrc)) {
return swDest
} else {
return 'static/js/[name].[hash].js'
}
},
chunkFileNames(chunkInfo) {
if (chunkInfo.facadeModuleId) {
if (
chunkInfo.facadeModuleId.includes(
'node_modules/@kazvmoe-infra/unicode-emoji-json/annotations/',
)
) {
return 'static/js/emoji-annotations/[name].[hash].js'
} else if (chunkInfo.facadeModuleId.includes('src/i18n/')) {
return 'static/js/i18n/[name].[hash].js'
}
}
return 'static/js/[name].[hash].js'
},
assetFileNames(assetInfo) {
const name = assetInfo.names?.[0] || ''
if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(name)) {
return 'static/img/[name].[hash][extname]'
} else if (/\.css$/.test(name)) {
return 'static/css/[name].[hash][extname]'
} else {
return 'static/misc/[name].[hash][extname]'
}
},
},
},
},
server: {
...(mode === 'test' ? {} : { proxy }),
port: Number(process.env.PORT) || 8080,
},
preview: {
proxy,
},
test: {
globals: true,
+ exclude: [...configDefaults.exclude, 'test/e2e-playwright/**'],
browser: {
enabled: true,
provider: 'playwright',
instances: [{ browser: 'firefox' }],
},
},
}
})

File Metadata

Mime Type
text/x-diff
Expires
Sun, Aug 30, 5:15 PM (1 d, 15 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1738086
Default Alt Text
(64 KB)

Event Timeline