mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-01 12:44:06 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ed62858dd | ||
|
|
f6ce14c051 | ||
|
|
6571c7b6aa | ||
|
|
85771965f1 | ||
|
|
f4204171a2 | ||
|
|
9ad14bd319 | ||
|
|
ce25867efd | ||
|
|
faa2a91266 | ||
|
|
2dd5fa5478 | ||
|
|
b734f38cda | ||
|
|
ab05d7fb5f | ||
|
|
79b5fe0784 | ||
|
|
2b2a3f63a6 | ||
|
|
94f3035489 | ||
|
|
c6918b6828 | ||
|
|
95aa00af90 | ||
|
|
1d89e3a58c | ||
|
|
41cbcf551d | ||
|
|
1e60d7af64 | ||
|
|
92bae242f1 | ||
|
|
34b037087b | ||
|
|
844b04c6ae | ||
|
|
c38fe60360 | ||
|
|
8c87ae8bad | ||
|
|
f85d03ce26 |
No files matched your search
@@ -15,7 +15,7 @@ on:
|
|||||||
- 'v*.*.*'
|
- 'v*.*.*'
|
||||||
# Only build when files in these directories have been changed
|
# Only build when files in these directories have been changed
|
||||||
paths:
|
paths:
|
||||||
- client/**
|
- scripts/fetch-client-react-runtime.js
|
||||||
- server/**
|
- server/**
|
||||||
- index.js
|
- index.js
|
||||||
- package.json
|
- package.json
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ on:
|
|||||||
- 'dependabot/**' # Don't run dependabot branches, as they are already covered by pull requests
|
- 'dependabot/**' # Don't run dependabot branches, as they are already covered by pull requests
|
||||||
# Only build when files in these directories have been changed
|
# Only build when files in these directories have been changed
|
||||||
paths:
|
paths:
|
||||||
- client/**
|
|
||||||
- server/**
|
- server/**
|
||||||
- test/**
|
- test/**
|
||||||
- index.js
|
- index.js
|
||||||
- package.json
|
- package.json
|
||||||
- tsconfig.server.json
|
- tsconfig.server.json
|
||||||
|
- scripts/fetch-client-react-runtime.js
|
||||||
|
- .github/workflows/integration-test.yml
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -30,24 +31,19 @@ jobs:
|
|||||||
- name: install pkg (using yao-pkg fork for targeting node24)
|
- name: install pkg (using yao-pkg fork for targeting node24)
|
||||||
run: npm install -g @yao-pkg/pkg
|
run: npm install -g @yao-pkg/pkg
|
||||||
|
|
||||||
- name: get client dependencies
|
|
||||||
working-directory: client
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: build client
|
|
||||||
working-directory: client
|
|
||||||
run: npm run generate
|
|
||||||
|
|
||||||
- name: get server dependencies and compile server
|
- name: get server dependencies and compile server
|
||||||
run: npm ci && npm run build:server && npm prune --omit=dev
|
run: npm ci && npm run build:server && npm prune --omit=dev
|
||||||
|
|
||||||
- name: build binary
|
- name: build binary
|
||||||
run: pkg --config package.json -t node24-linux-x64 -o audiobookshelf dist-server/index.js
|
run: pkg --config package.json -t node24-linux-x64 -o dist/pkg/audiobookshelf dist-server/index.js
|
||||||
|
|
||||||
|
- name: fetch the React client runtime
|
||||||
|
run: node scripts/fetch-client-react-runtime.js --out dist/pkg/client-react
|
||||||
|
|
||||||
- name: run audiobookshelf
|
- name: run audiobookshelf
|
||||||
run: |
|
run: |
|
||||||
./audiobookshelf &
|
REACT_CLIENT_PATH="$PWD/dist/pkg/client-react" ./dist/pkg/audiobookshelf &
|
||||||
sleep 5
|
sleep 5
|
||||||
|
|
||||||
- name: test if server is available
|
- name: test if server is available
|
||||||
run: curl -sf http://127.0.0.1:3333 | grep Audiobookshelf
|
run: curl -sf --retry 30 --retry-delay 2 --retry-connrefused http://127.0.0.1:3333/healthcheck
|
||||||
+11
-8
@@ -1,13 +1,13 @@
|
|||||||
ARG NUSQLITE3_DIR="/usr/local/lib/nusqlite3"
|
ARG NUSQLITE3_DIR="/usr/local/lib/nusqlite3"
|
||||||
ARG NUSQLITE3_PATH="${NUSQLITE3_DIR}/libnusqlite3.so"
|
ARG NUSQLITE3_PATH="${NUSQLITE3_DIR}/libnusqlite3.so"
|
||||||
|
|
||||||
### STAGE 0: Build client ###
|
### STAGE 0: Fetch the pinned React client runtime. ###
|
||||||
FROM node:24-alpine AS build-client
|
FROM node:24-alpine AS fetch-client
|
||||||
|
|
||||||
WORKDIR /client
|
WORKDIR /fetch
|
||||||
COPY /client /client
|
COPY package.json /fetch/package.json
|
||||||
RUN npm ci && npm cache clean --force
|
COPY scripts/fetch-client-react-runtime.js /fetch/scripts/fetch-client-react-runtime.js
|
||||||
RUN npm run generate
|
RUN node scripts/fetch-client-react-runtime.js --out /out/client-react
|
||||||
|
|
||||||
### STAGE 1: Compile server on the builder CPU (avoid QEMU SIGILL from tsc on arm64) ###
|
### STAGE 1: Compile server on the builder CPU (avoid QEMU SIGILL from tsc on arm64) ###
|
||||||
FROM --platform=$BUILDPLATFORM node:24-alpine AS compile-server
|
FROM --platform=$BUILDPLATFORM node:24-alpine AS compile-server
|
||||||
@@ -63,8 +63,10 @@ RUN apk add --no-cache --update \
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Copy compiled frontend and server from build stages
|
# The React runtime must be writable: startup rewrites the base-path placeholder
|
||||||
COPY --from=build-client /client/dist /app/client/dist
|
# and Next writes its cache under .next.
|
||||||
|
COPY --from=fetch-client /out/client-react /app/client-react
|
||||||
|
RUN chmod -R a+rwX /app/client-react/.next
|
||||||
COPY --from=build-server /server /app
|
COPY --from=build-server /server /app
|
||||||
COPY --from=build-server ${NUSQLITE3_PATH} ${NUSQLITE3_PATH}
|
COPY --from=build-server ${NUSQLITE3_PATH} ${NUSQLITE3_PATH}
|
||||||
|
|
||||||
@@ -75,6 +77,7 @@ ENV NODE_ENV=production
|
|||||||
ENV CONFIG_PATH="/config"
|
ENV CONFIG_PATH="/config"
|
||||||
ENV METADATA_PATH="/metadata"
|
ENV METADATA_PATH="/metadata"
|
||||||
ENV SOURCE="docker"
|
ENV SOURCE="docker"
|
||||||
|
ENV REACT_CLIENT_PATH="/app/client-react"
|
||||||
ENV NUSQLITE3_DIR=${NUSQLITE3_DIR}
|
ENV NUSQLITE3_DIR=${NUSQLITE3_DIR}
|
||||||
ENV NUSQLITE3_PATH=${NUSQLITE3_PATH}
|
ENV NUSQLITE3_PATH=${NUSQLITE3_PATH}
|
||||||
|
|
||||||
|
|||||||
@@ -44,4 +44,10 @@ if [ ! -d "$ABS_LOG_DIR" ]; then
|
|||||||
chown -R 'audiobookshelf:audiobookshelf' "$ABS_LOG_DIR"
|
chown -R 'audiobookshelf:audiobookshelf' "$ABS_LOG_DIR"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Startup rewrites the React client's base-path placeholder and Next writes its cache under .next.
|
||||||
|
CLIENT_REACT_DIR="/usr/share/audiobookshelf/client-react"
|
||||||
|
if [ -d "$CLIENT_REACT_DIR" ]; then
|
||||||
|
chown -R 'audiobookshelf:audiobookshelf' "$CLIENT_REACT_DIR"
|
||||||
|
fi
|
||||||
|
|
||||||
start_service 'audiobookshelf'
|
start_service 'audiobookshelf'
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
# dpkg removes the packaged files. This deletes the base-path snapshot and Next
|
||||||
|
# cache, which are created at runtime and are not in the package file list.
|
||||||
|
# postrm upgrade runs after the new package is unpacked, so leave the directory in place then.
|
||||||
|
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
|
||||||
|
rm -rf /usr/share/audiobookshelf/client-react
|
||||||
|
fi
|
||||||
@@ -46,19 +46,18 @@ add_group() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setup_config() {
|
setup_config() {
|
||||||
|
if [ ! -d "$DEFAULT_DATA_DIR" ]; then
|
||||||
|
# Create directory and set permissions
|
||||||
|
echo "Creating default data dir at $DEFAULT_DATA_DIR"
|
||||||
|
mkdir -p "$DEFAULT_DATA_DIR"
|
||||||
|
fi
|
||||||
|
chown 'audiobookshelf:audiobookshelf' "$DEFAULT_DATA_DIR"
|
||||||
|
|
||||||
if [ -f "$CONFIG_PATH" ]; then
|
if [ -f "$CONFIG_PATH" ]; then
|
||||||
echo "Existing config found."
|
echo "Existing config found."
|
||||||
cat $CONFIG_PATH
|
cat $CONFIG_PATH
|
||||||
|
|
||||||
else
|
else
|
||||||
|
|
||||||
if [ ! -d "$DEFAULT_DATA_DIR" ]; then
|
|
||||||
# Create directory and set permissions
|
|
||||||
echo "Creating default data dir at $DEFAULT_DATA_DIR"
|
|
||||||
mkdir "$DEFAULT_DATA_DIR"
|
|
||||||
chown -R 'audiobookshelf:audiobookshelf' "$DEFAULT_DATA_DIR"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Creating default config."
|
echo "Creating default config."
|
||||||
|
|
||||||
config_text="METADATA_PATH=$DEFAULT_DATA_DIR/metadata
|
config_text="METADATA_PATH=$DEFAULT_DATA_DIR/metadata
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ Restart=always
|
|||||||
User=audiobookshelf
|
User=audiobookshelf
|
||||||
Group=audiobookshelf
|
Group=audiobookshelf
|
||||||
Environment=HOME=/var/cache/audiobookshelf
|
Environment=HOME=/var/cache/audiobookshelf
|
||||||
|
Environment=REACT_CLIENT_PATH=/usr/share/audiobookshelf/client-react
|
||||||
CacheDirectory=audiobookshelf
|
CacheDirectory=audiobookshelf
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
|||||||
+7
-10
@@ -11,15 +11,6 @@ VERSION="$( eval echo $( jq '.version' package.json) )"
|
|||||||
DESCRIPTION="$( eval echo $( jq '.description' package.json) )"
|
DESCRIPTION="$( eval echo $( jq '.description' package.json) )"
|
||||||
OUTPUT_FILE="audiobookshelf_${VERSION}_amd64.deb"
|
OUTPUT_FILE="audiobookshelf_${VERSION}_amd64.deb"
|
||||||
|
|
||||||
echo ">>> Building Client"
|
|
||||||
echo "--------------------"
|
|
||||||
|
|
||||||
cd client
|
|
||||||
rm -rf node_modules
|
|
||||||
npm ci
|
|
||||||
npm run generate
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
echo ">>> Building Server"
|
echo ">>> Building Server"
|
||||||
echo "--------------------"
|
echo "--------------------"
|
||||||
|
|
||||||
@@ -47,11 +38,17 @@ Description: $DESCRIPTION"
|
|||||||
|
|
||||||
echo "$controlfile" > dist/debian/DEBIAN/control;
|
echo "$controlfile" > dist/debian/DEBIAN/control;
|
||||||
|
|
||||||
|
echo ">>> Fetching React client runtime"
|
||||||
|
echo "--------------------"
|
||||||
|
|
||||||
|
mkdir -p dist/debian/usr/share/audiobookshelf
|
||||||
|
node scripts/fetch-client-react-runtime.js --out dist/debian/usr/share/audiobookshelf/client-react
|
||||||
|
|
||||||
# Package contents: directories 0755, files 0644 (including the systemd unit).
|
# Package contents: directories 0755, files 0644 (including the systemd unit).
|
||||||
# Maintainer scripts must stay executable so dpkg can run them.
|
# Maintainer scripts must stay executable so dpkg can run them.
|
||||||
find dist/debian -type d -exec chmod 755 {} +
|
find dist/debian -type d -exec chmod 755 {} +
|
||||||
find dist/debian -type f -exec chmod 644 {} +
|
find dist/debian -type f -exec chmod 644 {} +
|
||||||
chmod 755 dist/debian/DEBIAN/preinst dist/debian/DEBIAN/postinst dist/debian/DEBIAN/prerm
|
chmod 755 dist/debian/DEBIAN/preinst dist/debian/DEBIAN/postinst dist/debian/DEBIAN/prerm dist/debian/DEBIAN/postrm
|
||||||
|
|
||||||
# Package debian
|
# Package debian
|
||||||
pkg --config package.json -t node24-linux-x64 -o dist/debian/usr/share/audiobookshelf/audiobookshelf dist-server/index.js
|
pkg --config package.json -t node24-linux-x64 -o dist/debian/usr/share/audiobookshelf/audiobookshelf dist-server/index.js
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "audiobookshelf-client",
|
"name": "audiobookshelf-client",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "audiobookshelf-client",
|
"name": "audiobookshelf-client",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nuxtjs/axios": "^5.13.6",
|
"@nuxtjs/axios": "^5.13.6",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "audiobookshelf-client",
|
"name": "audiobookshelf-client",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"buildNumber": 1,
|
"buildNumber": 1,
|
||||||
"description": "Self-hosted audiobook and podcast client",
|
"description": "Self-hosted audiobook and podcast client",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
|
|||||||
@@ -13,11 +13,6 @@
|
|||||||
<widgets-online-indicator :value="!!userOnline" />
|
<widgets-online-indicator :value="!!userOnline" />
|
||||||
<h1 class="text-xl pl-2">{{ username }}</h1>
|
<h1 class="text-xl pl-2">{{ username }}</h1>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="legacyToken" class="text-xs space-y-2 mt-4">
|
|
||||||
<ui-text-input-with-label label="Legacy API Token" :value="legacyToken" readonly show-copy />
|
|
||||||
|
|
||||||
<p class="text-warning" v-html="$strings.MessageAuthenticationLegacyTokenWarning" />
|
|
||||||
</div>
|
|
||||||
<div class="w-full h-px bg-white/10 my-2" />
|
<div class="w-full h-px bg-white/10 my-2" />
|
||||||
<div class="py-2">
|
<div class="py-2">
|
||||||
<h1 class="text-lg mb-2 text-white/90 px-2 sm:px-0">{{ $strings.HeaderListeningStats }}</h1>
|
<h1 class="text-lg mb-2 text-white/90 px-2 sm:px-0">{{ $strings.HeaderListeningStats }}</h1>
|
||||||
@@ -102,12 +97,6 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
legacyToken() {
|
|
||||||
return this.user.token
|
|
||||||
},
|
|
||||||
userToken() {
|
|
||||||
return this.user.accessToken
|
|
||||||
},
|
|
||||||
bookCoverAspectRatio() {
|
bookCoverAspectRatio() {
|
||||||
return this.$store.getters['libraries/getBookCoverAspectRatio']
|
return this.$store.getters['libraries/getBookCoverAspectRatio']
|
||||||
},
|
},
|
||||||
|
|||||||
+1
-24
@@ -40,15 +40,6 @@
|
|||||||
|
|
||||||
<p v-if="error" class="text-error text-center py-2">{{ error }}</p>
|
<p v-if="error" class="text-error text-center py-2">{{ error }}</p>
|
||||||
|
|
||||||
<div v-if="showNewAuthSystemMessage" class="mb-4">
|
|
||||||
<widgets-alert type="warning">
|
|
||||||
<div>
|
|
||||||
<p>{{ $strings.MessageAuthenticationSecurityMessage }}</p>
|
|
||||||
<a v-if="showNewAuthSystemAdminMessage" href="https://github.com/advplyr/audiobookshelf/discussions/4460" target="_blank" class="underline">{{ $strings.LabelMoreInfo }}</a>
|
|
||||||
</div>
|
|
||||||
</widgets-alert>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form v-show="login_local" @submit.prevent="submitForm">
|
<form v-show="login_local" @submit.prevent="submitForm">
|
||||||
<label class="text-xs text-gray-300 uppercase">{{ $strings.LabelUsername }}</label>
|
<label class="text-xs text-gray-300 uppercase">{{ $strings.LabelUsername }}</label>
|
||||||
<ui-text-input v-model.trim="username" autocomplete="username" :disabled="processing" class="mb-3 w-full" inputName="username" />
|
<ui-text-input v-model.trim="username" autocomplete="username" :disabled="processing" class="mb-3 w-full" inputName="username" />
|
||||||
@@ -94,10 +85,7 @@ export default {
|
|||||||
MetadataPath: '',
|
MetadataPath: '',
|
||||||
login_local: true,
|
login_local: true,
|
||||||
login_openid: false,
|
login_openid: false,
|
||||||
authFormData: null,
|
authFormData: null
|
||||||
// New JWT auth system re-login flags
|
|
||||||
showNewAuthSystemMessage: false,
|
|
||||||
showNewAuthSystemAdminMessage: false
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
@@ -201,8 +189,6 @@ export default {
|
|||||||
},
|
},
|
||||||
async submitForm() {
|
async submitForm() {
|
||||||
this.error = null
|
this.error = null
|
||||||
this.showNewAuthSystemMessage = false
|
|
||||||
this.showNewAuthSystemAdminMessage = false
|
|
||||||
this.processing = true
|
this.processing = true
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -238,15 +224,6 @@ export default {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
// Force re-login if user is using an old token with no expiration
|
|
||||||
if (res.user.isOldToken) {
|
|
||||||
this.username = res.user.username
|
|
||||||
this.showNewAuthSystemMessage = true
|
|
||||||
// Admin user sees link to github discussion
|
|
||||||
this.showNewAuthSystemAdminMessage = res.user.type === 'admin' || res.user.type === 'root'
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
this.setUser(res)
|
this.setUser(res)
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -43,12 +43,21 @@ const inputMetadata = options.metadata ? Path.resolve(options.metadata) : null
|
|||||||
|
|
||||||
const PORT = options.port || process.env.PORT || 3333
|
const PORT = options.port || process.env.PORT || 3333
|
||||||
const HOST = options.host || process.env.HOST
|
const HOST = options.host || process.env.HOST
|
||||||
|
// Keep process.env in sync so the embedded React client calls this server when CLI flags are used.
|
||||||
|
process.env.PORT = String(PORT)
|
||||||
|
if (HOST) process.env.HOST = HOST
|
||||||
const CONFIG_PATH = inputConfig || process.env.CONFIG_PATH || Path.resolve('config')
|
const CONFIG_PATH = inputConfig || process.env.CONFIG_PATH || Path.resolve('config')
|
||||||
const METADATA_PATH = inputMetadata || process.env.METADATA_PATH || Path.resolve('metadata')
|
const METADATA_PATH = inputMetadata || process.env.METADATA_PATH || Path.resolve('metadata')
|
||||||
const SOURCE = options.source || process.env.SOURCE || 'debian'
|
const SOURCE = options.source || process.env.SOURCE || 'debian'
|
||||||
|
|
||||||
const ROUTER_BASE_PATH = process.env.ROUTER_BASE_PATH ?? '/audiobookshelf'
|
const ROUTER_BASE_PATH = process.env.ROUTER_BASE_PATH ?? '/audiobookshelf'
|
||||||
|
|
||||||
|
// v3 serves only the React client.
|
||||||
|
if (!String(process.env.REACT_CLIENT_PATH || '').trim()) {
|
||||||
|
console.error('REACT_CLIENT_PATH is required')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`Running in ${process.env.NODE_ENV} mode.`)
|
console.log(`Running in ${process.env.NODE_ENV} mode.`)
|
||||||
console.log(`Options: CONFIG_PATH=${CONFIG_PATH}, METADATA_PATH=${METADATA_PATH}, PORT=${PORT}, HOST=${HOST}, SOURCE=${SOURCE}, ROUTER_BASE_PATH=${ROUTER_BASE_PATH}`)
|
console.log(`Options: CONFIG_PATH=${CONFIG_PATH}, METADATA_PATH=${METADATA_PATH}, PORT=${PORT}, HOST=${HOST}, SOURCE=${SOURCE}, ROUTER_BASE_PATH=${ROUTER_BASE_PATH}`)
|
||||||
|
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "audiobookshelf",
|
"name": "audiobookshelf",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "audiobookshelf",
|
"name": "audiobookshelf",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"license": "GPL-3.0",
|
"license": "GPL-3.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^0.27.2",
|
"axios": "^0.27.2",
|
||||||
|
|||||||
+5
-5
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "audiobookshelf",
|
"name": "audiobookshelf",
|
||||||
"version": "2.38.0",
|
"version": "3.0.0-beta",
|
||||||
"buildNumber": 1,
|
"buildNumber": 1,
|
||||||
|
"clientReactRelease": "v0.2.0",
|
||||||
"description": "Self-hosted audiobook and podcast server",
|
"description": "Self-hosted audiobook and podcast server",
|
||||||
"main": "dist-server/index.js",
|
"main": "dist-server/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -10,9 +11,9 @@
|
|||||||
"start": "node dist-server/index.js",
|
"start": "node dist-server/index.js",
|
||||||
"start-dev": "node dist-server/index.js --prod-with-dev-env",
|
"start-dev": "node dist-server/index.js --prod-with-dev-env",
|
||||||
"client": "cd client && npm ci && npm run generate",
|
"client": "cd client && npm ci && npm run generate",
|
||||||
"prod": "npm run client && npm ci && npm run build:server && npm run start",
|
"prod": "npm ci && npm run build:server && npm run start",
|
||||||
"build-win": "npm run client && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf -C GZip dist-server/index.js",
|
"build-win": "node scripts/fetch-client-react-runtime.js --out dist/win/client-react && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf -C GZip dist-server/index.js",
|
||||||
"build-win-no-compress": "npm run client && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf dist-server/index.js",
|
"build-win-no-compress": "node scripts/fetch-client-react-runtime.js --out dist/win/client-react && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf dist-server/index.js",
|
||||||
"build-linux": "build/linuxpackager",
|
"build-linux": "build/linuxpackager",
|
||||||
"docker": "docker buildx build --platform linux/amd64,linux/arm64 --push . -t advplyr/audiobookshelf",
|
"docker": "docker buildx build --platform linux/amd64,linux/arm64 --push . -t advplyr/audiobookshelf",
|
||||||
"docker-amd64-local": "docker buildx build --platform linux/amd64 --load . -t advplyr/audiobookshelf-amd64-local",
|
"docker-amd64-local": "docker buildx build --platform linux/amd64 --load . -t advplyr/audiobookshelf-amd64-local",
|
||||||
@@ -25,7 +26,6 @@
|
|||||||
"bin": "dist-server/index.js",
|
"bin": "dist-server/index.js",
|
||||||
"pkg": {
|
"pkg": {
|
||||||
"assets": [
|
"assets": [
|
||||||
"client/dist/**/*",
|
|
||||||
"node_modules/sqlite3/lib/binding/**/*.node",
|
"node_modules/sqlite3/lib/binding/**/*.node",
|
||||||
"dist-server/server/migrations/*.js"
|
"dist-server/server/migrations/*.js"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
/**
|
||||||
|
* Download the pinned audiobookshelf-client-react runtime archive and extract it.
|
||||||
|
*
|
||||||
|
* The tag comes from package.json "clientReactRelease" unless CLIENT_REACT_RELEASE is set.
|
||||||
|
* CLIENT_REACT_REPOSITORY overrides the GitHub repo (default audiobookshelf/audiobookshelf-client-react).
|
||||||
|
*
|
||||||
|
* Usage: node scripts/fetch-client-react-runtime.js --out <dest-dir>
|
||||||
|
*/
|
||||||
|
const fs = require('fs')
|
||||||
|
const os = require('os')
|
||||||
|
const path = require('path')
|
||||||
|
const { Readable } = require('stream')
|
||||||
|
const { pipeline } = require('stream/promises')
|
||||||
|
const { spawnSync } = require('child_process')
|
||||||
|
|
||||||
|
const ARCHIVE_NAME = 'audiobookshelf-client-runtime.tar.gz'
|
||||||
|
const DEFAULT_REPOSITORY = 'audiobookshelf/audiobookshelf-client-react'
|
||||||
|
const REPOSITORY_PATTERN = /^[\w.-]+\/[\w.-]+$/
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
const error = new Error(message)
|
||||||
|
error.userFacing = true
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
let out = null
|
||||||
|
for (let i = 2; i < argv.length; i++) {
|
||||||
|
const arg = argv[i]
|
||||||
|
if (arg === '--out') {
|
||||||
|
const value = argv[++i]
|
||||||
|
if (!value) fail('Missing value for --out')
|
||||||
|
out = value
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fail(`Unknown argument: ${arg}\nUsage: node scripts/fetch-client-react-runtime.js --out <dest-dir>`)
|
||||||
|
}
|
||||||
|
if (!out) fail('Usage: node scripts/fetch-client-react-runtime.js --out <dest-dir>')
|
||||||
|
return path.resolve(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPinnedTag() {
|
||||||
|
const fromEnv = process.env.CLIENT_REACT_RELEASE
|
||||||
|
if (fromEnv && fromEnv.trim()) return fromEnv.trim()
|
||||||
|
|
||||||
|
const packagePath = path.join(__dirname, '..', 'package.json')
|
||||||
|
let pkg
|
||||||
|
try {
|
||||||
|
pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
|
||||||
|
} catch (error) {
|
||||||
|
fail(`Cannot read ${packagePath}: ${error.message}`)
|
||||||
|
}
|
||||||
|
const tag = typeof pkg.clientReactRelease === 'string' ? pkg.clientReactRelease.trim() : ''
|
||||||
|
if (!tag || /[\s]/.test(tag)) {
|
||||||
|
fail(`package.json "clientReactRelease" must be one release tag, for example v0.1.0.`)
|
||||||
|
}
|
||||||
|
return tag
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRepository() {
|
||||||
|
const repository = (process.env.CLIENT_REACT_REPOSITORY || DEFAULT_REPOSITORY).trim()
|
||||||
|
if (!REPOSITORY_PATTERN.test(repository)) {
|
||||||
|
fail(`CLIENT_REACT_REPOSITORY must be owner/name. Got: ${repository}`)
|
||||||
|
}
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
function archiveUrl(repository, tag) {
|
||||||
|
return `https://github.com/${repository}/releases/download/${encodeURIComponent(tag)}/${ARCHIVE_NAME}`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadArchive(url, destination) {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
redirect: 'follow',
|
||||||
|
headers: { 'User-Agent': 'audiobookshelf-fetch-client-runtime' }
|
||||||
|
})
|
||||||
|
if (!response.ok) {
|
||||||
|
fail(`Failed to download ${url} (${response.status} ${response.statusText}). The client release must include ${ARCHIVE_NAME}.`)
|
||||||
|
}
|
||||||
|
if (!response.body) fail(`Failed to download ${url}: empty response body.`)
|
||||||
|
await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(destination))
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractArchive(archivePath, outDir) {
|
||||||
|
fs.rmSync(outDir, { recursive: true, force: true })
|
||||||
|
fs.mkdirSync(outDir, { recursive: true })
|
||||||
|
const result = spawnSync('tar', ['-xzf', archivePath, '-C', outDir, '--strip-components=1'], { stdio: 'inherit' })
|
||||||
|
if (result.error) {
|
||||||
|
fail(`Failed to run tar: ${result.error.message}. tar is required to extract the client runtime.`)
|
||||||
|
}
|
||||||
|
if (result.status !== 0) {
|
||||||
|
fail(`tar exited with status ${result.status} while extracting ${archivePath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertRuntime(outDir) {
|
||||||
|
const required = ['node_modules/next/package.json', '.next/BUILD_ID', 'next.config.mjs']
|
||||||
|
const missing = required.filter((relative) => !fs.existsSync(path.join(outDir, relative)))
|
||||||
|
if (missing.length) {
|
||||||
|
fail(`Extracted client runtime at ${outDir} is missing:\n${missing.join('\n')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const outDir = parseArgs(process.argv)
|
||||||
|
const tag = readPinnedTag()
|
||||||
|
const repository = readRepository()
|
||||||
|
const url = archiveUrl(repository, tag)
|
||||||
|
const archivePath = path.join(os.tmpdir(), `audiobookshelf-client-runtime-${process.pid}.tar.gz`)
|
||||||
|
|
||||||
|
console.log(`Fetching React client ${tag} from ${repository}`)
|
||||||
|
console.log(url)
|
||||||
|
try {
|
||||||
|
await downloadArchive(url, archivePath)
|
||||||
|
extractArchive(archivePath, outDir)
|
||||||
|
assertRuntime(outDir)
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(archivePath, { force: true })
|
||||||
|
}
|
||||||
|
console.log(`React client runtime extracted to ${outDir}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error(error && error.userFacing ? error.message : error && error.stack ? error.stack : String(error))
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
+2
-16
@@ -63,18 +63,6 @@ class Auth {
|
|||||||
return passport.authenticate('jwt', { session: false })(req, res, next)
|
return passport.authenticate('jwt', { session: false })(req, res, next)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Function to generate a jwt token for a given user
|
|
||||||
* TODO: Old method with no expiration
|
|
||||||
* @deprecated
|
|
||||||
*
|
|
||||||
* @param {{ id:string, username:string }} user
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
generateAccessToken(user) {
|
|
||||||
return this.tokenManager.generateAccessToken(user)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Invalidate all JWT sessions for a given user
|
* Invalidate all JWT sessions for a given user
|
||||||
* If user is current user and refresh token is valid, rotate tokens for the current session
|
* If user is current user and refresh token is valid, rotate tokens for the current session
|
||||||
@@ -270,10 +258,8 @@ class Auth {
|
|||||||
} else {
|
} else {
|
||||||
// UI request -> check if we have a callback url
|
// UI request -> check if we have a callback url
|
||||||
if (req.cookies.auth_cb) {
|
if (req.cookies.auth_cb) {
|
||||||
let stateQuery = req.cookies.auth_state ? `&state=${req.cookies.auth_state}` : ''
|
const stateQuery = req.cookies.auth_state ? `&state=${req.cookies.auth_state}` : ''
|
||||||
// UI request -> redirect to auth_cb url and send the jwt token as parameter
|
res.redirect(302, `${req.cookies.auth_cb}?accessToken=${userResponse.user.accessToken}${stateQuery}`)
|
||||||
// TODO: Temporarily continue sending the old token as setToken
|
|
||||||
res.redirect(302, `${req.cookies.auth_cb}?setToken=${userResponse.user.token}&accessToken=${userResponse.user.accessToken}${stateQuery}`)
|
|
||||||
} else {
|
} else {
|
||||||
Logger.error('[Auth] No callback or already expired')
|
Logger.error('[Auth] No callback or already expired')
|
||||||
res.redirect(`/login?error=${encodeURIComponent('No callback or already expired')}&autoLaunch=0`)
|
res.redirect(`/login?error=${encodeURIComponent('No callback or already expired')}&autoLaunch=0`)
|
||||||
|
|||||||
+2
-3
@@ -415,10 +415,9 @@ class Database {
|
|||||||
* Create root user
|
* Create root user
|
||||||
* @param {string} username
|
* @param {string} username
|
||||||
* @param {string} pash
|
* @param {string} pash
|
||||||
* @param {Auth} auth
|
|
||||||
* @returns {Promise<boolean>} true if created
|
* @returns {Promise<boolean>} true if created
|
||||||
*/
|
*/
|
||||||
async createRootUser(username, pash, auth) {
|
async createRootUser(username, pash) {
|
||||||
if (!this.sequelize) return false
|
if (!this.sequelize) return false
|
||||||
const transaction = await this.sequelize.transaction()
|
const transaction = await this.sequelize.transaction()
|
||||||
try {
|
try {
|
||||||
@@ -427,7 +426,7 @@ class Database {
|
|||||||
await transaction.rollback()
|
await transaction.rollback()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
await this.userModel.createRootUser(username, pash, auth, transaction)
|
await this.userModel.createRootUser(username, pash, transaction)
|
||||||
await transaction.commit()
|
await transaction.commit()
|
||||||
this.hasRootUser = true
|
this.hasRootUser = true
|
||||||
return true
|
return true
|
||||||
|
|||||||
+82
-58
@@ -1,4 +1,5 @@
|
|||||||
const Path = require('path')
|
const Path = require('path')
|
||||||
|
const Module = require('module')
|
||||||
const Sequelize = require('sequelize')
|
const Sequelize = require('sequelize')
|
||||||
const express = require('express')
|
const express = require('express')
|
||||||
const http = require('http')
|
const http = require('http')
|
||||||
@@ -68,6 +69,51 @@ function normalizeBasePath(basePath) {
|
|||||||
* one more `.server` down. Older react clients have no basePath and must keep
|
* one more `.server` down. Older react clients have no basePath and must keep
|
||||||
* Express-stripped URLs.
|
* Express-stripped URLs.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Next 16's production custom server loads `start-server.js` during prepare().
|
||||||
|
* That file loads `app-info-log.js`, which requires `inspector` at module scope
|
||||||
|
* to print a debugger URL. pkg's Node binary has no inspector, and calling the
|
||||||
|
* real builtin throws ERR_INSPECTOR_NOT_AVAILABLE. Return a stub instead of
|
||||||
|
* calling it. Outside pkg, Next gets the real module.
|
||||||
|
*/
|
||||||
|
function inspectorStub() {
|
||||||
|
const stub = {
|
||||||
|
url: () => undefined,
|
||||||
|
open() {},
|
||||||
|
close() {},
|
||||||
|
waitForDebugger() {},
|
||||||
|
console
|
||||||
|
}
|
||||||
|
stub.Session = class Session {
|
||||||
|
connect() {}
|
||||||
|
disconnect() {}
|
||||||
|
post(_method, callback) {
|
||||||
|
if (typeof callback === 'function') callback(null, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return stub
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInspectorRequest(id) {
|
||||||
|
return id === 'inspector' || id === 'node:inspector'
|
||||||
|
}
|
||||||
|
|
||||||
|
function allowPkgWithoutInspector() {
|
||||||
|
if (!process.pkg || Module.prototype.require.__absInspectorPatched) return
|
||||||
|
const originalRequire = Module.prototype.require
|
||||||
|
const originalLoad = Module._load
|
||||||
|
function requireWithInspectorFallback(id) {
|
||||||
|
if (isInspectorRequest(id)) return inspectorStub()
|
||||||
|
return originalRequire.apply(this, arguments)
|
||||||
|
}
|
||||||
|
requireWithInspectorFallback.__absInspectorPatched = true
|
||||||
|
Module.prototype.require = requireWithInspectorFallback
|
||||||
|
Module._load = function (request, parent, isMain) {
|
||||||
|
if (isInspectorRequest(request)) return inspectorStub()
|
||||||
|
return originalLoad.call(this, request, parent, isMain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function getPreparedNextBasePath(nextApp) {
|
function getPreparedNextBasePath(nextApp) {
|
||||||
const nodeServer = nextApp.server?.server
|
const nodeServer = nextApp.server?.server
|
||||||
const basePath = nodeServer?.nextConfig?.basePath
|
const basePath = nodeServer?.nextConfig?.basePath
|
||||||
@@ -395,65 +441,43 @@ class Server {
|
|||||||
})
|
})
|
||||||
router.get('/healthcheck', (req, res) => res.sendStatus(200))
|
router.get('/healthcheck', (req, res) => res.sendStatus(200))
|
||||||
|
|
||||||
|
// v3 serves only the React client. REACT_CLIENT_PATH is required.
|
||||||
|
// Next joins process.cwd() with dir. On Windows, path.join does not reset
|
||||||
|
// when dir is an absolute drive path, so the manifest lookup becomes
|
||||||
|
// cwd\D:\client\D:\client\.next\.... Run Next from the client directory
|
||||||
|
// and pass a relative dir.
|
||||||
const ReactClientPath = process.env.REACT_CLIENT_PATH
|
const ReactClientPath = process.env.REACT_CLIENT_PATH
|
||||||
if (!ReactClientPath) {
|
if (!String(ReactClientPath || '').trim()) {
|
||||||
// Static path to generated nuxt
|
throw new Error('REACT_CLIENT_PATH is required')
|
||||||
const distPath = Path.join(global.appRoot, '/client/dist')
|
|
||||||
router.use(express.static(distPath))
|
|
||||||
|
|
||||||
// Client dynamic routes
|
|
||||||
const dynamicRoutes = [
|
|
||||||
'/item/:id',
|
|
||||||
'/author/:id',
|
|
||||||
'/audiobook/:id/chapters',
|
|
||||||
'/audiobook/:id/edit',
|
|
||||||
'/audiobook/:id/manage',
|
|
||||||
'/library/:library',
|
|
||||||
'/library/:library/search',
|
|
||||||
'/library/:library/bookshelf/:id?',
|
|
||||||
'/library/:library/authors',
|
|
||||||
'/library/:library/narrators',
|
|
||||||
'/library/:library/stats',
|
|
||||||
'/library/:library/series/:id?',
|
|
||||||
'/library/:library/podcast/search',
|
|
||||||
'/library/:library/podcast/latest',
|
|
||||||
'/library/:library/podcast/download-queue',
|
|
||||||
'/config/users/:id',
|
|
||||||
'/config/users/:id/sessions',
|
|
||||||
'/config/item-metadata-utils/:id',
|
|
||||||
'/collection/:id',
|
|
||||||
'/playlist/:id',
|
|
||||||
'/share/:slug'
|
|
||||||
]
|
|
||||||
dynamicRoutes.forEach((route) => router.get(route, (req, res) => res.sendFile(Path.join(distPath, 'index.html'))))
|
|
||||||
} else {
|
|
||||||
// This is for using the experimental Next.js client
|
|
||||||
Logger.info(`Using React client at ${ReactClientPath}`)
|
|
||||||
const nextPath = Path.join(ReactClientPath, 'node_modules/next')
|
|
||||||
const next = require(nextPath)
|
|
||||||
const nextApp = next({ dev: Logger.isDev, dir: ReactClientPath })
|
|
||||||
const handle = nextApp.getRequestHandler()
|
|
||||||
await nextApp.prepare()
|
|
||||||
const nextBasePath = getPreparedNextBasePath(nextApp)
|
|
||||||
if (nextBasePath) {
|
|
||||||
Logger.info(`[Server] Next client basePath is "${nextBasePath}"`)
|
|
||||||
} else {
|
|
||||||
Logger.info(`[Server] Next client has no basePath; leaving Express-stripped URLs as-is`)
|
|
||||||
}
|
|
||||||
router.all('*', (req, res) => {
|
|
||||||
// Next is configured with the same base path as this router, but Express strips the mount
|
|
||||||
// prefix from req.url, so put it back. The bare mount path is passed through without a
|
|
||||||
// trailing slash, which Next would otherwise redirect away from on every request.
|
|
||||||
// Skip when Next has no basePath (older client on master).
|
|
||||||
if (nextBasePath && req.baseUrl) {
|
|
||||||
const queryIndex = req.url.indexOf('?')
|
|
||||||
const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex)
|
|
||||||
const search = queryIndex === -1 ? '' : req.url.slice(queryIndex)
|
|
||||||
req.url = `${req.baseUrl}${pathname === '/' ? '' : pathname}${search}`
|
|
||||||
}
|
|
||||||
handle(req, res)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
const reactClientDir = Path.resolve(ReactClientPath)
|
||||||
|
process.chdir(reactClientDir)
|
||||||
|
Logger.info(`Using React client at ${reactClientDir}`)
|
||||||
|
allowPkgWithoutInspector()
|
||||||
|
const nextPath = Path.join(reactClientDir, 'node_modules', 'next')
|
||||||
|
const next = require(nextPath)
|
||||||
|
const nextApp = next({ dev: Logger.isDev, dir: '.' })
|
||||||
|
const handle = nextApp.getRequestHandler()
|
||||||
|
await nextApp.prepare()
|
||||||
|
const nextBasePath = getPreparedNextBasePath(nextApp)
|
||||||
|
if (nextBasePath) {
|
||||||
|
Logger.info(`[Server] Next client basePath is "${nextBasePath}"`)
|
||||||
|
} else {
|
||||||
|
Logger.info(`[Server] Next client has no basePath; leaving Express-stripped URLs as-is`)
|
||||||
|
}
|
||||||
|
router.all('*', (req, res) => {
|
||||||
|
// Next is configured with the same base path as this router, but Express strips the mount
|
||||||
|
// prefix from req.url, so put it back. The bare mount path is passed through without a
|
||||||
|
// trailing slash, which Next would otherwise redirect away from on every request.
|
||||||
|
// Skip when Next has no basePath (older client on master).
|
||||||
|
if (nextBasePath && req.baseUrl) {
|
||||||
|
const queryIndex = req.url.indexOf('?')
|
||||||
|
const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex)
|
||||||
|
const search = queryIndex === -1 ? '' : req.url.slice(queryIndex)
|
||||||
|
req.url = `${req.baseUrl}${pathname === '/' ? '' : pathname}${search}`
|
||||||
|
}
|
||||||
|
handle(req, res)
|
||||||
|
})
|
||||||
|
|
||||||
const unixSocketPrefix = 'unix/'
|
const unixSocketPrefix = 'unix/'
|
||||||
if (this.Host?.startsWith(unixSocketPrefix)) {
|
if (this.Host?.startsWith(unixSocketPrefix)) {
|
||||||
@@ -479,7 +503,7 @@ class Server {
|
|||||||
const rootUsername = newRoot.username || 'root'
|
const rootUsername = newRoot.username || 'root'
|
||||||
const rootPash = newRoot.password ? await this.auth.localAuthStrategy.hashPassword(newRoot.password) : ''
|
const rootPash = newRoot.password ? await this.auth.localAuthStrategy.hashPassword(newRoot.password) : ''
|
||||||
if (!rootPash) Logger.warn(`[Server] Creating root user with no password`)
|
if (!rootPash) Logger.warn(`[Server] Creating root user with no password`)
|
||||||
const created = await Database.createRootUser(rootUsername, rootPash, this.auth)
|
const created = await Database.createRootUser(rootUsername, rootPash)
|
||||||
if (!created) {
|
if (!created) {
|
||||||
Logger.error(`[Server] attempt to init server when server already has a root user`)
|
Logger.error(`[Server] attempt to init server when server already has a root user`)
|
||||||
return res.sendStatus(500)
|
return res.sendStatus(500)
|
||||||
|
|||||||
@@ -80,7 +80,9 @@ class TokenManager {
|
|||||||
*/
|
*/
|
||||||
static isBearerAccessTokenPayload(decoded) {
|
static isBearerAccessTokenPayload(decoded) {
|
||||||
if (!decoded?.userId) return false
|
if (!decoded?.userId) return false
|
||||||
if (decoded.type === 'refresh') return false
|
// Legacy API tokens were signed with only userId and username, and never expired.
|
||||||
|
if (decoded.type !== 'access') return false
|
||||||
|
if (!decoded.exp) return false
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,30 +102,6 @@ class TokenManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate a JWT token for a given user
|
|
||||||
* TODO: Old method with no expiration
|
|
||||||
* @deprecated
|
|
||||||
*
|
|
||||||
* @param {{ id:string, username:string }} user
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
static generateAccessToken(user) {
|
|
||||||
return jwt.sign({ userId: user.id, username: user.username }, TokenManager.TokenSecret)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Function to generate a jwt token for a given user
|
|
||||||
* TODO: Old method with no expiration
|
|
||||||
* @deprecated
|
|
||||||
*
|
|
||||||
* @param {{ id:string, username:string }} user
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
generateAccessToken(user) {
|
|
||||||
return TokenManager.generateAccessToken(user)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate access token for a given user
|
* Generate access token for a given user
|
||||||
*
|
*
|
||||||
@@ -325,15 +303,6 @@ class TokenManager {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Temporary flag to report old tokens to users
|
|
||||||
// May be a better place for this but here means we dont have to decode the token again
|
|
||||||
if (!jwt_payload.exp && !user.isOldToken) {
|
|
||||||
Logger.debug(`[TokenManager] User ${user.username} is using an access token without an expiration`)
|
|
||||||
user.isOldToken = true
|
|
||||||
} else if (jwt_payload.exp && user.isOldToken !== undefined) {
|
|
||||||
delete user.isOldToken
|
|
||||||
}
|
|
||||||
|
|
||||||
// approve login
|
// approve login
|
||||||
done(null, user)
|
done(null, user)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,13 +28,12 @@ class UserController {
|
|||||||
*/
|
*/
|
||||||
async findAll(req, res) {
|
async findAll(req, res) {
|
||||||
if (!req.user.isAdminOrUp) return res.sendStatus(403)
|
if (!req.user.isAdminOrUp) return res.sendStatus(403)
|
||||||
const hideRootToken = !req.user.isRoot
|
|
||||||
|
|
||||||
const includes = (req.query.include || '').split(',').map((i) => i.trim())
|
const includes = (req.query.include || '').split(',').map((i) => i.trim())
|
||||||
|
|
||||||
// Minimal toJSONForBrowser does not include mediaProgress and bookmarks
|
// Minimal toJSONForBrowser does not include mediaProgress and bookmarks
|
||||||
const allUsers = await Database.userModel.findAll()
|
const allUsers = await Database.userModel.findAll()
|
||||||
const users = allUsers.map((u) => u.toOldJSONForBrowser(hideRootToken, true))
|
const users = allUsers.map((u) => u.toOldJSONForBrowser(true))
|
||||||
|
|
||||||
if (includes.includes('latestSession')) {
|
if (includes.includes('latestSession')) {
|
||||||
for (const user of users) {
|
for (const user of users) {
|
||||||
@@ -97,7 +96,7 @@ class UserController {
|
|||||||
return oldMediaProgress
|
return oldMediaProgress
|
||||||
})
|
})
|
||||||
|
|
||||||
const userJson = req.reqUser.toOldJSONForBrowser(!req.user.isRoot)
|
const userJson = req.reqUser.toOldJSONForBrowser()
|
||||||
|
|
||||||
userJson.mediaProgress = oldMediaProgresses
|
userJson.mediaProgress = oldMediaProgresses
|
||||||
|
|
||||||
@@ -128,7 +127,6 @@ class UserController {
|
|||||||
|
|
||||||
const userId = uuidv4()
|
const userId = uuidv4()
|
||||||
const pash = await this.auth.localAuthStrategy.hashPassword(req.body.password)
|
const pash = await this.auth.localAuthStrategy.hashPassword(req.body.password)
|
||||||
const token = this.auth.generateAccessToken({ id: userId, username: req.body.username })
|
|
||||||
const userType = req.body.type || 'user'
|
const userType = req.body.type || 'user'
|
||||||
|
|
||||||
// librariesAccessible and itemTagsSelected can be on req.body or req.body.permissions
|
// librariesAccessible and itemTagsSelected can be on req.body or req.body.permissions
|
||||||
@@ -173,7 +171,6 @@ class UserController {
|
|||||||
username: req.body.username,
|
username: req.body.username,
|
||||||
email: typeof req.body.email === 'string' ? req.body.email : null,
|
email: typeof req.body.email === 'string' ? req.body.email : null,
|
||||||
pash,
|
pash,
|
||||||
token,
|
|
||||||
isActive: !!req.body.isActive,
|
isActive: !!req.body.isActive,
|
||||||
permissions,
|
permissions,
|
||||||
bookmarks: [],
|
bookmarks: [],
|
||||||
@@ -236,16 +233,13 @@ class UserController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let hasUpdates = false
|
let hasUpdates = false
|
||||||
let shouldUpdateToken = false
|
|
||||||
let shouldInvalidateJwtSessions = false
|
let shouldInvalidateJwtSessions = false
|
||||||
// When changing username create a new API token
|
|
||||||
if (updatePayload.username && updatePayload.username !== user.username) {
|
if (updatePayload.username && updatePayload.username !== user.username) {
|
||||||
const usernameExists = await Database.userModel.checkUserExistsWithUsername(updatePayload.username)
|
const usernameExists = await Database.userModel.checkUserExistsWithUsername(updatePayload.username)
|
||||||
if (usernameExists) {
|
if (usernameExists) {
|
||||||
return res.status(400).send('Username already taken')
|
return res.status(400).send('Username already taken')
|
||||||
}
|
}
|
||||||
user.username = updatePayload.username
|
user.username = updatePayload.username
|
||||||
shouldUpdateToken = true
|
|
||||||
shouldInvalidateJwtSessions = true
|
shouldInvalidateJwtSessions = true
|
||||||
hasUpdates = true
|
hasUpdates = true
|
||||||
}
|
}
|
||||||
@@ -327,11 +321,6 @@ class UserController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (hasUpdates) {
|
if (hasUpdates) {
|
||||||
if (shouldUpdateToken) {
|
|
||||||
user.token = this.auth.generateAccessToken(user)
|
|
||||||
Logger.info(`[UserController] User ${user.username} has generated a new api token`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle JWT session invalidation for username/password changes
|
// Handle JWT session invalidation for username/password changes
|
||||||
if (shouldInvalidateJwtSessions) {
|
if (shouldInvalidateJwtSessions) {
|
||||||
const newTokens = await this.auth.invalidateJwtSessionsForUser(user, req, res)
|
const newTokens = await this.auth.invalidateJwtSessionsForUser(user, req, res)
|
||||||
|
|||||||
+3
-18
@@ -5,7 +5,6 @@ const { LRUCache } = require('lru-cache')
|
|||||||
const Logger = require('../Logger')
|
const Logger = require('../Logger')
|
||||||
const SocketAuthority = require('../SocketAuthority')
|
const SocketAuthority = require('../SocketAuthority')
|
||||||
const { isNullOrNaN } = require('../utils')
|
const { isNullOrNaN } = require('../utils')
|
||||||
const TokenManager = require('../auth/TokenManager')
|
|
||||||
|
|
||||||
class UserCache {
|
class UserCache {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -94,8 +93,6 @@ class User extends Model {
|
|||||||
this.pash
|
this.pash
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
this.type
|
this.type
|
||||||
/** @type {string} */
|
|
||||||
this.token
|
|
||||||
/** @type {boolean} */
|
/** @type {boolean} */
|
||||||
this.isActive
|
this.isActive
|
||||||
/** @type {boolean} */
|
/** @type {boolean} */
|
||||||
@@ -186,20 +183,16 @@ class User extends Model {
|
|||||||
* Create root user
|
* Create root user
|
||||||
* @param {string} username
|
* @param {string} username
|
||||||
* @param {string} pash
|
* @param {string} pash
|
||||||
* @param {import('../Auth')} auth
|
|
||||||
* @returns {Promise<User>}
|
* @returns {Promise<User>}
|
||||||
*/
|
*/
|
||||||
static async createRootUser(username, pash, auth, transaction = null) {
|
static async createRootUser(username, pash, transaction = null) {
|
||||||
const userId = uuidv4()
|
const userId = uuidv4()
|
||||||
|
|
||||||
const token = auth.generateAccessToken({ id: userId, username })
|
|
||||||
|
|
||||||
const newUser = {
|
const newUser = {
|
||||||
id: userId,
|
id: userId,
|
||||||
type: 'root',
|
type: 'root',
|
||||||
username,
|
username,
|
||||||
pash,
|
pash,
|
||||||
token,
|
|
||||||
isActive: true,
|
isActive: true,
|
||||||
permissions: this.getDefaultPermissionsForUserType('root'),
|
permissions: this.getDefaultPermissionsForUserType('root'),
|
||||||
bookmarks: [],
|
bookmarks: [],
|
||||||
@@ -314,15 +307,12 @@ class User extends Model {
|
|||||||
const username = userinfo.preferred_username || userinfo.name || userinfo.sub
|
const username = userinfo.preferred_username || userinfo.name || userinfo.sub
|
||||||
const email = userinfo.email && userinfo.email_verified ? userinfo.email : null
|
const email = userinfo.email && userinfo.email_verified ? userinfo.email : null
|
||||||
|
|
||||||
const token = TokenManager.generateAccessToken({ id: userId, username })
|
|
||||||
|
|
||||||
const newUser = {
|
const newUser = {
|
||||||
id: userId,
|
id: userId,
|
||||||
type: 'user',
|
type: 'user',
|
||||||
username,
|
username,
|
||||||
email,
|
email,
|
||||||
pash: null,
|
pash: null,
|
||||||
token,
|
|
||||||
isActive: true,
|
isActive: true,
|
||||||
permissions: this.getDefaultPermissionsForUserType('user'),
|
permissions: this.getDefaultPermissionsForUserType('user'),
|
||||||
bookmarks: [],
|
bookmarks: [],
|
||||||
@@ -514,6 +504,7 @@ class User extends Model {
|
|||||||
email: DataTypes.STRING,
|
email: DataTypes.STRING,
|
||||||
pash: DataTypes.STRING,
|
pash: DataTypes.STRING,
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
|
// Column remains so existing databases do not need a migration. New users leave it null.
|
||||||
token: DataTypes.STRING,
|
token: DataTypes.STRING,
|
||||||
isActive: {
|
isActive: {
|
||||||
type: DataTypes.BOOLEAN,
|
type: DataTypes.BOOLEAN,
|
||||||
@@ -596,11 +587,10 @@ class User extends Model {
|
|||||||
/**
|
/**
|
||||||
* User data for browser using old model
|
* User data for browser using old model
|
||||||
*
|
*
|
||||||
* @param {boolean} [hideRootToken=false]
|
|
||||||
* @param {boolean} [minimal=false]
|
* @param {boolean} [minimal=false]
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
toOldJSONForBrowser(hideRootToken = false, minimal = false) {
|
toOldJSONForBrowser(minimal = false) {
|
||||||
const seriesHideFromContinueListening = this.extraData?.seriesHideFromContinueListening || []
|
const seriesHideFromContinueListening = this.extraData?.seriesHideFromContinueListening || []
|
||||||
const librariesAccessible = this.permissions?.librariesAccessible || []
|
const librariesAccessible = this.permissions?.librariesAccessible || []
|
||||||
const itemTagsSelected = this.permissions?.itemTagsSelected || []
|
const itemTagsSelected = this.permissions?.itemTagsSelected || []
|
||||||
@@ -613,11 +603,6 @@ class User extends Model {
|
|||||||
username: this.username,
|
username: this.username,
|
||||||
email: this.email,
|
email: this.email,
|
||||||
type: this.type,
|
type: this.type,
|
||||||
// TODO: Old non-expiring token
|
|
||||||
token: this.type === 'root' && hideRootToken ? '' : this.token,
|
|
||||||
// TODO: Temporary flag not saved in db that is set in Auth.js jwtAuthCheck
|
|
||||||
// Necessary to detect apps using old tokens that no longer match the old token stored on the user
|
|
||||||
isOldToken: this.isOldToken,
|
|
||||||
mediaProgress: this.mediaProgresses?.map((mp) => mp.getOldMediaProgress()) || [],
|
mediaProgress: this.mediaProgresses?.map((mp) => mp.getOldMediaProgress()) || [],
|
||||||
seriesHideFromContinueListening: [...seriesHideFromContinueListening],
|
seriesHideFromContinueListening: [...seriesHideFromContinueListening],
|
||||||
bookmarks: this.bookmarks?.map((b) => ({ ...b })) || [],
|
bookmarks: this.bookmarks?.map((b) => ({ ...b })) || [],
|
||||||
|
|||||||
@@ -75,9 +75,6 @@ class Stream extends EventEmitter {
|
|||||||
get codecsToForceAAC() {
|
get codecsToForceAAC() {
|
||||||
return ['alac', 'ac3', 'eac3', 'opus']
|
return ['alac', 'ac3', 'eac3', 'opus']
|
||||||
}
|
}
|
||||||
get userToken() {
|
|
||||||
return this.user.token
|
|
||||||
}
|
|
||||||
// Fmp4 does not work on iOS devices: https://github.com/advplyr/audiobookshelf-app/issues/85
|
// Fmp4 does not work on iOS devices: https://github.com/advplyr/audiobookshelf-app/issues/85
|
||||||
// Workaround: Force AAC transcode for FLAC
|
// Workaround: Force AAC transcode for FLAC
|
||||||
get hlsSegmentType() {
|
get hlsSegmentType() {
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ describe('TokenManager', () => {
|
|||||||
describe('jwtAuthCheck', () => {
|
describe('jwtAuthCheck', () => {
|
||||||
const user = { id: userId, username: 'testuser', isActive: true }
|
const user = { id: userId, username: 'testuser', isActive: true }
|
||||||
|
|
||||||
|
it('rejects legacy API tokens that have no type or expiration', async () => {
|
||||||
|
const legacyToken = jwt.sign({ userId, username: 'testuser' }, secret)
|
||||||
|
const decoded = jwt.verify(legacyToken, secret)
|
||||||
|
const done = sinon.spy()
|
||||||
|
|
||||||
|
await tokenManager.jwtAuthCheck(decoded, done)
|
||||||
|
|
||||||
|
expect(done.calledWith(null, null)).to.be.true
|
||||||
|
})
|
||||||
|
|
||||||
it('rejects refresh tokens for API auth', async () => {
|
it('rejects refresh tokens for API auth', async () => {
|
||||||
const refreshToken = tokenManager.generateRefreshToken(user)
|
const refreshToken = tokenManager.generateRefreshToken(user)
|
||||||
const decoded = jwt.verify(refreshToken, secret)
|
const decoded = jwt.verify(refreshToken, secret)
|
||||||
|
|||||||
Reference in new issue
Block a user