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

263 lines
13 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).
*/
export async function startAppwriteMock({ schema = {} } = {}) {
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
// 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 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')
docs(collection).set(doc.$id, stamp(doc, collection))
}
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]
switch (query.method) {
case 'equal':
return query.values.includes(value)
case 'greaterThan':
return value > query.values[0]
case 'lessThan':
return value < query.values[0]
default:
return true
}
}
const list = (collection, rawQueries) => {
const queries = rawQueries.map((q) => JSON.parse(q))
const unsupported = queries.find((q) => !['equal', 'greaterThan', 'lessThan', 'orderAsc', 'orderDesc', 'limit'].includes(q.method))
if (unsupported) return [400, { message: `Query ${unsupported.method} wird nicht nachgebaut`, code: 400 }]
let result = [...docs(collection).values()].filter((doc) => queries.every((q) => matches(doc, q)))
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 = a[q.attribute]
const y = b[q.attribute]
if (x === y) return (a.$seq - b.$seq) * dir
return (x > y ? 1 : -1) * dir
})
}
const limit = queries.find((q) => q.method === 'limit')
if (limit) result = result.slice(0, limit.values[0])
return [200, { total: result.length, 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` }]
}
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 }]
}
}
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
}
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: [] }]
if (jwt === 'jwt-halb') return moreFactors
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' }]
// 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 { documentId, data = {} } = await readBody(req)
if (!validDocumentId(documentId)) return invalidDocumentId
if (store.has(documentId)) {
return [409, { message: 'Document with the requested ID already exists.', code: 409, type: 'document_already_exists' }]
}
const bad = unknownAttribute(collection, data)
if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }]
const doc = stamp({ ...data, $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 doc = { ...store.get(id), ...data, $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,
/** 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,
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)),
}
}