SPB Git

Repository Public

openapi.ts 25.9 KB 523 lines typescript

1// Explorateur d'API — logique pure : document OpenAPI 3.1 → opérations groupées, modèle de formulaire, requête à émettre,2// classement des opérations risquées et pré-vérification locale des permissions (le serveur reste l'autorité).34export type Json = null | boolean | number | string | Json[] | { [k: string]: Json }5export type Schema = Record<string, unknown>6export interface OpenApiDoc {7  openapi?: string8  tags?: { name: string }[]9  paths?: Record<string, Record<string, unknown>>10  components?: Record<string, unknown>11  [k: string]: unknown12}1314const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v)15const str = (v: unknown): string => (typeof v === "string" ? v : "")16const METHODS = ["get", "post", "put", "patch", "delete"] as const17export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"1819// ---------------------------------------------------------------- $ref20/** Suit un pointeur JSON local (`#/components/schemas/Error`). Un pointeur externe ou introuvable rend null. */21export function resolvePointer(doc: unknown, ref: string): unknown {22  if (!ref.startsWith("#")) return null23  let cur: unknown = doc24  for (const raw of ref.slice(1).split("/").filter(Boolean)) {25    const key = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~")26    if (Array.isArray(cur)) cur = cur[Number(key)]27    else if (isObj(cur)) cur = cur[key]28    else return null29    if (cur === undefined) return null30  }31  return cur32}33/** Schéma avec ses `$ref` de tête résolus (les cycles s'arrêtent : schéma vide). Les mots-clés voisins du `$ref` sont conservés. */34export function deref(doc: unknown, schema: unknown, seen: string[] = []): Schema {35  if (!isObj(schema)) return {}36  const ref = schema.$ref37  if (typeof ref !== "string") return schema38  if (seen.includes(ref) || seen.length > 20) return {}39  const { $ref: _drop, ...rest } = schema40  return { ...deref(doc, resolvePointer(doc, ref), [...seen, ref]), ...rest }41}4243// ---------------------------------------------------------------- modèle de formulaire44export type FieldKind = "string" | "number" | "integer" | "boolean" | "enum" | "stringList" | "object" | "json"45export interface Field {46  name: string47  kind: FieldKind48  required: boolean49  nullable: boolean50  description: string51  format: string52  /** valeurs permises (kind "enum", ou éléments d'une liste) */53  options: string[]54  /** valeur par défaut annoncée par le schéma (montrée en indication, jamais envoyée d'office) */55  defaultValue: Json | undefined56  /** exemple du schéma : pré-remplit le champ */57  example: Json | undefined58  /** texte long (corps de message, HTML…) */59  multiline: boolean60  children: Field[]61}6263/** Profondeur maximale des objets imbriqués rendus en champs ; au-delà : JSON brut. */64export const MAX_DEPTH = 36566const typesOf = (s: Schema): string[] => (Array.isArray(s.type) ? s.type.filter((x): x is string => typeof x === "string") : typeof s.type === "string" ? [s.type] : [])6768/** Retire la variante `null` (anyOf / oneOf / type en liste) : rend le schéma utile et le fait qu'il accepte null. */69export function unwrapNullable(doc: unknown, schema: unknown): { schema: Schema; nullable: boolean; variants: Schema[] } {70  let s = deref(doc, schema)71  let nullable = false72  const types = typesOf(s)73  if (types.length > 1 && types.includes("null")) {74    nullable = true75    const rest = types.filter((x) => x !== "null")76    s = { ...s, type: rest.length === 1 ? rest[0] : rest }77  }78  const alt = Array.isArray(s.anyOf) ? s.anyOf : Array.isArray(s.oneOf) ? s.oneOf : null79  if (!alt) return { schema: s, nullable, variants: [s] }80  const variants = alt.map((v) => deref(doc, v)).filter((v) => {81    const isNull = typesOf(v).length === 1 && typesOf(v)[0] === "null"82    if (isNull) nullable = true83    return !isNull84  })85  const { anyOf: _a, oneOf: _o, ...outer } = s86  if (variants.length === 1) return { schema: { ...outer, ...variants[0] }, nullable, variants }87  return { schema: outer, nullable, variants }88}8990const enumOf = (s: Schema): string[] | null => {91  if (Array.isArray(s.enum) && s.enum.length && s.enum.every((x) => typeof x === "string" || typeof x === "number")) return s.enum.map(String)92  if (typeof s.const === "string" || typeof s.const === "number") return [String(s.const)]93  return null94}95const isJson = (v: unknown): v is Json => v === null || ["string", "number", "boolean"].includes(typeof v) || Array.isArray(v) || isObj(v)96const exampleOf = (s: Schema): Json | undefined => (s.example !== undefined && isJson(s.example) ? s.example : Array.isArray(s.examples) && s.examples.length && isJson(s.examples[0]) ? s.examples[0] : undefined)97const LONG_TEXT = 20009899/** Champ de formulaire d'un schéma. Ce que le formulaire ne sait pas représenter devient un champ « JSON brut ». */100export function fieldOf(doc: unknown, name: string, schema: unknown, required = false, depth = 0): Field {101  const { schema: s, nullable, variants } = unwrapNullable(doc, schema)102  const base: Field = {103    name, kind: "json", required, nullable, description: str(s.description), format: str(s.format), options: [],104    defaultValue: s.default !== undefined && isJson(s.default) ? s.default : undefined, example: exampleOf(s), multiline: false, children: [],105  }106  if (variants.length > 1) {107    // plusieurs formes possibles : du texte si toutes sont des scalaires dont une chaîne, sinon JSON brut108    const scalar = variants.every((v) => ["string", "number", "integer", "boolean"].includes(typesOf(v)[0] ?? ""))109    return scalar && variants.some((v) => typesOf(v)[0] === "string") ? { ...base, kind: "string" } : base110  }111  const en = enumOf(s)112  if (en) return { ...base, kind: "enum", options: en }113  const type = typesOf(s)[0] ?? (isObj(s.properties) ? "object" : s.items !== undefined ? "array" : "")114  if (type === "string") return { ...base, kind: s.format === "binary" ? "json" : "string", multiline: typeof s.maxLength === "number" && s.maxLength > LONG_TEXT }115  if (type === "number" || type === "integer") return { ...base, kind: type }116  if (type === "boolean") return { ...base, kind: "boolean" }117  if (type === "array") {118    const items = unwrapNullable(doc, s.items)119    // liste de chaînes : aussi quand l'élément accepte « chaîne OU objet » (destinataires : "a@b" ou {email, name})120    const stringy = items.variants.some((v) => typesOf(v)[0] === "string" && v.format !== "binary") && items.variants.every((v) => ["string", "object"].includes(typesOf(v)[0] ?? ""))121    if (stringy) return { ...base, kind: "stringList", options: items.variants.length === 1 ? (enumOf(items.variants[0]) ?? []) : [] }122    return base123  }124  if (type === "object") {125    const props = isObj(s.properties) ? s.properties : null126    if (!props || !Object.keys(props).length || depth >= MAX_DEPTH) return base127    const req = Array.isArray(s.required) ? s.required : []128    return { ...base, kind: "object", children: Object.entries(props).map(([k, v]) => fieldOf(doc, k, v, req.includes(k), depth + 1)) }129  }130  return base131}132133// ---------------------------------------------------------------- opérations134export type DangerKind = "none" | "write" | "send" | "delete"135export interface Param {136  name: string137  in: "path" | "query" | "header"138  field: Field139}140export interface ErrorDoc {141  status: string142  description: string143}144export interface Operation {145  /** « GET /me » : identifiant stable dans l'interface */146  id: string147  method: Method148  path: string149  operationId: string150  tag: string151  summary: string152  description: string153  /** l'un de ces scopes suffit ; vide = tout appelant authentifié */154  scopes: string[]155  /** aucune authentification */156  public: boolean157  params: Param[]158  body: { kind: "none" } | { kind: "binary"; required: boolean } | { kind: "json"; required: boolean; field: Field }159  /** réponses autres que le succès, telles que la spécification les annonce */160  errors: ErrorDoc[]161  /** l'enveloppe d'erreur commune (`default`) est déclarée */162  errorEnvelope: boolean163  success: string[]164  /** la réponse de succès est un contenu binaire (téléchargement) */165  binaryResponse: boolean166  danger: DangerKind167}168169const SEND_PATHS = [/^\/messages\/send$/, /^\/messages\/send-batch$/, /^\/messages\/\{[^}]+\}\/reply$/, /^\/messages\/\{[^}]+\}\/forward$/, /^\/drafts\/\{[^}]+\}\/send$/, /^\/webhooks\/\{[^}]+\}\/test$/]170/** GET : rien à confirmer. DELETE : supprime des données. Envois de courrier (et essai de webhook) : avertissement renforcé. Autre : simple confirmation. */171export function classifyDanger(method: string, path: string): DangerKind {172  const m = method.toUpperCase()173  if (m === "GET" || m === "HEAD") return "none"174  if (m === "DELETE") return "delete"175  if (m === "POST" && SEND_PATHS.some((re) => re.test(path))) return "send"176  return "write"177}178179function paramsOf(doc: unknown, list: unknown): Param[] {180  if (!Array.isArray(list)) return []181  const out: Param[] = []182  for (const raw of list) {183    const p = deref(doc, raw)184    const where = p.in185    const name = str(p.name)186    if (!name || (where !== "path" && where !== "query" && where !== "header")) continue187    const field = fieldOf(doc, name, p.schema ?? {}, where === "path" || p.required === true, MAX_DEPTH)188    // un paramètre d'URL ou d'en-tête est toujours du texte : pas de repli « JSON brut » pour un schéma sans type189    out.push({ name, in: where, field: { ...field, kind: field.kind === "json" || field.kind === "object" ? "string" : field.kind, children: [], description: str(p.description) || field.description, example: p.example !== undefined && isJson(p.example) ? p.example : field.example } })190  }191  return out192}193194function bodyOf(doc: unknown, raw: unknown): Operation["body"] {195  if (!isObj(raw)) return { kind: "none" }196  const rb = deref(doc, raw)197  const content = isObj(rb.content) ? rb.content : {}198  const required = rb.required === true199  const json = Object.entries(content).find(([type]) => /json/i.test(type))200  if (json && isObj(json[1])) return { kind: "json", required, field: fieldOf(doc, "body", json[1].schema ?? {}, required, 0) }201  return Object.keys(content).length ? { kind: "binary", required } : { kind: "none" }202}203204/** Toutes les opérations du document, dans l'ordre des étiquettes déclarées puis des chemins. */205export function parseOperations(doc: OpenApiDoc): Operation[] {206  const out: Operation[] = []207  const paths = isObj(doc.paths) ? doc.paths : {}208  for (const [path, rawItem] of Object.entries(paths)) {209    const item = deref(doc, rawItem)210    for (const m of METHODS) {211      const op = item[m]212      if (!isObj(op)) continue213      const method = m.toUpperCase() as Method214      const responses = isObj(op.responses) ? op.responses : {}215      const errors: ErrorDoc[] = []216      const success: string[] = []217      let binaryResponse = false218      for (const [status, r] of Object.entries(responses)) {219        if (status === "default") continue220        const res = deref(doc, r)221        if (/^2/.test(status)) {222          success.push(status)223          const content = isObj(res.content) ? Object.keys(res.content) : []224          if (content.length && !content.some((c) => /json/i.test(c))) binaryResponse = true225        } else errors.push({ status, description: str(res.description) })226      }227      const sec = op.security228      out.push({229        id: `${method} ${path}`, method, path, operationId: str(op.operationId),230        tag: Array.isArray(op.tags) && typeof op.tags[0] === "string" ? op.tags[0] : "",231        summary: str(op.summary), description: str(op.description),232        scopes: Array.isArray(op["x-required-scopes"]) ? op["x-required-scopes"].filter((x): x is string => typeof x === "string") : [],233        public: Array.isArray(sec) && sec.length === 0,234        params: [...paramsOf(doc, item.parameters), ...paramsOf(doc, op.parameters)],235        body: bodyOf(doc, op.requestBody),236        errors: errors.sort((a, b) => a.status.localeCompare(b.status)), errorEnvelope: "default" in responses, success, binaryResponse,237        danger: classifyDanger(method, path),238      })239    }240  }241  const tagOrder = (doc.tags ?? []).map((x) => x.name)242  const rank = (tag: string) => (tagOrder.includes(tag) ? tagOrder.indexOf(tag) : tagOrder.length)243  const methodRank = (m: string) => METHODS.indexOf(m.toLowerCase() as (typeof METHODS)[number])244  return out.sort((a, b) => rank(a.tag) - rank(b.tag) || a.tag.localeCompare(b.tag) || a.path.localeCompare(b.path) || methodRank(a.method) - methodRank(b.method))245}246247export function groupByTag(ops: readonly Operation[]): { tag: string; operations: Operation[] }[] {248  const out: { tag: string; operations: Operation[] }[] = []249  for (const op of ops) {250    const g = out.find((x) => x.tag === op.tag)251    if (g) g.operations.push(op)252    else out.push({ tag: op.tag, operations: [op] })253  }254  return out255}256257/** Recherche par chemin, méthode, résumé, étiquette : chaque mot doit apparaître (sans tenir compte de la casse ni des accents). */258export function searchOperations(ops: readonly Operation[], query: string): Operation[] {259  const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()260  const words = fold(query).split(/\s+/).filter(Boolean)261  if (!words.length) return [...ops]262  return ops.filter((op) => {263    const hay = fold(`${op.method} ${op.path} ${op.summary} ${op.tag} ${op.operationId}`)264    return words.every((w) => hay.includes(w))265  })266}267268// ---------------------------------------------------------------- valeurs du formulaire269/**270 * Valeur d'un champ dans l'interface : texte pour les champs saisis (chaîne, nombre, énumération, liste « une par ligne », JSON brut),271 * booléen pour une case (undefined = non touchée, donc non envoyée), dictionnaire pour un objet.272 */273export type FormValue = string | boolean | undefined | { [k: string]: FormValue }274export type FormValues = { [k: string]: FormValue }275export interface Problem {276  /** chemin du champ : « body.to », « query.limit », « path.id » */277  path: string278  kind: "required" | "number" | "json"279}280281const asText = (v: Json): string => (typeof v === "string" ? v : JSON.stringify(v))282283/** Valeur initiale d'un champ : son exemple s'il en a un, sinon vide (la valeur par défaut du serveur n'est pas renvoyée). */284export function initialValue(f: Field): FormValue {285  const ex = f.example286  if (f.kind === "object") {287    const src = isObj(ex) ? ex : {}288    return Object.fromEntries(f.children.map((c) => [c.name, initialValue(src[c.name] !== undefined ? { ...c, example: src[c.name] as Json } : c)]))289  }290  if (ex === undefined) return f.kind === "boolean" ? undefined : ""291  if (f.kind === "boolean") return typeof ex === "boolean" ? ex : undefined292  if (f.kind === "stringList") return Array.isArray(ex) ? ex.map(asText).join("\n") : asText(ex)293  if (f.kind === "json") return JSON.stringify(ex, null, 2)294  return asText(ex)295}296297/** Valeur JSON d'un champ ; `undefined` = champ omis de la requête (champ facultatif laissé vide). */298export function fieldToJson(f: Field, v: FormValue, path: string, problems: Problem[]): Json | undefined {299  const missing = () => {300    if (f.required) problems.push({ path, kind: "required" })301    return undefined302  }303  switch (f.kind) {304    case "boolean":305      return typeof v === "boolean" ? v : missing()306    case "object": {307      const src = isObj(v) ? (v as FormValues) : {}308      const out: { [k: string]: Json } = {}309      for (const c of f.children) {310        const j = fieldToJson(c, src[c.name], `${path}.${c.name}`, problems)311        if (j !== undefined) out[c.name] = j312      }313      return Object.keys(out).length || f.required ? out : undefined314    }315    case "stringList": {316      const lines = typeof v === "string" ? v.split(/\r?\n/).map((x) => x.trim()).filter(Boolean) : []317      return lines.length ? lines : missing()318    }319    case "number":320    case "integer": {321      const s = typeof v === "string" ? v.trim() : ""322      if (!s) return missing()323      const n = Number(s.replace(",", "."))324      if (!Number.isFinite(n) || (f.kind === "integer" && !Number.isInteger(n))) {325        problems.push({ path, kind: "number" })326        return undefined327      }328      return n329    }330    case "json": {331      const s = typeof v === "string" ? v.trim() : ""332      if (!s) return missing()333      try {334        return JSON.parse(s) as Json335      } catch {336        problems.push({ path, kind: "json" })337        return undefined338      }339    }340    default: {341      // chaîne ou énumération : le texte tel quel (les espaces d'un corps de message comptent) ; vide = omis342      const s = typeof v === "string" ? v : ""343      return s === "" ? missing() : s344    }345  }346}347348/**349 * Sens inverse (JSON brut → formulaire). `lossy` : le JSON contient quelque chose que le formulaire ne sait pas porter350 * (clé inconnue, objet dans une liste « une par ligne », type inattendu) — l'interface reste alors en JSON brut.351 */352export function jsonToField(f: Field, j: Json | undefined): { value: FormValue; lossy: boolean } {353  if (j === undefined) return { value: f.kind === "object" ? Object.fromEntries(f.children.map((c) => [c.name, jsonToField(c, undefined).value])) : f.kind === "boolean" ? undefined : "", lossy: false }354  switch (f.kind) {355    case "boolean":356      return typeof j === "boolean" ? { value: j, lossy: false } : { value: undefined, lossy: true }357    case "object": {358      if (!isObj(j)) return { value: jsonToField(f, undefined).value, lossy: true }359      let lossy = Object.keys(j).some((k) => !f.children.some((c) => c.name === k))360      const value: FormValues = {}361      for (const c of f.children) {362        const r = jsonToField(c, j[c.name] as Json | undefined)363        value[c.name] = r.value364        lossy ||= r.lossy365      }366      // un objet facultatif présent mais vide ne se distingue pas, dans le formulaire, d'un objet absent367      if (!f.required && !Object.keys(j).length) lossy = true368      return { value, lossy }369    }370    case "stringList": {371      if (!Array.isArray(j)) return { value: "", lossy: true }372      const ok = j.every((x) => typeof x === "string" && x.trim() === x && x !== "" && !/[\r\n]/.test(x))373      return { value: ok ? j.join("\n") : "", lossy: !ok || j.length === 0 }374    }375    case "number":376    case "integer":377      return typeof j === "number" ? { value: String(j), lossy: false } : { value: "", lossy: true }378    case "json":379      return { value: JSON.stringify(j, null, 2), lossy: false }380    default:381      return typeof j === "string" && j !== "" ? { value: j, lossy: false } : { value: "", lossy: true }382  }383}384385// ---------------------------------------------------------------- requête386export const API_BASE = "/api/v1"387export interface RequestInput {388  /** valeurs des paramètres, par nom */389  path: FormValues390  query: FormValues391  header: FormValues392  /** corps saisi dans le formulaire (ignoré quand `raw` est fourni) */393  body?: FormValue394  /** corps saisi en JSON brut */395  raw?: string396}397export interface BuiltRequest {398  method: Method399  /** chemin interpolé, sans la base : « /messages/msg_1 » */400  path: string401  query: [string, string][]402  /** URL relative complète : « /api/v1/messages?limit=5 » */403  url: string404  headers: Record<string, string>405  /** corps JSON à envoyer (undefined = aucun corps) */406  body: Json | undefined407  /** corps binaire attendu (téléversement) : fourni à part par l'appelant */408  binary: boolean409  problems: Problem[]410}411412const queryText = (j: Json): string => (Array.isArray(j) ? j.map(asText).join(",") : asText(j))413414export function buildRequest(op: Operation, input: RequestInput, base = API_BASE): BuiltRequest {415  const problems: Problem[] = []416  let path = op.path417  const query: [string, string][] = []418  const headers: Record<string, string> = {}419  for (const p of op.params) {420    const j = fieldToJson(p.field, input[p.in][p.name], `${p.in}.${p.name}`, problems)421    if (p.in === "path") path = path.split(`{${p.name}}`).join(j === undefined ? `{${p.name}}` : encodeURIComponent(queryText(j)))422    else if (j === undefined) continue423    else if (p.in === "query") query.push([p.name, queryText(j)])424    else headers[p.name] = queryText(j)425  }426  let body: Json | undefined427  if (op.body.kind === "json") {428    if (input.raw !== undefined) {429      if (input.raw.trim()) {430        try {431          body = JSON.parse(input.raw) as Json432        } catch {433          problems.push({ path: "body", kind: "json" })434        }435      } else if (op.body.required) problems.push({ path: "body", kind: "required" })436    } else {437      // le serveur valide toujours un objet : un formulaire vide envoie `{}` plutôt que rien438      body = fieldToJson(op.body.field, input.body, "body", problems) ?? (op.body.field.kind === "object" ? {} : undefined)439    }440  }441  const qs = query.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")442  return { method: op.method, path, query, url: `${base}${path}${qs ? `?${qs}` : ""}`, headers, body, binary: op.body.kind === "binary", problems }443}444445/** Problèmes qui empêchent l'envoi : valeur illisible, ou paramètre de chemin manquant (l'URL serait fausse). Le reste est laissé au serveur. */446export const blocking = (problems: readonly Problem[]): Problem[] => problems.filter((p) => p.kind !== "required" || p.path.startsWith("path."))447448// ---------------------------------------------------------------- pré-vérification des permissions449/** Ce que l'on sait de l'appelant : clé choisie (GET /api/admin/api-keys) ou réponse de GET /me. */450export interface Caller {451  scopes: readonly string[]452  /** `all_addresses` : n'a d'effet, côté serveur, qu'avec le scope mail.admin */453  allAddresses: boolean454  /** identifiants de la liste d'autorisation de la clé */455  addressIds?: readonly string[]456  /** adresses permises connues par leur nom (réponse de /me) */457  addresses?: readonly string[]458}459/** Annuaire connu de la console (GET /api/v1/addresses avec la session) : peut être incomplet. */460export type AddressBook = readonly { id: string; address: string }[]461462export type AddressVerdict = "allowed" | "not_allowed" | "unknown"463export interface PermissionCheck {464  verdict: "allowed" | "denied" | "unknown"465  public: boolean466  scope: { ok: boolean; required: string[]; missing: string[] }467  addresses: { address: string; where: string; verdict: AddressVerdict }[]468  /** l'opération vise une ressource par identifiant : seul le serveur sait si elle est visible de l'appelant */469  resource: boolean470}471472export const callerFromKey = (k: { scopes: readonly string[]; address_ids?: readonly string[]; all_addresses?: boolean }): Caller => ({ scopes: k.scopes, allAddresses: !!k.all_addresses, addressIds: k.address_ids ?? [] })473export const callerFromMe = (me: { scopes: readonly string[]; all_addresses?: boolean; addresses?: readonly { id?: string; address: string }[] }): Caller => ({474  scopes: me.scopes, allAddresses: !!me.all_addresses, addresses: (me.addresses ?? []).map((a) => a.address), addressIds: (me.addresses ?? []).flatMap((a) => (a.id ? [a.id] : [])),475})476477const splitList = (v: unknown): string[] => (typeof v === "string" ? v.split(",") : Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []).map((x) => x.trim().toLowerCase()).filter(Boolean)478479/** Adresses au nom desquelles la requête agit : `from` du corps (et de chaque message d'un lot), paramètres `address` / `mailbox`. */480export function namedAddresses(req: Pick<BuiltRequest, "query" | "body">): { address: string; where: string }[] {481  const out: { address: string; where: string }[] = []482  const add = (where: string, v: unknown) => {483    for (const address of splitList(v)) if (!out.some((x) => x.address === address)) out.push({ address, where })484  }485  for (const [k, v] of req.query) if (k === "address" || k === "mailbox") add(k, v)486  const b = req.body487  if (isObj(b)) {488    if (typeof b.from === "string") add("from", b.from)489    if (Array.isArray(b.messages)) for (const m of b.messages) if (isObj(m) && typeof m.from === "string") add("from", m.from)490  }491  return out492}493494function addressVerdict(caller: Caller, address: string, book: AddressBook): AddressVerdict {495  const scopes = new Set(caller.scopes)496  if (caller.allAddresses && scopes.has("mail.admin")) return "allowed"497  const ids = new Set((caller.addressIds ?? []).map((x) => x.toLowerCase()))498  const names = new Set((caller.addresses ?? []).map((x) => x.toLowerCase()))499  if (ids.has(address) || names.has(address)) return "allowed"500  const hit = book.find((a) => a.address.toLowerCase() === address || a.id.toLowerCase() === address)501  if (hit && (ids.has(hit.id.toLowerCase()) || names.has(hit.address.toLowerCase()))) return "allowed"502  // la liste complète des adresses permises est-elle connue par leur nom ? (réponse de /me, ou chaque identifiant retrouvé dans l'annuaire)503  const complete = caller.addresses !== undefined || [...ids].every((id) => book.some((a) => a.id.toLowerCase() === id))504  return hit || complete ? "not_allowed" : "unknown"505}506507/**508 * Pré-vérification locale : scope requis (mail.admin les vaut tous) et adresses nommées par la requête.509 * `caller` null = droits inconnus (résultat « inconnu avant l'exécution »). Jamais une autorisation : le serveur décide.510 */511export function checkPermission(caller: Caller | null, op: Pick<Operation, "scopes" | "public" | "params">, req: Pick<BuiltRequest, "query" | "body">, book: AddressBook = []): PermissionCheck {512  const required = [...op.scopes]513  const resource = op.params.some((p) => p.in === "path")514  if (op.public) return { verdict: "allowed", public: true, scope: { ok: true, required, missing: [] }, addresses: [], resource: false }515  const named = namedAddresses(req)516  if (!caller) return { verdict: "unknown", public: false, scope: { ok: false, required, missing: [] }, addresses: named.map((n) => ({ ...n, verdict: "unknown" })), resource }517  const have = new Set(caller.scopes)518  const ok = !required.length || have.has("mail.admin") || required.some((s) => have.has(s))519  const addresses = named.map((n) => ({ ...n, verdict: addressVerdict(caller, n.address, book) }))520  const verdict = !ok || addresses.some((a) => a.verdict === "not_allowed") ? "denied" : addresses.some((a) => a.verdict === "unknown") ? "unknown" : "allowed"521  return { verdict, public: false, scope: { ok, required, missing: ok ? [] : required }, addresses, resource }522}523
Files main
Menu

Theme