mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-07-24 13:38:39 +02:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c900676be7 | ||
|
|
a6cde926ee | ||
|
|
e8db14fe33 | ||
|
|
e9b533637f | ||
|
|
8b97da500d | ||
|
|
37b42601ef | ||
|
|
5da4ec51ce | ||
|
|
4c65a87d5c | ||
|
|
0e5618dcd8 | ||
|
|
d063d851e1 | ||
|
|
6458e6d3d2 | ||
|
|
70953d8c82 | ||
|
|
2d9f63963e | ||
|
|
f12abca3fc | ||
|
|
bced308462 | ||
|
|
528d03fef3 | ||
|
|
b93c3133a9 | ||
|
|
8d9db8d103 | ||
|
|
08bbf9cd9d | ||
|
|
95af4812cd | ||
|
|
8ec547e302 | ||
|
|
32e4da8c92 | ||
|
|
0ce37004af | ||
|
|
527745b54e | ||
|
|
3c016314e6 | ||
|
|
59c7d0275c | ||
|
|
4883d0f60c | ||
|
|
9d9ab49664 | ||
|
|
82aec5f60c | ||
|
|
7ee5e1bdf6 | ||
|
|
3bb53d939d | ||
|
|
6f03467f35 | ||
|
|
b2f593f1c4 | ||
|
|
58dcda36a5 | ||
|
|
354e0bf793 | ||
|
|
0784373b61 | ||
|
|
2f219ea3cc | ||
|
|
56e60b8420 | ||
|
|
9b92b5de34 | ||
|
|
3417c0c721 | ||
|
|
cbda0360aa | ||
|
|
036bc081f0 | ||
|
|
e70e4b9d40 |
@@ -22,7 +22,7 @@
|
||||
<div v-if="entityName === 'collections' || entityName === 'playlists'" class="flex justify-center mt-4">
|
||||
{{ emptyMessageHelp }}
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/collections" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/playlists" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<div class="px-6 py-8 w-full text-sm rounded-lg bg-bg shadow-lg border border-black-300 overflow-y-auto overflow-x-hidden" style="max-height: 80vh">
|
||||
<div class="absolute top-0 right-0 p-4">
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/media-item-shares" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/public-shares#media-item-shares" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<div class="text-sm flex items-center justify-center text-gray-200">
|
||||
<p>{{ $strings.MessageBookshelfNoCollectionsHelp }}</p>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/collections" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/playlists" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<div class="flex items-center justify-between md:justify-start mb-4">
|
||||
<p class="text-sm text-gray-300 pr-2">{{ $strings.LabelMetadataOrderOfPrecedenceDescription }}</p>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex">
|
||||
<a href="https://www.audiobookshelf.org/guides/book-scanner" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/book-library/book-metadata" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<div class="text-sm flex items-center justify-center text-gray-200">
|
||||
<p>{{ $strings.MessageNoUserPlaylistsHelp }}</p>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/collections" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/playlists" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</div>
|
||||
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/api-keys" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/server-management/api-keys" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<ui-checkbox v-model="enableOpenIDAuth" checkbox-bg="bg" />
|
||||
<p class="text-lg pl-4">{{ $strings.HeaderOpenIDConnectAuthentication }}</p>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/oidc_authentication" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/server-management/oidc-authentication" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<app-settings-content :header-text="$strings.HeaderEmailSettings" :description="''">
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/send_to_ereader" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/book-library/ebooks" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
</template>
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/custom-metadata-providers" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/community/community-providers" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<app-settings-content :header-text="$strings.HeaderLibraries">
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/library_creation" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/overview" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<app-settings-content :header-text="$strings.HeaderLogs" :description="$strings.MessageLogsDescription">
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/server_logs" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/server-management/server-logs" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<app-settings-content :header-text="$strings.HeaderRSSFeeds">
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/rss_feeds" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/libraries/common-content/public-shares#rss-feed" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</div>
|
||||
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides/users" target="_blank" class="inline-flex">
|
||||
<a href="https://audiobookshelf.org/docs/documentation/server-management/user-management" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
@@ -31,6 +31,11 @@ if (isDev || options['prod-with-dev-env']) {
|
||||
if (devEnv.AllowIframe) process.env.ALLOW_IFRAME = '1'
|
||||
if (devEnv.BackupPath) process.env.BACKUP_PATH = devEnv.BackupPath
|
||||
if (devEnv.ReactClientPath) process.env.REACT_CLIENT_PATH = devEnv.ReactClientPath
|
||||
if (devEnv.AllowedDevOrigins) {
|
||||
process.env.ALLOWED_DEV_ORIGINS = Array.isArray(devEnv.AllowedDevOrigins)
|
||||
? devEnv.AllowedDevOrigins.join(',')
|
||||
: String(devEnv.AllowedDevOrigins)
|
||||
}
|
||||
process.env.SOURCE = 'local'
|
||||
process.env.ROUTER_BASE_PATH = devEnv.RouterBasePath ?? '/audiobookshelf'
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
<br />
|
||||
<a href="https://audiobookshelf.org/docs">Documentation</a>
|
||||
·
|
||||
<a href="https://audiobookshelf.org/guides">User Guides</a>
|
||||
·
|
||||
<a href="https://audiobookshelf.org/support">Support</a>
|
||||
·
|
||||
<a href="https://audiobooks.dev/">Demo</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -57,21 +57,17 @@ Try it out on the [Google Play Store](https://play.google.com/store/apps/details
|
||||
|
||||
Using Test Flight: https://testflight.apple.com/join/wiic7QIW **_(beta is full)_**
|
||||
|
||||
### Build your own tools & clients
|
||||
|
||||
Check out the [API documentation](https://api.audiobookshelf.org/)
|
||||
|
||||
<br />
|
||||
|
||||
<img alt="Library Screenshot" src="https://github.com/advplyr/audiobookshelf/raw/master/images/DemoLibrary.png" />
|
||||
|
||||
<br />
|
||||
|
||||
# Organizing your audiobooks
|
||||
# Organizing your media
|
||||
|
||||
#### Directory structure and folder names are important to Audiobookshelf!
|
||||
|
||||
See [documentation](https://audiobookshelf.org/docs#book-directory-structure) for supported directory structure, folder naming conventions, and audio file metadata usage.
|
||||
See [library docs](https://audiobookshelf.org/docs/category/libraries) for supported directory structures, folder naming conventions, and audio file metadata usage.
|
||||
|
||||
<br />
|
||||
|
||||
@@ -87,275 +83,24 @@ See [install docs](https://www.audiobookshelf.org/docs)
|
||||
|
||||
#### Note: Using a subfolder is supported with no additional changes but the path must be `/audiobookshelf` (this is not changeable). See [discussion](https://github.com/advplyr/audiobookshelf/discussions/3535)
|
||||
|
||||
### NGINX Proxy Manager
|
||||
See [reverse proxy docs](https://audiobookshelf.org/docs/category/reverse-proxy)
|
||||
|
||||
Toggle websockets support.
|
||||
|
||||
<img alt="NGINX Web socket" src="https://user-images.githubusercontent.com/67830747/153679106-b2a7f5b9-0702-48c6-9740-b26b401986e9.png" />
|
||||
|
||||
### NGINX Reverse Proxy
|
||||
|
||||
Add this to the site config file on your nginx server after you have changed the relevant parts in the <> brackets, and inserted your certificate paths.
|
||||
|
||||
```bash
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name <sub>.<domain>.<tld>;
|
||||
|
||||
access_log /var/log/nginx/audiobookshelf.access.log;
|
||||
error_log /var/log/nginx/audiobookshelf.error.log;
|
||||
|
||||
ssl_certificate /path/to/certificate;
|
||||
ssl_certificate_key /path/to/key;
|
||||
|
||||
location / {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_pass http://<URL_to_forward_to>;
|
||||
proxy_redirect http:// https://;
|
||||
|
||||
# Prevent 413 Request Entity Too Large error
|
||||
# by increasing the maximum allowed size of the client request body
|
||||
# For example, set it to 10 GiB
|
||||
client_max_body_size 10240M;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Apache Reverse Proxy
|
||||
|
||||
Add this to the site config file on your Apache server after you have changed the relevant parts in the <> brackets, and inserted your certificate paths.
|
||||
|
||||
For this to work you must enable at least the following mods using `a2enmod`:
|
||||
|
||||
- `ssl`
|
||||
- `proxy`
|
||||
- `proxy_http`
|
||||
- `proxy_balancer`
|
||||
- `proxy_wstunnel`
|
||||
- `rewrite`
|
||||
|
||||
```bash
|
||||
<IfModule mod_ssl.c>
|
||||
<VirtualHost *:443>
|
||||
ServerName <sub>.<domain>.<tld>
|
||||
|
||||
ErrorLog ${APACHE_LOG_DIR}/error.log
|
||||
CustomLog ${APACHE_LOG_DIR}/access.log combined
|
||||
|
||||
ProxyPreserveHost On
|
||||
ProxyPass / http://localhost:<audiobookshelf_port>/
|
||||
RewriteEngine on
|
||||
RewriteCond %{HTTP:Upgrade} websocket [NC]
|
||||
RewriteCond %{HTTP:Connection} upgrade [NC]
|
||||
RewriteRule ^/?(.*) "ws://localhost:<audiobookshelf_port>/$1" [P,L]
|
||||
|
||||
# unless you're doing something special this should be generated by a
|
||||
# tool like certbot by let's encrypt
|
||||
SSLCertificateFile /path/to/cert/file
|
||||
SSLCertificateKeyFile /path/to/key/file
|
||||
</VirtualHost>
|
||||
</IfModule>
|
||||
```
|
||||
|
||||
If using Apache >= 2.4.47 you can use the following, without having to use any of the `RewriteEngine`, `RewriteCond`, or `RewriteRule` directives. For example:
|
||||
|
||||
```xml
|
||||
<Location /audiobookshelf>
|
||||
ProxyPreserveHost on
|
||||
ProxyPass http://localhost:<audiobookshelf_port>/audiobookshelf upgrade=websocket
|
||||
ProxyPassReverse http://localhost:<audiobookshelf_port>/audiobookshelf
|
||||
</Location>
|
||||
```
|
||||
|
||||
Some SSL certificates like those signed by Let's Encrypt require ACME validation. To allow Let's Encrypt to write and confirm the ACME challenge, edit your VirtualHost definition to prevent proxying traffic that queries `/.well-known` and instead serve that directly:
|
||||
|
||||
```bash
|
||||
<VirtualHost *:443>
|
||||
# ...
|
||||
|
||||
# create the directory structure /.well-known/acme-challenges
|
||||
# within DocumentRoot and give the HTTP user recursive write
|
||||
# access to it.
|
||||
DocumentRoot /path/to/local/directory
|
||||
|
||||
ProxyPreserveHost On
|
||||
ProxyPass /.well-known !
|
||||
ProxyPass / http://localhost:<audiobookshelf_port>/
|
||||
|
||||
# ...
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
### SWAG Reverse Proxy
|
||||
|
||||
[See LinuxServer.io config sample](https://github.com/linuxserver/reverse-proxy-confs/blob/master/audiobookshelf.subdomain.conf.sample)
|
||||
|
||||
### Synology NAS Reverse Proxy Setup (DSM 7+/Quickconnect)
|
||||
|
||||
1. **Open Control Panel**
|
||||
|
||||
- Navigate to `Login Portal > Advanced`.
|
||||
|
||||
2. **General Tab**
|
||||
|
||||
- Click `Reverse Proxy` > `Create`.
|
||||
|
||||
| Setting | Value |
|
||||
| ------------------ | -------------- |
|
||||
| Reverse Proxy Name | audiobookshelf |
|
||||
|
||||
3. **Source Configuration**
|
||||
|
||||
| Setting | Value |
|
||||
| ---------------------- | ---------------------------------------- |
|
||||
| Protocol | HTTPS |
|
||||
| Hostname | `<sub>.<quickconnectdomain>.synology.me` |
|
||||
| Port | 443 |
|
||||
| Access Control Profile | Leave as is |
|
||||
|
||||
- Example Hostname: `audiobookshelf.mydomain.synology.me`
|
||||
|
||||
4. **Destination Configuration**
|
||||
|
||||
| Setting | Value |
|
||||
| -------- | ----------- |
|
||||
| Protocol | HTTP |
|
||||
| Hostname | Your NAS IP |
|
||||
| Port | 13378 |
|
||||
|
||||
5. **Custom Header Tab**
|
||||
|
||||
- Go to `Create > Websocket`.
|
||||
- Configure Headers (leave as is):
|
||||
|
||||
| Header Name | Value |
|
||||
| ----------- | --------------------- |
|
||||
| Upgrade | `$http_upgrade` |
|
||||
| Connection | `$connection_upgrade` |
|
||||
|
||||
6. **Advanced Settings Tab**
|
||||
- Leave as is.
|
||||
|
||||
### [Traefik Reverse Proxy](https://doc.traefik.io/traefik/)
|
||||
|
||||
Middleware relating to CORS will cause the app to report Unknown Error when logging in. To prevent this don't apply any of the following headers to the router for this site:
|
||||
|
||||
<ul>
|
||||
<li>accessControlAllowMethods</li>
|
||||
<li>accessControlAllowOriginList</li>
|
||||
<li>accessControlMaxAge</li>
|
||||
</ul>
|
||||
|
||||
From [@Dondochaka](https://discord.com/channels/942908292873723984/942914154254176257/945074590374318170) and [@BeastleeUK](https://discord.com/channels/942908292873723984/942914154254176257/970366039294611506) <br />
|
||||
|
||||
### Example Caddyfile - [Caddy Reverse Proxy](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy)
|
||||
|
||||
```
|
||||
subdomain.domain.com {
|
||||
encode gzip zstd
|
||||
reverse_proxy <LOCAL_IP>:<PORT>
|
||||
}
|
||||
```
|
||||
|
||||
### HAProxy
|
||||
|
||||
Below is a generic HAProxy config, using `audiobookshelf.YOUR_DOMAIN.COM`.
|
||||
|
||||
To use `http2`, `ssl` is needed.
|
||||
|
||||
```make
|
||||
global
|
||||
# ... (your global settings go here)
|
||||
|
||||
defaults
|
||||
mode http
|
||||
# ... (your default settings go here)
|
||||
|
||||
frontend my_frontend
|
||||
# Bind to port 443, enable SSL, and specify the certificate list file
|
||||
bind :443 name :443 ssl crt-list /path/to/cert.crt_list alpn h2,http/1.1
|
||||
mode http
|
||||
|
||||
# Define an ACL for subdomains starting with "audiobookshelf"
|
||||
acl is_audiobookshelf hdr_beg(host) -i audiobookshelf
|
||||
|
||||
# Use the ACL to route traffic to audiobookshelf_backend if the condition is met,
|
||||
# otherwise, use the default_backend
|
||||
use_backend audiobookshelf_backend if is_audiobookshelf
|
||||
default_backend default_backend
|
||||
|
||||
backend audiobookshelf_backend
|
||||
mode http
|
||||
# ... (backend settings for audiobookshelf go here)
|
||||
|
||||
# Define the server for the audiobookshelf backend
|
||||
server audiobookshelf_server 127.0.0.99:13378
|
||||
|
||||
backend default_backend
|
||||
mode http
|
||||
# ... (default backend settings go here)
|
||||
|
||||
# Define the server for the default backend
|
||||
server default_server 127.0.0.123:8081
|
||||
|
||||
```
|
||||
|
||||
### pfSense and HAProxy
|
||||
|
||||
For pfSense the inputs are graphical, and `Health checking` is enabled.
|
||||
|
||||
#### Frontend, Default backend, access control lists and actions
|
||||
|
||||
##### Access Control lists
|
||||
|
||||
| Name | Expression | CS | Not | Value |
|
||||
| :------------: | :---------------: | :-: | :-: | :-------------: |
|
||||
| audiobookshelf | Host starts with: | | | audiobookshelf. |
|
||||
|
||||
##### Actions
|
||||
|
||||
The `condition acl names` needs to match the name above `audiobookshelf`.
|
||||
|
||||
| Action | Parameters | Condition acl names |
|
||||
| :-----------: | :------------: | :-----------------: |
|
||||
| `Use Backend` | audiobookshelf | audiobookshelf |
|
||||
|
||||
#### Backend
|
||||
|
||||
The `Name` needs to match the `Parameters` above `audiobookshelf`.
|
||||
|
||||
| Name | audiobookshelf |
|
||||
| ---- | -------------- |
|
||||
|
||||
##### Server list:
|
||||
|
||||
| Name | Expression | CS | Not | Value |
|
||||
| :------------: | :---------------: | :-: | :-: | :-------------: |
|
||||
| audiobookshelf | Host starts with: | | | audiobookshelf. |
|
||||
|
||||
##### Health checking:
|
||||
|
||||
Health checking is enabled by default. `Http check method` of `OPTIONS` is not supported on Audiobookshelf. If Health check fails, data will not be forwared. Need to do one of following:
|
||||
|
||||
- To disable: Change `Health check method` to `none`.
|
||||
- To make Health checking function: Change `Http check method` to `HEAD` or `GET`.
|
||||
|
||||
# Run from source
|
||||
<br />
|
||||
|
||||
# Contributing
|
||||
|
||||
This application is built using [NodeJs](https://nodejs.org/).
|
||||
See [contributing docs](https://audiobookshelf.org/docs/contributing/general/)
|
||||
|
||||
### Localization
|
||||
|
||||
Thank you to [Weblate](https://hosted.weblate.org/engage/audiobookshelf/) for hosting our localization infrastructure pro-bono. If you want to see Audiobookshelf in your language, please help us localize. Additional information on helping with the translations [here](https://www.audiobookshelf.org/faq#how-do-i-help-with-translations). <a href="https://hosted.weblate.org/engage/audiobookshelf/"> <img src="https://hosted.weblate.org/widget/audiobookshelf/abs-web-client/multi-auto.svg" alt="Translation status" /> </a>
|
||||
Thank you to [Weblate](https://hosted.weblate.org/engage/audiobookshelf/) for hosting our localization infrastructure pro-bono. If you want to see Audiobookshelf in your language, please help us localize. Additional information on helping with the translations [here](https://www.audiobookshelf.org/faq#how-do-i-help-with-translations).
|
||||
<a href="https://hosted.weblate.org/engage/audiobookshelf/"> <img src="https://hosted.weblate.org/widget/audiobookshelf/abs-web-client/multi-auto.svg" alt="Translation status" /> </a>
|
||||
|
||||
<br />
|
||||
|
||||
# Run from source
|
||||
|
||||
This application is built using [NodeJs](https://nodejs.org/).
|
||||
|
||||
### Dev Container Setup
|
||||
|
||||
@@ -447,6 +192,3 @@ If you are using VSCode, this project includes a couple of pre-defined targets t
|
||||
- `Debug client (nuxt)`—Run the client with live reload.
|
||||
- `Debug server and client (nuxt)`—Runs both the preceding two debug targets.
|
||||
|
||||
# How to Support
|
||||
|
||||
[See the incomplete "How to Support" page](https://www.audiobookshelf.org/support)
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ class Auth {
|
||||
* @param {import('./models/User')} user
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @returns {Promise<string>} accessToken only if user is current user and refresh token is valid
|
||||
* @returns {Promise<{ accessToken:string, refreshToken:string }|null>} new tokens for the current session if kept alive
|
||||
*/
|
||||
async invalidateJwtSessionsForUser(user, req, res) {
|
||||
return this.tokenManager.invalidateJwtSessionsForUser(user, req, res)
|
||||
|
||||
+5
-3
@@ -14,6 +14,7 @@ const { version } = require('../package.json')
|
||||
const is = require('./libs/requestIp/isJs')
|
||||
const fileUtils = require('./utils/fileUtils')
|
||||
const { toNumber } = require('./utils/index')
|
||||
const { getRequestOrigin } = require('./utils/requestUtils')
|
||||
const Logger = require('./Logger')
|
||||
|
||||
const Auth = require('./Auth')
|
||||
@@ -288,10 +289,9 @@ class Server {
|
||||
// if RouterBasePath is set, modify all requests to include the base path
|
||||
app.use((req, res, next) => {
|
||||
const urlStartsWithRouterBasePath = req.url.startsWith(global.RouterBasePath)
|
||||
const host = req.get('host')
|
||||
const protocol = req.secure || req.get('x-forwarded-proto') === 'https' ? 'https' : 'http'
|
||||
const { origin } = getRequestOrigin(req)
|
||||
const prefix = urlStartsWithRouterBasePath ? global.RouterBasePath : ''
|
||||
req.originalHostPrefix = `${protocol}://${host}${prefix}`
|
||||
req.originalHostPrefix = `${origin}${prefix}`
|
||||
if (!urlStartsWithRouterBasePath) {
|
||||
req.url = `${global.RouterBasePath}${req.url}`
|
||||
}
|
||||
@@ -302,7 +302,9 @@ class Server {
|
||||
|
||||
this.server = http.createServer(app)
|
||||
|
||||
// Skip file upload parsing for internal-api routes (Next.js proxies read multipart bodies).
|
||||
router.use(
|
||||
/^(?!\/internal-api).*/,
|
||||
fileUpload({
|
||||
defCharset: 'utf8',
|
||||
defParamCharset: 'utf8',
|
||||
|
||||
@@ -4,6 +4,7 @@ const OpenIDClient = require('openid-client')
|
||||
const axios = require('axios')
|
||||
const Database = require('../Database')
|
||||
const Logger = require('../Logger')
|
||||
const { getRequestOrigin } = require('../utils/requestUtils')
|
||||
|
||||
/**
|
||||
* OpenID Connect authentication strategy
|
||||
@@ -289,8 +290,8 @@ class OidcAuthStrategy {
|
||||
const sessionKey = strategy._key
|
||||
|
||||
try {
|
||||
const protocol = req.secure || req.get('x-forwarded-proto') === 'https' ? 'https' : 'http'
|
||||
const hostUrl = new URL(`${protocol}://${req.get('host')}`)
|
||||
const { origin } = getRequestOrigin(req)
|
||||
const hostUrl = new URL(origin)
|
||||
const isMobileFlow = req.query.response_type === 'code' || req.query.redirect_uri || req.query.code_challenge
|
||||
|
||||
// Only allow code flow (for mobile clients)
|
||||
@@ -394,11 +395,10 @@ class OidcAuthStrategy {
|
||||
let postLogoutRedirectUri = null
|
||||
|
||||
if (authMethod === 'openid') {
|
||||
const protocol = req.secure || req.get('x-forwarded-proto') === 'https' ? 'https' : 'http'
|
||||
const host = req.get('host')
|
||||
const { origin } = getRequestOrigin(req)
|
||||
// TODO: ABS does currently not support subfolders for installation
|
||||
// If we want to support it we need to include a config for the serverurl
|
||||
postLogoutRedirectUri = `${protocol}://${host}${global.RouterBasePath}/login`
|
||||
postLogoutRedirectUri = `${origin}${global.RouterBasePath}/login`
|
||||
}
|
||||
// else for openid-mobile we keep postLogoutRedirectUri on null
|
||||
// nice would be to redirect to the app here, but for example Authentik does not implement
|
||||
@@ -515,42 +515,33 @@ class OidcAuthStrategy {
|
||||
if (!callbackUrl) return false
|
||||
|
||||
try {
|
||||
// Handle relative URLs - these are always safe if they start with router base path
|
||||
if (callbackUrl.startsWith('/')) {
|
||||
// Only allow relative paths that start with the router base path
|
||||
if (callbackUrl.startsWith(global.RouterBasePath + '/')) {
|
||||
return true
|
||||
}
|
||||
// Reject protocol-relative (//host) and backslash-prefixed (/\host) values,
|
||||
// which browsers resolve to a cross-origin absolute URL.
|
||||
if (callbackUrl.startsWith('//') || callbackUrl.startsWith('/\\')) {
|
||||
Logger.warn(`[OidcAuth] Rejected protocol-relative callback URL: ${callbackUrl}`)
|
||||
return false
|
||||
}
|
||||
|
||||
const { origin: serverOrigin } = getRequestOrigin(req)
|
||||
const resolvedUrl = callbackUrl.startsWith('/') ? new URL(callbackUrl, serverOrigin) : new URL(callbackUrl)
|
||||
|
||||
if (resolvedUrl.origin !== serverOrigin) {
|
||||
Logger.warn(`[OidcAuth] Rejected callback URL to different origin: ${callbackUrl} (expected ${serverOrigin})`)
|
||||
return false
|
||||
}
|
||||
|
||||
const pathname = decodeURIComponent(resolvedUrl.pathname)
|
||||
if (pathname.startsWith('//') || pathname.startsWith('/\\')) {
|
||||
Logger.warn(`[OidcAuth] Rejected protocol-relative callback URL path: ${callbackUrl}`)
|
||||
return false
|
||||
}
|
||||
|
||||
if (!resolvedUrl.pathname.startsWith(global.RouterBasePath + '/')) {
|
||||
Logger.warn(`[OidcAuth] Rejected callback URL outside router base path: ${callbackUrl}`)
|
||||
return false
|
||||
}
|
||||
|
||||
// For absolute URLs, ensure they point to the same origin
|
||||
const callbackUrlObj = new URL(callbackUrl)
|
||||
// NPM appends both http and https in x-forwarded-proto sometimes, so we need to check for both
|
||||
const xfp = (req.get('x-forwarded-proto') || '').toLowerCase()
|
||||
const currentProtocol =
|
||||
req.secure ||
|
||||
xfp
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.includes('https')
|
||||
? 'https'
|
||||
: 'http'
|
||||
const currentHost = req.get('host')
|
||||
|
||||
// Check if protocol and host match exactly
|
||||
if (callbackUrlObj.protocol === currentProtocol + ':' && callbackUrlObj.host === currentHost) {
|
||||
// Additional check: ensure path starts with router base path
|
||||
if (callbackUrlObj.pathname.startsWith(global.RouterBasePath + '/')) {
|
||||
return true
|
||||
}
|
||||
Logger.warn(`[OidcAuth] Rejected same-origin callback URL outside router base path: ${callbackUrl}`)
|
||||
return false
|
||||
}
|
||||
|
||||
Logger.warn(`[OidcAuth] Rejected callback URL to different origin: ${callbackUrl} (expected ${currentProtocol}://${currentHost})`)
|
||||
return false
|
||||
return true
|
||||
} catch (error) {
|
||||
Logger.error(`[OidcAuth] Invalid callback URL format: ${callbackUrl}`, error)
|
||||
return false
|
||||
|
||||
@@ -6,6 +6,7 @@ const Logger = require('../Logger')
|
||||
|
||||
const requestIp = require('../libs/requestIp')
|
||||
const jwt = require('../libs/jsonwebtoken')
|
||||
const { isRequestSecure } = require('../utils/requestUtils')
|
||||
|
||||
class TokenManager {
|
||||
/** @type {string} JWT secret key */
|
||||
@@ -16,6 +17,8 @@ class TokenManager {
|
||||
this.RefreshTokenExpiry = parseInt(process.env.REFRESH_TOKEN_EXPIRY) || 30 * 24 * 60 * 60 // 30 days
|
||||
/** @type {number} Access token expiry in seconds */
|
||||
this.AccessTokenExpiry = parseInt(process.env.ACCESS_TOKEN_EXPIRY) || 1 * 60 * 60 // 1 hour
|
||||
/** @type {number} Grace period in seconds during which a rotated (old) refresh token is still accepted */
|
||||
this.RefreshTokenGracePeriod = parseInt(process.env.REFRESH_TOKEN_GRACE_PERIOD) || 10 * 60 // 10 minutes
|
||||
|
||||
if (parseInt(process.env.REFRESH_TOKEN_EXPIRY) > 0) {
|
||||
Logger.info(`[TokenManager] Refresh token expiry set from ENV variable to ${this.RefreshTokenExpiry} seconds`)
|
||||
@@ -23,6 +26,9 @@ class TokenManager {
|
||||
if (parseInt(process.env.ACCESS_TOKEN_EXPIRY) > 0) {
|
||||
Logger.info(`[TokenManager] Access token expiry set from ENV variable to ${this.AccessTokenExpiry} seconds`)
|
||||
}
|
||||
if (parseInt(process.env.REFRESH_TOKEN_GRACE_PERIOD) > 0) {
|
||||
Logger.info(`[TokenManager] Refresh token grace period set from ENV variable to ${this.RefreshTokenGracePeriod} seconds`)
|
||||
}
|
||||
}
|
||||
|
||||
get TokenSecret() {
|
||||
@@ -59,13 +65,25 @@ class TokenManager {
|
||||
setRefreshTokenCookie(req, res, refreshToken) {
|
||||
res.cookie('refresh_token', refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: req.secure || req.get('x-forwarded-proto') === 'https',
|
||||
secure: isRequestSecure(req),
|
||||
sameSite: 'lax',
|
||||
maxAge: this.RefreshTokenExpiry * 1000,
|
||||
path: '/'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a decoded JWT payload may authenticate API/socket requests (not refresh-only credentials).
|
||||
*
|
||||
* @param {Object} decoded
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isBearerAccessTokenPayload(decoded) {
|
||||
if (!decoded?.userId) return false
|
||||
if (decoded.type === 'refresh') return false
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a jwt token for a given user
|
||||
* Used to authenticate socket connections
|
||||
@@ -76,7 +94,9 @@ class TokenManager {
|
||||
*/
|
||||
static validateAccessToken(token) {
|
||||
try {
|
||||
return jwt.verify(token, TokenManager.TokenSecret)
|
||||
const decoded = jwt.verify(token, TokenManager.TokenSecret)
|
||||
if (!TokenManager.isBearerAccessTokenPayload(decoded)) return null
|
||||
return decoded
|
||||
} catch (err) {
|
||||
return null
|
||||
}
|
||||
@@ -199,9 +219,13 @@ class TokenManager {
|
||||
let lastRefreshTokenExpiresAt = null
|
||||
if (gracePeriod) {
|
||||
// Set grace period of old refresh token in case of race condition in token rotation.
|
||||
// This grace period may need to be longer if fetching the user data takes longer due to large progress objects
|
||||
// During this window a retry with the old refresh token returns the already-rotated
|
||||
// current token instead of failing, so a client that never received the rotation
|
||||
// response (e.g. dropped/suspended mobile request) can still recover the session.
|
||||
// Configurable via REFRESH_TOKEN_GRACE_PERIOD; may need to be longer if fetching the
|
||||
// user data takes longer due to large progress objects.
|
||||
lastRefreshToken = previousRefreshToken
|
||||
lastRefreshTokenExpiresAt = new Date(Date.now() + 60 * 1000) // 1 minute grace period
|
||||
lastRefreshTokenExpiresAt = new Date(Date.now() + this.RefreshTokenGracePeriod * 1000)
|
||||
}
|
||||
|
||||
// Only update if this session row still has the refresh token we read
|
||||
@@ -282,7 +306,11 @@ class TokenManager {
|
||||
|
||||
done(null, user)
|
||||
} else {
|
||||
// JWT based authentication
|
||||
// JWT based authentication — refresh tokens are only valid at POST /auth/refresh
|
||||
if (!TokenManager.isBearerAccessTokenPayload(jwt_payload)) {
|
||||
done(null, null)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the jwt is expired
|
||||
if (jwt_payload.exp && jwt_payload.exp < Date.now() / 1000) {
|
||||
@@ -436,14 +464,19 @@ class TokenManager {
|
||||
* @param {import('../models/User')} user
|
||||
* @param {import('express').Request} req
|
||||
* @param {import('express').Response} res
|
||||
* @returns {Promise<string>} accessToken only if user is current user and refresh token is valid
|
||||
* @returns {Promise<{ accessToken:string, refreshToken:string }|null>} new tokens for the current session if kept alive
|
||||
*/
|
||||
async invalidateJwtSessionsForUser(user, req, res) {
|
||||
const currentRefreshToken = req.cookies.refresh_token
|
||||
const currentRefreshToken = req.cookies.refresh_token || req.headers['x-refresh-token']
|
||||
if (req.user.id === user.id && currentRefreshToken) {
|
||||
// Current user is the same as the user to invalidate sessions for
|
||||
// So rotate token for current session
|
||||
const currentSession = await Database.sessionModel.findOne({ where: { refreshToken: currentRefreshToken } })
|
||||
const currentSession = await Database.sessionModel.findOne({
|
||||
where: {
|
||||
userId: user.id,
|
||||
[Op.or]: [{ refreshToken: currentRefreshToken }, { lastRefreshToken: currentRefreshToken }]
|
||||
}
|
||||
})
|
||||
if (currentSession) {
|
||||
const newTokens = await this.rotateTokensForSession(currentSession, user, req, res, false)
|
||||
|
||||
@@ -457,7 +490,10 @@ class TokenManager {
|
||||
}
|
||||
})
|
||||
|
||||
return newTokens.accessToken
|
||||
return {
|
||||
accessToken: newTokens.accessToken,
|
||||
refreshToken: newTokens.refreshToken
|
||||
}
|
||||
} else {
|
||||
Logger.error(`[TokenManager] No session found to rotate tokens`)
|
||||
}
|
||||
|
||||
@@ -1432,14 +1432,17 @@ class LibraryController {
|
||||
|
||||
const itemIds = req.query.ids.split(',')
|
||||
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'libraryId', 'path', 'isFile'],
|
||||
where: {
|
||||
id: itemIds,
|
||||
libraryId: req.library.id
|
||||
}
|
||||
const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({
|
||||
id: itemIds,
|
||||
libraryId: req.library.id
|
||||
})
|
||||
|
||||
for (const libraryItem of libraryItems) {
|
||||
if (!req.user.checkCanAccessLibraryItem(libraryItem)) {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
}
|
||||
|
||||
if (libraryItems.length < itemIds.length) {
|
||||
Logger.warn(`[LibraryController] User "${req.user.username}" requested ${itemIds.length} items but only ${libraryItems.length} are in library "${req.library.id}"`)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,49 @@ class MeController {
|
||||
res.json(req.user.toOldJSONForBrowser())
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/me/progress
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
getAllMediaProgress(req, res) {
|
||||
const mediaProgress = req.user.mediaProgresses?.map((mp) => mp.getOldMediaProgress()) || []
|
||||
res.json({ mediaProgress })
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/me/bookmarks
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
getAllBookmarks(req, res) {
|
||||
const bookmarks = req.user.bookmarks?.map((bookmark) => ({ ...bookmark })) || []
|
||||
res.json({ bookmarks })
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/me/bookmarks/:libraryItemId
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getBookmarksForLibraryItem(req, res) {
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(req.params.libraryItemId)
|
||||
if (!libraryItem) {
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (!req.user.checkCanAccessLibraryItem(libraryItem)) {
|
||||
Logger.error(`[MeController] User "${req.user.username}" attempted to access bookmarks for library item "${req.params.libraryItemId}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
const bookmarks = req.user.bookmarks?.filter((bookmark) => bookmark.libraryItemId === libraryItem.id).map((bookmark) => ({ ...bookmark })) || []
|
||||
res.json({ bookmarks })
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/me/listening-sessions
|
||||
*
|
||||
@@ -308,6 +351,8 @@ class MeController {
|
||||
* User change password. Requires current password.
|
||||
* Guest users cannot change password.
|
||||
*
|
||||
* Invalidates all other JWT sessions for the user. If using x-refresh-token, returns new tokens for the current session.
|
||||
*
|
||||
* @this import('../routers/ApiRouter')
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
@@ -330,6 +375,24 @@ class MeController {
|
||||
return res.status(400).send(result.error)
|
||||
}
|
||||
|
||||
const shouldReturnTokens = !!req.headers['x-refresh-token']
|
||||
const newTokens = await this.auth.invalidateJwtSessionsForUser(req.user, req, res)
|
||||
|
||||
if (newTokens?.accessToken) {
|
||||
Logger.info(`[MeController] Invalidated other JWT sessions for user ${req.user.username} after password change`)
|
||||
if (shouldReturnTokens) {
|
||||
return res.json({
|
||||
success: true,
|
||||
user: {
|
||||
accessToken: newTokens.accessToken,
|
||||
refreshToken: newTokens.refreshToken
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
Logger.info(`[MeController] Invalidated all JWT sessions for user ${req.user.username} after password change`)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
|
||||
@@ -437,6 +437,17 @@ class PodcastController {
|
||||
}
|
||||
|
||||
updatePayload[key] = req.body[key]
|
||||
} else if (key === 'enclosure') {
|
||||
const enclosure = req.body.enclosure
|
||||
if (enclosure === null) {
|
||||
updatePayload.enclosureURL = null
|
||||
updatePayload.enclosureSize = null
|
||||
updatePayload.enclosureType = null
|
||||
} else if (typeof enclosure === 'object' && typeof enclosure.url === 'string') {
|
||||
updatePayload.enclosureURL = enclosure.url
|
||||
updatePayload.enclosureType = typeof enclosure.type === 'string' ? enclosure.type : null
|
||||
updatePayload.enclosureSize = enclosure.length !== undefined && enclosure.length !== null ? enclosure.length : null
|
||||
}
|
||||
} else if (key === 'chapters' && Array.isArray(req.body[key]) && req.body[key].every((ch) => typeof ch === 'object' && ch.title && ch.start)) {
|
||||
updatePayload[key] = req.body[key]
|
||||
} else if (key === 'publishedAt' && typeof req.body[key] === 'number') {
|
||||
|
||||
@@ -253,6 +253,7 @@ class UserController {
|
||||
// Updating password
|
||||
if (updatePayload.password) {
|
||||
user.pash = await this.auth.localAuthStrategy.hashPassword(updatePayload.password)
|
||||
shouldInvalidateJwtSessions = true
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
@@ -331,14 +332,11 @@ class UserController {
|
||||
Logger.info(`[UserController] User ${user.username} has generated a new api token`)
|
||||
}
|
||||
|
||||
// Handle JWT session invalidation for username changes
|
||||
// Handle JWT session invalidation for username/password changes
|
||||
if (shouldInvalidateJwtSessions) {
|
||||
const newAccessToken = await this.auth.invalidateJwtSessionsForUser(user, req, res)
|
||||
if (newAccessToken) {
|
||||
user.accessToken = newAccessToken
|
||||
// Refresh tokens are only returned for mobile clients
|
||||
// Mobile apps currently do not use this API endpoint so always set to null
|
||||
user.refreshToken = null
|
||||
const newTokens = await this.auth.invalidateJwtSessionsForUser(user, req, res)
|
||||
if (newTokens) {
|
||||
// Note: for admin users changing their own password they should use MeController.updatePassword instead. This endpoint does not return tokens
|
||||
Logger.info(`[UserController] Invalidated JWT sessions for user ${user.username} and rotated tokens for current session`)
|
||||
} else {
|
||||
Logger.info(`[UserController] Invalidated JWT sessions for user ${user.username}`)
|
||||
@@ -363,15 +361,16 @@ class UserController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
if (req.params.id === 'root') {
|
||||
Logger.error('[UserController] Attempt to delete root user. Root user cannot be deleted')
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
const user = req.reqUser
|
||||
|
||||
if (req.user.id === req.params.id) {
|
||||
Logger.error(`[UserController] User ${req.user.username} is attempting to delete self`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
const user = req.reqUser
|
||||
if (user.isRoot) {
|
||||
Logger.error(`[UserController] Admin user "${req.user.username}" attempted to delete root user`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
// Todo: check if user is logged in and cancel streams
|
||||
|
||||
|
||||
+13
-6
@@ -647,6 +647,11 @@ class Book extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minified book JSON for list/shelf endpoints.
|
||||
* `toOldJSONExpanded()` must be a strict superset: every key here must exist in expanded
|
||||
* with the same value semantics. Only additive changes to expanded; never remove or rename keys.
|
||||
*/
|
||||
toOldJSONMinified() {
|
||||
if (!this.authors) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because authors are not loaded`)
|
||||
@@ -669,6 +674,12 @@ class Book extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expanded book JSON for item detail and socket events.
|
||||
* Must be a strict superset of `toOldJSONMinified()` — built by spreading minified, then adding expanded-only fields.
|
||||
*
|
||||
* @param {string} libraryItemId
|
||||
*/
|
||||
toOldJSONExpanded(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
@@ -681,16 +692,12 @@ class Book extends Model {
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
...this.toOldJSONMinified(),
|
||||
libraryItemId,
|
||||
metadata: this.oldMetadataToJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
audioFiles: structuredClone(this.audioFiles),
|
||||
chapters: structuredClone(this.chapters),
|
||||
ebookFile: structuredClone(this.ebookFile),
|
||||
duration: this.duration,
|
||||
size: this.size,
|
||||
tracks: this.getTracklist(libraryItemId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const { DataTypes, Model } = require('sequelize')
|
||||
const { DataTypes, Model, fn, col } = require('sequelize')
|
||||
|
||||
class BookAuthor extends Model {
|
||||
constructor(values, options) {
|
||||
@@ -37,6 +37,32 @@ class BookAuthor extends Model {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of books for each author
|
||||
*
|
||||
* @param {string[]} authorIds
|
||||
* @returns {Promise<Record<string, number>>}
|
||||
*/
|
||||
static async getCountsForAuthors(authorIds) {
|
||||
if (!authorIds.length) return {}
|
||||
|
||||
const rows = await this.findAll({
|
||||
attributes: ['authorId', [fn('COUNT', col('id')), 'count']],
|
||||
where: {
|
||||
authorId: authorIds
|
||||
},
|
||||
group: ['authorId'],
|
||||
raw: true
|
||||
})
|
||||
|
||||
/** @type {Record<string, number>} */
|
||||
const counts = {}
|
||||
for (const row of rows) {
|
||||
counts[row.authorId] = Number(row.count)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize model
|
||||
* @param {import('../Database').sequelize} sequelize
|
||||
|
||||
@@ -1004,6 +1004,11 @@ class LibraryItem extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minified library item JSON for list/shelf endpoints.
|
||||
* `toOldJSONExpanded()` must be a strict superset: every key here must exist in expanded
|
||||
* with the same value semantics. Only additive changes to expanded; never remove or rename keys.
|
||||
*/
|
||||
toOldJSONMinified() {
|
||||
if (!this.media) {
|
||||
throw new Error(`[LibraryItem] Cannot convert to old JSON without media for library item "${this.id}"`)
|
||||
@@ -1032,30 +1037,18 @@ class LibraryItem extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expanded library item JSON for item detail and socket events.
|
||||
* Must be a strict superset of `toOldJSONMinified()` — built by spreading minified, then adding expanded-only fields.
|
||||
*/
|
||||
toOldJSONExpanded() {
|
||||
return {
|
||||
id: this.id,
|
||||
ino: this.ino,
|
||||
oldLibraryItemId: this.extraData?.oldLibraryItemId || null,
|
||||
libraryId: this.libraryId,
|
||||
folderId: this.libraryFolderId,
|
||||
path: this.path,
|
||||
relPath: this.relPath,
|
||||
isFile: this.isFile,
|
||||
mtimeMs: this.mtime?.valueOf(),
|
||||
ctimeMs: this.ctime?.valueOf(),
|
||||
birthtimeMs: this.birthtime?.valueOf(),
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf(),
|
||||
...this.toOldJSONMinified(),
|
||||
lastScan: this.lastScan?.valueOf(),
|
||||
scanVersion: this.lastScanVersion,
|
||||
isMissing: !!this.isMissing,
|
||||
isInvalid: !!this.isInvalid,
|
||||
mediaType: this.mediaType,
|
||||
media: this.media.toOldJSONExpanded(this.id),
|
||||
// LibraryFile JSON includes a fileType property that may not be saved in libraryFiles column in the database
|
||||
libraryFiles: this.getLibraryFilesJson(),
|
||||
size: this.size
|
||||
libraryFiles: this.getLibraryFilesJson()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-12
@@ -451,6 +451,11 @@ class Podcast extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minified podcast JSON for list/shelf endpoints.
|
||||
* `toOldJSONExpanded()` must be a strict superset: every key here must exist in expanded
|
||||
* with the same value semantics. Only additive changes to expanded; never remove or rename keys.
|
||||
*/
|
||||
toOldJSONMinified() {
|
||||
return {
|
||||
id: this.id,
|
||||
@@ -468,6 +473,12 @@ class Podcast extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expanded podcast JSON for item detail and socket events.
|
||||
* Must be a strict superset of `toOldJSONMinified()` — built by spreading minified, then adding expanded-only fields.
|
||||
*
|
||||
* @param {string} libraryItemId
|
||||
*/
|
||||
toOldJSONExpanded(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Podcast] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
@@ -477,18 +488,9 @@ class Podcast extends Model {
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
metadata: this.oldMetadataToJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
episodes: this.podcastEpisodes.map((e) => e.toOldJSONExpanded(libraryItemId)),
|
||||
autoDownloadEpisodes: this.autoDownloadEpisodes,
|
||||
autoDownloadSchedule: this.autoDownloadSchedule,
|
||||
lastEpisodeCheck: this.lastEpisodeCheck?.valueOf() || null,
|
||||
maxEpisodesToKeep: this.maxEpisodesToKeep,
|
||||
maxNewEpisodesToDownload: this.maxNewEpisodesToDownload,
|
||||
size: this.size
|
||||
...this.toOldJSONMinified(),
|
||||
libraryItemId,
|
||||
episodes: this.podcastEpisodes.map((e) => e.toOldJSONExpanded(libraryItemId))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,7 +530,14 @@ class User extends Model {
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'user'
|
||||
modelName: 'user',
|
||||
hooks: {
|
||||
beforeDestroy(user) {
|
||||
if (user.type === 'root') {
|
||||
throw new Error('Root user cannot be deleted')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -260,6 +260,18 @@ class ServerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Host timezone used by cron schedulers (not persisted in settings)
|
||||
* @returns {string} IANA timezone name, e.g. "America/New_York"
|
||||
*/
|
||||
static getHostTimeZone() {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
|
||||
} catch {
|
||||
return 'UTC'
|
||||
}
|
||||
}
|
||||
|
||||
toJSONForBrowser() {
|
||||
const json = this.toJSON()
|
||||
delete json.tokenSecret
|
||||
@@ -268,6 +280,7 @@ class ServerSettings {
|
||||
delete json.authOpenIDMobileRedirectURIs
|
||||
delete json.authOpenIDGroupClaim
|
||||
delete json.authOpenIDAdvancedPermsClaim
|
||||
json.timeZone = ServerSettings.getHostTimeZone()
|
||||
return json
|
||||
}
|
||||
|
||||
|
||||
@@ -171,6 +171,9 @@ class ApiRouter {
|
||||
// Current User Routes (Me)
|
||||
//
|
||||
this.router.get('/me', MeController.getCurrentUser.bind(this))
|
||||
this.router.get('/me/progress', MeController.getAllMediaProgress.bind(this))
|
||||
this.router.get('/me/bookmarks', MeController.getAllBookmarks.bind(this))
|
||||
this.router.get('/me/bookmarks/:libraryItemId', MeController.getBookmarksForLibraryItem.bind(this))
|
||||
this.router.get('/me/listening-sessions', MeController.getListeningSessions.bind(this))
|
||||
this.router.get('/me/item/listening-sessions/:libraryItemId/:episodeId?', MeController.getItemListeningSessions.bind(this))
|
||||
this.router.get('/me/listening-stats', MeController.getListeningStats.bind(this))
|
||||
|
||||
@@ -228,6 +228,7 @@ class BookScanner {
|
||||
bookId: media.id,
|
||||
authorId: existingAuthorId
|
||||
})
|
||||
libraryScan.authorsNumBooksChangedIds.add(existingAuthorId)
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added author "${authorName}"`)
|
||||
authorsUpdated = true
|
||||
} else {
|
||||
@@ -238,6 +239,7 @@ class BookScanner {
|
||||
})
|
||||
await media.addAuthor(newAuthor)
|
||||
Database.addAuthorToFilterData(libraryItemData.libraryId, newAuthor.name, newAuthor.id)
|
||||
SocketAuthority.emitter('author_added', newAuthor.toOldJSON())
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added new author "${authorName}"`)
|
||||
authorsUpdated = true
|
||||
}
|
||||
@@ -247,6 +249,7 @@ class BookScanner {
|
||||
for (const author of media.authors) {
|
||||
if (!bookMetadata.authors.includes(author.name)) {
|
||||
await author.bookAuthor.destroy()
|
||||
libraryScan.authorsNumBooksChangedIds.add(author.id)
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" removed author "${author.name}"`)
|
||||
authorsUpdated = true
|
||||
bookAuthorsRemoved.push(author.id)
|
||||
@@ -478,6 +481,7 @@ class BookScanner {
|
||||
}
|
||||
|
||||
const createdAtTimestamp = new Date().getTime()
|
||||
const newAuthorNames = new Set()
|
||||
if (bookMetadata.authors.length) {
|
||||
for (const authorName of bookMetadata.authors) {
|
||||
const matchingAuthorId = await Database.getAuthorIdByName(libraryItemData.libraryId, authorName)
|
||||
@@ -485,6 +489,8 @@ class BookScanner {
|
||||
bookObject.bookAuthors.push({
|
||||
authorId: matchingAuthorId
|
||||
})
|
||||
// Existing author — only numBooks changes; batch emit at scan end
|
||||
libraryScan.authorsNumBooksChangedIds.add(matchingAuthorId)
|
||||
} else {
|
||||
// New author
|
||||
bookObject.bookAuthors.push({
|
||||
@@ -496,6 +502,7 @@ class BookScanner {
|
||||
lastFirst: Database.authorModel.getLastFirst(authorName)
|
||||
}
|
||||
})
|
||||
newAuthorNames.add(authorName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -593,6 +600,9 @@ class BookScanner {
|
||||
for (const ba of libraryItem.book.bookAuthors) {
|
||||
if (ba.author) {
|
||||
Database.addAuthorToFilterData(libraryItemData.libraryId, ba.author.name, ba.author.id)
|
||||
if (newAuthorNames.has(ba.author.name)) {
|
||||
SocketAuthority.emitter('author_added', ba.author.toOldJSON())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -891,6 +901,34 @@ class BookScanner {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit authors_num_books_updated for authors whose book count changed during a scan (linked or unlinked).
|
||||
* Authors with no book links are omitted — orphans are handled by author_removed.
|
||||
* @param {string} libraryId
|
||||
* @param {import('./LibraryScan')|import('./ScanLogger')} scanLogger
|
||||
* @returns {Promise}
|
||||
*/
|
||||
async emitAuthorsNumBooksUpdated(libraryId, scanLogger) {
|
||||
if (!scanLogger.authorsNumBooksChangedIds?.size) return
|
||||
|
||||
const authorIds = [...scanLogger.authorsNumBooksChangedIds]
|
||||
scanLogger.authorsNumBooksChangedIds.clear()
|
||||
|
||||
const countsByAuthorId = await Database.bookAuthorModel.getCountsForAuthors(authorIds)
|
||||
|
||||
const authors = Object.entries(countsByAuthorId).map(([id, numBooks]) => ({
|
||||
id,
|
||||
numBooks
|
||||
}))
|
||||
|
||||
if (!authors.length) return
|
||||
|
||||
SocketAuthority.emitter('authors_num_books_updated', {
|
||||
libraryId,
|
||||
authors
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Check authors that were removed from a book and remove them if they no longer have any books
|
||||
* keep authors without books that have a asin, description or imagePath
|
||||
|
||||
@@ -66,7 +66,7 @@ class LibraryItemScanner {
|
||||
if (libraryItemDataUpdated || wasUpdated) {
|
||||
SocketAuthority.libraryItemEmitter('item_updated', expandedLibraryItem)
|
||||
|
||||
await this.checkAuthorsAndSeriesRemovedFromBooks(library.id, scanLogger)
|
||||
await this.finalizeAuthorsAndSeriesFromScan(library.id, scanLogger)
|
||||
|
||||
return ScanResult.UPDATED
|
||||
}
|
||||
@@ -76,12 +76,13 @@ class LibraryItemScanner {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove empty authors and series
|
||||
* Emit author book count updates, then remove empty authors/series left after the scan
|
||||
* @param {string} libraryId
|
||||
* @param {ScanLogger} scanLogger
|
||||
* @returns {Promise}
|
||||
*/
|
||||
async checkAuthorsAndSeriesRemovedFromBooks(libraryId, scanLogger) {
|
||||
async finalizeAuthorsAndSeriesFromScan(libraryId, scanLogger) {
|
||||
await BookScanner.emitAuthorsNumBooksUpdated(libraryId, scanLogger)
|
||||
if (scanLogger.authorsRemovedFromBooks.length) {
|
||||
await BookScanner.checkAuthorsRemovedFromBooks(libraryId, scanLogger)
|
||||
}
|
||||
@@ -215,7 +216,10 @@ class LibraryItemScanner {
|
||||
scanLogger.verbose = true
|
||||
scanLogger.setData('libraryItem', libraryItemScanData.relPath)
|
||||
|
||||
return this.scanNewLibraryItem(libraryItemScanData, library.settings, scanLogger)
|
||||
const newLibraryItem = await this.scanNewLibraryItem(libraryItemScanData, library.settings, scanLogger)
|
||||
// Watcher path does not go through full-library scan cleanup — emit author book count updates here
|
||||
await BookScanner.emitAuthorsNumBooksUpdated(library.id, scanLogger)
|
||||
return newLibraryItem
|
||||
}
|
||||
}
|
||||
module.exports = new LibraryItemScanner()
|
||||
|
||||
@@ -24,6 +24,8 @@ class LibraryScan {
|
||||
|
||||
/** @type {string[]} */
|
||||
this.authorsRemovedFromBooks = []
|
||||
/** @type {Set<string>} */
|
||||
this.authorsNumBooksChangedIds = new Set()
|
||||
/** @type {string[]} */
|
||||
this.seriesRemovedFromBooks = []
|
||||
|
||||
|
||||
@@ -234,8 +234,7 @@ class LibraryScanner {
|
||||
SocketAuthority.libraryItemsEmitter('items_updated', libraryItemsUpdated)
|
||||
}
|
||||
|
||||
// Authors and series that were removed from books should be removed if they are now empty
|
||||
await LibraryItemScanner.checkAuthorsAndSeriesRemovedFromBooks(libraryScan.libraryId, libraryScan)
|
||||
if (this.shouldCancelScan(libraryScan)) return true
|
||||
|
||||
// Update missing library items
|
||||
if (libraryItemIdsMissing.length) {
|
||||
@@ -281,6 +280,9 @@ class LibraryScanner {
|
||||
}
|
||||
}
|
||||
|
||||
// Author book count updates and empty authors/series cleanup after all items are processed
|
||||
await LibraryItemScanner.finalizeAuthorsAndSeriesFromScan(libraryScan.libraryId, libraryScan)
|
||||
|
||||
libraryScan.addLog(LogLevel.INFO, `Scan completed. ${libraryScan.resultStats}`)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ class ScanLogger {
|
||||
|
||||
/** @type {string[]} */
|
||||
this.authorsRemovedFromBooks = []
|
||||
/** @type {Set<string>} */
|
||||
this.authorsNumBooksChangedIds = new Set()
|
||||
/** @type {string[]} */
|
||||
this.seriesRemovedFromBooks = []
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ module.exports.notificationData = {
|
||||
variables: ['version'],
|
||||
defaults: {
|
||||
title: 'Test Notification on Abs {{version}}',
|
||||
body: 'Test notificataion body for abs {{version}}.'
|
||||
body: 'Test notification body for abs {{version}}.'
|
||||
},
|
||||
testData: {
|
||||
version: 'v' + version
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Whether the request was made over HTTPS.
|
||||
* Uses Express `req.secure` and `x-forwarded-proto`
|
||||
*
|
||||
* @param {import('express').Request} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isRequestSecure(req) {
|
||||
if (req.secure) return true
|
||||
const xfp = (req.get('x-forwarded-proto') || '').toLowerCase()
|
||||
// Nginx Proxy Manager sends "http, https"; see https://github.com/advplyr/audiobookshelf/pull/4635
|
||||
return (
|
||||
xfp === 'https' ||
|
||||
xfp
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.includes('https')
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('express').Request} req
|
||||
* @returns {'https' | 'http'}
|
||||
*/
|
||||
function getRequestProtocol(req) {
|
||||
return isRequestSecure(req) ? 'https' : 'http'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('express').Request} req
|
||||
* @returns {{ protocol: 'https' | 'http', host: string, origin: string }}
|
||||
*/
|
||||
function getRequestOrigin(req) {
|
||||
const protocol = getRequestProtocol(req)
|
||||
const host = req.get('host')
|
||||
return { protocol, host, origin: `${protocol}://${host}` }
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isRequestSecure,
|
||||
getRequestProtocol,
|
||||
getRequestOrigin
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
|
||||
// Load Database first so Auth resolves OidcAuthStrategy before the circular require completes.
|
||||
require('../../../server/Database')
|
||||
const OidcAuthStrategy = require('../../../server/auth/OidcAuthStrategy')
|
||||
const Logger = require('../../../server/Logger')
|
||||
|
||||
describe('OidcAuthStrategy - isValidWebCallbackUrl', () => {
|
||||
/** @type {OidcAuthStrategy} */
|
||||
let strategy
|
||||
|
||||
beforeEach(() => {
|
||||
global.RouterBasePath = ''
|
||||
strategy = new OidcAuthStrategy()
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
function mockReq({ secure = false, host = 'books.example.com', xForwardedProto = null } = {}) {
|
||||
return {
|
||||
secure,
|
||||
get(header) {
|
||||
if (header === 'host') return host
|
||||
if (header === 'x-forwarded-proto') return xForwardedProto
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('accepts a same-origin relative path when router base path is empty', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('/library', mockReq())).to.equal(true)
|
||||
})
|
||||
|
||||
it('accepts a same-origin absolute https URL', () => {
|
||||
const req = mockReq({ secure: true })
|
||||
expect(strategy.isValidWebCallbackUrl('https://books.example.com/library', req)).to.equal(true)
|
||||
})
|
||||
|
||||
it('rejects protocol-relative URLs', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('//evil.example/capture', mockReq())).to.equal(false)
|
||||
})
|
||||
|
||||
it('rejects backslash-prefixed URLs', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('/\\evil.example/capture', mockReq())).to.equal(false)
|
||||
})
|
||||
|
||||
it('rejects absolute external URLs', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('http://evil.example/capture', mockReq())).to.equal(false)
|
||||
})
|
||||
|
||||
it('rejects encoded protocol-relative path segments', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('/%2F%2Fevil.example/capture', mockReq())).to.equal(false)
|
||||
})
|
||||
|
||||
it('rejects same-origin URLs outside router base path', () => {
|
||||
global.RouterBasePath = '/audiobookshelf'
|
||||
expect(strategy.isValidWebCallbackUrl('/login', mockReq())).to.equal(false)
|
||||
expect(strategy.isValidWebCallbackUrl('/audiobookshelf/login', mockReq())).to.equal(true)
|
||||
})
|
||||
|
||||
it('rejects empty and malformed callback URLs', () => {
|
||||
expect(strategy.isValidWebCallbackUrl('', mockReq())).to.equal(false)
|
||||
expect(strategy.isValidWebCallbackUrl(null, mockReq())).to.equal(false)
|
||||
expect(strategy.isValidWebCallbackUrl('not a url', mockReq())).to.equal(false)
|
||||
})
|
||||
|
||||
it('uses x-forwarded-proto when determining same-origin https URLs', () => {
|
||||
const req = mockReq({ xForwardedProto: 'https' })
|
||||
expect(strategy.isValidWebCallbackUrl('https://books.example.com/login', req)).to.equal(true)
|
||||
expect(strategy.isValidWebCallbackUrl('http://books.example.com/login', req)).to.equal(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const { Op } = require('sequelize')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const jwt = require('../../../server/libs/jsonwebtoken')
|
||||
|
||||
// Database → Auth → TokenManager circular require can leave TokenManager with a partial Database reference; reload before each test
|
||||
function loadTokenManager() {
|
||||
delete require.cache[require.resolve('../../../server/auth/TokenManager')]
|
||||
return require('../../../server/auth/TokenManager')
|
||||
}
|
||||
|
||||
describe('TokenManager', () => {
|
||||
const secret = 'test-jwt-secret'
|
||||
const userId = 'user-uuid-1'
|
||||
let TokenManager
|
||||
let tokenManager
|
||||
|
||||
beforeEach(() => {
|
||||
TokenManager = loadTokenManager()
|
||||
TokenManager.TokenSecret = secret
|
||||
tokenManager = new TokenManager()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
describe('validateAccessToken', () => {
|
||||
it('rejects refresh tokens', () => {
|
||||
const refreshToken = jwt.sign({ userId, type: 'refresh' }, secret, { expiresIn: 3600 })
|
||||
expect(TokenManager.validateAccessToken(refreshToken)).to.equal(null)
|
||||
})
|
||||
|
||||
it('accepts access tokens', () => {
|
||||
const accessToken = jwt.sign({ userId, type: 'access' }, secret, { expiresIn: 3600 })
|
||||
const decoded = TokenManager.validateAccessToken(accessToken)
|
||||
expect(decoded.userId).to.equal(userId)
|
||||
expect(decoded.type).to.equal('access')
|
||||
})
|
||||
})
|
||||
|
||||
describe('jwtAuthCheck', () => {
|
||||
const user = { id: userId, username: 'testuser', isActive: true }
|
||||
|
||||
it('rejects refresh tokens for API auth', async () => {
|
||||
const refreshToken = tokenManager.generateRefreshToken(user)
|
||||
const decoded = jwt.verify(refreshToken, secret)
|
||||
const done = sinon.spy()
|
||||
|
||||
await tokenManager.jwtAuthCheck(decoded, done)
|
||||
|
||||
expect(done.calledWith(null, null)).to.be.true
|
||||
})
|
||||
|
||||
it('allows access tokens for active users', async () => {
|
||||
sinon.stub(Database, 'userModel').get(() => ({
|
||||
getUserByIdOrOldId: sinon.stub().resolves(user)
|
||||
}))
|
||||
const decoded = jwt.verify(tokenManager.generateTempAccessToken(user), secret)
|
||||
const done = sinon.spy()
|
||||
|
||||
await tokenManager.jwtAuthCheck(decoded, done)
|
||||
|
||||
expect(done.calledWith(null, user)).to.be.true
|
||||
})
|
||||
})
|
||||
|
||||
describe('invalidateJwtSessionsForUser', () => {
|
||||
const targetUser = { id: userId, username: 'testuser' }
|
||||
const currentSession = {
|
||||
id: 'session-current',
|
||||
userId,
|
||||
refreshToken: 'refresh-current'
|
||||
}
|
||||
|
||||
/** Minimal req/res for session invalidation (ApiRouter provides auth on real requests). */
|
||||
function makeReq({ requestUserId = userId, refreshToken = null, cookieRefreshToken = null } = {}) {
|
||||
return {
|
||||
user: { id: requestUserId },
|
||||
cookies: cookieRefreshToken ? { refresh_token: cookieRefreshToken } : {},
|
||||
headers: refreshToken ? { 'x-refresh-token': refreshToken } : {}
|
||||
}
|
||||
}
|
||||
|
||||
let sessionFindOne
|
||||
let sessionDestroy
|
||||
let rotateStub
|
||||
|
||||
beforeEach(() => {
|
||||
sessionFindOne = sinon.stub().resolves(currentSession)
|
||||
sessionDestroy = sinon.stub().resolves(1)
|
||||
sinon.stub(Database, 'sessionModel').get(() => ({
|
||||
findOne: sessionFindOne,
|
||||
destroy: sessionDestroy
|
||||
}))
|
||||
rotateStub = sinon.stub(tokenManager, 'rotateTokensForSession').resolves({
|
||||
accessToken: 'access-new',
|
||||
refreshToken: 'refresh-new'
|
||||
})
|
||||
})
|
||||
|
||||
it('self password change: keeps current session, deletes others', async () => {
|
||||
const req = makeReq({ refreshToken: 'refresh-current' })
|
||||
const res = { cookie: sinon.spy() }
|
||||
|
||||
const result = await tokenManager.invalidateJwtSessionsForUser(targetUser, req, res)
|
||||
|
||||
// Found this device's session using the x-refresh-token header
|
||||
expect(sessionFindOne.calledOnce).to.be.true
|
||||
const findWhere = sessionFindOne.firstCall.args[0].where
|
||||
expect(findWhere.userId).to.equal(userId)
|
||||
expect(findWhere[Op.or]).to.deep.equal([{ refreshToken: 'refresh-current' }, { lastRefreshToken: 'refresh-current' }])
|
||||
|
||||
// Rotated in place (no grace period) so the caller keeps a valid session
|
||||
expect(rotateStub.calledOnceWith(currentSession, targetUser, req, res, false)).to.be.true
|
||||
|
||||
// Deleted all other sessions, but not this one
|
||||
expect(sessionDestroy.calledOnce).to.be.true
|
||||
const destroyWhere = sessionDestroy.firstCall.args[0].where
|
||||
expect(destroyWhere.userId).to.equal(userId)
|
||||
expect(destroyWhere.id[Op.ne]).to.equal(currentSession.id)
|
||||
|
||||
expect(result).to.deep.equal({ accessToken: 'access-new', refreshToken: 'refresh-new' })
|
||||
})
|
||||
|
||||
it('admin password reset: deletes all target sessions', async () => {
|
||||
const req = makeReq({ requestUserId: 'admin-id', refreshToken: 'refresh-current' })
|
||||
const res = { cookie: sinon.spy() }
|
||||
|
||||
const result = await tokenManager.invalidateJwtSessionsForUser(targetUser, req, res)
|
||||
|
||||
// Token rotation did not happen because target is a different user
|
||||
expect(sessionFindOne.called).to.be.false
|
||||
expect(rotateStub.called).to.be.false
|
||||
|
||||
expect(sessionDestroy.calledOnceWith(sinon.match({ where: { userId } }))).to.be.true
|
||||
expect(result).to.equal(null)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const LibraryController = require('../../../server/controllers/LibraryController')
|
||||
const zipHelpers = require('../../../server/utils/zipHelpers')
|
||||
const Logger = require('../../../server/Logger')
|
||||
|
||||
describe('LibraryController.downloadMultiple', () => {
|
||||
let library
|
||||
let libraryFolder
|
||||
let allowedItemId
|
||||
let explicitItemId
|
||||
let taggedItemId
|
||||
let restrictedUser
|
||||
let libraryRecord
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
libraryFolder = await Database.libraryFolderModel.create({ path: '/test-lib', libraryId: library.id })
|
||||
libraryRecord = await Database.libraryModel.findByIdWithFolders(library.id)
|
||||
|
||||
const allowedBook = await Database.bookModel.create({
|
||||
title: 'Allowed Book',
|
||||
explicit: false,
|
||||
audioFiles: [],
|
||||
tags: ['allowed-tag'],
|
||||
narrators: [],
|
||||
genres: [],
|
||||
chapters: []
|
||||
})
|
||||
const allowedItem = await Database.libraryItemModel.create({
|
||||
path: '/test-lib/allowed',
|
||||
isFile: false,
|
||||
libraryFiles: [],
|
||||
mediaId: allowedBook.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
allowedItemId = allowedItem.id
|
||||
|
||||
const explicitBook = await Database.bookModel.create({
|
||||
title: 'Explicit Book',
|
||||
explicit: true,
|
||||
audioFiles: [],
|
||||
tags: [],
|
||||
narrators: [],
|
||||
genres: [],
|
||||
chapters: []
|
||||
})
|
||||
const explicitItem = await Database.libraryItemModel.create({
|
||||
path: '/test-lib/explicit',
|
||||
isFile: false,
|
||||
libraryFiles: [],
|
||||
mediaId: explicitBook.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
explicitItemId = explicitItem.id
|
||||
|
||||
const taggedBook = await Database.bookModel.create({
|
||||
title: 'Tagged Book',
|
||||
explicit: false,
|
||||
audioFiles: [],
|
||||
tags: ['restricted-tag'],
|
||||
narrators: [],
|
||||
genres: [],
|
||||
chapters: []
|
||||
})
|
||||
const taggedItem = await Database.libraryItemModel.create({
|
||||
path: '/test-lib/tagged',
|
||||
isFile: false,
|
||||
libraryFiles: [],
|
||||
mediaId: taggedBook.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
taggedItemId = taggedItem.id
|
||||
|
||||
const permissions = Database.userModel.getDefaultPermissionsForUserType('user')
|
||||
permissions.download = true
|
||||
permissions.accessExplicitContent = false
|
||||
permissions.accessAllLibraries = false
|
||||
permissions.accessAllTags = false
|
||||
permissions.librariesAccessible = [library.id]
|
||||
permissions.itemTagsSelected = ['allowed-tag']
|
||||
permissions.selectedTagsNotAccessible = false
|
||||
|
||||
restrictedUser = await Database.userModel.create({
|
||||
username: 'restricted',
|
||||
pash: 'hash',
|
||||
token: 'token',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
permissions,
|
||||
bookmarks: [],
|
||||
extraData: {}
|
||||
})
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
function makeReq(ids) {
|
||||
return {
|
||||
query: { ids: ids.join(',') },
|
||||
user: restrictedUser,
|
||||
library: libraryRecord
|
||||
}
|
||||
}
|
||||
|
||||
function makeRes() {
|
||||
return {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
}
|
||||
|
||||
it('returns 403 for bulk download of an explicit item', async () => {
|
||||
const req = makeReq([explicitItemId])
|
||||
const res = makeRes()
|
||||
|
||||
await LibraryController.downloadMultiple(req, res)
|
||||
|
||||
expect(res.sendStatus.calledWith(403)).to.be.true
|
||||
expect(zipHelpers.zipDirectoriesPipe.called).to.be.false
|
||||
})
|
||||
|
||||
it('returns 403 for bulk download of a tag-restricted item', async () => {
|
||||
const req = makeReq([taggedItemId])
|
||||
const res = makeRes()
|
||||
|
||||
await LibraryController.downloadMultiple(req, res)
|
||||
|
||||
expect(res.sendStatus.calledWith(403)).to.be.true
|
||||
expect(zipHelpers.zipDirectoriesPipe.called).to.be.false
|
||||
})
|
||||
|
||||
it('returns 403 when bulk download includes both allowed and forbidden items', async () => {
|
||||
const req = makeReq([allowedItemId, explicitItemId])
|
||||
const res = makeRes()
|
||||
|
||||
await LibraryController.downloadMultiple(req, res)
|
||||
|
||||
expect(res.sendStatus.calledWith(403)).to.be.true
|
||||
expect(zipHelpers.zipDirectoriesPipe.called).to.be.false
|
||||
})
|
||||
|
||||
it('starts zip download for allowed items only', async () => {
|
||||
const req = makeReq([allowedItemId])
|
||||
const res = makeRes()
|
||||
|
||||
await LibraryController.downloadMultiple(req, res)
|
||||
|
||||
expect(res.sendStatus.called).to.be.false
|
||||
expect(zipHelpers.zipDirectoriesPipe.calledOnce).to.be.true
|
||||
const pathObjects = zipHelpers.zipDirectoriesPipe.firstCall.args[0]
|
||||
expect(pathObjects).to.have.length(1)
|
||||
expect(pathObjects[0].path).to.equal('/test-lib/allowed')
|
||||
})
|
||||
})
|
||||
@@ -1,636 +0,0 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const ApiRouter = require('../../../server/routers/ApiRouter')
|
||||
const MeController = require('../../../server/controllers/MeController')
|
||||
const Auth = require('../../../server/Auth')
|
||||
const Logger = require('../../../server/Logger')
|
||||
const SocketAuthority = require('../../../server/SocketAuthority')
|
||||
|
||||
describe('MeController - IDOR Security Tests', () => {
|
||||
/** @type {ApiRouter} */
|
||||
let apiRouter
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
// Create mock server object with required dependencies
|
||||
const mockServer = {
|
||||
auth: new Auth(),
|
||||
playbackSessionManager: { sessions: [] },
|
||||
abMergeManager: {},
|
||||
backupManager: {},
|
||||
podcastManager: {},
|
||||
audioMetadataManager: {},
|
||||
cronManager: {},
|
||||
emailManager: {},
|
||||
apiCacheManager: { middleware: (req, res, next) => next() }
|
||||
}
|
||||
|
||||
apiRouter = new ApiRouter(mockServer)
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'error')
|
||||
sinon.stub(SocketAuthority, 'clientEmitter')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
|
||||
// Clear all tables
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
describe('removeMediaProgress - IDOR Protection', () => {
|
||||
let user1, user2
|
||||
let mediaProgress1, mediaProgress2
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create two users
|
||||
user1 = await Database.userModel.create({
|
||||
username: 'user1',
|
||||
pash: 'hashed_password_1',
|
||||
type: 'user',
|
||||
isActive: true
|
||||
})
|
||||
|
||||
user2 = await Database.userModel.create({
|
||||
username: 'user2',
|
||||
pash: 'hashed_password_2',
|
||||
type: 'user',
|
||||
isActive: true
|
||||
})
|
||||
|
||||
// Create library and book
|
||||
const library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
const libraryFolder = await Database.libraryFolderModel.create({ path: '/test', libraryId: library.id })
|
||||
const book = await Database.bookModel.create({ title: 'Test Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const libraryItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
// Create media progress for each user
|
||||
mediaProgress1 = await Database.mediaProgressModel.create({
|
||||
userId: user1.id,
|
||||
mediaItemId: book.id,
|
||||
mediaItemType: 'book',
|
||||
duration: 1000,
|
||||
currentTime: 500,
|
||||
isFinished: false
|
||||
})
|
||||
|
||||
mediaProgress2 = await Database.mediaProgressModel.create({
|
||||
userId: user2.id,
|
||||
mediaItemId: book.id,
|
||||
mediaItemType: 'book',
|
||||
duration: 1000,
|
||||
currentTime: 300,
|
||||
isFinished: false
|
||||
})
|
||||
|
||||
// Load media progresses into users
|
||||
user1.mediaProgresses = await user1.getMediaProgresses()
|
||||
user2.mediaProgresses = await user2.getMediaProgresses()
|
||||
})
|
||||
|
||||
it('should allow user to delete their own media progress', async () => {
|
||||
const fakeReq = {
|
||||
user: user1,
|
||||
params: { id: mediaProgress1.id }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
await MeController.removeMediaProgress(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(200)).to.be.true
|
||||
|
||||
// Verify media progress was deleted
|
||||
const deletedProgress = await Database.mediaProgressModel.findByPk(mediaProgress1.id)
|
||||
expect(deletedProgress).to.be.null
|
||||
})
|
||||
|
||||
it('should prevent user from deleting another users media progress (IDOR)', async () => {
|
||||
const fakeReq = {
|
||||
user: user1,
|
||||
params: { id: mediaProgress2.id } // Trying to delete user2's progress
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
await MeController.removeMediaProgress(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(404)).to.be.true
|
||||
|
||||
// Verify media progress was NOT deleted
|
||||
const existingProgress = await Database.mediaProgressModel.findByPk(mediaProgress2.id)
|
||||
expect(existingProgress).to.not.be.null
|
||||
expect(existingProgress.userId).to.equal(user2.id)
|
||||
})
|
||||
|
||||
it('should return 404 for non-existent media progress', async () => {
|
||||
const fakeReq = {
|
||||
user: user1,
|
||||
params: { id: 'non-existent-id' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
await MeController.removeMediaProgress(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(404)).to.be.true
|
||||
})
|
||||
})
|
||||
|
||||
describe('Bookmark Operations - Authorization Checks', () => {
|
||||
let user1, user2
|
||||
let library1, library2
|
||||
let libraryItem1, libraryItem2
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create two users with different library access
|
||||
user1 = await Database.userModel.create({
|
||||
username: 'user1',
|
||||
pash: 'hashed_password_1',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
librariesAccessible: null // Access to all libraries
|
||||
})
|
||||
|
||||
user2 = await Database.userModel.create({
|
||||
username: 'user2',
|
||||
pash: 'hashed_password_2',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
librariesAccessible: [] // Will be set to specific library
|
||||
})
|
||||
|
||||
// Create two libraries
|
||||
library1 = await Database.libraryModel.create({ name: 'Library 1', mediaType: 'book' })
|
||||
library2 = await Database.libraryModel.create({ name: 'Library 2', mediaType: 'book' })
|
||||
|
||||
// User2 only has access to library1
|
||||
user2.librariesAccessible = [library1.id]
|
||||
await user2.save()
|
||||
|
||||
const libraryFolder1 = await Database.libraryFolderModel.create({ path: '/test1', libraryId: library1.id })
|
||||
const libraryFolder2 = await Database.libraryFolderModel.create({ path: '/test2', libraryId: library2.id })
|
||||
|
||||
const book1 = await Database.bookModel.create({ title: 'Book 1', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const book2 = await Database.bookModel.create({ title: 'Book 2', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
|
||||
libraryItem1 = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book1.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library1.id,
|
||||
libraryFolderId: libraryFolder1.id
|
||||
})
|
||||
|
||||
libraryItem2 = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book2.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library2.id,
|
||||
libraryFolderId: libraryFolder2.id
|
||||
})
|
||||
|
||||
// Initialize bookmarks
|
||||
user1.bookmarks = []
|
||||
user2.bookmarks = []
|
||||
})
|
||||
|
||||
describe('createBookmark', () => {
|
||||
it('should allow user to create bookmark for accessible library item', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
const bookmark = { libraryItemId: libraryItem1.id, time: 100, title: 'Test Bookmark', createdAt: Date.now() }
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user2.toJSON(),
|
||||
id: user2.id,
|
||||
username: user2.username,
|
||||
checkCanAccessLibraryItem: () => true,
|
||||
createBookmark: sinon.stub().resolves(bookmark),
|
||||
toOldJSONForBrowser: () => ({ id: user2.id, username: user2.username })
|
||||
},
|
||||
params: { id: libraryItem1.id },
|
||||
body: { time: 100, title: 'Test Bookmark' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.createBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.json.calledOnce).to.be.true
|
||||
expect(fakeRes.json.calledWith(bookmark)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should prevent user from creating bookmark for inaccessible library item (IDOR)', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem2.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: user2, // user2 doesn't have access to library2
|
||||
params: { id: libraryItem2.id },
|
||||
body: { time: 100, title: 'Test Bookmark' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
// Mock getExpandedById
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.createBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(403)).to.be.true
|
||||
expect(fakeRes.json.called).to.be.false
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should return 404 for non-existent library item', async () => {
|
||||
const fakeReq = {
|
||||
user: user1,
|
||||
params: { id: 'non-existent-id' },
|
||||
body: { time: 100, title: 'Test Bookmark' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
// Mock getExpandedById to return null
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(null)
|
||||
|
||||
await MeController.createBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(404)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should validate bookmark time parameter', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user1.toJSON(),
|
||||
id: user1.id,
|
||||
username: user1.username,
|
||||
checkCanAccessLibraryItem: () => true
|
||||
},
|
||||
params: { id: libraryItem1.id },
|
||||
body: { time: null, title: 'Test Bookmark' } // null time is invalid
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.createBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.status.calledWith(400)).to.be.true
|
||||
expect(fakeRes.send.calledWith('Invalid time')).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateBookmark', () => {
|
||||
beforeEach(async () => {
|
||||
// Add existing bookmark to user1
|
||||
user1.bookmarks = [{ libraryItemId: libraryItem1.id, time: 100, title: 'Original Title' }]
|
||||
await user1.save()
|
||||
})
|
||||
|
||||
it('should allow user to update bookmark for accessible library item', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
const bookmark = { libraryItemId: libraryItem1.id, time: 100, title: 'Updated Title' }
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user1.toJSON(),
|
||||
id: user1.id,
|
||||
username: user1.username,
|
||||
checkCanAccessLibraryItem: () => true,
|
||||
updateBookmark: sinon.stub().resolves(bookmark),
|
||||
toOldJSONForBrowser: () => ({ id: user1.id, username: user1.username })
|
||||
},
|
||||
params: { id: libraryItem1.id },
|
||||
body: { time: 100, title: 'Updated Title' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.updateBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.json.calledOnce).to.be.true
|
||||
expect(fakeRes.json.calledWith(bookmark)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should prevent user from updating bookmark for inaccessible library item (IDOR)', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem2.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: user2, // user2 doesn't have access to library2
|
||||
params: { id: libraryItem2.id },
|
||||
body: { time: 100, title: 'Updated Title' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.updateBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(403)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeBookmark', () => {
|
||||
beforeEach(async () => {
|
||||
// Add existing bookmark to user1
|
||||
user1.bookmarks = [{ libraryItemId: libraryItem1.id, time: 100, title: 'Test Bookmark' }]
|
||||
await user1.save()
|
||||
})
|
||||
|
||||
it('should allow user to remove bookmark for accessible library item', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user1.toJSON(),
|
||||
id: user1.id,
|
||||
username: user1.username,
|
||||
checkCanAccessLibraryItem: () => true,
|
||||
findBookmark: sinon.stub().returns({ libraryItemId: libraryItem1.id, time: 100, title: 'Test Bookmark' }),
|
||||
removeBookmark: sinon.stub().resolves(true),
|
||||
toOldJSONForBrowser: () => ({ id: user1.id, username: user1.username })
|
||||
},
|
||||
params: { id: libraryItem1.id, time: '100' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.removeBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(200)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should prevent user from removing bookmark for inaccessible library item (IDOR)', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem2.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: user2, // user2 doesn't have access to library2
|
||||
params: { id: libraryItem2.id, time: '100' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.removeBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(403)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
|
||||
it('should validate time parameter is a number', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user1.toJSON(),
|
||||
id: user1.id,
|
||||
username: user1.username,
|
||||
checkCanAccessLibraryItem: () => true
|
||||
},
|
||||
params: { id: libraryItem1.id, time: 'not-a-number' }
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
|
||||
await MeController.removeBookmark(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.status.calledWith(400)).to.be.true
|
||||
expect(fakeRes.send.calledWith('Invalid time')).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getItemListeningSessions - Authorization Check', () => {
|
||||
let user1, user2
|
||||
let library1, library2
|
||||
let libraryItem1, libraryItem2
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create two users with different library access
|
||||
user1 = await Database.userModel.create({
|
||||
username: 'user1',
|
||||
pash: 'hashed_password_1',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
librariesAccessible: null // Access to all libraries
|
||||
})
|
||||
|
||||
user2 = await Database.userModel.create({
|
||||
username: 'user2',
|
||||
pash: 'hashed_password_2',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
librariesAccessible: [] // Will be set to specific library
|
||||
})
|
||||
|
||||
// Create two libraries
|
||||
library1 = await Database.libraryModel.create({ name: 'Library 1', mediaType: 'book' })
|
||||
library2 = await Database.libraryModel.create({ name: 'Library 2', mediaType: 'book' })
|
||||
|
||||
// User2 only has access to library1
|
||||
user2.librariesAccessible = [library1.id]
|
||||
await user2.save()
|
||||
|
||||
const libraryFolder1 = await Database.libraryFolderModel.create({ path: '/test1', libraryId: library1.id })
|
||||
const libraryFolder2 = await Database.libraryFolderModel.create({ path: '/test2', libraryId: library2.id })
|
||||
|
||||
const book1 = await Database.bookModel.create({ title: 'Book 1', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const book2 = await Database.bookModel.create({ title: 'Book 2', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
|
||||
libraryItem1 = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book1.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library1.id,
|
||||
libraryFolderId: libraryFolder1.id
|
||||
})
|
||||
|
||||
libraryItem2 = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book2.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library2.id,
|
||||
libraryFolderId: libraryFolder2.id
|
||||
})
|
||||
})
|
||||
|
||||
it('should allow user to view listening sessions for accessible library item', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem1.id)
|
||||
|
||||
// Create mock context with getUserItemListeningSessionsHelper
|
||||
const mockContext = {
|
||||
getUserItemListeningSessionsHelper: sinon.stub().resolves([{ id: 'session1', timeListening: 300, startedAt: Date.now() }])
|
||||
}
|
||||
|
||||
const fakeReq = {
|
||||
user: {
|
||||
...user1.toJSON(),
|
||||
id: user1.id,
|
||||
username: user1.username,
|
||||
checkCanAccessLibraryItem: () => true
|
||||
},
|
||||
params: { libraryItemId: libraryItem1.id },
|
||||
query: {}
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
sinon.stub(Database.podcastEpisodeModel, 'findByPk').resolves(null)
|
||||
|
||||
await MeController.getItemListeningSessions.bind(mockContext)(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.json.calledOnce).to.be.true
|
||||
expect(fakeRes.sendStatus.called).to.be.false
|
||||
|
||||
// Verify the payload structure
|
||||
const payload = fakeRes.json.firstCall.args[0]
|
||||
expect(payload).to.have.property('total')
|
||||
expect(payload).to.have.property('sessions')
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
Database.podcastEpisodeModel.findByPk.restore()
|
||||
})
|
||||
|
||||
it('should prevent user from viewing listening sessions for inaccessible library item (IDOR)', async () => {
|
||||
const expandedItem = await Database.libraryItemModel.getExpandedById(libraryItem2.id)
|
||||
|
||||
const fakeReq = {
|
||||
user: user2, // user2 doesn't have access to library2
|
||||
params: { libraryItemId: libraryItem2.id },
|
||||
query: {}
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(expandedItem)
|
||||
sinon.stub(Database.podcastEpisodeModel, 'findByPk').resolves(null)
|
||||
|
||||
await MeController.getItemListeningSessions.bind(apiRouter)(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(403)).to.be.true
|
||||
expect(fakeRes.json.called).to.be.false
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
Database.podcastEpisodeModel.findByPk.restore()
|
||||
})
|
||||
|
||||
it('should return 404 for non-existent library item', async () => {
|
||||
const fakeReq = {
|
||||
user: user1,
|
||||
params: { libraryItemId: 'non-existent-id' },
|
||||
query: {}
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
sinon.stub(Database.libraryItemModel, 'getExpandedById').resolves(null)
|
||||
|
||||
await MeController.getItemListeningSessions.bind(apiRouter)(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(404)).to.be.true
|
||||
|
||||
Database.libraryItemModel.getExpandedById.restore()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const UserController = require('../../../server/controllers/UserController')
|
||||
const Logger = require('../../../server/Logger')
|
||||
|
||||
describe('UserController - delete', () => {
|
||||
beforeEach(() => {
|
||||
sinon.stub(Logger, 'error')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('rejects deleting the root user by UUID', async () => {
|
||||
const rootUser = { id: 'root-uuid', isRoot: true, username: 'root' }
|
||||
const adminUser = { id: 'admin-uuid', isRoot: false, username: 'admin' }
|
||||
const fakeRes = { sendStatus: sinon.spy(), json: sinon.spy() }
|
||||
|
||||
await UserController.delete({ user: adminUser, reqUser: rootUser, params: { id: rootUser.id } }, fakeRes)
|
||||
|
||||
expect(fakeRes.sendStatus.calledWith(403)).to.be.true
|
||||
expect(fakeRes.json.called).to.be.false
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
|
||||
/**
|
||||
* Assert that `expanded` contains every key from `minified` with matching values.
|
||||
* Used to enforce the contract: toOldJSONExpanded() is a strict superset of toOldJSONMinified().
|
||||
*
|
||||
* @param {object} minified
|
||||
* @param {object} expanded
|
||||
* @param {string} [path]
|
||||
*/
|
||||
function assertExpandedSuperset(minified, expanded, path = '') {
|
||||
for (const key of Object.keys(minified)) {
|
||||
const keyPath = path ? `${path}.${key}` : key
|
||||
expect(expanded, `missing key ${keyPath}`).to.have.property(key)
|
||||
|
||||
const minifiedValue = minified[key]
|
||||
const expandedValue = expanded[key]
|
||||
|
||||
if (minifiedValue !== null && typeof minifiedValue === 'object' && !Array.isArray(minifiedValue)) {
|
||||
assertExpandedSuperset(minifiedValue, expandedValue, keyPath)
|
||||
} else if (Array.isArray(minifiedValue)) {
|
||||
expect(expandedValue, `expected array at ${keyPath}`).to.be.an('array')
|
||||
expect(expandedValue).to.deep.equal(minifiedValue)
|
||||
} else {
|
||||
expect(expandedValue, `value mismatch at ${keyPath}`).to.equal(minifiedValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('old JSON serialization', () => {
|
||||
let bookLibraryItemId
|
||||
let podcastLibraryItemId
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
const bookLibrary = await Database.libraryModel.create({ name: 'Book Library', mediaType: 'book' })
|
||||
const bookLibraryFolder = await Database.libraryFolderModel.create({ path: '/books', libraryId: bookLibrary.id })
|
||||
|
||||
const book = await Database.bookModel.create({
|
||||
title: 'Test Book',
|
||||
audioFiles: [{ index: 1, ino: '1', metadata: { filename: 'track.mp3', ext: '.mp3', path: '/track.mp3', relPath: 'track.mp3', size: 1000 } }],
|
||||
tags: ['fiction'],
|
||||
narrators: ['Narrator One'],
|
||||
genres: ['Fantasy'],
|
||||
chapters: [{ id: 0, start: 0, end: 100, title: 'Chapter 1' }],
|
||||
ebookFile: { ino: '2', metadata: { filename: 'book.epub', ext: '.epub', path: '/book.epub', relPath: 'book.epub', size: 500 }, ebookFormat: 'epub' }
|
||||
})
|
||||
const bookLibraryItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [{ ino: '1', metadata: { filename: 'track.mp3', ext: '.mp3', path: '/track.mp3', relPath: 'track.mp3' } }],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: bookLibrary.id,
|
||||
libraryFolderId: bookLibraryFolder.id
|
||||
})
|
||||
bookLibraryItemId = bookLibraryItem.id
|
||||
|
||||
const author = await Database.authorModel.create({ name: 'Test Author', libraryId: bookLibrary.id })
|
||||
await Database.bookAuthorModel.create({ bookId: book.id, authorId: author.id })
|
||||
|
||||
const series = await Database.seriesModel.create({ name: 'Test Series', libraryId: bookLibrary.id })
|
||||
await Database.bookSeriesModel.create({ bookId: book.id, seriesId: series.id, sequence: '2' })
|
||||
|
||||
const podcastLibrary = await Database.libraryModel.create({ name: 'Podcast Library', mediaType: 'podcast' })
|
||||
const podcastLibraryFolder = await Database.libraryFolderModel.create({ path: '/podcasts', libraryId: podcastLibrary.id })
|
||||
|
||||
const podcast = await Database.podcastModel.create({
|
||||
title: 'Test Podcast',
|
||||
tags: ['news'],
|
||||
genres: ['Technology'],
|
||||
autoDownloadEpisodes: false
|
||||
})
|
||||
const podcastLibraryItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: podcast.id,
|
||||
mediaType: 'podcast',
|
||||
libraryId: podcastLibrary.id,
|
||||
libraryFolderId: podcastLibraryFolder.id
|
||||
})
|
||||
podcastLibraryItemId = podcastLibraryItem.id
|
||||
|
||||
await Database.podcastEpisodeModel.create({
|
||||
podcastId: podcast.id,
|
||||
title: 'Episode 1',
|
||||
index: 1,
|
||||
audioFile: { ino: '3', metadata: { filename: 'ep1.mp3', ext: '.mp3', path: '/ep1.mp3', relPath: 'ep1.mp3' } }
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
describe('Book', () => {
|
||||
it('toOldJSONExpanded is a strict superset of toOldJSONMinified', async () => {
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(bookLibraryItemId)
|
||||
const minified = libraryItem.media.toOldJSONMinified()
|
||||
const expanded = libraryItem.media.toOldJSONExpanded(libraryItem.id)
|
||||
|
||||
assertExpandedSuperset(minified, expanded)
|
||||
|
||||
expect(expanded).to.have.property('libraryItemId', libraryItem.id)
|
||||
expect(expanded).to.have.property('audioFiles')
|
||||
expect(expanded).to.have.property('chapters')
|
||||
expect(expanded).to.have.property('tracks')
|
||||
expect(expanded.numTracks).to.equal(expanded.tracks.length)
|
||||
expect(expanded.numAudioFiles).to.equal(expanded.audioFiles.length)
|
||||
expect(expanded.numChapters).to.equal(expanded.chapters.length)
|
||||
expect(expanded.ebookFormat).to.equal('epub')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Podcast', () => {
|
||||
it('toOldJSONExpanded is a strict superset of toOldJSONMinified', async () => {
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(podcastLibraryItemId)
|
||||
const minified = libraryItem.media.toOldJSONMinified()
|
||||
const expanded = libraryItem.media.toOldJSONExpanded(libraryItem.id)
|
||||
|
||||
assertExpandedSuperset(minified, expanded)
|
||||
|
||||
expect(expanded).to.have.property('libraryItemId', libraryItem.id)
|
||||
expect(expanded).to.have.property('episodes')
|
||||
expect(expanded.numEpisodes).to.equal(expanded.episodes.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LibraryItem', () => {
|
||||
it('book library item expanded is a strict superset of minified', async () => {
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(bookLibraryItemId)
|
||||
const minified = libraryItem.toOldJSONMinified()
|
||||
const expanded = libraryItem.toOldJSONExpanded()
|
||||
|
||||
assertExpandedSuperset(minified, expanded)
|
||||
|
||||
expect(expanded).to.have.property('libraryFiles')
|
||||
expect(expanded).to.have.property('lastScan')
|
||||
expect(expanded.numFiles).to.equal(expanded.libraryFiles.length)
|
||||
expect(expanded.media.numTracks).to.equal(expanded.media.tracks.length)
|
||||
})
|
||||
|
||||
it('podcast library item expanded is a strict superset of minified', async () => {
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(podcastLibraryItemId)
|
||||
const minified = libraryItem.toOldJSONMinified()
|
||||
const expanded = libraryItem.toOldJSONExpanded()
|
||||
|
||||
assertExpandedSuperset(minified, expanded)
|
||||
|
||||
expect(expanded).to.have.property('libraryFiles')
|
||||
expect(expanded.media.numEpisodes).to.equal(expanded.media.episodes.length)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
const { expect } = require('chai')
|
||||
|
||||
const { isRequestSecure, getRequestProtocol, getRequestOrigin } = require('../../../server/utils/requestUtils')
|
||||
|
||||
function mockReq({ secure = false, host = 'books.example.com', xForwardedProto = null } = {}) {
|
||||
return {
|
||||
secure,
|
||||
get(header) {
|
||||
if (header === 'host') return host
|
||||
if (header === 'x-forwarded-proto') return xForwardedProto
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('requestUtils', () => {
|
||||
it('isRequestSecure uses req.secure', () => {
|
||||
expect(isRequestSecure(mockReq({ secure: true }))).to.equal(true)
|
||||
expect(isRequestSecure(mockReq({ secure: false }))).to.equal(false)
|
||||
})
|
||||
|
||||
it('isRequestSecure uses x-forwarded-proto', () => {
|
||||
expect(isRequestSecure(mockReq({ xForwardedProto: 'https' }))).to.equal(true)
|
||||
expect(isRequestSecure(mockReq({ xForwardedProto: 'http' }))).to.equal(false)
|
||||
expect(isRequestSecure(mockReq({ xForwardedProto: 'http, https' }))).to.equal(true)
|
||||
})
|
||||
|
||||
it('getRequestProtocol returns https or http', () => {
|
||||
expect(getRequestProtocol(mockReq({ secure: true }))).to.equal('https')
|
||||
expect(getRequestProtocol(mockReq())).to.equal('http')
|
||||
})
|
||||
|
||||
it('getRequestOrigin builds origin from protocol and host', () => {
|
||||
expect(getRequestOrigin(mockReq({ secure: true }))).to.deep.equal({
|
||||
protocol: 'https',
|
||||
host: 'books.example.com',
|
||||
origin: 'https://books.example.com'
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user