Skip to content

An open-source, self-hosted system for apps built with web technologies.

10.6 KB
Raw Blame
import { readFile, rename, rm, writeFile } from "node:fs/promises"
import { randomBytes, randomUUID, scrypt as derive, timingSafeEqual } from "node:crypto"
import { parseAuthenticationCredentials, type AuthenticationRequirements } from "@phreshos/core"
import Sessions, { type SessionRecord } from "./sessions"
import Keyv from "keyv"

const parameters = {

    cost: 16_384,

    blockSize: 8,

    parallelization: 1,

    keyLength: 64
} as const

const requirements: AuthenticationRequirements = Object.freeze({

    username: Object.freeze({

        minimumLength: 1,

        maximumLength: 64
    }),

    password: Object.freeze({

        minimumLength: 8,

        maximumLength: 1_024
    })
})

/** Persistent credentials for the sole owner of one installation. */
export default class Authentication {

    private owner: Owner | null

    private readonly path: string

    private readonly sessions: Sessions

    private changingCredentials: Promise<void> = Promise.resolve()

    private constructor(path: string, owner: Owner | null, sessions: Sessions) {

        this.path = path

        this.owner = owner

        this.sessions = sessions
    }

    public static async open(path: string, store: Keyv) {

        const sessions = await Sessions.open(store)

        try {

            return new Authentication(path, parse(await readFile(path, "utf8")), sessions)
        }

        catch (exception) {

            if (isMissing(exception)) return new Authentication(path, null, sessions)

            throw exception
        }
    }

    public get username(): string | null {

        return this.owner?.username ?? null
    }

    public state(): AuthenticationState {

        return {

            signedUp: this.owner !== null,

            requirements
        }
    }

    public requirements(): AuthenticationRequirements {

        return requirements
    }

    /** Replaces only the credential record; Session authority is independent. */
    public setCredentials(value: unknown) {

        const credentials = parseAuthenticationCredentials(value)

        return this.changeCredentials(async () => {

            const username = normalizeUsername(credentials.username)

            const invalid = validate(username, credentials.password)

            if (invalid) throw new Error(`The credentials are invalid: ${invalid}`)

            const owner = await createOwner(username, credentials.password)

            await this.replaceOwner(owner)

            this.owner = owner
        })
    }

    public async signUp(username: string, password: string): Promise<SignUpResult> {

        return this.changeCredentials(() => this.signUpNow(username, password))
    }

    private async signUpNow(username: string, password: string): Promise<SignUpResult> {

        if (this.owner) return { error: "signed-up" }

        const normalizedUsername = normalizeUsername(username)

        const invalid = validate(normalizedUsername, password)

        if (invalid) return { error: invalid }

        const owner = await createOwner(normalizedUsername, password)

        try {

            await writeFile(this.path, JSON.stringify(owner), { flag: "wx", mode: 0o600 })

            this.owner = owner

            return { signedUp: true }
        }

        catch (exception) {

            if (!isExisting(exception)) throw exception

            // Another sign-up won the exclusive write. Load that owner
            // before reporting the closed state so this instance cannot reopen it.
            this.owner = parse(await readFile(this.path, "utf8"))

            return { error: "signed-up" }
        }
    }

    private changeCredentials<Result>(change: () => Promise<Result>): Promise<Result> {

        const next = this.changingCredentials.then(change, change)

        this.changingCredentials = next.then(() => undefined, () => undefined)

        return next
    }

    private async replaceOwner(owner: Owner) {

        const temporary = `${this.path}.${randomUUID()}.changing`

        // Credential replacement crosses one filesystem boundary so an
        // interrupted update cannot leave an unreadable authentication record.
        try {

            await writeFile(temporary, JSON.stringify(owner), { flag: "wx", mode: 0o600 })

            await rename(temporary, this.path)
        }

        finally {

            await rm(temporary, { force: true }).catch(() => undefined)
        }
    }

    public async verify(username: string, password: string) {

        if (!this.owner) return false

        if ([...password].length > requirements.password.maximumLength) return false

        const candidate = await hashPassword(password, Buffer.from(this.owner.password.salt, "base64"), this.owner.password)

        const expected = Buffer.from(this.owner.password.hash, "base64")

        return normalizeUsername(username) === this.owner.username

            && candidate.length === expected.length

            && timingSafeEqual(candidate, expected)
    }

    /** Creates a Session and returns its Client-owned raw token exactly once. */
    public createSession(device: string | null) {

        return this.sessions.create(device)
    }

    /** Resolves one Client-owned raw token to a valid Session identity. */
    public resolveSession(token: string) {

        return this.sessions.resolve(token)
    }

