Files
Webklar-Kundenbereich/test/support/appwriteMock.js
T

433 lines
23 KiB
JavaScript

import http from 'node:http'
/**
* Appwrite-Nachbau für Tests: die REST-Pfade, die server/services/appwriteAdmin.js benutzt, im
* Speicher. Mit schema = { collection: ['attr', ...] } lehnt er unbekannte Attribute ab wie
* Appwrite ("Invalid document structure: Unknown attribute"). Dokument-IDs prüft er wie Appwrite
* (höchstens 36 Zeichen aus a-z, A-Z, 0-9, Punkt, Bindestrich, Unterstrich, kein Sonderzeichen am
* Anfang). failNext({ collection?, method?, status, message?, after? }) lässt die nächste passende Anfrage
* mit diesem Status scheitern (Fehlerpfade wie "Appwrite nicht erreichbar" oder "Collection fehlt");
* after = Zahl passender Anfragen, die vorher noch durchgehen (z. B. erst die zweite PATCH scheitert).
*
* Bulk-Create (POST .../documents mit { documents: [{ $id, ...felder }] }, 1 bis 100 Dokumente) ist alles oder
* nichts: vorhandene oder doppelte $id => 409, ungueltige $id, unbekanntes Attribut oder ungueltiges Datum => 400,
* dann ist nichts geschrieben. Abfragen: equal, notEqual (mit Liste: keiner von; ein Dokument ohne das Feld passt),
* greaterThan(Equal), lessThan(Equal), between (inklusiv), orderAsc/orderDesc, limit, cursorAfter, select (nur die
* genannten Felder plus alle $-Felder). Die Antwort traegt total = Treffer der Filter, unabhaengig von limit und
* cursorAfter. listCalls(collection?) / resetListCalls() zeichnen die Listenabfragen auf. Zwei Werte, die beide
* wie "YYYY-MM-DDT..." aussehen, vergleicht er als Zeitpunkte (Schreibweise Z, +00:00, +02:00 ist egal), alle
* anderen wie bisher.
*
* Optionen (ohne sie verhaelt sich der Nachbau wie zuvor):
* datetimes { collection: ['feld', ...] } Datumsfelder; beim Schreiben (Anlegen, Aendern, Bulk, seed) wie
* Appwrite auf "...000+00:00" (UTC) normalisiert, '' oder Unlesbares => 400, null bleibt erlaubt
* defaultLimit Zahl: gilt ohne limit-Abfrage wie Appwrites 25 (Termine-Tests: 25), null = unbegrenzt
*/
export async function startAppwriteMock({ schema = {}, datetimes = {}, defaultLimit = null } = {}) {
const collections = new Map()
let sequence = 0
let pendingFailure = null
// Konten, Sitzungen und MFA wie Appwrite 1.8.1 (Mitarbeiter-2FA): addUser(), lastOtp(), mailsSent()
const users = new Map()
const sessions = new Map()
const challenges = new Map()
const mails = new Map()
const userCalls = []
let lastLocale = null
let failUserLookups = false
let sessionDeletes = 0
// Aufzeichnung der Listenabfragen (GET .../documents ohne ID): [{ collection, queries: [geparste Abfragen] }]
let listLog = []
// Wie Appwrite (Validator UID): 'unique()' ist erlaubt, sonst [A-Za-z0-9][A-Za-z0-9._-]{0,35}
const validDocumentId = (id) => id === 'unique()' || (typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,35}$/.test(id))
const invalidDocumentId = [
400,
{
message: 'Invalid `documentId` param: UID must contain at most 36 chars. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char',
code: 400,
type: 'general_argument_invalid',
},
]
const documentExists = [409, { message: 'Document with the requested ID already exists.', code: 409, type: 'document_already_exists' }]
const docs = (collection) => {
if (!collections.has(collection)) collections.set(collection, new Map())
return collections.get(collection)
}
const stamp = (doc, collection) => {
const now = new Date().toISOString()
return { $createdAt: now, $updatedAt: now, $collectionId: collection, ...doc, $seq: (sequence += 1) }
}
const seed = (collection, doc) => {
if (!doc?.$id) throw new Error('seed: $id fehlt')
const [normalized, badDate] = normalizeDates(collection, doc)
if (badDate) throw new Error(`seed: ${collection}.${badDate} ist kein gueltiges Datum`)
docs(collection).set(doc.$id, stamp(normalized, collection))
}
// Zeitpunkt eines Textes wie "2026-10-05T10:00:00Z" (ohne Zonenangabe gilt UTC); NaN, wenn es keiner ist
const isoStart = /^\d{4}-\d\d-\d\dT/
const hasZone = /(?:Z|[+-]\d\d(?::?\d\d)?)$/i
const instant = (value) => (typeof value === 'string' && isoStart.test(value) ? Date.parse(hasZone.test(value) ? value : `${value}Z`) : Number.NaN)
// Beide Seiten Zeitpunkte => deren Millisekunden, sonst die Werte selbst (Vergleich wie bisher)
const comparable = (a, b) => {
const x = instant(a)
const y = instant(b)
return Number.isNaN(x) || Number.isNaN(y) ? [a, b] : [x, y]
}
const same = (a, b) => {
const [x, y] = comparable(a, b)
return x === y
}
const greater = (a, b) => {
const [x, y] = comparable(a, b)
return x > y
}
const less = (a, b) => {
const [x, y] = comparable(a, b)
return x < y
}
const atLeast = (a, b) => {
const [x, y] = comparable(a, b)
return x >= y
}
const atMost = (a, b) => {
const [x, y] = comparable(a, b)
return x <= y
}
// Datumsfelder der Collection wie Appwrite speichern: UTC mit Millisekunden und "+00:00". Liefert
// [Daten, Schluessel des ersten ungueltigen Datums | null]
const normalizeDates = (collection, data) => {
const keys = datetimes[collection]
if (!keys?.length) return [data, null]
const out = { ...data }
for (const key of keys) {
const value = out[key]
if (value === undefined || value === null) continue
let ms = Number.NaN
if (value instanceof Date) ms = value.getTime()
else if (typeof value === 'string') ms = isoStart.test(value) ? instant(value) : /^\d{4}-\d\d-\d\d$/.test(value) ? Date.parse(value) : Number.NaN
if (Number.isNaN(ms)) return [data, key]
out[key] = new Date(ms).toISOString().replace('Z', '+00:00')
}
return [out, null]
}
const invalidDate = (key) => [400, { message: `Invalid document structure: Attribute "${key}" has invalid format. Value must be a valid date`, code: 400, type: 'document_invalid_structure' }]
const unknownAttribute = (collection, data) => {
const allowed = schema[collection]
if (!allowed) return null
return Object.keys(data).find((key) => !key.startsWith('$') && !allowed.includes(key)) || null
}
const matches = (doc, query) => {
const value = doc[query.attribute]
const [first, last] = query.values || []
switch (query.method) {
case 'equal':
return query.values.some((candidate) => same(value, candidate))
case 'notEqual':
return !query.values.some((candidate) => same(value, candidate))
case 'greaterThan':
return greater(value, first)
case 'greaterThanEqual':
return atLeast(value, first)
case 'lessThan':
return less(value, first)
case 'lessThanEqual':
return atMost(value, first)
case 'between':
return atLeast(value, first) && atMost(value, last)
default:
return true
}
}
const supportedQueries = ['equal', 'greaterThan', 'greaterThanEqual', 'lessThan', 'lessThanEqual', 'between', 'notEqual', 'orderAsc', 'orderDesc', 'limit', 'cursorAfter', 'select']
// Nur die genannten Felder plus alle $-Felder (wie Appwrite); $seq ist intern und faellt in publicDoc weg
const project = (doc, attributes) => Object.fromEntries(Object.entries(doc).filter(([key]) => key.startsWith('$') || attributes.includes(key)))
const list = (collection, rawQueries) => {
const queries = rawQueries.map((q) => JSON.parse(q))
const unsupported = queries.find((q) => !supportedQueries.includes(q.method))
if (unsupported) return [400, { message: `Query ${unsupported.method} wird nicht nachgebaut`, code: 400 }]
// cursorAfter: das Dokument mit dieser ID muss es geben (es muss aber nicht zu den Filtern passen)
const cursorId = queries.find((q) => q.method === 'cursorAfter')?.values[0]
if (cursorId !== undefined && !docs(collection).has(cursorId)) {
return [400, { message: 'The cursor is invalid. This can happen if the item represented by the cursor has been deleted.', code: 400, type: 'general_cursor_not_found' }]
}
const all = [...docs(collection).values()]
const hit = (doc) => queries.every((q) => matches(doc, q))
// total wie Appwrite: alle Treffer der Filter, ohne limit und cursorAfter
const total = all.filter(hit).length
let result = all.filter((doc) => doc.$id === cursorId || hit(doc))
for (const q of queries.filter((q) => q.method === 'orderAsc' || q.method === 'orderDesc')) {
const dir = q.method === 'orderAsc' ? 1 : -1
result.sort((a, b) => {
const [x, y] = comparable(a[q.attribute], b[q.attribute])
if (x === y) return (a.$seq - b.$seq) * dir
return (x > y ? 1 : -1) * dir
})
}
if (cursorId !== undefined) result = result.slice(result.findIndex((doc) => doc.$id === cursorId) + 1)
const limit = queries.find((q) => q.method === 'limit')?.values[0] ?? defaultLimit
if (limit !== null) result = result.slice(0, limit)
const selected = queries.filter((q) => q.method === 'select').flatMap((q) => q.values)
if (queries.some((q) => q.method === 'select')) result = result.map((doc) => project(doc, selected))
return [200, { total, documents: result.map(publicDoc) }]
}
const publicDoc = ({ $seq, ...doc }) => doc
const readBody = (req) =>
new Promise((resolve) => {
let raw = ''
req.on('data', (chunk) => (raw += chunk))
req.on('end', () => resolve(raw ? JSON.parse(raw) : {}))
})
const sessionOf = (req) => {
const match = String(req.headers.cookie || '').match(/a_session_[^=]+=([^;]+)/)
return match ? sessions.get(decodeURIComponent(match[1])) || null : null
}
const needsMoreFactors = (session) => {
const user = users.get(session.userId)
return Boolean(user?.mfa && user?.emailVerification && session.factors.length < 2)
}
const moreFactors = [401, { message: 'More factors are required to complete the sign in process.', code: 401, type: 'user_more_factors_required' }]
const publicUser = ({ password: _pw, ...user }) => ({ passwordUpdate: '', labels: [], mfa: false, emailVerification: false, ...user })
const handleAuth = async (req, url) => {
if (url.pathname === '/v1/account/sessions/email' && req.method === 'POST') {
const { email, password } = await readBody(req)
const user = [...users.values()].find((u) => u.email === email && u.password === password)
if (!user) return [401, { message: 'Invalid credentials.', code: 401, type: 'user_invalid_credentials' }]
const secret = `sess-${user.$id}`
sessions.set(secret, { userId: user.$id, factors: ['password'] })
const project = req.headers['x-appwrite-project'] || 'x'
return [201, { $id: `s-${user.$id}`, userId: user.$id }, { 'Set-Cookie': `a_session_${project}=${secret}; path=/; httponly` }]
}
// Abmelden der eben erzeugten Sitzung (Portal-Login lehnt Mitarbeiter ab)
if (url.pathname === '/v1/account/sessions/current' && req.method === 'DELETE') {
const match = String(req.headers.cookie || '').match(/a_session_[^=]+=([^;]+)/)
if (!match || !sessions.delete(decodeURIComponent(match[1]))) return [401, { message: 'Unauthorized', code: 401, type: 'general_unauthorized_scope' }]
sessionDeletes += 1
return [204, null]
}
if (url.pathname === '/v1/account/mfa/challenges') {
const session = sessionOf(req)
if (!session) return [401, { message: 'Unauthorized', code: 401, type: 'general_unauthorized_scope' }]
const user = users.get(session.userId)
if (req.method === 'POST') {
lastLocale = req.headers['x-appwrite-locale'] || null
if (!user.emailVerification) return [400, { message: 'Email not verified', code: 400, type: 'user_email_not_verified' }]
const id = `ch${(sequence += 1)}`
const otp = String(100000 + Math.floor(Math.random() * 900000))
challenges.set(id, { userId: user.$id, otp, expired: false })
mails.set(user.$id, (mails.get(user.$id) || 0) + 1)
return [201, { $id: id, userId: user.$id, expire: new Date(Date.now() + 3600e3).toISOString() }]
}
if (req.method === 'PUT') {
const { challengeId, otp } = await readBody(req)
const challenge = challenges.get(challengeId)
if (!challenge || challenge.expired || challenge.userId !== user.$id || challenge.otp !== otp) {
return [401, { message: 'Invalid token passed in the request.', code: 401, type: 'user_invalid_token' }]
}
challenges.delete(challengeId)
session.factors.push('email')
return [200, { $id: `s-${user.$id}`, userId: user.$id, factors: session.factors }]
}
}
// Konto anlegen und Labels setzen (Mitarbeiter-Verwaltung, employeeAdmin.js)
if (url.pathname === '/v1/users' && req.method === 'POST') {
const { userId, email, password, name } = await readBody(req)
users.set(userId, { $id: userId, email, password, name, labels: [], mfa: false, emailVerification: false })
userCalls.push(`create:${userId}`)
return [201, publicUser(users.get(userId))]
}
const deleteUserPath = url.pathname.match(/^\/v1\/users\/([^/]+)$/)
if (deleteUserPath && req.method === 'DELETE') {
if (!users.delete(deleteUserPath[1])) return [404, { message: 'User not found', code: 404, type: 'user_not_found' }]
userCalls.push(`delete:${deleteUserPath[1]}`)
return [204, null]
}
const labelsPath = url.pathname.match(/^\/v1\/users\/([^/]+)\/labels$/)
if (labelsPath && req.method === 'PUT') {
const user = users.get(labelsPath[1])
if (!user) return [404, { message: 'User not found', code: 404, type: 'user_not_found' }]
user.labels = (await readBody(req)).labels
userCalls.push(`labels:${labelsPath[1]}`)
return [200, publicUser(user)]
}
const mfaPath = url.pathname.match(/^\/v1\/users\/([^/]+)\/(mfa|verification)$/)
if (mfaPath && req.method === 'PATCH') {
const user = users.get(mfaPath[1])
if (!user) return [404, { message: 'User not found', code: 404, type: 'user_not_found' }]
const body = await readBody(req)
if (mfaPath[2] === 'mfa') user.mfa = Boolean(body.mfa)
else user.emailVerification = Boolean(body.emailVerification)
userCalls.push(`${mfaPath[2]}:${mfaPath[1]}`)
return [200, publicUser(user)]
}
return null
}
// Bulk-Create (Appwrite 1.8.1, API-Schluessel): alles oder nichts. Erst jedes Dokument pruefen (400), dann auf
// vorhandene oder doppelte IDs (409); geschrieben wird erst, wenn alles durch ist. Anders als Appwrite (das eine
// fehlende $id selbst vergibt) verlangt der Nachbau die $id, die Belegungszellen brauchen feste IDs.
const createMany = (collection, documents) => {
if (documents.length < 1 || documents.length > 100) {
return [400, { message: 'Invalid `documents` param: Value must be a valid array and contain between 1 and 100 items', code: 400, type: 'general_argument_invalid' }]
}
const prepared = []
for (const document of documents) {
if (!document || typeof document !== 'object' || Array.isArray(document) || !validDocumentId(document.$id)) return invalidDocumentId
const bad = unknownAttribute(collection, document)
if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }]
const [dated, badDate] = normalizeDates(collection, document)
if (badDate) return invalidDate(badDate)
prepared.push(dated)
}
const store = docs(collection)
const ids = new Set()
for (const { $id } of prepared) {
if (store.has($id) || ids.has($id)) return documentExists
ids.add($id)
}
const created = prepared.map((document) => stamp(document, collection))
for (const document of created) store.set(document.$id, document)
return [201, { total: created.length, documents: created.map(publicDoc) }]
}
const handle = async (req) => {
const url = new URL(req.url, 'http://127.0.0.1')
const auth = await handleAuth(req, url)
if (auth) return auth
const docPath = url.pathname.match(/^\/v1\/databases\/[^/]+\/collections\/([^/]+)\/documents(?:\/([^/]+))?$/)
const userPath = url.pathname.match(/^\/v1\/users\/([^/]+)$/)
if (userPath && req.method === 'GET') {
if (failUserLookups) return [503, { message: 'Nachbau: Konto-Abruf gestoert', code: 503, type: 'general_server_error' }]
return [200, users.has(userPath[1]) ? publicUser(users.get(userPath[1])) : { $id: userPath[1], passwordUpdate: '' }]
}
// GET /v1/account (requireAppwriteStaff, Ticketsystem-JWT): jwt-admin = Mitarbeiter mit Label admin,
// jwt-kunde = angemeldet ohne Label, alles andere 401 wie Appwrite bei einem ungueltigen JWT
if (url.pathname === '/v1/account' && req.method === 'GET') {
const jwt = req.headers['x-appwrite-jwt']
if (jwt === 'jwt-admin') return [200, { $id: 'u_admin', email: 'kenso@webklar.com', labels: ['admin'] }]
if (jwt === 'jwt-kunde') return [200, { $id: 'u_admin', email: 'kenso@webklar.com', labels: [] }]
// jwt-staff = Mitarbeiter ohne Label admin, jwt-halb = JWT aus einer Sitzung ohne zweiten Faktor
if (jwt === 'jwt-staff') return [200, { $id: 'u_staff2', email: 'andrej@webklar.com', name: 'Andrej', labels: ['mitarbeiter'] }]
// jwt-kunde-eintrag = Kunde ohne Label, dessen Konto-ID ein (selbst angelegter) employees-Eintrag traegt
if (jwt === 'jwt-kunde-eintrag') return [200, { $id: 'u_kunde_e', email: 'kunde@example.invalid', name: 'Kunde', labels: [] }]
if (jwt === 'jwt-halb') return moreFactors
// Team-Eingang: Konto-Mail gleicht einem Mitarbeiter, ist aber unbestaetigt bzw. bestaetigt (ohne userId-Treffer)
if (jwt === 'jwt-mail-ungeprueft') return [200, { $id: 'u_fremd', email: 'andrej@webklar.com', emailVerification: false, labels: [] }]
if (jwt === 'jwt-mail-geprueft') return [200, { $id: 'u_neu', email: 'nico@webklar.com', emailVerification: true, name: 'Nico', labels: [] }]
const session = sessionOf(req)
if (session) return needsMoreFactors(session) ? moreFactors : [200, publicUser(users.get(session.userId))]
return [401, { message: 'User (role: guests) missing scope (account)', code: 401, type: 'general_unauthorized_scope' }]
}
if (!docPath) return [404, { message: 'Route not found', code: 404 }]
const [, collection, id] = docPath
const store = docs(collection)
const notFound = [404, { message: 'Document with the requested ID could not be found.', code: 404, type: 'document_not_found' }]
if (!id && req.method === 'GET') listLog.push({ collection, queries: url.searchParams.getAll('queries[]').map((q) => JSON.parse(q)) })
// Eingeplanter Fehler (failNext): genau eine passende Anfrage scheitert
if (
pendingFailure &&
(!pendingFailure.collection || pendingFailure.collection === collection) &&
(!pendingFailure.method || pendingFailure.method === req.method)
) {
if (pendingFailure.after > 0) {
pendingFailure.after -= 1
} else {
const { status, message } = pendingFailure
pendingFailure = null
return [status, { message: message || `Nachbau: eingeplanter Fehler ${status}`, code: status, type: 'general_server_error' }]
}
}
if (!id && req.method === 'GET') return list(collection, url.searchParams.getAll('queries[]'))
if (!id && req.method === 'POST') {
const body = await readBody(req)
if (Array.isArray(body.documents)) return createMany(collection, body.documents)
const { documentId, data = {} } = body
if (!validDocumentId(documentId)) return invalidDocumentId
if (store.has(documentId)) return documentExists
const bad = unknownAttribute(collection, data)
if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }]
const [dated, badDate] = normalizeDates(collection, data)
if (badDate) return invalidDate(badDate)
const doc = stamp({ ...dated, $id: documentId }, collection)
store.set(documentId, doc)
return [201, publicDoc(doc)]
}
if (id && req.method === 'GET') return store.has(id) ? [200, publicDoc(store.get(id))] : notFound
if (id && req.method === 'PATCH') {
if (!store.has(id)) return notFound
const { data = {} } = await readBody(req)
const bad = unknownAttribute(collection, data)
if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }]
const [dated, badDate] = normalizeDates(collection, data)
if (badDate) return invalidDate(badDate)
const doc = { ...store.get(id), ...dated, $updatedAt: new Date().toISOString() }
store.set(id, doc)
return [200, publicDoc(doc)]
}
if (id && req.method === 'DELETE') {
if (!store.delete(id)) return notFound
return [204, null]
}
return [405, { message: 'Method not allowed', code: 405 }]
}
const server = http.createServer(async (req, res) => {
try {
const [status, body, headers = {}] = await handle(req)
res.writeHead(status, { 'Content-Type': 'application/json', ...headers })
res.end(body === null ? '' : JSON.stringify(body))
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: err.message, code: 500 }))
}
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
return {
url: `http://127.0.0.1:${server.address().port}/v1`,
docs: (collection) => new Map([...docs(collection)].map(([id, doc]) => [id, publicDoc(doc)])),
seed,
/** Aufgezeichnete Listenabfragen (nur GET auf eine Collection, auch fehlgeschlagene), je Aufruf eine Kopie; optional einer Collection */
listCalls: (collection = null) => structuredClone(listLog.filter((call) => !collection || call.collection === collection)),
resetListCalls: () => {
listLog = []
},
/** Naechste passende Dokument-Anfrage scheitert mit status (einmalig); after passende Anfragen gehen vorher durch. */
failNext: ({ collection = null, method = null, status = 500, message = '', after = 0 }) => {
pendingFailure = { collection, method, status, message, after }
},
addUser: (user) => users.set(user.$id, { labels: [], mfa: false, emailVerification: false, ...user }),
user: (id) => (users.has(id) ? publicUser(users.get(id)) : null),
lastOtp: (userId) => [...challenges.values()].filter((c) => c.userId === userId).at(-1)?.otp || null,
expireChallenges: () => challenges.forEach((c) => (c.expired = true)),
mailsSent: (userId) => mails.get(userId) || 0,
/** Zahl der beendeten Appwrite-Sitzungen (DELETE /account/sessions/current) */
sessionDeletes: () => sessionDeletes,
lastLocale: () => lastLocale,
/** GET /v1/users/:id scheitert (503), bis wieder false gesetzt wird */
failUserLookups: (on) => (failUserLookups = Boolean(on)),
userCalls: () => [...userCalls],
close: () => new Promise((resolve) => server.close(resolve)),
}
}