@panneau/protocol 5.0.0-alpha.14 → 5.0.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/addresses.d.ts +23 -0
  2. package/dist/addresses.d.ts.map +1 -0
  3. package/dist/addresses.js +52 -0
  4. package/dist/addresses.js.map +1 -0
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +222 -2
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/constants.d.ts +63 -2
  9. package/dist/constants.d.ts.map +1 -1
  10. package/dist/constants.js +94 -3
  11. package/dist/constants.js.map +1 -1
  12. package/dist/currencies.d.ts +22 -0
  13. package/dist/currencies.d.ts.map +1 -0
  14. package/dist/currencies.js +231 -0
  15. package/dist/currencies.js.map +1 -0
  16. package/dist/index.js +7 -4
  17. package/dist/links.d.ts +38 -0
  18. package/dist/links.d.ts.map +1 -0
  19. package/dist/links.js +65 -0
  20. package/dist/links.js.map +1 -0
  21. package/dist/lint.js +6 -2
  22. package/dist/lint.js.map +1 -1
  23. package/dist/mock/auth.d.ts +71 -0
  24. package/dist/mock/auth.d.ts.map +1 -0
  25. package/dist/mock/auth.js +346 -0
  26. package/dist/mock/auth.js.map +1 -0
  27. package/dist/mock/index.d.ts +8 -0
  28. package/dist/mock/index.d.ts.map +1 -1
  29. package/dist/mock/index.js +27 -3
  30. package/dist/mock/index.js.map +1 -1
  31. package/dist/openapi.d.ts.map +1 -1
  32. package/dist/openapi.js +227 -30
  33. package/dist/openapi.js.map +1 -1
  34. package/dist/query.d.ts +4 -0
  35. package/dist/query.d.ts.map +1 -1
  36. package/dist/query.js +23 -7
  37. package/dist/query.js.map +1 -1
  38. package/dist/rules.d.ts +4 -1
  39. package/dist/rules.d.ts.map +1 -1
  40. package/dist/rules.js +165 -7
  41. package/dist/rules.js.map +1 -1
  42. package/dist/runtime/index.d.ts +3 -0
  43. package/dist/runtime/index.d.ts.map +1 -1
  44. package/dist/runtime/index.js +5 -2
  45. package/dist/schemas/action.d.ts +46 -1
  46. package/dist/schemas/action.d.ts.map +1 -1
  47. package/dist/schemas/api.d.ts +78 -3
  48. package/dist/schemas/api.d.ts.map +1 -1
  49. package/dist/schemas/api.js +58 -1
  50. package/dist/schemas/api.js.map +1 -1
  51. package/dist/schemas/boot.d.ts +1 -0
  52. package/dist/schemas/boot.d.ts.map +1 -1
  53. package/dist/schemas/definition.d.ts +95 -3
  54. package/dist/schemas/definition.d.ts.map +1 -1
  55. package/dist/schemas/definition.js +6 -5
  56. package/dist/schemas/definition.js.map +1 -1
  57. package/dist/schemas/field.d.ts +193 -2
  58. package/dist/schemas/field.d.ts.map +1 -1
  59. package/dist/schemas/field.js +91 -7
  60. package/dist/schemas/field.js.map +1 -1
  61. package/dist/schemas/index.d.ts +476 -14
  62. package/dist/schemas/index.d.ts.map +1 -1
  63. package/dist/schemas/index.js +20 -4
  64. package/dist/schemas/index.js.map +1 -1
  65. package/dist/schemas/list.d.ts +2 -2
  66. package/dist/schemas/resource.d.ts +93 -3
  67. package/dist/schemas/resource.d.ts.map +1 -1
  68. package/dist/validate.d.ts +2 -1
  69. package/dist/validate.d.ts.map +1 -1
  70. package/dist/validate.js +18 -4
  71. package/dist/validate.js.map +1 -1
  72. package/package.json +1 -1
  73. package/schema/boot.schema.json +167 -2
  74. package/schema/definition.schema.json +167 -2
  75. package/schema/openapi.json +1842 -117