    /** Returns every valid browser Session identity. */
    public sessionsList() {

        return this.sessions.list()
    }

    /** Resolves one valid browser Session identity. */
    public sessionFind(identity: string) {

        return this.sessions.find(identity)
    }

    /** Publishes a newly delivered browser Session into the authoritative registry. */
    public exposeSession(identity: string) {

        return this.sessions.expose(identity)
    }

    /** Observes browser Sessions removed by disconnected-lifetime expiration. */
    public onSessionExpire(listener: (identity: string, record: SessionRecord) => void) {

        return this.sessions.onExpire(listener)
    }

    /** When one known Session signed in and was last used, or `null` when it is unknown. */
    public describeSession(identity: string) {

        return this.sessions.describe(identity)
    }

    /** Whether a session is still within its connection-bound lifetime. */
    public sessionValid(identity: string) {

        return this.sessions.valid(identity)
    }

    /** Attaches one live Connection to a Session. */
    public connectSession(identity: string) {

        return this.sessions.attach(identity)
    }

    /** Detaches one live Connection and records its normal disconnection time. */
    public disconnectSession(identity: string) {

        return this.sessions.detach(identity)
    }

    /** Revokes a Session through an explicit sign-out operation. */
    public removeSession(identity: string) {

        return this.sessions.remove(identity)
    }
}

function normalizeUsername(username: string) {

    return username.trim().normalize("NFKC")
}

function validate(username: string, password: string): SignUpError | null {

    const usernameLength = [...username].length

    if (usernameLength < requirements.username.minimumLength) return "username-required"

    if (usernameLength > requirements.username.maximumLength || /\p{Cc}/u.test(username)) return "username-invalid"

    const passwordLength = [...password].length

    if (passwordLength < requirements.password.minimumLength) return "password-too-short"

    if (passwordLength > requirements.password.maximumLength) return "password-too-long"

    if (password.normalize("NFKC").toLowerCase() === username.toLowerCase()) return "password-matches-username"

    return null
}

function hashPassword(password: string, salt: Buffer, parameters: ScryptParameters) {

    return new Promise<Buffer>(function (resolve, reject) {

        derive(password, salt, parameters.keyLength, {

            cost: parameters.cost,

            blockSize: parameters.blockSize,

            parallelization: parameters.parallelization,

            maxmem: 64 * 1_024 * 1_024

        }, function (exception, key) {

            if (exception) reject(exception)

            else resolve(key)
        })
    })
}

async function createOwner(username: string, password: string): Promise<Owner> {

    const salt = randomBytes(16)

    const hash = await hashPassword(password, salt, parameters)

    return {

        version: 1,

        username,

        password: {

            algorithm: "scrypt",

            salt: salt.toString("base64"),

            hash: hash.toString("base64"),

            ...parameters
        }
    }
}

function parse(contents: string): Owner {

    const value: unknown = JSON.parse(contents)

    if (!isOwner(value)) throw new Error("The owner credentials are invalid")

    return value
}

function isOwner(value: unknown): value is Owner {

    if (!value || typeof value !== "object") return false

    const candidate = value as Partial<Owner>

    if (candidate.version !== 1

        || typeof candidate.username !== "string"

        || candidate.password?.algorithm !== "scrypt"

        || typeof candidate.password.salt !== "string"

        || typeof candidate.password.hash !== "string"

        || candidate.password.cost !== parameters.cost

        || candidate.password.blockSize !== parameters.blockSize

        || candidate.password.parallelization !== parameters.parallelization

        || candidate.password.keyLength !== parameters.keyLength) return false

    return Buffer.from(candidate.password.salt, "base64").length === 16

        && Buffer.from(candidate.password.hash, "base64").length === parameters.keyLength
}

function isMissing(exception: unknown) {

    return isFileError(exception, "ENOENT")
}

function isExisting(exception: unknown) {

    return isFileError(exception, "EEXIST")
}

function isFileError(exception: unknown, code: string) {

    return exception instanceof Error && "code" in exception && exception.code === code
}

export interface AuthenticationState {

    signedUp: boolean

    requirements: AuthenticationRequirements
}

export type SignUpResult = {

    signedUp: true

} | {

    error: SignUpError
}

export type SignUpError = "signed-up" | "username-required" | "username-invalid" | "password-too-short" | "password-too-long" | "password-matches-username"

interface Owner {

    version: 1

    username: string

    password: {

        algorithm: "scrypt"

        salt: string

        hash: string

        cost: number

        blockSize: number

        parallelization: number

        keyLength: number
    }
}

interface ScryptParameters {

    cost: number

    blockSize: number

    parallelization: number

    keyLength: number
}