Compare commits

...
24 Commits
Author SHA1 Message Date
advplyr f6ce14c051 Merge branch 'master' into v3 2026-11-29 17:36:32 -06:00
advplyr 6571c7b6aa Merge pull request #5777 from mikiher/v3-deployment
Require the React client in v3 builds
2026-11-28 15:23:39 -06:00
mikiher 85771965f1 Sync CLI port and host to process.env for the embedded React client 2026-11-28 08:03:32 +02:00
mikiher f4204171a2 Ensure Debian preinst creates and owns the data directory on reinstall 2026-11-27 17:15:38 +02:00
mikiher 9ad14bd319 Fetch the React client for Windows builds instead of bundling Vue 2026-11-26 21:18:41 +02:00
mikiher ce25867efd Package the React client in the Debian build 2026-11-26 21:17:59 +02:00
mikiher faa2a91266 Serve the fetched React client from the Docker image 2026-11-26 17:26:23 +02:00
mikiher 2dd5fa5478 Require the React client instead of serving Vue 2026-11-26 17:03:58 +02:00
mikiher b734f38cda Pin the React client runtime used by release builds 2026-11-26 17:02:41 +02:00
advplyr ab05d7fb5f Merge branch 'master' into v3 2026-11-19 17:39:40 -06:00
advplyr 79b5fe0784 Merge 2026-11-18 17:34:14 -06:00
advplyr 2b2a3f63a6 Merge branch 'master' into v3 2026-11-16 16:18:38 -06:00
advplyr 94f3035489 Merge branch 'master' into v3 2026-11-14 15:16:21 -06:00
advplyr c6918b6828 Merge branch 'master' into v3 2026-11-13 16:20:29 -06:00
advplyr 95aa00af90 When accessAll permission is false and allow list is empty then treat as dont allow any 2026-11-13 16:17:58 -06:00
advplyr 1d89e3a58c Merge branch 'master' into v3 2026-11-12 17:11:21 -06:00
advplyr 41cbcf551d Merge branch 'master' into v3 2026-11-11 19:09:07 -06:00
advplyr 1e60d7af64 Merge branch 'master' into v3 2026-11-09 17:10:29 -06:00
advplyr 92bae242f1 Merge branch 'master' into v3 2026-11-08 18:15:39 -06:00
advplyr 34b037087b Merge branch 'master' into v3 2026-11-05 17:50:37 -06:00
advplyr 844b04c6ae Merge branch 'master' into v3 2026-11-04 17:52:01 -06:00
advplyr c38fe60360 Remove User legacy API token 2026-11-03 17:00:53 -06:00
advplyr 8c87ae8bad Merge branch 'master' into v3 2026-11-01 17:27:04 -06:00
advplyr f85d03ce26 Set 3.0.0-beta package.json version 2026-10-31 12:08:29 -05:00
24 changed files with 301 additions and 229 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ on:
- 'v*.*.*'
# Only build when files in these directories have been changed
paths:
- client/**
- scripts/fetch-client-react-runtime.js
- server/**
- index.js
- package.json
+8 -12
View File
@@ -7,12 +7,13 @@ on:
- 'dependabot/**' # Don't run dependabot branches, as they are already covered by pull requests
# Only build when files in these directories have been changed
paths:
- client/**
- server/**
- test/**
- index.js
- package.json
- tsconfig.server.json
- scripts/fetch-client-react-runtime.js
- .github/workflows/integration-test.yml
jobs:
build:
@@ -30,24 +31,19 @@ jobs:
- name: install pkg (using yao-pkg fork for targeting node24)
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
run: npm ci && npm run build:server && npm prune --omit=dev
- 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
run: |
./audiobookshelf &
REACT_CLIENT_PATH="$PWD/dist/pkg/client-react" ./dist/pkg/audiobookshelf &
sleep 5
- 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
View File
@@ -1,13 +1,13 @@
ARG NUSQLITE3_DIR="/usr/local/lib/nusqlite3"
ARG NUSQLITE3_PATH="${NUSQLITE3_DIR}/libnusqlite3.so"
### STAGE 0: Build client ###
FROM node:24-alpine AS build-client
### STAGE 0: Fetch the pinned React client runtime. ###
FROM node:24-alpine AS fetch-client
WORKDIR /client
COPY /client /client
RUN npm ci && npm cache clean --force
RUN npm run generate
WORKDIR /fetch
COPY package.json /fetch/package.json
COPY scripts/fetch-client-react-runtime.js /fetch/scripts/fetch-client-react-runtime.js
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) ###
FROM --platform=$BUILDPLATFORM node:24-alpine AS compile-server
@@ -63,8 +63,10 @@ RUN apk add --no-cache --update \
WORKDIR /app
# Copy compiled frontend and server from build stages
COPY --from=build-client /client/dist /app/client/dist
# The React runtime must be writable: startup rewrites the base-path placeholder
# 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 ${NUSQLITE3_PATH} ${NUSQLITE3_PATH}
@@ -75,6 +77,7 @@ ENV NODE_ENV=production
ENV CONFIG_PATH="/config"
ENV METADATA_PATH="/metadata"
ENV SOURCE="docker"
ENV REACT_CLIENT_PATH="/app/client-react"
ENV NUSQLITE3_DIR=${NUSQLITE3_DIR}
ENV NUSQLITE3_PATH=${NUSQLITE3_PATH}
+6
View File
@@ -44,4 +44,10 @@ if [ ! -d "$ABS_LOG_DIR" ]; then
chown -R 'audiobookshelf:audiobookshelf' "$ABS_LOG_DIR"
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'
+10
View File
@@ -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
+7 -8
View File
@@ -46,19 +46,18 @@ add_group() {
}
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
echo "Existing config found."
cat $CONFIG_PATH
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."
config_text="METADATA_PATH=$DEFAULT_DATA_DIR/metadata
@@ -12,6 +12,7 @@ Restart=always
User=audiobookshelf
Group=audiobookshelf
Environment=HOME=/var/cache/audiobookshelf
Environment=REACT_CLIENT_PATH=/usr/share/audiobookshelf/client-react
CacheDirectory=audiobookshelf
[Install]
+7 -10
View File
@@ -11,15 +11,6 @@ VERSION="$( eval echo $( jq '.version' package.json) )"
DESCRIPTION="$( eval echo $( jq '.description' package.json) )"
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 "--------------------"
@@ -47,11 +38,17 @@ Description: $DESCRIPTION"
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).
# Maintainer scripts must stay executable so dpkg can run them.
find dist/debian -type d -exec chmod 755 {} +
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
pkg --config package.json -t node24-linux-x64 -o dist/debian/usr/share/audiobookshelf/audiobookshelf dist-server/index.js
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "audiobookshelf-client",
"version": "2.38.0",
"version": "3.0.0-beta",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "audiobookshelf-client",
"version": "2.38.0",
"version": "3.0.0-beta",
"license": "ISC",
"dependencies": {
"@nuxtjs/axios": "^5.13.6",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "audiobookshelf-client",
"version": "2.38.0",
"version": "3.0.0-beta",
"buildNumber": 1,
"description": "Self-hosted audiobook and podcast client",
"main": "index.js",
-11
View File
@@ -13,11 +13,6 @@
<widgets-online-indicator :value="!!userOnline" />
<h1 class="text-xl pl-2">{{ username }}</h1>
</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="py-2">
<h1 class="text-lg mb-2 text-white/90 px-2 sm:px-0">{{ $strings.HeaderListeningStats }}</h1>
@@ -102,12 +97,6 @@ export default {
}
},
computed: {
legacyToken() {
return this.user.token
},
userToken() {
return this.user.accessToken
},
bookCoverAspectRatio() {
return this.$store.getters['libraries/getBookCoverAspectRatio']
},
+1 -24
View File
@@ -40,15 +40,6 @@
<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">
<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" />
@@ -94,10 +85,7 @@ export default {
MetadataPath: '',
login_local: true,
login_openid: false,
authFormData: null,
// New JWT auth system re-login flags
showNewAuthSystemMessage: false,
showNewAuthSystemAdminMessage: false
authFormData: null
}
},
watch: {
@@ -201,8 +189,6 @@ export default {
},
async submitForm() {
this.error = null
this.showNewAuthSystemMessage = false
this.showNewAuthSystemAdminMessage = false
this.processing = true
const payload = {
@@ -238,15 +224,6 @@ export default {
}
})
.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)
return true
})
+9
View File
@@ -43,12 +43,21 @@ const inputMetadata = options.metadata ? Path.resolve(options.metadata) : null
const PORT = options.port || process.env.PORT || 3333
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 METADATA_PATH = inputMetadata || process.env.METADATA_PATH || Path.resolve('metadata')
const SOURCE = options.source || process.env.SOURCE || 'debian'
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(`Options: CONFIG_PATH=${CONFIG_PATH}, METADATA_PATH=${METADATA_PATH}, PORT=${PORT}, HOST=${HOST}, SOURCE=${SOURCE}, ROUTER_BASE_PATH=${ROUTER_BASE_PATH}`)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "audiobookshelf",
"version": "2.38.0",
"version": "3.0.0-beta",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "audiobookshelf",
"version": "2.38.0",
"version": "3.0.0-beta",
"license": "GPL-3.0",
"dependencies": {
"axios": "^0.27.2",
+5 -5
View File
@@ -1,7 +1,8 @@
{
"name": "audiobookshelf",
"version": "2.38.0",
"version": "3.0.0-beta",
"buildNumber": 1,
"clientReactRelease": "v0.2.0",
"description": "Self-hosted audiobook and podcast server",
"main": "dist-server/index.js",
"scripts": {
@@ -10,9 +11,9 @@
"start": "node dist-server/index.js",
"start-dev": "node dist-server/index.js --prod-with-dev-env",
"client": "cd client && npm ci && npm run generate",
"prod": "npm run client && 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-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",
"prod": "npm ci && npm run build:server && npm run start",
"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": "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",
"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",
@@ -25,7 +26,6 @@
"bin": "dist-server/index.js",
"pkg": {
"assets": [
"client/dist/**/*",
"node_modules/sqlite3/lib/binding/**/*.node",
"dist-server/server/migrations/*.js"
],
+126
View File
@@ -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
View File
@@ -63,18 +63,6 @@ class Auth {
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
* If user is current user and refresh token is valid, rotate tokens for the current session
@@ -270,10 +258,8 @@ class Auth {
} else {
// UI request -> check if we have a callback url
if (req.cookies.auth_cb) {
let stateQuery = req.cookies.auth_state ? `&state=${req.cookies.auth_state}` : ''
// UI request -> redirect to auth_cb url and send the jwt token as parameter
// 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}`)
const stateQuery = req.cookies.auth_state ? `&state=${req.cookies.auth_state}` : ''
res.redirect(302, `${req.cookies.auth_cb}?accessToken=${userResponse.user.accessToken}${stateQuery}`)
} else {
Logger.error('[Auth] No callback or already expired')
res.redirect(`/login?error=${encodeURIComponent('No callback or already expired')}&autoLaunch=0`)
+2 -3
View File
@@ -415,10 +415,9 @@ class Database {
* Create root user
* @param {string} username
* @param {string} pash
* @param {Auth} auth
* @returns {Promise<boolean>} true if created
*/
async createRootUser(username, pash, auth) {
async createRootUser(username, pash) {
if (!this.sequelize) return false
const transaction = await this.sequelize.transaction()
try {
@@ -427,7 +426,7 @@ class Database {
await transaction.rollback()
return false
}
await this.userModel.createRootUser(username, pash, auth, transaction)
await this.userModel.createRootUser(username, pash, transaction)
await transaction.commit()
this.hasRootUser = true
return true
+82 -58
View File
@@ -1,4 +1,5 @@
const Path = require('path')
const Module = require('module')
const Sequelize = require('sequelize')
const express = require('express')
const http = require('http')
@@ -68,6 +69,51 @@ function normalizeBasePath(basePath) {
* one more `.server` down. Older react clients have no basePath and must keep
* 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) {
const nodeServer = nextApp.server?.server
const basePath = nodeServer?.nextConfig?.basePath
@@ -395,65 +441,43 @@ class Server {
})
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
if (!ReactClientPath) {
// Static path to generated nuxt
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)
})
if (!String(ReactClientPath || '').trim()) {
throw new Error('REACT_CLIENT_PATH is required')
}
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/'
if (this.Host?.startsWith(unixSocketPrefix)) {
@@ -479,7 +503,7 @@ class Server {
const rootUsername = newRoot.username || 'root'
const rootPash = newRoot.password ? await this.auth.localAuthStrategy.hashPassword(newRoot.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) {
Logger.error(`[Server] attempt to init server when server already has a root user`)
return res.sendStatus(500)
+3 -34
View File
@@ -80,7 +80,9 @@ class TokenManager {
*/
static isBearerAccessTokenPayload(decoded) {
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
}
@@ -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
*
@@ -325,15 +303,6 @@ class TokenManager {
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
done(null, user)
}
+2 -13
View File
@@ -28,13 +28,12 @@ class UserController {
*/
async findAll(req, res) {
if (!req.user.isAdminOrUp) return res.sendStatus(403)
const hideRootToken = !req.user.isRoot
const includes = (req.query.include || '').split(',').map((i) => i.trim())
// Minimal toJSONForBrowser does not include mediaProgress and bookmarks
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')) {
for (const user of users) {
@@ -97,7 +96,7 @@ class UserController {
return oldMediaProgress
})
const userJson = req.reqUser.toOldJSONForBrowser(!req.user.isRoot)
const userJson = req.reqUser.toOldJSONForBrowser()
userJson.mediaProgress = oldMediaProgresses
@@ -128,7 +127,6 @@ class UserController {
const userId = uuidv4()
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'
// librariesAccessible and itemTagsSelected can be on req.body or req.body.permissions
@@ -173,7 +171,6 @@ class UserController {
username: req.body.username,
email: typeof req.body.email === 'string' ? req.body.email : null,
pash,
token,
isActive: !!req.body.isActive,
permissions,
bookmarks: [],
@@ -236,16 +233,13 @@ class UserController {
}
let hasUpdates = false
let shouldUpdateToken = false
let shouldInvalidateJwtSessions = false
// When changing username create a new API token
if (updatePayload.username && updatePayload.username !== user.username) {
const usernameExists = await Database.userModel.checkUserExistsWithUsername(updatePayload.username)
if (usernameExists) {
return res.status(400).send('Username already taken')
}
user.username = updatePayload.username
shouldUpdateToken = true
shouldInvalidateJwtSessions = true
hasUpdates = true
}
@@ -327,11 +321,6 @@ class UserController {
}
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
if (shouldInvalidateJwtSessions) {
const newTokens = await this.auth.invalidateJwtSessionsForUser(user, req, res)
+3 -18
View File
@@ -5,7 +5,6 @@ const { LRUCache } = require('lru-cache')
const Logger = require('../Logger')
const SocketAuthority = require('../SocketAuthority')
const { isNullOrNaN } = require('../utils')
const TokenManager = require('../auth/TokenManager')
class UserCache {
constructor() {
@@ -94,8 +93,6 @@ class User extends Model {
this.pash
/** @type {string} */
this.type
/** @type {string} */
this.token
/** @type {boolean} */
this.isActive
/** @type {boolean} */
@@ -186,20 +183,16 @@ class User extends Model {
* Create root user
* @param {string} username
* @param {string} pash
* @param {import('../Auth')} auth
* @returns {Promise<User>}
*/
static async createRootUser(username, pash, auth, transaction = null) {
static async createRootUser(username, pash, transaction = null) {
const userId = uuidv4()
const token = auth.generateAccessToken({ id: userId, username })
const newUser = {
id: userId,
type: 'root',
username,
pash,
token,
isActive: true,
permissions: this.getDefaultPermissionsForUserType('root'),
bookmarks: [],
@@ -314,15 +307,12 @@ class User extends Model {
const username = userinfo.preferred_username || userinfo.name || userinfo.sub
const email = userinfo.email && userinfo.email_verified ? userinfo.email : null
const token = TokenManager.generateAccessToken({ id: userId, username })
const newUser = {
id: userId,
type: 'user',
username,
email,
pash: null,
token,
isActive: true,
permissions: this.getDefaultPermissionsForUserType('user'),
bookmarks: [],
@@ -514,6 +504,7 @@ class User extends Model {
email: DataTypes.STRING,
pash: DataTypes.STRING,
type: DataTypes.STRING,
// Column remains so existing databases do not need a migration. New users leave it null.
token: DataTypes.STRING,
isActive: {
type: DataTypes.BOOLEAN,
@@ -596,11 +587,10 @@ class User extends Model {
/**
* User data for browser using old model
*
* @param {boolean} [hideRootToken=false]
* @param {boolean} [minimal=false]
* @returns
*/
toOldJSONForBrowser(hideRootToken = false, minimal = false) {
toOldJSONForBrowser(minimal = false) {
const seriesHideFromContinueListening = this.extraData?.seriesHideFromContinueListening || []
const librariesAccessible = this.permissions?.librariesAccessible || []
const itemTagsSelected = this.permissions?.itemTagsSelected || []
@@ -613,11 +603,6 @@ class User extends Model {
username: this.username,
email: this.email,
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()) || [],
seriesHideFromContinueListening: [...seriesHideFromContinueListening],
bookmarks: this.bookmarks?.map((b) => ({ ...b })) || [],
-3
View File
@@ -75,9 +75,6 @@ class Stream extends EventEmitter {
get codecsToForceAAC() {
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
// Workaround: Force AAC transcode for FLAC
get hlsSegmentType() {
+10
View File
@@ -39,6 +39,16 @@ describe('TokenManager', () => {
describe('jwtAuthCheck', () => {
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 () => {
const refreshToken = tokenManager.generateRefreshToken(user)
const decoded = jwt.verify(refreshToken, secret)