package/dist/lint.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lint.js","names":[],"sources":["../src/lint.ts"],"sourcesContent":["import type { DefinitionInput, Field, LayoutNode, ResourceInput } from './schemas';\nimport type { ValidationIssue } from './validate';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n if (resource.form?.layout !== undefined) {\n checkLayout(resource.form.layout, names, `${path}.form.layout`, issues);\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n const calendar = resource.list?.calendar;\n if (calendar !== undefined) {\n const field = resource.fields.find((candidate) => candidate.name === calendar.field);\n const filter = calendar.filter ?? calendar.field;\n if (field === undefined) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: `No field named \\`${calendar.field}\\`.`,\n });\n } else if (field.type !== 'date' && field.type !== 'datetime') {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: 'The field of a calendar must be a `date` or a `datetime`.',\n });\n }\n if (\n !(resource.list?.filters ?? []).some(\n (candidate) => candidate.id === filter && candidate.type === 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.list.calendar`,\n message: `The calendar needs a \\`date-range\\` filter \\`${filter}\\` in the list.`,\n });\n }\n }\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n resource.fields.forEach((field, index) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n } else if (field.type === 'relation' && Array.isArray(field.resource)) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field names one resource.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations, `media` and `image` fields that name a resource,\n * unique names), and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n resource.fields.forEach((field, fieldIndex) => {\n if (\n field.type === 'relation' &&\n typeof field.resource === 'string' &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `resources.${index}.fields.${fieldIndex}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media' || field.type === 'image') {\n const fieldPath = `resources.${index}.fields.${fieldIndex}.resource`;\n if (field.resource === undefined) {\n // Every library of the definition (decision 0027).\n if (libraries.length === 0) {\n issues.push({\n path: fieldPath,\n message: `${field.type === 'image' ? 'An' : 'A'} \\`${field.type}\\` field needs a resource of kind \\`media\\`.`,\n });\n }\n } else {\n const named =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n named.forEach((id, idIndex) => {\n if (!libraries.includes(id)) {\n issues.push({\n path:\n typeof field.resource === 'string'\n ? fieldPath\n : `${fieldPath}.${String(idIndex)}`,\n message: `No resource of kind \\`media\\` named \\`${id}\\`.`,\n });\n }\n });\n }\n }\n });\n });\n return issues;\n}\n"],"mappings":";AAGA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,MAAM,WAAW,GAAG,KAAK,GAAG;EAC5B,IAAI,KAAK,SAAS,SAAS;GACvB,IAAI,KAAK,SAAS,KAAA,GACd,OAAO,KAAK;IAAE,MAAM;IAAU,SAAS;GAAiC,CAAC;QACtE,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GAC3B,OAAO,KAAK;IACR,MAAM,GAAG,SAAS;IAClB,SAAS,oBAAoB,KAAK,KAAK;GAC3C,CAAC;EAET;EACA,IAAI,KAAK,SAAS,eAAe,KAAK,cAAc,KAAA,GAChD,OAAO,KAAK;GAAE,MAAM;GAAU,SAAS;EAA0C,CAAC;EAEtF,IAAI,KAAK,SAAS,UAAU,KAAK,UAAU,MAAM,UAAU,MAAM,SAAS,KAAK,GAC3E,OAAO,KAAK;GACR,MAAM,GAAG,SAAS;GAClB,SAAS;EACb,CAAC;EAEL,IAAI,KAAK,aAAa,KAAA,GAClB,YAAY,KAAK,UAAU,OAAO,GAAG,SAAS,YAAY,MAAM;CAExE,CAAC;AACL;AAEA,SAAS,cAAc,UAAyB,MAAc,QAA2B;CACrF,MAAM,QAAQ,WAAW,SAAS,MAAM;CACxC,IAAI,MAAM,SAAS,SAAS,OAAO,QAC/B,OAAO,KAAK;EAAE,MAAM,GAAG,KAAK;EAAU,SAAS;CAA8B,CAAC;CAElF,IAAI,SAAS,MAAM,WAAW,KAAA,GAC1B,YAAY,SAAS,KAAK,QAAQ,O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,MAAM,aAAa,WAAW,CAAC,MAAM,QAAQ,IAAI,MAAM,SAAA,CAC5D,SAAS,IAAI,YAAY;KAC3B,IAAI,CAAC,UAAU,SAAS,EAAE,GACtB,OAAO,KAAK;MACR,MACI,OAAO,MAAM,aAAa,WACpB,YACA,GAAG,UAAU,GAAG,OAAO,OAAO;MACxC,SAAS,yCAAyC,GAAG;KACzD,CAAC;IAET,CAAC;GAET;EACJ,CAAC;CACL,CAAC;CACD,OAAO;AACX"}
1
+ {"version":3,"file":"lint.js","names":[],"sources":["../src/lint.ts"],"sourcesContent":["import type { DefinitionInput, Field, LayoutNode, ResourceInput } from './schemas';\nimport type { ValidationIssue } from './validate';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n if (resource.form?.layout !== undefined) {\n checkLayout(resource.form.layout, names, `${path}.form.layout`, issues);\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n const calendar = resource.list?.calendar;\n if (calendar !== undefined) {\n const field = resource.fields.find((candidate) => candidate.name === calendar.field);\n const filter = calendar.filter ?? calendar.field;\n if (field === undefined) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: `No field named \\`${calendar.field}\\`.`,\n });\n } else if (!['date', 'datetime', 'daterange'].includes(field.type)) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: 'The field of a calendar must be a `date`, a `datetime` or a `daterange`.',\n });\n }\n if (\n !(resource.list?.filters ?? []).some(\n (candidate) => candidate.id === filter && candidate.type === 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.list.calendar`,\n message: `The calendar needs a \\`date-range\\` filter \\`${filter}\\` in the list.`,\n });\n }\n }\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n resource.fields.forEach((field, index) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n } else if (field.type === 'relation' && Array.isArray(field.resource)) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field names one resource.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations, `media` and `image` fields that name a resource,\n * unique names), and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n resource.fields.forEach((field, fieldIndex) => {\n if (\n field.type === 'relation' &&\n typeof field.resource === 'string' &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `resources.${index}.fields.${fieldIndex}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media' || field.type === 'image') {\n const fieldPath = `resources.${index}.fields.${fieldIndex}.resource`;\n if (field.resource === undefined) {\n // Every library of the definition (decision 0027).\n if (libraries.length === 0) {\n issues.push({\n path: fieldPath,\n message: `${field.type === 'image' ? 'An' : 'A'} \\`${field.type}\\` field needs a resource of kind \\`media\\`.`,\n });\n }\n } else {\n const named =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n named.forEach((id, idIndex) => {\n if (!libraries.includes(id)) {\n issues.push({\n path:\n typeof field.resource === 'string'\n ? fieldPath\n : `${fieldPath}.${String(idIndex)}`,\n message: `No resource of kind \\`media\\` named \\`${id}\\`.`,\n });\n }\n });\n }\n }\n });\n });\n return issues;\n}\n"],"mappings":";AAGA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,MAAM,WAAW,GAAG,KAAK,GAAG;EAC5B,IAAI,KAAK,SAAS,SAAS;GACvB,IAAI,KAAK,SAAS,KAAA,GACd,OAAO,KAAK;IAAE,MAAM;IAAU,SAAS;GAAiC,CAAC;QACtE,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GAC3B,OAAO,KAAK;IACR,MAAM,GAAG,SAAS;IAClB,SAAS,oBAAoB,KAA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WAAW,UACxB,QAAQ,aAAa,SAAS,SAAS,OAAO,CAAC,CAC/C,KAAK,aAAa,SAAS,EAAE;CAClC,WAAW,UAAU,SAAS,UAAU,UAAU;EAC9C,cAAc,UAAU,aAAa,SAAS,MAAM;EACpD,SAAS,OAAO,SAAS,OAAO,eAAe;GAC3C,IACI,MAAM,SAAS,cACf,OAAO,MAAM,aAAa,YAC1B,CAAC,YAAY,IAAI,MAAM,QAAQ,GAE/B,OAAO,KAAK;IACR,MAAM,aAAa,MAAM,UAAU,WAAW;IAC9C,SAAS,iBAAiB,MAAM,SAAS;GAC7C,CAAC;GAEL,IAAI,MAAM,SAAS,WAAW,MAAM,SAAS,SAAS;IAClD,MAAM,YAAY,aAAa,MAAM,UAAU,WAAW;IAC1D,IAAI,MAAM,aAAa,KAAA,GAEf;SAAA,UAAU,WAAW,GACrB,OAAO,KAAK;MACR,MAAM;MACN,SAAS,GAAG,MAAM,SAAS,UAAU,OAAO,IAAI,KAAK,MAAM,KAAK;KACpE,CAAC;IAAA,OAKL,CADI,OAAO,MAAM,aAAa,WAAW,CAAC,MAAM,QAAQ,IAAI,MAAM,SAAA,CAC5D,SAAS,IAAI,YAAY;KAC3B,IAAI,CAAC,UAAU,SAAS,EAAE,GACtB,OAAO,KAAK;MACR,MACI,OAAO,MAAM,aAAa,WACpB,YACA,GAAG,UAAU,GAAG,OAAO,OAAO;MACxC,SAAS,yCAAyC,GAAG;KACzD,CAAC;IAET,CAAC;GAET;EACJ,CAAC;CACL,CAAC;CACD,OAAO;AACX"}
@@ -0,0 +1,71 @@
1
+ import type { Auth, User } from '../schemas/index.js';
2
+ /** A user of the mock backend. */
3
+ export interface MockUser {
4
+ /** Defaults to the position of the user in `users`, from 1. */
5
+ id?: string;
6
+ /** Defaults to the email. */
7
+ name?: string;
8
+ email: string;
9
+ password: string;
10
+ /** Whether the email address is verified, for `auth.emailVerification`. Defaults to true. */
11
+ emailVerified?: boolean;
12
+ /**
13
+ * Whether the user has two-factor authentication, for `auth.twoFactor`: their password login
14
+ * then asks for `twoFactorCode` or a recovery code. Defaults to false.
15
+ */
16
+ twoFactor?: boolean;
17
+ /** Recovery codes of a user with `twoFactor`. Defaults to none. */
18
+ recoveryCodes?: string[];
19
+ /** Whether the backend requires two-factor authentication for the user. Defaults to false. */
20
+ twoFactorRequired?: boolean;
21
+ /**
22
+ * The passkeys of the user, for `auth.passkeys`: the `id` of their credential, and a name. The
23
+ * mock doesn't check signatures: a credential with one of these ids logs in.
24
+ */
25
+ passkeys?: {
26
+ id: string;
27
+ name: string;
28
+ }[];
29
+ }
30
+ /** An email that the mock backend "sends", with the path of its link under the app's base path. */
31
+ export interface MockMail {
32
+ kind: 'password-reset' | 'email-verification';
33
+ to: string;
34
+ token: string;
35
+ /** The page of the app that the link opens, with its query: `auth/reset-password?token=…`. */
36
+ path: string;
37
+ }
38
+ /**
39
+ * The auth of the mock backend: its users, and who is logged in. With it, the routes of the
40
+ * `panneau` auth mode answer (`/auth/login`, `/auth/logout`, `/auth/session`, and those of
41
+ * `auth.passwordReset` and `auth.emailVerification`), and the other routes answer `401` to
42
+ * guests.
43
+ */
44
+ export interface MockAuthOptions {
45
+ users: MockUser[];
46
+ /** The email of the user logged in at the start. Defaults to the first user; `null`: a guest. */
47
+ loggedIn?: string | null;
48
+ /** Called with each email the backend sends: there is no mailbox. */
49
+ onMail?: (mail: MockMail) => void;
50
+ /** The code of the authenticator app of every user, for `auth.twoFactor`. Defaults to `123456`. */
51
+ twoFactorCode?: string;
52
+ /**
53
+ * The email of the user that each OAuth provider of `auth.providers` logs in, at once, when the
54
+ * app goes to its `redirect` (decision 0052). A provider without one fails with `access`.
55
+ */
56
+ providerUsers?: Record<string, string>;
57
+ }
58
+ type Values = Record<string, unknown>;
59
+ export interface MockAuth {
60
+ /** The current user, as the definition and `/auth/session` give it. */
61
+ user(): User | null;
62
+ /** The answer of a route of `/auth/…`, without its first segment. */
63
+ answer(segments: string[], method: string, readBody: () => Promise<Values>, url?: URL): Promise<Response>;
64
+ /** The answer of a route of `/account/…`, without its first segment, or null for another. */
65
+ account(segments: string[], method: string, readBody: () => Promise<Values>): Promise<Response> | null;
66
+ /** The answer to a request of another route by the current user, when it is refused. */
67
+ refuse(): Response | null;
68
+ }
69
+ export declare function createMockAuth(options: MockAuthOptions, settings: Auth | undefined): MockAuth;
70
+ export {};
71
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/mock/auth.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAI7C,kCAAkC;AAClC,MAAM,WAAW,QAAQ;IACrB,+DAA+D;IAC/D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,6BAA6B;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,6FAA6F;IAC7F,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,8FAA8F;IAC9F,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC7C;AAED,mGAAmG;AACnG,MAAM,WAAW,QAAQ;IACrB,IAAI,EAAE,gBAAgB,GAAG,oBAAoB,CAAC;IAC9C,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,8FAA8F;IAC9F,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC5B,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,iGAAiG;IACjG,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,qEAAqE;IACrE,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,KAAK,IAAI,CAAC;IAClC,mGAAmG;IACnG,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC1C;AAED,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AA6EtC,MAAM,WAAW,QAAQ;IACrB,uEAAuE;IACvE,IAAI,IAAI,IAAI,GAAG,IAAI,CAAC;IACpB,qEAAqE;IACrE,MAAM,CACF,QAAQ,EAAE,MAAM,EAAE,EAClB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,EAC/B,GAAG,CAAC,EAAE,GAAG,GACV,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrB,6FAA6F;IAC7F,OAAO,CACH,QAAQ,EAAE,MAAM,EAAE,EAClB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,GAChC,OAAO,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;IAC5B,wFAAwF;IACxF,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;CAC7B;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,IAAI,GAAG,SAAS,GAAG,QAAQ,CA8a7F"}
@@ -0,0 +1,346 @@
1
+ import { PROBLEM_CONTENT_TYPE } from "../version.js";
2
+ import { AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, EMAIL_UNVERIFIED_PROBLEM_TYPE, TWO_FACTOR_REQUIRED_PROBLEM_TYPE } from "../constants.js";
3
+ //#region src/mock/auth.ts
4
+ /** The secret that the mock backend gives every two-factor setup. */
5
+ var SECRET = "JBSWY3DPEHPK3PXP";
6
+ var EMAIL = /^[^\s@]+@[^\s@]+$/;
7
+ function json(status, body) {
8
+ return new Response(status === 204 ? null : JSON.stringify(body), {
9
+ status,
10
+ headers: status === 204 ? {} : { "Content-Type": "application/json" }
11
+ });
12
+ }
13
+ function problem(status, title, extra = {}) {
14
+ const body = {
15
+ type: "about:blank",
16
+ title,
17
+ status,
18
+ ...extra
19
+ };
20
+ return new Response(JSON.stringify(body), {
21
+ status,
22
+ headers: { "Content-Type": PROBLEM_CONTENT_TYPE }
23
+ });
24
+ }
25
+ function invalid(errors) {
26
+ return problem(422, "The given data was invalid.", {
27
+ type: "urn:panneau:problem:validation",
28
+ errors
29
+ });
30
+ }
31
+ function randomToken() {
32
+ return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
33
+ }
34
+ /** Text in base64url, without padding, as WebAuthn's JSON form has binary values. */
35
+ function base64Url(text) {
36
+ return btoa(text).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
37
+ }
38
+ /** A credential in the JSON form of the WebAuthn spec: the mock only reads its id. */
39
+ function isCredential(value) {
40
+ return value !== null && typeof value === "object" && typeof value.id === "string" && value.id !== "";
41
+ }
42
+ function recoveryCodes() {
43
+ return Array.from({ length: 8 }, () => `${randomToken().slice(0, 5)}-${randomToken().slice(0, 5)}`);
44
+ }
45
+ function createMockAuth(options, settings) {
46
+ let nextPasskey = 1;
47
+ const accounts = options.users.map((user, index) => ({
48
+ id: user.id ?? String(index + 1),
49
+ name: user.name ?? user.email,
50
+ email: user.email,
51
+ password: user.password,
52
+ emailVerified: user.emailVerified ?? true,
53
+ twoFactor: user.twoFactor === true ? "enabled" : "disabled",
54
+ recoveryCodes: [...user.recoveryCodes ?? []],
55
+ twoFactorRequired: user.twoFactorRequired ?? false,
56
+ passkeys: (user.passkeys ?? []).map((passkey) => ({
57
+ id: String(nextPasskey++),
58
+ credentialId: passkey.id,
59
+ name: passkey.name,
60
+ createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
61
+ lastUsedAt: null
62
+ }))
63
+ }));
64
+ const code = options.twoFactorCode ?? "123456";
65
+ let pending = null;
66
+ let current = options.loggedIn === null ? null : (options.loggedIn !== void 0 ? accounts.find((account) => account.email === options.loggedIn) : accounts[0]) ?? null;
67
+ const resets = /* @__PURE__ */ new Map();
68
+ const verifications = /* @__PURE__ */ new Map();
69
+ const find = (email) => typeof email === "string" ? accounts.find((account) => account.email.toLowerCase() === email.toLowerCase()) : void 0;
70
+ const userOf = (account) => ({
71
+ id: account.id,
72
+ name: account.name,
73
+ email: account.email,
74
+ abilities: {}
75
+ });
76
+ const send = (kind, account) => {
77
+ const token = randomToken();
78
+ const query = new URLSearchParams({ token });
79
+ if (kind === "password-reset") {
80
+ resets.set(token, account);
81
+ query.set("email", account.email);
82
+ } else verifications.set(token, account);
83
+ const page = kind === "password-reset" ? AUTH_PAGE_PATHS.resetPassword : AUTH_PAGE_PATHS.verifyEmail;
84
+ options.onMail?.({
85
+ kind,
86
+ to: account.email,
87
+ token,
88
+ path: `${page}?${query.toString()}`
89
+ });
90
+ };
91
+ const routes = {
92
+ "GET session": () => Promise.resolve(current !== null ? json(200, { user: userOf(current) }) : problem(401, "Unauthenticated.")),
93
+ "POST login": async (body) => {
94
+ const { email, password } = await body();
95
+ const account = find(email);
96
+ if (account === void 0 || account.password !== password) return invalid({ email: ["These credentials do not match our records."] });
97
+ if (settings?.twoFactor === true && account.twoFactor === "enabled") {
98
+ pending = { account };
99
+ return json(202, { twoFactor: true });
100
+ }
101
+ current = account;
102
+ return json(200, { user: userOf(account) });
103
+ },
104
+ "POST logout": () => {
105
+ current = null;
106
+ pending = null;
107
+ return Promise.resolve(json(204, null));
108
+ }
109
+ };
110
+ if (settings?.twoFactor === true) {
111
+ routes["POST two-factor/challenge"] = async (body) => {
112
+ const answer = await body();
113
+ if (pending === null) return invalid({ code: ["The login has expired. Log in again."] });
114
+ const { account } = pending;
115
+ if (typeof answer.recoveryCode === "string") {
116
+ const index = account.recoveryCodes.indexOf(answer.recoveryCode);
117
+ if (index === -1) return invalid({ recoveryCode: ["This recovery code is invalid."] });
118
+ account.recoveryCodes.splice(index, 1);
119
+ } else if (answer.code !== code) return invalid({ code: ["This code is invalid."] });
120
+ pending = null;
121
+ current = account;
122
+ return json(200, { user: userOf(account) });
123
+ };
124
+ routes["POST password/confirm"] = async (body) => {
125
+ const { password } = await body();
126
+ if (current === null) return problem(401, "Unauthenticated.");
127
+ return password === current.password ? json(204, null) : invalid({ password: ["The password is incorrect."] });
128
+ };
129
+ }
130
+ if (settings?.passkeys === true) {
131
+ routes["POST passkeys/options"] = () => Promise.resolve(json(200, { options: {
132
+ challenge: randomToken(),
133
+ timeout: 6e4,
134
+ userVerification: "preferred",
135
+ allowCredentials: []
136
+ } }));
137
+ routes["POST passkeys/login"] = async (body) => {
138
+ const { credential } = await body();
139
+ const id = isCredential(credential) ? credential.id : null;
140
+ const account = accounts.find((candidate) => candidate.passkeys.some((passkey) => passkey.credentialId === id));
141
+ const passkey = account?.passkeys.find((candidate) => candidate.credentialId === id);
142
+ if (account === void 0 || passkey === void 0) return invalid({ credential: ["This passkey isn’t known. It may have been removed."] });
143
+ passkey.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString();
144
+ pending = null;
145
+ current = account;
146
+ return json(200, { user: userOf(account) });
147
+ };
148
+ }
149
+ if (settings?.passwordReset === true) {
150
+ routes["POST password/forgot"] = async (body) => {
151
+ const { email } = await body();
152
+ if (typeof email !== "string" || !EMAIL.test(email)) return invalid({ email: ["The email field must be a valid email address."] });
153
+ const account = find(email);
154
+ if (account !== void 0) send("password-reset", account);
155
+ return json(204, null);
156
+ };
157
+ routes["POST password/reset"] = async (body) => {
158
+ const { token, email, password } = await body();
159
+ const account = typeof token === "string" ? resets.get(token) : void 0;
160
+ if (account === void 0 || find(email) !== account) return invalid({ email: ["This password reset token is invalid."] });
161
+ if (typeof password !== "string" || password.length < 8) return invalid({ password: ["The password field must be at least 8 characters."] });
162
+ account.password = password;
163
+ resets.delete(token);
164
+ return json(204, null);
165
+ };
166
+ }
167
+ if (settings?.emailVerification === true) {
168
+ routes["POST email/verification"] = () => {
169
+ if (current === null) return Promise.resolve(problem(401, "Unauthenticated."));
170
+ if (!current.emailVerified) send("email-verification", current);
171
+ return Promise.resolve(json(204, null));
172
+ };
173
+ routes["POST email/verify"] = async (body) => {
174
+ const { token } = await body();
175
+ const account = typeof token === "string" ? verifications.get(token) : void 0;
176
+ if (account === void 0) return invalid({ token: ["This verification link is invalid or has expired."] });
177
+ account.emailVerified = true;
178
+ verifications.delete(token);
179
+ return json(204, null);
180
+ };
181
+ }
182
+ const conflict = (title) => problem(409, title);
183
+ const twoFactorRoutes = {
184
+ GET: (account) => json(200, {
185
+ status: account.twoFactor,
186
+ required: account.twoFactorRequired
187
+ }),
188
+ POST: (account) => {
189
+ if (account.twoFactor === "enabled") return conflict("Two-factor authentication is already on.");
190
+ account.twoFactor = "pending";
191
+ return json(200, {
192
+ secret: SECRET,
193
+ otpauthUrl: `otpauth://totp/${encodeURIComponent(`Panneau:${account.email}`)}?secret=${SECRET}&issuer=Panneau`
194
+ });
195
+ },
196
+ DELETE: (account) => {
197
+ if (account.twoFactorRequired) return conflict("Two-factor authentication is required for this account.");
198
+ account.twoFactor = "disabled";
199
+ account.recoveryCodes = [];
200
+ return json(204, null);
201
+ },
202
+ "POST confirm": async (account, body) => {
203
+ if (account.twoFactor !== "pending") return conflict("Two-factor authentication isn’t being set up.");
204
+ if ((await body()).code !== code) return invalid({ code: ["This code is invalid."] });
205
+ account.twoFactor = "enabled";
206
+ account.recoveryCodes = recoveryCodes();
207
+ return json(200, { recoveryCodes: account.recoveryCodes });
208
+ },
209
+ "POST recovery-codes": (account) => {
210
+ if (account.twoFactor !== "enabled") return conflict("Two-factor authentication is off.");
211
+ account.recoveryCodes = recoveryCodes();
212
+ return json(200, { recoveryCodes: account.recoveryCodes });
213
+ }
214
+ };
215
+ const accountRoutes = {
216
+ GET: (account) => json(200, { data: userOf(account) }),
217
+ PATCH: async (account, body) => {
218
+ const { name, email } = await body();
219
+ const errors = {};
220
+ if (typeof name !== "string" || name.trim() === "") errors.name = ["The name field is required."];
221
+ if (typeof email !== "string" || !EMAIL.test(email)) errors.email = ["The email field must be a valid email address."];
222
+ else if (find(email) !== void 0 && find(email) !== account) errors.email = ["The email has already been taken."];
223
+ if (Object.keys(errors).length > 0) return invalid(errors);
224
+ const changed = email.toLowerCase() !== account.email.toLowerCase();
225
+ account.name = name;
226
+ account.email = email;
227
+ if (changed && settings?.emailVerification === true) {
228
+ account.emailVerified = false;
229
+ send("email-verification", account);
230
+ }
231
+ return json(200, { data: userOf(account) });
232
+ },
233
+ "PUT password": async (account, body) => {
234
+ const { currentPassword, password } = await body();
235
+ if (currentPassword !== account.password) return invalid({ currentPassword: ["The provided password does not match your current password."] });
236
+ if (typeof password !== "string" || password.length < 8) return invalid({ password: ["The password field must be at least 8 characters."] });
237
+ account.password = password;
238
+ return json(204, null);
239
+ }
240
+ };
241
+ const redirectToProvider = (id, url) => {
242
+ if (!(settings?.providers ?? []).some((provider) => provider.id === id)) return problem(404, "Not found.");
243
+ const next = url?.searchParams.get("next") ?? "/";
244
+ const local = next.startsWith("/") && !next.startsWith("//") ? next : "/";
245
+ const account = find(options.providerUsers?.[id]);
246
+ if (account === void 0) return new Response(null, {
247
+ status: 302,
248
+ headers: { Location: `/?${AUTH_ERROR_PARAM}=access` }
249
+ });
250
+ current = account;
251
+ return new Response(null, {
252
+ status: 302,
253
+ headers: { Location: local }
254
+ });
255
+ };
256
+ const passkeyOf = ({ id, name, createdAt, lastUsedAt }) => ({
257
+ id,
258
+ name,
259
+ authenticator: null,
260
+ createdAt,
261
+ lastUsedAt
262
+ });
263
+ const passkeyRoutes = async (account, method, segments, body) => {
264
+ const [, second] = segments;
265
+ if (method === "GET" && second === void 0) return json(200, { data: account.passkeys.map(passkeyOf) });
266
+ if (method === "POST" && second === "options") return json(200, { options: {
267
+ challenge: randomToken(),
268
+ rp: { name: "Panneau" },
269
+ user: {
270
+ id: base64Url(account.id),
271
+ name: account.email,
272
+ displayName: account.name
273
+ },
274
+ pubKeyCredParams: [{
275
+ type: "public-key",
276
+ alg: -7
277
+ }, {
278
+ type: "public-key",
279
+ alg: -257
280
+ }],
281
+ authenticatorSelection: {
282
+ residentKey: "required",
283
+ userVerification: "preferred"
284
+ },
285
+ excludeCredentials: account.passkeys.map((passkey) => ({
286
+ type: "public-key",
287
+ id: passkey.credentialId
288
+ })),
289
+ timeout: 6e4
290
+ } });
291
+ if (method === "POST" && second === void 0) {
292
+ const { name, credential } = await body();
293
+ if (!isCredential(credential)) return invalid({ credential: ["This passkey could not be added. Try again."] });
294
+ const passkey = {
295
+ id: String(nextPasskey++),
296
+ credentialId: credential.id,
297
+ name: typeof name === "string" && name.trim() !== "" ? name : "Passkey",
298
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
299
+ lastUsedAt: null
300
+ };
301
+ account.passkeys.push(passkey);
302
+ return json(201, { data: passkeyOf(passkey) });
303
+ }
304
+ const index = account.passkeys.findIndex((passkey) => passkey.id === second);
305
+ if (method === "DELETE" && segments.length === 2 && index !== -1) {
306
+ account.passkeys.splice(index, 1);
307
+ return json(204, null);
308
+ }
309
+ return problem(404, "Not found.");
310
+ };
311
+ const refuseUnverified = (account) => settings?.emailVerification === true && !account.emailVerified ? problem(403, "Your email address is not verified.", { type: EMAIL_UNVERIFIED_PROBLEM_TYPE }) : null;
312
+ return {
313
+ user: () => current !== null ? userOf(current) : null,
314
+ account: (segments, method, readBody) => {
315
+ const twoFactor = segments[0] === "two-factor" && settings?.twoFactor === true;
316
+ const passkeys = segments[0] === "passkeys" && settings?.passkeys === true;
317
+ if (!twoFactor && !passkeys && settings?.account !== true) return null;
318
+ if (current === null) return Promise.resolve(problem(401, "Unauthenticated."));
319
+ if (passkeys) {
320
+ const refusedPasskeys = refuse();
321
+ return refusedPasskeys !== null ? Promise.resolve(refusedPasskeys) : passkeyRoutes(current, method, segments, readBody);
322
+ }
323
+ const refused = twoFactor ? refuseUnverified(current) : refuse();
324
+ const route = twoFactor ? twoFactorRoutes[[method, ...segments.slice(1)].join(" ")] : accountRoutes[[method, ...segments].join(" ")];
325
+ if (refused !== null || route === void 0) return Promise.resolve(refused ?? problem(404, "Not found."));
326
+ return Promise.resolve(route(current, readBody));
327
+ },
328
+ answer: (segments, method, readBody, url) => {
329
+ if (method === "GET" && segments.length === 3 && segments[0] === "providers" && segments[2] === "redirect") return Promise.resolve(redirectToProvider(segments[1] ?? "", url));
330
+ const route = routes[`${method} ${segments.join("/")}`];
331
+ return route !== void 0 ? route(readBody) : Promise.resolve(problem(404, "Not found."));
332
+ },
333
+ refuse
334
+ };
335
+ function refuse() {
336
+ if (current === null) return problem(401, "Unauthenticated.");
337
+ const unverified = refuseUnverified(current);
338
+ if (unverified !== null) return unverified;
339
+ if (settings?.twoFactor === true && current.twoFactorRequired && current.twoFactor !== "enabled") return problem(403, "Two-factor authentication is required for this account.", { type: TWO_FACTOR_REQUIRED_PROBLEM_TYPE });
340
+ return null;
341
+ }
342
+ }
343
+ //#endregion
344
+ export { createMockAuth };
345
+
346
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../../src/mock/auth.ts"],"sourcesContent":["import {\n AUTH_ERROR_PARAM,\n AUTH_PAGE_PATHS,\n EMAIL_UNVERIFIED_PROBLEM_TYPE,\n TWO_FACTOR_REQUIRED_PROBLEM_TYPE,\n} from '../constants';\nimport type { Auth, User } from '../schemas';\nimport type { Problem, TwoFactorStatus } from '../schemas/api';\nimport { PROBLEM_CONTENT_TYPE } from '../version';\n\n/** A user of the mock backend. */\nexport interface MockUser {\n /** Defaults to the position of the user in `users`, from 1. */\n id?: string;\n /** Defaults to the email. */\n name?: string;\n email: string;\n password: string;\n /** Whether the email address is verified, for `auth.emailVerification`. Defaults to true. */\n emailVerified?: boolean;\n /**\n * Whether the user has two-factor authentication, for `auth.twoFactor`: their password login\n * then asks for `twoFactorCode` or a recovery code. Defaults to false.\n */\n twoFactor?: boolean;\n /** Recovery codes of a user with `twoFactor`. Defaults to none. */\n recoveryCodes?: string[];\n /** Whether the backend requires two-factor authentication for the user. Defaults to false. */\n twoFactorRequired?: boolean;\n /**\n * The passkeys of the user, for `auth.passkeys`: the `id` of their credential, and a name. The\n * mock doesn't check signatures: a credential with one of these ids logs in.\n */\n passkeys?: { id: string; name: string }[];\n}\n\n/** An email that the mock backend \"sends\", with the path of its link under the app's base path. */\nexport interface MockMail {\n kind: 'password-reset' | 'email-verification';\n to: string;\n token: string;\n /** The page of the app that the link opens, with its query: `auth/reset-password?token=…`. */\n path: string;\n}\n\n/**\n * The auth of the mock backend: its users, and who is logged in. With it, the routes of the\n * `panneau` auth mode answer (`/auth/login`, `/auth/logout`, `/auth/session`, and those of\n * `auth.passwordReset` and `auth.emailVerification`), and the other routes answer `401` to\n * guests.\n */\nexport interface MockAuthOptions {\n users: MockUser[];\n /** The email of the user logged in at the start. Defaults to the first user; `null`: a guest. */\n loggedIn?: string | null;\n /** Called with each email the backend sends: there is no mailbox. */\n onMail?: (mail: MockMail) => void;\n /** The code of the authenticator app of every user, for `auth.twoFactor`. Defaults to `123456`. */\n twoFactorCode?: string;\n /**\n * The email of the user that each OAuth provider of `auth.providers` logs in, at once, when the\n * app goes to its `redirect` (decision 0052). A provider without one fails with `access`.\n */\n providerUsers?: Record<string, string>;\n}\n\ntype Values = Record<string, unknown>;\n\ninterface Account {\n id: string;\n name: string;\n email: string;\n password: string;\n emailVerified: boolean;\n twoFactor: TwoFactorStatus['status'];\n recoveryCodes: string[];\n twoFactorRequired: boolean;\n passkeys: StoredPasskey[];\n}\n\ninterface StoredPasskey {\n id: string;\n credentialId: string;\n name: string;\n createdAt: string;\n lastUsedAt: string | null;\n}\n\n/** The secret that the mock backend gives every two-factor setup. */\nconst SECRET = 'JBSWY3DPEHPK3PXP';\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+$/;\n\nfunction json(status: number, body: unknown): Response {\n return new Response(status === 204 ? null : JSON.stringify(body), {\n status,\n headers: status === 204 ? {} : { 'Content-Type': 'application/json' },\n });\n}\n\nfunction problem(status: number, title: string, extra: Partial<Problem> = {}): Response {\n const body: Problem = { type: 'about:blank', title, status, ...extra };\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': PROBLEM_CONTENT_TYPE },\n });\n}\n\nfunction invalid(errors: Record<string, string[]>): Response {\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors,\n });\n}\n\nfunction randomToken(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('');\n}\n\n/** Text in base64url, without padding, as WebAuthn's JSON form has binary values. */\nfunction base64Url(text: string): string {\n return btoa(text).replace(/=+$/, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\n/** A credential in the JSON form of the WebAuthn spec: the mock only reads its id. */\nfunction isCredential(value: unknown): value is { id: string } {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as Record<string, unknown>).id === 'string' &&\n (value as Record<string, unknown>).id !== ''\n );\n}\n\nfunction recoveryCodes(): string[] {\n return Array.from(\n { length: 8 },\n () => `${randomToken().slice(0, 5)}-${randomToken().slice(0, 5)}`,\n );\n}\n\nexport interface MockAuth {\n /** The current user, as the definition and `/auth/session` give it. */\n user(): User | null;\n /** The answer of a route of `/auth/…`, without its first segment. */\n answer(\n segments: string[],\n method: string,\n readBody: () => Promise<Values>,\n url?: URL,\n ): Promise<Response>;\n /** The answer of a route of `/account/…`, without its first segment, or null for another. */\n account(\n segments: string[],\n method: string,\n readBody: () => Promise<Values>,\n ): Promise<Response> | null;\n /** The answer to a request of another route by the current user, when it is refused. */\n refuse(): Response | null;\n}\n\nexport function createMockAuth(options: MockAuthOptions, settings: Auth | undefined): MockAuth {\n let nextPasskey = 1;\n const accounts: Account[] = options.users.map((user, index) => ({\n id: user.id ?? String(index + 1),\n name: user.name ?? user.email,\n email: user.email,\n password: user.password,\n emailVerified: user.emailVerified ?? true,\n twoFactor: user.twoFactor === true ? 'enabled' : 'disabled',\n recoveryCodes: [...(user.recoveryCodes ?? [])],\n twoFactorRequired: user.twoFactorRequired ?? false,\n passkeys: (user.passkeys ?? []).map((passkey) => ({\n id: String(nextPasskey++),\n credentialId: passkey.id,\n name: passkey.name,\n createdAt: new Date(0).toISOString(),\n lastUsedAt: null,\n })),\n }));\n const code = options.twoFactorCode ?? '123456';\n // A password login that waits for its second factor\n let pending: { account: Account } | null = null;\n let current: Account | null =\n options.loggedIn === null\n ? null\n : ((options.loggedIn !== undefined\n ? accounts.find((account) => account.email === options.loggedIn)\n : accounts[0]) ?? null);\n // Tokens of the links sent, to their account\n const resets = new Map<string, Account>();\n const verifications = new Map<string, Account>();\n\n const find = (email: unknown) =>\n typeof email === 'string'\n ? accounts.find((account) => account.email.toLowerCase() === email.toLowerCase())\n : undefined;\n const userOf = (account: Account): User => ({\n id: account.id,\n name: account.name,\n email: account.email,\n abilities: {},\n });\n const send = (kind: MockMail['kind'], account: Account) => {\n const token = randomToken();\n const query = new URLSearchParams({ token });\n if (kind === 'password-reset') {\n resets.set(token, account);\n query.set('email', account.email);\n } else {\n verifications.set(token, account);\n }\n const page =\n kind === 'password-reset' ? AUTH_PAGE_PATHS.resetPassword : AUTH_PAGE_PATHS.verifyEmail;\n options.onMail?.({ kind, to: account.email, token, path: `${page}?${query.toString()}` });\n };\n\n const routes: Record<string, (body: () => Promise<Values>) => Promise<Response>> = {\n 'GET session': () =>\n Promise.resolve(\n current !== null\n ? json(200, { user: userOf(current) })\n : problem(401, 'Unauthenticated.'),\n ),\n 'POST login': async (body) => {\n const { email, password } = await body();\n const account = find(email);\n if (account === undefined || account.password !== password) {\n return invalid({ email: ['These credentials do not match our records.'] });\n }\n if (settings?.twoFactor === true && account.twoFactor === 'enabled') {\n pending = { account };\n return json(202, { twoFactor: true });\n }\n current = account;\n return json(200, { user: userOf(account) });\n },\n 'POST logout': () => {\n current = null;\n pending = null;\n return Promise.resolve(json(204, null));\n },\n };\n if (settings?.twoFactor === true) {\n routes['POST two-factor/challenge'] = async (body) => {\n const answer = await body();\n if (pending === null) {\n return invalid({ code: ['The login has expired. Log in again.'] });\n }\n const { account } = pending;\n if (typeof answer.recoveryCode === 'string') {\n const index = account.recoveryCodes.indexOf(answer.recoveryCode);\n if (index === -1) {\n return invalid({ recoveryCode: ['This recovery code is invalid.'] });\n }\n account.recoveryCodes.splice(index, 1);\n } else if (answer.code !== code) {\n return invalid({ code: ['This code is invalid.'] });\n }\n pending = null;\n current = account;\n return json(200, { user: userOf(account) });\n };\n routes['POST password/confirm'] = async (body) => {\n const { password } = await body();\n if (current === null) {\n return problem(401, 'Unauthenticated.');\n }\n return password === current.password\n ? json(204, null)\n : invalid({ password: ['The password is incorrect.'] });\n };\n }\n if (settings?.passkeys === true) {\n routes['POST passkeys/options'] = () =>\n Promise.resolve(\n json(200, {\n options: {\n challenge: randomToken(),\n timeout: 60000,\n userVerification: 'preferred',\n allowCredentials: [],\n },\n }),\n );\n routes['POST passkeys/login'] = async (body) => {\n const { credential } = await body();\n const id = isCredential(credential) ? credential.id : null;\n const account = accounts.find((candidate) =>\n candidate.passkeys.some((passkey) => passkey.credentialId === id),\n );\n const passkey = account?.passkeys.find((candidate) => candidate.credentialId === id);\n if (account === undefined || passkey === undefined) {\n return invalid({\n credential: ['This passkey isn’t known. It may have been removed.'],\n });\n }\n passkey.lastUsedAt = new Date().toISOString();\n pending = null;\n current = account;\n return json(200, { user: userOf(account) });\n };\n }\n if (settings?.passwordReset === true) {\n routes['POST password/forgot'] = async (body) => {\n const { email } = await body();\n if (typeof email !== 'string' || !EMAIL.test(email)) {\n return invalid({ email: ['The email field must be a valid email address.'] });\n }\n const account = find(email);\n if (account !== undefined) {\n send('password-reset', account);\n }\n return json(204, null);\n };\n routes['POST password/reset'] = async (body) => {\n const { token, email, password } = await body();\n const account = typeof token === 'string' ? resets.get(token) : undefined;\n if (account === undefined || find(email) !== account) {\n return invalid({ email: ['This password reset token is invalid.'] });\n }\n if (typeof password !== 'string' || password.length < 8) {\n return invalid({ password: ['The password field must be at least 8 characters.'] });\n }\n account.password = password;\n resets.delete(token as string);\n return json(204, null);\n };\n }\n if (settings?.emailVerification === true) {\n routes['POST email/verification'] = () => {\n if (current === null) {\n return Promise.resolve(problem(401, 'Unauthenticated.'));\n }\n if (!current.emailVerified) {\n send('email-verification', current);\n }\n return Promise.resolve(json(204, null));\n };\n routes['POST email/verify'] = async (body) => {\n const { token } = await body();\n const account = typeof token === 'string' ? verifications.get(token) : undefined;\n if (account === undefined) {\n return invalid({ token: ['This verification link is invalid or has expired.'] });\n }\n account.emailVerified = true;\n verifications.delete(token as string);\n return json(204, null);\n };\n }\n\n const conflict = (title: string) => problem(409, title);\n const twoFactorRoutes: Record<\n string,\n (account: Account, body: () => Promise<Values>) => Promise<Response> | Response\n > = {\n GET: (account) =>\n json(200, { status: account.twoFactor, required: account.twoFactorRequired }),\n POST: (account) => {\n if (account.twoFactor === 'enabled') {\n return conflict('Two-factor authentication is already on.');\n }\n account.twoFactor = 'pending';\n const label = encodeURIComponent(`Panneau:${account.email}`);\n return json(200, {\n secret: SECRET,\n otpauthUrl: `otpauth://totp/${label}?secret=${SECRET}&issuer=Panneau`,\n });\n },\n DELETE: (account) => {\n if (account.twoFactorRequired) {\n return conflict('Two-factor authentication is required for this account.');\n }\n account.twoFactor = 'disabled';\n account.recoveryCodes = [];\n return json(204, null);\n },\n 'POST confirm': async (account, body) => {\n if (account.twoFactor !== 'pending') {\n return conflict('Two-factor authentication isn’t being set up.');\n }\n if ((await body()).code !== code) {\n return invalid({ code: ['This code is invalid.'] });\n }\n account.twoFactor = 'enabled';\n account.recoveryCodes = recoveryCodes();\n return json(200, { recoveryCodes: account.recoveryCodes });\n },\n 'POST recovery-codes': (account) => {\n if (account.twoFactor !== 'enabled') {\n return conflict('Two-factor authentication is off.');\n }\n account.recoveryCodes = recoveryCodes();\n return json(200, { recoveryCodes: account.recoveryCodes });\n },\n };\n const accountRoutes: Record<\n string,\n (account: Account, body: () => Promise<Values>) => Promise<Response> | Response\n > = {\n GET: (account) => json(200, { data: userOf(account) }),\n PATCH: async (account, body) => {\n const { name, email } = await body();\n const errors: Record<string, string[]> = {};\n if (typeof name !== 'string' || name.trim() === '') {\n errors.name = ['The name field is required.'];\n }\n if (typeof email !== 'string' || !EMAIL.test(email)) {\n errors.email = ['The email field must be a valid email address.'];\n } else if (find(email) !== undefined && find(email) !== account) {\n errors.email = ['The email has already been taken.'];\n }\n if (Object.keys(errors).length > 0) {\n return invalid(errors);\n }\n const changed = (email as string).toLowerCase() !== account.email.toLowerCase();\n account.name = name as string;\n account.email = email as string;\n if (changed && settings?.emailVerification === true) {\n account.emailVerified = false;\n send('email-verification', account);\n }\n return json(200, { data: userOf(account) });\n },\n 'PUT password': async (account, body) => {\n const { currentPassword, password } = await body();\n if (currentPassword !== account.password) {\n return invalid({\n currentPassword: [\n 'The provided password does not match your current password.',\n ],\n });\n }\n if (typeof password !== 'string' || password.length < 8) {\n return invalid({ password: ['The password field must be at least 8 characters.'] });\n }\n account.password = password;\n return json(204, null);\n },\n };\n // A provider that logs in at once: it goes to `next`, or comes back with `authError`\n const redirectToProvider = (id: string, url: URL | undefined) => {\n if (!(settings?.providers ?? []).some((provider) => provider.id === id)) {\n return problem(404, 'Not found.');\n }\n const next = url?.searchParams.get('next') ?? '/';\n const local = next.startsWith('/') && !next.startsWith('//') ? next : '/';\n const account = find(options.providerUsers?.[id]);\n if (account === undefined) {\n return new Response(null, {\n status: 302,\n headers: { Location: `/?${AUTH_ERROR_PARAM}=access` },\n });\n }\n current = account;\n return new Response(null, { status: 302, headers: { Location: local } });\n };\n const passkeyOf = ({ id, name, createdAt, lastUsedAt }: StoredPasskey) => ({\n id,\n name,\n authenticator: null,\n createdAt,\n lastUsedAt,\n });\n const passkeyRoutes = async (\n account: Account,\n method: string,\n segments: string[],\n body: () => Promise<Values>,\n ): Promise<Response> => {\n const [, second] = segments;\n if (method === 'GET' && second === undefined) {\n return json(200, { data: account.passkeys.map(passkeyOf) });\n }\n if (method === 'POST' && second === 'options') {\n return json(200, {\n options: {\n challenge: randomToken(),\n rp: { name: 'Panneau' },\n user: {\n id: base64Url(account.id),\n name: account.email,\n displayName: account.name,\n },\n pubKeyCredParams: [\n { type: 'public-key', alg: -7 },\n { type: 'public-key', alg: -257 },\n ],\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'preferred',\n },\n excludeCredentials: account.passkeys.map((passkey) => ({\n type: 'public-key',\n id: passkey.credentialId,\n })),\n timeout: 60000,\n },\n });\n }\n if (method === 'POST' && second === undefined) {\n const { name, credential } = await body();\n if (!isCredential(credential)) {\n return invalid({ credential: ['This passkey could not be added. Try again.'] });\n }\n const passkey: StoredPasskey = {\n id: String(nextPasskey++),\n credentialId: credential.id,\n name: typeof name === 'string' && name.trim() !== '' ? name : 'Passkey',\n createdAt: new Date().toISOString(),\n lastUsedAt: null,\n };\n account.passkeys.push(passkey);\n return json(201, { data: passkeyOf(passkey) });\n }\n const index = account.passkeys.findIndex((passkey) => passkey.id === second);\n if (method === 'DELETE' && segments.length === 2 && index !== -1) {\n account.passkeys.splice(index, 1);\n return json(204, null);\n }\n return problem(404, 'Not found.');\n };\n const refuseUnverified = (account: Account) =>\n settings?.emailVerification === true && !account.emailVerified\n ? problem(403, 'Your email address is not verified.', {\n type: EMAIL_UNVERIFIED_PROBLEM_TYPE,\n })\n : null;\n\n return {\n user: () => (current !== null ? userOf(current) : null),\n account: (segments, method, readBody) => {\n const twoFactor = segments[0] === 'two-factor' && settings?.twoFactor === true;\n const passkeys = segments[0] === 'passkeys' && settings?.passkeys === true;\n if (!twoFactor && !passkeys && settings?.account !== true) {\n return null;\n }\n if (current === null) {\n return Promise.resolve(problem(401, 'Unauthenticated.'));\n }\n if (passkeys) {\n const refusedPasskeys = refuse();\n return refusedPasskeys !== null\n ? Promise.resolve(refusedPasskeys)\n : passkeyRoutes(current, method, segments, readBody);\n }\n const refused = twoFactor ? refuseUnverified(current) : refuse();\n const route = twoFactor\n ? twoFactorRoutes[[method, ...segments.slice(1)].join(' ')]\n : accountRoutes[[method, ...segments].join(' ')];\n if (refused !== null || route === undefined) {\n return Promise.resolve(refused ?? problem(404, 'Not found.'));\n }\n return Promise.resolve(route(current, readBody));\n },\n answer: (segments, method, readBody, url) => {\n if (\n method === 'GET' &&\n segments.length === 3 &&\n segments[0] === 'providers' &&\n segments[2] === 'redirect'\n ) {\n return Promise.resolve(redirectToProvider(segments[1] ?? '', url));\n }\n const route = routes[`${method} ${segments.join('/')}`];\n return route !== undefined\n ? route(readBody)\n : Promise.resolve(problem(404, 'Not found.'));\n },\n refuse,\n };\n\n function refuse(): Response | null {\n if (current === null) {\n return problem(401, 'Unauthenticated.');\n }\n const unverified = refuseUnverified(current);\n if (unverified !== null) {\n return unverified;\n }\n if (\n settings?.twoFactor === true &&\n current.twoFactorRequired &&\n current.twoFactor !== 'enabled'\n ) {\n return problem(403, 'Two-factor authentication is required for this account.', {\n type: TWO_FACTOR_REQUIRED_PROBLEM_TYPE,\n });\n }\n return null;\n }\n}\n"],"mappings":";;;;AAyFA,IAAM,SAAS;AAEf,IAAM,QAAQ;AAEd,SAAS,KAAK,QAAgB,MAAyB;CACnD,OAAO,IAAI,SAAS,WAAW,MAAM,OAAO,KAAK,UAAU,IAAI,GAAG;EAC9D;EACA,SAAS,WAAW,MAAM,CAAC,IAAI,EAAE,gBAAgB,mBAAmB;CACxE,CAAC;AACL;AAEA,SAAS,QAAQ,QAAgB,OAAe,QAA0B,CAAC,GAAa;CACpF,MAAM,OAAgB;EAAE,MAAM;EAAe;EAAO;EAAQ,GAAG;CAAM;CACrE,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;EACtC;EACA,SAAS,EAAE,gBAAgB,qBAAqB;CACpD,CAAC;AACL;AAEA,SAAS,QAAQ,QAA4C;CACzD,OAAO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A2D,EAC3E,MAAM,iCACV,CAAC;EAEL,OAAO;CACX;AACJ"}
@@ -1,6 +1,8 @@
1
1
  import { type ContextValues } from '../context.js';
2
2
  import type { ContextOption, DefinitionInput } from '../schemas/index.js';
3
3
  import type { EmbedValue, Item } from '../schemas/api.js';
4
+ import { type MockAuthOptions } from './auth.js';
5
+ export type { MockAuthOptions, MockMail, MockUser } from './auth.js';
4
6
  type Values = Record<string, unknown>;
5
7
  export interface MockBackendOptions {
6
8
  /** The definition served by `GET /definition`. Its `api.baseUrl` is the prefix of every route. */
@@ -26,6 +28,12 @@ export interface MockBackendOptions {
26
28
  * one is a `403` problem.
27
29
  */
28
30
  context?: MockContextOptions;
31
+ /**
32
+ * Users and a session, for the `panneau` auth mode: the auth routes answer, guests get a `401`
33
+ * on the other routes, and with `auth.emailVerification`, users whose address isn't verified
34
+ * get its `403` problem (decision 0048). Without it, every request is the user's.
35
+ */
36
+ auth?: MockAuthOptions;
29
37
  }
30
38
  /** How the mock backend answers the context of its definition (decision 0045). */
31
39
  export interface MockContextOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mock/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,aAAa,EAAqC,MAAM,YAAY,CAAC;AAInF,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAiB,MAAM,YAAY,CAAC;AAChF,OAAO,KAAK,EAER,UAAU,EAEV,IAAI,EAUP,MAAM,gBAAgB,CAAC;AAKxB,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEtC,MAAM,WAAW,kBAAkB;IAC/B,kGAAkG;IAClG,UAAU,EAAE,eAAe,CAAC;IAC5B,mFAAmF;IACnF,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACjC;;;OAGG;IACH,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,QAAQ,EAAE,M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