diff --git a/lib/Controller/AccountController.php b/lib/Controller/AccountController.php index 57d6d0ebd4..17f330f145 100644 --- a/lib/Controller/AccountController.php +++ b/lib/Controller/AccountController.php @@ -44,7 +44,7 @@ * @psalm-import-type LibresignConfigValueResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignUserConfigValue from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignCreateToSignResponse from \OCA\Libresign\ResponseDefinitions - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignMessageResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignPagination from \OCA\Libresign\ResponseDefinitions */ diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 8f6ddf7a12..b6463cb242 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -336,7 +336,7 @@ public function signatureBackgroundSave(): DataResponse { /** * Get custom background image * - * @return FileDisplayResponse + * @return FileDisplayResponse * * 200: Image returned */ @@ -346,14 +346,17 @@ public function signatureBackgroundSave(): DataResponse { public function signatureBackgroundGet(): FileDisplayResponse { $file = $this->signatureBackgroundService->getImage(); - $response = new FileDisplayResponse($file); + $response = new FileDisplayResponse($file, Http::STATUS_OK, [ + 'Content-Disposition' => 'attachment; filename="background.png"', + 'Content-Type' => 'image/png', + ]); + // The constructor always sets Content-Disposition to "inline" using the + // file name, so the attachment disposition must be set again afterwards. + $response->addHeader('Content-Disposition', 'attachment; filename="background.png"'); $csp = new ContentSecurityPolicy(); $csp->allowInlineStyle(); $response->setContentSecurityPolicy($csp); $response->cacheFor(3600); - $response->addHeader('Content-Type', 'image/png'); - $response->addHeader('Content-Disposition', 'attachment; filename="background.png"'); - $response->addHeader('Content-Type', 'image/png'); return $response; } diff --git a/lib/Controller/CrlController.php b/lib/Controller/CrlController.php index 5be9f3a801..6ac70dbeb9 100644 --- a/lib/Controller/CrlController.php +++ b/lib/Controller/CrlController.php @@ -42,7 +42,7 @@ public function __construct( * @param string $instanceId Instance identifier * @param int $generation Generation identifier * @param string $engineType Engine type identifier - * @return DataDownloadResponse|DataResponse + * @return DataDownloadResponse|DataResponse * * 200: CRL retrieved successfully in DER format * 500: Failed to generate CRL diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 503d4ca5aa..87cfb02b62 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -50,7 +50,7 @@ use Psr\Log\LoggerInterface; /** - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFileResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions @@ -585,7 +585,7 @@ private function getMimeFallbackResponse(string $mimeType): ?\OCP\AppFramework\H * @param string $name The name of file to sign * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param list $files Multiple files to create an envelope (optional, use either file or files) - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK * 422: Failed to save data @@ -630,7 +630,7 @@ public function save( * Multipart clients can send optional expectedFilesCount to reject incomplete batches. * * @param string $uuid The UUID of the envelope - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: Files added successfully * 400: Invalid request diff --git a/lib/Controller/IdDocsController.php b/lib/Controller/IdDocsController.php index 4cea12a79d..4ddc24d686 100644 --- a/lib/Controller/IdDocsController.php +++ b/lib/Controller/IdDocsController.php @@ -29,7 +29,7 @@ use Psr\Log\LoggerInterface; /** - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocs from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocsApprovalListResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocsListResponse from \OCA\Libresign\ResponseDefinitions diff --git a/lib/Controller/IdentifyController.php b/lib/Controller/IdentifyController.php index 5bf8f473ea..7b2509fcf1 100644 --- a/lib/Controller/IdentifyController.php +++ b/lib/Controller/IdentifyController.php @@ -32,6 +32,7 @@ use OCP\IRequest; /** + * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdentifyAccount from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdentifyAccountsResponse from \OCA\Libresign\ResponseDefinitions */ @@ -59,9 +60,10 @@ public function __construct( * @param string $method filter by method (email, account, sms, signal, telegram, whatsapp, whatsappbusiness, xmpp) * @param int $page the number of page to return. Default: 1 * @param int $limit Total of elements to return. Default: 25 - * @return DataResponse + * @return DataResponse|DataResponse * * 200: Certificate saved with success + * 422: User is not allowed to request signatures */ #[NoAdminRequired] #[RequireManager] diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 4d27495eca..f1316e1665 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -212,7 +212,7 @@ public function updateSignatureRequest( * * @param integer $fileId LibreSign file ID * @param integer $signRequestId The sign request id - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK * 401: Failed diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 81fe277cdf..d12fc7a37e 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -657,7 +657,7 @@ * name: string, * status: int, * statusText: string, - * nodeId: int, + * nodeId: ?int, * totalPages?: non-negative-int, * size: non-negative-int, * pdfVersion?: string, @@ -671,7 +671,7 @@ * name: string, * status: 0|1|2|3|4|6, * statusText: string, - * nodeId: non-negative-int, + * nodeId: non-negative-int|null, * nodeType: 'file'|'envelope', * signatureFlow: 'none'|'parallel'|'ordered_numeric', * policySnapshotFrozen?: bool, @@ -778,7 +778,7 @@ * files: list, * filesCount: int<0, max>, * id: int, - * nodeId: int, + * nodeId: ?int, * uuid: string, * name: non-falsy-string, * status: int, @@ -805,7 +805,7 @@ * * Account, elements, and ID document contracts * - * @psalm-type LibresignFile = array{ + * @psalm-type LibresignIdDocFile = array{ * account: array{ * userId: string, * displayName: string, @@ -882,11 +882,11 @@ * } * @psalm-type LibresignIdDocsListResponse = array{ * pagination: LibresignPagination, - * data: list, + * data: list, * } * @psalm-type LibresignIdDocsApprovalListResponse = array{ * pagination: LibresignPagination, - * data: list, + * data: list, * } * @psalm-type LibresignCreateToSignPdfReference = array{ * url: string, diff --git a/openapi-administration.json b/openapi-administration.json index d4ce2ce7d4..f699fd9c72 100644 --- a/openapi-administration.json +++ b/openapi-administration.json @@ -2013,8 +2013,18 @@ "responses": { "200": { "description": "Image returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"background.png\"" + ] + } + } + }, "content": { - "*/*": { + "image/png": { "schema": { "type": "string", "format": "binary" diff --git a/openapi-full.json b/openapi-full.json index c7c79e3450..b374e9aba7 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -809,7 +809,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "uuid": { "type": "string" @@ -1183,126 +1184,6 @@ } } }, - "File": { - "type": "object", - "required": [ - "account", - "file_type", - "created_at", - "file" - ], - "properties": { - "account": { - "type": "object", - "required": [ - "userId", - "displayName" - ], - "properties": { - "userId": { - "type": "string" - }, - "displayName": { - "type": "string" - } - } - }, - "file_type": { - "type": "object", - "required": [ - "type", - "name", - "description" - ], - "properties": { - "type": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string", - "nullable": true - } - } - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "name", - "status", - "statusText", - "created_at", - "file", - "uuid", - "signers" - ], - "properties": { - "name": { - "type": "string" - }, - "status": { - "type": "integer", - "format": "int64", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 6 - ] - }, - "statusText": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "type", - "nodeId", - "signedNodeId", - "url" - ], - "properties": { - "type": { - "type": "string" - }, - "nodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "signedNodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "url": { - "type": "string" - } - } - }, - "uuid": { - "type": "string" - }, - "signers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SignerDetail" - } - } - } - } - } - }, "FileElementIdResponse": { "type": "object", "required": [ @@ -1780,6 +1661,126 @@ } } }, + "IdDocFile": { + "type": "object", + "required": [ + "account", + "file_type", + "created_at", + "file" + ], + "properties": { + "account": { + "type": "object", + "required": [ + "userId", + "displayName" + ], + "properties": { + "userId": { + "type": "string" + }, + "displayName": { + "type": "string" + } + } + }, + "file_type": { + "type": "object", + "required": [ + "type", + "name", + "description" + ], + "properties": { + "type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + } + } + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "name", + "status", + "statusText", + "created_at", + "file", + "uuid", + "signers" + ], + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "integer", + "format": "int64", + "enum": [ + 0, + 1, + 2, + 3, + 4, + 6 + ] + }, + "statusText": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "type", + "nodeId", + "signedNodeId", + "url" + ], + "properties": { + "type": { + "type": "string" + }, + "nodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "signedNodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "url": { + "type": "string" + } + } + }, + "uuid": { + "type": "string" + }, + "signers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignerDetail" + } + } + } + } + } + }, "IdDocs": { "type": "object", "required": [ @@ -1810,7 +1811,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -1828,7 +1829,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -3902,7 +3903,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "totalPages": { "type": "integer", @@ -3998,6 +4000,7 @@ "nodeId": { "type": "integer", "format": "int64", + "nullable": true, "minimum": 0 }, "nodeType": { @@ -4282,7 +4285,7 @@ "200": { "description": "CRL retrieved successfully in DER format", "content": { - "*/*": { + "application/pkix-crl": { "schema": { "type": "string", "format": "binary" @@ -6881,7 +6884,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -7082,7 +7092,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -9178,6 +9195,36 @@ } } }, + "422": { + "description": "User is not allowed to request signatures", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -12807,7 +12854,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/ActionErrorResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -16148,8 +16202,18 @@ "responses": { "200": { "description": "Image returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"background.png\"" + ] + } + } + }, "content": { - "*/*": { + "image/png": { "schema": { "type": "string", "format": "binary" diff --git a/openapi.json b/openapi.json index 6b4e635e67..288494d135 100644 --- a/openapi.json +++ b/openapi.json @@ -536,7 +536,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "uuid": { "type": "string" @@ -856,126 +857,6 @@ } } }, - "File": { - "type": "object", - "required": [ - "account", - "file_type", - "created_at", - "file" - ], - "properties": { - "account": { - "type": "object", - "required": [ - "userId", - "displayName" - ], - "properties": { - "userId": { - "type": "string" - }, - "displayName": { - "type": "string" - } - } - }, - "file_type": { - "type": "object", - "required": [ - "type", - "name", - "description" - ], - "properties": { - "type": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string", - "nullable": true - } - } - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "name", - "status", - "statusText", - "created_at", - "file", - "uuid", - "signers" - ], - "properties": { - "name": { - "type": "string" - }, - "status": { - "type": "integer", - "format": "int64", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 6 - ] - }, - "statusText": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "type", - "nodeId", - "signedNodeId", - "url" - ], - "properties": { - "type": { - "type": "string" - }, - "nodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "signedNodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "url": { - "type": "string" - } - } - }, - "uuid": { - "type": "string" - }, - "signers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SignerDetail" - } - } - } - } - } - }, "FileElementIdResponse": { "type": "object", "required": [ @@ -1405,6 +1286,126 @@ } ] }, + "IdDocFile": { + "type": "object", + "required": [ + "account", + "file_type", + "created_at", + "file" + ], + "properties": { + "account": { + "type": "object", + "required": [ + "userId", + "displayName" + ], + "properties": { + "userId": { + "type": "string" + }, + "displayName": { + "type": "string" + } + } + }, + "file_type": { + "type": "object", + "required": [ + "type", + "name", + "description" + ], + "properties": { + "type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + } + } + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "name", + "status", + "statusText", + "created_at", + "file", + "uuid", + "signers" + ], + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "integer", + "format": "int64", + "enum": [ + 0, + 1, + 2, + 3, + 4, + 6 + ] + }, + "statusText": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "type", + "nodeId", + "signedNodeId", + "url" + ], + "properties": { + "type": { + "type": "string" + }, + "nodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "signedNodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "url": { + "type": "string" + } + } + }, + "uuid": { + "type": "string" + }, + "signers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignerDetail" + } + } + } + } + } + }, "IdDocs": { "type": "object", "required": [ @@ -1435,7 +1436,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -1453,7 +1454,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -3360,7 +3361,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "totalPages": { "type": "integer", @@ -3456,6 +3458,7 @@ "nodeId": { "type": "integer", "format": "int64", + "nullable": true, "minimum": 0 }, "nodeType": { @@ -3740,7 +3743,7 @@ "200": { "description": "CRL retrieved successfully in DER format", "content": { - "*/*": { + "application/pkix-crl": { "schema": { "type": "string", "format": "binary" @@ -6339,7 +6342,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -6540,7 +6550,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -8441,6 +8458,36 @@ } } }, + "422": { + "description": "User is not allowed to request signatures", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -12070,7 +12117,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/ActionErrorResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } diff --git a/src/services/validationDocument.ts b/src/services/validationDocument.ts index 7af705ae58..af2b19a1da 100644 --- a/src/services/validationDocument.ts +++ b/src/services/validationDocument.ts @@ -476,7 +476,7 @@ export function toValidationDocument(data: unknown): ValidationDocumentState | n if (files.some(file => file === null)) { return null } - const normalizedFiles = files.filter((file): file is ValidatedChildFileRecord => file !== null) + const normalizedFiles = files.filter((file): file is NonNullable => file !== null) const metadata = isValidationMetadata(data.metadata) ? data.metadata diff --git a/src/tests/views/Documents/IdDocsValidation.spec.ts b/src/tests/views/Documents/IdDocsValidation.spec.ts index 639e6386cc..696022d0c9 100644 --- a/src/tests/views/Documents/IdDocsValidation.spec.ts +++ b/src/tests/views/Documents/IdDocsValidation.spec.ts @@ -110,7 +110,7 @@ vi.mock('@nextcloud/vue/components/NcIconSvgWrapper', () => ({ })) describe('IdDocsValidation.vue', () => { - type IdDocEntry = components['schemas']['File'] + type IdDocEntry = components['schemas']['IdDocFile'] const signedDoc: IdDocEntry = { account: { diff --git a/src/types/openapi/openapi-administration.ts b/src/types/openapi/openapi-administration.ts index 6a280db00c..29e2778155 100644 --- a/src/types/openapi/openapi-administration.ts +++ b/src/types/openapi/openapi-administration.ts @@ -984,10 +984,11 @@ export interface operations { /** @description Image returned */ 200: { headers: { + "Content-Disposition"?: "attachment; filename=\"background.png\""; [name: string]: unknown; }; content: { - "*/*": string; + "image/png": string; }; }; /** @description Current user is not logged in */ diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index a37db13462..5308b2d464 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -1571,7 +1571,7 @@ export type components = { /** Format: int64 */ id: number; /** Format: int64 */ - nodeId: number; + nodeId: number | null; uuid: string; name: string; /** Format: int64 */ @@ -1673,38 +1673,6 @@ export type components = { status: "failure"; message: string; }; - File: { - account: { - userId: string; - displayName: string; - }; - file_type: { - type: string; - name: string; - description: string | null; - }; - created_at: string; - file: { - name: string; - /** - * Format: int64 - * @enum {integer} - */ - status: 0 | 1 | 2 | 3 | 4 | 6; - statusText: string; - created_at: string; - file: { - type: string; - /** Format: int64 */ - nodeId: number; - /** Format: int64 */ - signedNodeId: number; - url: string; - }; - uuid: string; - signers: components["schemas"]["SignerDetail"][]; - }; - }; FileElementIdResponse: { /** Format: int64 */ fileElementId: number; @@ -1836,6 +1804,38 @@ export type components = { HasRootCertResponse: { hasRootCert: boolean; }; + IdDocFile: { + account: { + userId: string; + displayName: string; + }; + file_type: { + type: string; + name: string; + description: string | null; + }; + created_at: string; + file: { + name: string; + /** + * Format: int64 + * @enum {integer} + */ + status: 0 | 1 | 2 | 3 | 4 | 6; + statusText: string; + created_at: string; + file: { + type: string; + /** Format: int64 */ + nodeId: number; + /** Format: int64 */ + signedNodeId: number; + url: string; + }; + uuid: string; + signers: components["schemas"]["SignerDetail"][]; + }; + }; IdDocs: { file: components["schemas"]["NewFile"]; name?: string; @@ -1843,11 +1843,11 @@ export type components = { }; IdDocsApprovalListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsUploadErrorResponse: { /** Format: int64 */ @@ -2424,7 +2424,7 @@ export type components = { status: number; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** Format: int64 */ totalPages?: number; /** Format: int64 */ @@ -2449,7 +2449,7 @@ export type components = { status: 0 | 1 | 2 | 3 | 4 | 6; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** @enum {string} */ nodeType: "file" | "envelope"; /** @enum {string} */ @@ -2565,7 +2565,7 @@ export interface operations { [name: string]: unknown; }; content: { - "*/*": string; + "application/pkix-crl": string; }; }; /** @description Failed to generate CRL */ @@ -3668,7 +3668,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -3756,7 +3756,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -4659,6 +4659,20 @@ export interface operations { }; }; }; + /** @description User is not allowed to request signatures */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "notify-signers": { @@ -6214,7 +6228,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -7606,10 +7620,11 @@ export interface operations { /** @description Image returned */ 200: { headers: { + "Content-Disposition"?: "attachment; filename=\"background.png\""; [name: string]: unknown; }; content: { - "*/*": string; + "image/png": string; }; }; /** @description Current user is not logged in */ diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 9fd7aa8f47..3226ee12da 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1171,7 +1171,7 @@ export type components = { /** Format: int64 */ id: number; /** Format: int64 */ - nodeId: number; + nodeId: number | null; uuid: string; name: string; /** Format: int64 */ @@ -1259,38 +1259,6 @@ export type components = { ErrorsResponse: { errors: components["schemas"]["ErrorItem"][]; }; - File: { - account: { - userId: string; - displayName: string; - }; - file_type: { - type: string; - name: string; - description: string | null; - }; - created_at: string; - file: { - name: string; - /** - * Format: int64 - * @enum {integer} - */ - status: 0 | 1 | 2 | 3 | 4 | 6; - statusText: string; - created_at: string; - file: { - type: string; - /** Format: int64 */ - nodeId: number; - /** Format: int64 */ - signedNodeId: number; - url: string; - }; - uuid: string; - signers: components["schemas"]["SignerDetail"][]; - }; - }; FileElementIdResponse: { /** Format: int64 */ fileElementId: number; @@ -1409,6 +1377,38 @@ export type components = { deletableByCurrentActor: boolean; }; GroupPolicyWriteResponse: components["schemas"]["MessageResponse"] & components["schemas"]["GroupPolicyResponse"]; + IdDocFile: { + account: { + userId: string; + displayName: string; + }; + file_type: { + type: string; + name: string; + description: string | null; + }; + created_at: string; + file: { + name: string; + /** + * Format: int64 + * @enum {integer} + */ + status: 0 | 1 | 2 | 3 | 4 | 6; + statusText: string; + created_at: string; + file: { + type: string; + /** Format: int64 */ + nodeId: number; + /** Format: int64 */ + signedNodeId: number; + url: string; + }; + uuid: string; + signers: components["schemas"]["SignerDetail"][]; + }; + }; IdDocs: { file: components["schemas"]["NewFile"]; name?: string; @@ -1416,11 +1416,11 @@ export type components = { }; IdDocsApprovalListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsUploadErrorResponse: { /** Format: int64 */ @@ -1956,7 +1956,7 @@ export type components = { status: number; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** Format: int64 */ totalPages?: number; /** Format: int64 */ @@ -1981,7 +1981,7 @@ export type components = { status: 0 | 1 | 2 | 3 | 4 | 6; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** @enum {string} */ nodeType: "file" | "envelope"; /** @enum {string} */ @@ -2097,7 +2097,7 @@ export interface operations { [name: string]: unknown; }; content: { - "*/*": string; + "application/pkix-crl": string; }; }; /** @description Failed to generate CRL */ @@ -3200,7 +3200,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -3288,7 +3288,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -4097,6 +4097,20 @@ export interface operations { }; }; }; + /** @description User is not allowed to request signatures */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "notify-signers": { @@ -5652,7 +5666,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; diff --git a/src/views/Documents/IdDocsValidation.vue b/src/views/Documents/IdDocsValidation.vue index 9e561d64e1..7da52e2bbf 100644 --- a/src/views/Documents/IdDocsValidation.vue +++ b/src/views/Documents/IdDocsValidation.vue @@ -221,7 +221,7 @@ type StatusOption = { } type PersistedStatusFilter = StatusOption['value'] | null -type IdDocEntry = components['schemas']['File'] +type IdDocEntry = components['schemas']['IdDocFile'] type IdDocsListQuery = NonNullable type IdDocsListSuccess = operations['id_docs-list-to-approval']['responses'][200]['content']['application/json'] type IdDocsListError = operations['id_docs-list-to-approval']['responses'][404]['content']['application/json'] diff --git a/tests/php/Unit/Controller/AdminControllerTest.php b/tests/php/Unit/Controller/AdminControllerTest.php index 765a547bbe..c807026598 100644 --- a/tests/php/Unit/Controller/AdminControllerTest.php +++ b/tests/php/Unit/Controller/AdminControllerTest.php @@ -20,6 +20,7 @@ use OCA\Libresign\Service\SetupCheckResultService; use OCA\Libresign\Service\SignatureBackgroundService; use OCP\AppFramework\Http; +use OCP\Files\SimpleFS\ISimpleFile; use OCP\IAppConfig; use OCP\IEventSource; use OCP\IEventSourceFactory; @@ -32,6 +33,7 @@ class AdminControllerTest extends TestCase { private AdminController $controller; private ActiveSigningsService&MockObject $activeSigningsService; + private SignatureBackgroundService&MockObject $signatureBackgroundService; private IRequest&MockObject $request; protected function setUp(): void { @@ -42,7 +44,7 @@ protected function setUp(): void { $eventSourceFactory = $this->createMock(IEventSourceFactory::class); $l10n = $this->createMock(IL10N::class); $session = $this->createMock(ISession::class); - $signatureBackgroundService = $this->createMock(SignatureBackgroundService::class); + $this->signatureBackgroundService = $this->createMock(SignatureBackgroundService::class); $certificatePolicyService = $this->createMock(CertificatePolicyService::class); $validateService = $this->createMock(ValidateService::class); $identifyMethodService = $this->createMock(IdentifyMethodService::class); @@ -64,7 +66,7 @@ protected function setUp(): void { $eventSourceFactory, $l10n, $session, - $signatureBackgroundService, + $this->signatureBackgroundService, $certificatePolicyService, $validateService, $identifyMethodService, @@ -114,4 +116,18 @@ public function testGetActiveSigningsReturnsErrorResponseWhenServiceFails(): voi $this->assertSame(Http::STATUS_INTERNAL_SERVER_ERROR, $response->getStatus()); $this->assertSame(['error' => 'boom'], $response->getData()); } + + public function testSignatureBackgroundGetSendsTheDocumentedHeaders(): void { + $this->signatureBackgroundService + ->expects($this->once()) + ->method('getImage') + ->willReturn($this->createMock(ISimpleFile::class)); + + $response = $this->controller->signatureBackgroundGet(); + + $this->assertSame(Http::STATUS_OK, $response->getStatus()); + $headers = $response->getHeaders(); + $this->assertSame('image/png', $headers['Content-Type']); + $this->assertSame('attachment; filename="background.png"', $headers['Content-Disposition']); + } } diff --git a/tests/php/openapi/OpenApiBinaryMediaTypesTest.php b/tests/php/openapi/OpenApiBinaryMediaTypesTest.php new file mode 100644 index 0000000000..82b5d29054 --- /dev/null +++ b/tests/php/openapi/OpenApiBinaryMediaTypesTest.php @@ -0,0 +1,46 @@ + ['openapi-full.json', 'crl-get-revocation-list', 'application/pkix-crl'], + 'CRL download in the default scope' => ['openapi.json', 'crl-get-revocation-list', 'application/pkix-crl'], + 'admin background image' => ['openapi-full.json', 'admin-signature-background-get', 'image/png'], + 'certificate policy PDF' => ['openapi-full.json', 'certificate_policy-get-certificate-policy', 'application/pdf'], + ]; + } + + #[DataProvider('mediaTypeProvider')] + public function testBinaryResponseDeclaresItsFixedMediaType(string $file, string $operationId, string $mediaType): void { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + $spec = json_decode($source, true, 512, JSON_THROW_ON_ERROR); + + $content = null; + foreach ($spec['paths'] as $methods) { + foreach ($methods as $operation) { + if (is_array($operation) && ($operation['operationId'] ?? null) === $operationId) { + $content = $operation['responses']['200']['content'] ?? null; + } + } + } + + // Thumbnails and signature element previews keep */* on purpose: their + // media type depends on the previewed file. + self::assertIsArray($content, $operationId); + self::assertSame([$mediaType], array_keys($content), $operationId); + self::assertSame(['type' => 'string', 'format' => 'binary'], $content[$mediaType]['schema'], $operationId); + } +} diff --git a/tests/php/openapi/OpenApiErrorBodyContractTest.php b/tests/php/openapi/OpenApiErrorBodyContractTest.php new file mode 100644 index 0000000000..638a44dfaa --- /dev/null +++ b/tests/php/openapi/OpenApiErrorBodyContractTest.php @@ -0,0 +1,128 @@ + ['openapi.json'], + 'full scope' => ['openapi-full.json'], + ]; + } + + #[DataProvider('specificationProvider')] + public function testRequestSignatureDocumentsBothBodiesAt422(string $file): void { + $paths = $this->load($file)['paths']; + + foreach (['post', 'patch'] as $method) { + $this->assertBothBodies($paths[self::BASE . 'request-signature'][$method], $method); + } + } + + #[DataProvider('specificationProvider')] + public function testRemoveSignerDocumentsBothBodiesAt422(string $file): void { + // The catch block answers {message} with 422 when the exception code is 422. + $this->assertBothBodies( + $this->load($file)['paths'][self::BASE . 'sign/file_id/{fileId}/{signRequestId}']['delete'], + 'removeSigner', + ); + } + + #[DataProvider('specificationProvider')] + public function testDeleteOperationsDocumentTheMiddleware422(string $file): void { + // Their catch blocks answer 401, but the middleware rejects a user + // without permission with 422 before the method runs. + $paths = $this->load($file)['paths']; + + foreach (['file/file_id/{fileId}', 'sign/file_id/{fileId}'] as $path) { + self::assertSame( + self::ACTION_ERROR, + $this->errorData($paths[self::BASE . $path]['delete'], '422')['$ref'] ?? null, + $path, + ); + } + } + + #[DataProvider('specificationProvider')] + public function testFileUploadsDocumentBothBodiesAt422(string $file): void { + // The middleware rejects a user without permission before the method; the + // catch block answers {message}. + $paths = $this->load($file)['paths']; + + $this->assertBothBodies($paths[self::BASE . 'file']['post'], 'file-save'); + $this->assertBothBodies($paths[self::BASE . 'file/{uuid}/add-file']['post'], 'file-add-file-to-envelope'); + } + + #[DataProvider('specificationProvider')] + public function testIdentifySearchDocumentsTheMiddleware422(string $file): void { + // The method has no try block: only the middleware can answer 422. + $operation = $this->load($file)['paths'][self::BASE . 'identify-account/search']['get']; + + self::assertSame(self::ACTION_ERROR, $this->errorData($operation, '422')['$ref'] ?? null); + } + + #[DataProvider('specificationProvider')] + public function testNotifyKeepsBothRealBodiesAt422(string $file): void { + // canRequestSign() throws an action/errors body, other validations a message body. + $paths = $this->load($file)['paths']; + + foreach (['notify/signers', 'notify/signer'] as $path) { + $this->assertBothBodies($paths[self::BASE . $path]['post'], $path); + } + } + + #[DataProvider('specificationProvider')] + public function testFileSchemasWithTheEntityNodeIdAreNullable(string $file): void { + // libresign_file.node_id is nullable (BeforeNodeDeletedListener clears it + // when the original file is deleted) and the value is copied as is. + $schemas = $this->load($file)['components']['schemas']; + + foreach (['DetailedFile', 'ValidatedFile', 'ValidatedChildFile'] as $schema) { + self::assertTrue($schemas[$schema]['properties']['nodeId']['nullable'] ?? false, $schema); + } + } + + private function assertBothBodies(array $operation, string $label): void { + $data = $this->errorData($operation, '422'); + + self::assertEqualsCanonicalizing( + [self::MESSAGE, self::ACTION_ERROR], + array_column($data['anyOf'] ?? [], '$ref'), + $label, + ); + } + + private function errorData(array $operation, string $status): array { + return $operation['responses'][$status]['content']['application/json']['schema']['properties']['ocs']['properties']['data'] ?? []; + } + + private function load(string $file): array { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + + return json_decode($source, true, 512, JSON_THROW_ON_ERROR); + } +} diff --git a/tests/php/openapi/OpenApiIdDocSchemaTest.php b/tests/php/openapi/OpenApiIdDocSchemaTest.php new file mode 100644 index 0000000000..b6562e9ce1 --- /dev/null +++ b/tests/php/openapi/OpenApiIdDocSchemaTest.php @@ -0,0 +1,42 @@ + ['openapi.json'], + 'full scope' => ['openapi-full.json'], + ]; + } + + #[DataProvider('specificationProvider')] + public function testIdDocumentRecordHasADomainSpecificSchemaName(string $file): void { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + + $schemas = json_decode($source, true, 512, JSON_THROW_ON_ERROR)['components']['schemas']; + + // A schema named File collides with the global File type of TypeScript + // and is too generic: other schemas describe different file records. + self::assertArrayNotHasKey('File', $schemas); + self::assertArrayHasKey('IdDocFile', $schemas); + foreach (['IdDocsListResponse', 'IdDocsApprovalListResponse'] as $response) { + self::assertSame( + '#/components/schemas/IdDocFile', + $schemas[$response]['properties']['data']['items']['$ref'] ?? null, + $response, + ); + } + } +} diff --git a/tests/php/openapi/phpunit.xml b/tests/php/openapi/phpunit.xml index c9ec9062ea..bc3ff0aa7c 100644 --- a/tests/php/openapi/phpunit.xml +++ b/tests/php/openapi/phpunit.xml @@ -13,8 +13,11 @@ colors="true"> + OpenApiBinaryMediaTypesTest.php + OpenApiErrorBodyContractTest.php OpenApiFunctionalTagsTest.php OpenApiGenerationTest.php + OpenApiIdDocSchemaTest.php OpenApiPolicyNumberUnionTest.php OpenApiRequestHeadersTest.php OpenApiSigningRequestContractsTest.php diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index 98b66ff0ef..350e536b42 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -18,12 +18,16 @@ npm test --prefix tests/sdk-generation npm run test:anyof --prefix tests/sdk-generation ``` -The last command **passes while the known defect exists**: it assigns an invalid -array to the generated `EffectivePolicyValue` without suppressing diagnostics. -A missing client fails with TS2307; a corrected type that rejects arrays fails -with TS2322 and requires reevaluating the No-Go report. `npm test` checks -transport, generation cleanup and live-check error handling, and writes -the generated operation inventory to `build/sdk-generation/inventory.md`. +`test:anyof` has two parts. `anyof-defect.ts` is a regression guard: the generated +`EffectivePolicyValue` must keep rejecting arrays and `undefined`. `union-defects.ts` +**passes while known defects exist**: a `@ts-expect-error` marks a valid contract +value that the generated model rejects, and a plain assignment marks an invalid +value that it accepts. When a defect is fixed, compilation fails: TS2578 for an +unused `@ts-expect-error`, TS2322 for an assignment that is now rejected. The +report must then be reevaluated. `npm test` checks +transport, generation cleanup, live-check error handling and real `@nextcloud/axios` +injection under jsdom, and writes the generated operation inventory to +`build/sdk-generation/inventory.md`. Compare that inventory with the checked-in evaluation snapshot when changing the specification. This does not prove every operation's runtime serialization. @@ -38,7 +42,7 @@ See [REPORT.md](REPORT.md) and [inventory.md](inventory.md) for results. ## Normalized-input experiment -This separate experiment changes all 22 `anyOf` keywords to `oneOf` in a +This separate experiment changes all 17 `anyOf` keywords to `oneOf` in a **disposable generator input**, never in the committed specification: ```sh @@ -47,24 +51,30 @@ tests/sdk-generation/generate.sh build/sdk-generation/normalized/typescript buil npm run test:normalized --prefix tests/sdk-generation ``` -The positive/negative type checks pass, including rejection of the invalid -policy array and invalid scalar object unions. They also explicitly record that -schema-valid `null` is still rejected. This is partial mitigation, not a Go. -`oneOf` and `anyOf` are not equivalent validation contracts: `integer` and -`number` overlap. The transformed file must never replace the source contract. +The positive/negative type checks pass, including the object unions that the +unmodified output merges incorrectly. They also record that `null` is still +rejected by the standalone union; how `nullable` should work on a composed schema +is itself unresolved (see UPSTREAM-NOTES.md E4). This is partial mitigation, not +a Go. +`oneOf` and `anyOf` are not equivalent validation contracts: overlapping object +branches would violate `oneOf`. The transformed file must never replace the +source contract. -## Real Nextcloud Axios import probe +## Real Nextcloud Axios ```sh +npm test --prefix tests/sdk-generation # includes nextcloud-axios.test.ts npm run test:nextcloud --prefix tests/sdk-generation ``` -With the locked `@nextcloud/axios` 2.6.0 on Node 24.22.2 this **fails** with -`ReferenceError: window is not defined` in `@nextcloud/browser-storage`, imported -by `@nextcloud/auth`. This invokes the real ESM package without browser shims. -Real Nextcloud instance injection therefore remains unverified; the deterministic -transport tests use ordinary Axios. Browser integration and CSRF retry behavior -need a separate browser environment. +`nextcloud-axios.test.ts` installs a jsdom window, injects the real locked +`@nextcloud/axios` instance into a generated API class and checks its default +`requesttoken`/`X-Requested-With` headers, the `OCS-APIRequest` header and the +package's own 412 CSRF retry. Only the network adapter and `fetch` are +replaced. `test:nextcloud` is the Node-only probe without browser globals; it +**fails** with `ReferenceError: window is not defined`, recording that the +package needs a browser-like environment. A real browser and Nextcloud server +remain unverified. ## Optional live Nextcloud check diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index 5afd01fba7..1494ec8d0f 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -5,134 +5,249 @@ # Compatibility evaluation -## Decision: No-Go for unmodified input - -OpenAPI Generator 7.27.0's `typescript-axios` output is not a sufficiently -faithful SDK foundation: `EffectivePolicyValue` is an empty interface and -accepts invalid arrays. Version 7.15.0 has the same defect. The separate -normalized-input experiment partially improves unions; it does not change -this decision or approve any source contract change. Multipart is tracked -separately in #9435. +## Decision: still No-Go for unmodified input, with a different blocker + +Re-run against `main` at `40ee2280737e54ebf798bbc1f77bf4272cbe9320`. The defect +that justified the earlier No-Go is fixed: `EffectivePolicyValue` is now +`boolean | number | string | { [key: string]: object }`, rejects arrays and +keeps `| null` at the properties that reference it (disjoint `oneOf` contract, +#9494). Generation, strict compilation, inventory, transport and real +`@nextcloud/axios` injection all pass. + +The decision remains No-Go for unmodified input because three generated models +and seven merged 422 error-body models of the remaining 17 `anyOf` constructs +are still incorrect (the other seven, envelope 401/403 bodies, read the contract +faithfully; see [Remaining model defects](#remaining-model-defects)), and multipart +bodies are still absent from the contract. Every blocker left is on the +extractor/generator side or needs a maintainer decision about the contract +shape; see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). This evaluation selects no +option and changes no extractor, generator, CI job or permanent SDK. Its only +LibreSign changes are the annotation, committed OpenAPI and generated type +changes listed under [Input and toolchain](#input-and-toolchain), the frontend +type alias for the renamed schema and a type predicate in +`src/services/validationDocument.ts`; none changes runtime behavior. ## Input and toolchain -- Application base: `9aebe13938369e70344a4fb1e16fc331387427ea` (upstream main). -- `openapi-full.json` SHA-256: - `2501bc11fcee0545dfb703a28d93018a80e62f6e14ba81bae549d1b130de9243`. +- Application base: `40ee2280737e54ebf798bbc1f77bf4272cbe9320` (`main`), plus + three LibreSign changes described below: the ID document schema `File` renamed + to `IdDocFile`, literal media types for the CRL and the admin background, and + annotations aligned with what the code returns (see + [Annotations aligned with the code](#annotations-aligned-with-the-code)). +- `openapi-full.json` SHA-256 with those changes: `b586418da879f0650b4e9ee4f9b0553c8cb3b72472c80cd998cf395491855387` + (`64c52fa2ba243af292eba30055982954bfd8c19136567e50e28c4abcffcc9405` on `main`). +- Extractor used to produce the contract: `nextcloud/openapi-extractor` 1.9.1. - Generator: `openapitools/openapi-generator-cli` 7.27.0 at `sha256:949efd0d5cf3c093ef169887b2ebe0879ee2e8074b6476264232ce4fd8ef46d0`; `typescript-axios`, `useSingleRequestParameter=true`. -- Previous comparison: 7.15.0 at - `sha256:509f01c3c7eee9d1ad286506a7b6aa4624a95b410be9a238a306d209e900621f`. -- TypeScript 5.8.3, Axios 1.20.0, `@nextcloud/axios` 2.6.0, tsx 4.19.4; - Node 24.22.2, npm 11.19.1. npm dependencies/transitives are locked. - Axios matches the application's locked version and satisfies Nextcloud Axios. -- All deterministic README commands ran with fresh generated directories. - Validation succeeded with unused `Capabilities` and `PublicCapabilities` - warnings. Two generations had an empty recursive diff including metadata. +- TypeScript 5.8.3, Axios 1.20.0, `@nextcloud/axios` 2.6.0, jsdom 26.1.0 + (test only), tsx 4.19.4; Node 24.22.3, npm 11.19.1 (an independent re-run on + Node 26.0.0 also passed). Dependencies and + transitives are locked. +- Validation succeeds with the unused `Capabilities`/`PublicCapabilities` + warnings. Two generations have an empty recursive diff including metadata. No generated source was edited. -- Warm timings: setup 1.05 s; validation/generation 4.91 s (repeat 5.79 s); - strict compilation 2.09 s; transport/inventory 1.06 s; normalized - validation/generation 4.71 s and type checks 1.36 s. These are single-machine - observations with cached images, not cold CI benchmarks. No CI job is added. +- Warm timings on one machine with cached images (not a cold CI benchmark): + setup about 1 s; validation + generation 4.6 s (repeat 4.1 s); strict + compilation 1.4 s; `npm test` 2.3 s; union checks 0.9 s. No CI job is added. -## Unmodified input results +## Results for the unmodified input The [inventory](inventory.md) covers 90 operations (69 default, 21 -administration), rather than the issue's original 88: 90 matched, zero inventory -errors, ten functional classes. The checked-in snapshot matches the new output. -The check matches method/path, generated documentation and public TypeScript +administration) across the ten functional tags: 90 matched, zero inventory +errors. Tag counts: appearance 17, certificates 12, documents 6, identity 14, +notifications 4, policies 17, requests 5, signing 8, system 3, verification 4. +This differs from the 88 operations and per-tag counts of the original issue +(appearance +1, notifications +1) because operations were added after it was +written. The check matches method/path, generated documentation and public class methods; it does not exhaustively validate signatures or serialization. -Generated Markdown examples still use positional arguments despite the chosen -single-request-parameter configuration; use actual class signatures. +Generated Markdown examples still use positional arguments despite +`useSingleRequestParameter=true`; use the actual class signatures. -Strict compilation with `skipLibCheck` passes. `types.ts` tests number/string -`NewFile.nodeId` (rejecting boolean), inherited/local `SignerDetail` fields, -nullable/optional fields and enums. `test:anyof` exits 0 because the generated -empty interface accepts an invalid policy array. This is a passing reproduction -of a failed SDK acceptance criterion, so the decision remains No-Go. The fixture -has no error suppression: missing generated output fails with TS2307; a type -that rejects arrays fails with TS2322, requiring the report to be reevaluated. +Strict compilation with `skipLibCheck` passes. `types.ts` checks number/string +`NewFile.nodeId` (rejecting boolean), inherited and local `SignerDetail` +fields, nullable/optional fields and enums. `RequestSignatureRequest` no longer +has `callback` (removed by #9505), so the nullable check uses `status`. +`anyof-defect.ts` is now a regression guard: arrays and `undefined` are +rejected by `EffectivePolicyValue`, and `effectiveValue: null` is accepted. The controlled Axios adapter tests generated calls for account GET and typed OCS envelope, encoded policy path and simulated HTTP 403, signature-request -JSON POST, and non-OCS PDF with explicit `responseType: arraybuffer`. Basic-only -and bearer-only configurations are independent, with assertions that the other -credential mechanism is absent. Both root and subdirectory paths pass. -An instance at `https://instance.test/installed` overrides configuration -`https://example.test/nextcloud` for both OCS and PDF URLs, proving precedence -with different values. - -The real locked `@nextcloud/axios` ESM import probe exits 1 in Node with -`ReferenceError: window is not defined`: `@nextcloud/auth` imports -`@nextcloud/browser-storage`, whose `StorageBuilder.build` accesses browser -storage during initialization. No browser globals are mocked. Real Nextcloud -Axios injection and its CSRF/session interceptors remain unverified; the -successful transport tests use ordinary Axios. +JSON POST, signing, appearance elements and non-OCS PDF with explicit +`responseType: arraybuffer`. Basic-only and bearer-only configurations are +independent. Root and subdirectory paths pass, and an instance base URL +overrides the configuration base path for OCS and PDF URLs. + +### Real `@nextcloud/axios` + +The Node-only import probe (`npm run test:nextcloud`) still fails with +`ReferenceError: window is not defined`: this is expected for a browser +package and is kept as the record of that requirement. A new test, +`nextcloud-axios.test.ts`, installs a jsdom window and injects the real locked +`@nextcloud/axios` instance into a generated `IdentityApi`. Only the network +adapter and `fetch` are replaced. It verifies the package defaults reach the +request (`requesttoken`, `X-Requested-With`), the generated `OCS-APIRequest` +header, the absolute subdirectory URL, and the package's own 412 "CSRF check +failed" retry: the retried request carries the refreshed token and +`/nextcloud/index.php/csrftoken` is the only token URL fetched. A real browser +and a real Nextcloud server remain unverified (real XHR adapter, cookies, +maintenance-mode and not-logged-in interceptors). + +### Remaining model defects + +`union-defects.ts` reproduces these defects with assertions that compile only +while the defect exists (`@ts-expect-error` for a valid value that is rejected, +a plain assignment for an invalid value that is accepted). Revisit the report as +soon as one of them fails (TS2578 or TS2322): + +| Schema | Contract | Generated | Effect | +| --- | --- | --- | --- | +| `FileListResponse.data[]` items | `anyOf` `FileSummary`, `DetailedFile` | one merged interface requiring `files`, `size` and `visibleElements`; `nodeId` narrowed to `number`; `signers` typed as `SignerDetail` | a valid `FileSummary` is not assignable | +| `FileRuntimeMetadata` | `anyOf` `ValidateMetadata`, `{ [key]: DynamicMetadataValue }` | only the `ValidateMetadata` fields, with `extension` and `p` required | a valid dynamic metadata object is rejected | +| `RequestPolicyOverrides` values | `anyOf` `EffectivePolicyValue`, array of it | empty interface `RequestPolicyOverridesValue` | accepts any non-null value | + +The other 14 `anyOf` occurrences are in 4xx bodies. Seven (the 422 responses of +`notify-signers`, `notify-signer`, `request-signature`, +`update-signature-request`, `removeSigner`, `file-save` and +`file-add-file-to-envelope`) are real unions of an +`{action, errors}` body (`ActionErrorResponse`, a `LibresignException` with a +JSON message) and a `{message}` body (`MessageResponse`). For +`request-signature` (POST and PATCH), `removeSigner`, `file-save` and +`file-add-file-to-envelope` the first comes from `#[RequireManager]`, which runs +`canRequestSign()` before the method and is serialized by the middleware's +`afterException`; the second is a `DataResponse` built by the method's own +`catch`. The two notify endpoints have no `RequireManager`: `NotifyService` +calls `canRequestSign()` inside the action, `sendNotification()` rethrows the +exception and `afterException` serializes both bodies (JSON message as +`{action, errors}`, plain message as `{message}`). The generator merges +the alternatives into one interface (for example +`NotifySigners422ResponseOcsData` requires `action` and `errors`, which the +`MessageResponse` alternative does not have). The other seven (six 401 bodies +and the `footer-template` 403) are envelope-level `anyOf` whose second branch +has an untyped `data: {}`; they are generated as `...AnyOf1Ocs` models with +`data: any`. That reads the contract faithfully: the extractor's implicit 401/403 +has no typed body, so `X | {}` accepts anything. The typed branch is not lost by +the generator; the extractor adds the untyped one next to it. In +both cases the generator creates models for error bodies but method return +types only cover the success response, so callers receive errors as +`AxiosError` and must cast `error.response.data`. The `oneOf` constructs +(`NewFile.nodeId`, `RootCertificateName.value`, `UserConfigValue`, +`EffectivePolicyValue` and the inline `rootCert.names[].value` request +properties) generate correct unions. `UserConfigValue` includes `Array`; +`allowedValues` and the `values` maps are generated as `EffectivePolicyValue` +items without the contract's `null`. + +The schema formerly named `File` (an ID document record) was renamed to +`IdDocFile` in LibreSign. With the old name the generator renamed the model to +`ModelFile` but not its references, so `IdDocsListResponse.data` and +`IdDocsApprovalListResponse.data` were generated as `Array`, the only +unbounded `any` in the models. After the rename no `Array` remains and +`anyof-defect.ts` guards it. The underlying generator defect with reserved +model names is unchanged (see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md) G3). + +Other generator observations: binary responses are typed +as the DOM `File` although `responseType: arraybuffer` returns bytes; the +`OCS-APIRequest` header is a required boolean field named `oCSAPIRequest` of the +request object on all 87 OCS operations (positional only in the lower-level +generated functions and Markdown examples; the 3 non-OCS operations have none); +envelopes are not unwrapped. + +### Annotations aligned with the code + +LibreSign annotations that did not match the data were corrected: + +- `removeSigner` documented only an `ActionErrorResponse` 422, but its `catch` + also answers `{message}` with 422 when the exception code is 422. + `file-save` and `file-add-file-to-envelope` documented only a + `MessageResponse` 422, but `#[RequireManager]` rejects a user without + permission with an `{action, errors}` 422 before the method runs. The three + now document `MessageResponse | ActionErrorResponse`, which adds three `anyOf` + (14 became 17). +- `identify-account/search` documented no 422 although it has + `#[RequireManager]` and no `try` block: it now documents the middleware's + `ActionErrorResponse`. +- `nodeId` is nullable in `DetailedFile`, `ValidatedFile` and + `ValidatedChildFile`: `libresign_file.node_id` is nullable (the + `BeforeNodeDeletedListener` clears it when the original file is deleted) and + the entity value is copied as is (`FileSummary` already allowed null). + `src/services/validationDocument.ts` already rejects a validation payload with + a null `nodeId`; only the type predicate of its file filter changed, not its + behavior. + +`tests/php/openapi/OpenApiErrorBodyContractTest.php` guards these and the other +422 unions. A review of this branch caught an earlier mistaken narrowing: the +422 of `request-signature` (POST, PATCH), `removeSigner`, `deleteFile` and +`deleteSignatureRequest` can also be an `{action, errors}` body, because +`#[RequireManager]` runs `canRequestSign()` before the method and its `try` +block (`InjectionMiddleware.php`, `SigningRequestValidator.php`), so the +original `ActionErrorResponse` documentation was kept. + +Open decision for the maintainers, not changed here: several methods answer +HTTP 401 for failures that are not authentication failures. +`signatureGenerate`, the two certificate generators (`catch \Exception`), +`deleteFile` and `deleteSignatureRequest` (`catch \Throwable`) return 401 for +every caught failure, including validation and business errors, and +`removeSigner` returns 401 for any `LibresignException` whose code is not 422. +A 401 means "unauthenticated", so an SDK cannot tell an invalid session from a +business failure. Changing the status breaks compatibility and the Behat +scenarios, so it needs its own change. ## Normalized-input experiment `normalize-input.cjs` writes only -`build/sdk-generation/normalized/openapi-full.oneof.json`, renaming all 22 -`anyOf` keywords to `oneOf`. Generation is separate from the main evaluation. -It produces: - -- `EffectivePolicyValue = boolean | number | string | { [key: string]: object }`; -- `FileListResponseDataInner = DetailedFile | FileSummary`; -- `FileRuntimeMetadata = ValidateMetadata | { [key: string]: object }`. - -`test:normalized` passes strict compilation and positive/negative checks: -policy primitives/object values and object union members compile; policy arrays, -undefined and scalar file/metadata values are rejected. It also records a -remaining defect: schema-valid `null` is rejected by `EffectivePolicyValue`. -Passing this diagnostic suite does not establish full contract fidelity. - -This transformation is **generator-input normalization only**, not an equivalent -validation contract. In particular, integers match both `integer` and `number` -alternatives: `anyOf` allows that overlap, while `oneOf` requires exactly one -match. Never replace committed OpenAPI with this experiment's output. +`build/sdk-generation/normalized/openapi-full.oneof.json`, renaming the +remaining 17 `anyOf` keywords to `oneOf`. It generates +`FileListResponseDataInner = DetailedFile | FileSummary` and +`FileRuntimeMetadata = ValidateMetadata | { [key: string]: ... }`, and +`test:normalized` passes. It is generator-input normalization only: object +branches that overlap would also violate the `oneOf` "exactly one" rule, and +the transformed file must never replace the committed contract. The earlier +`integer`/`number` overlap argument no longer applies to policy values. ## Remaining limits -OCS envelopes are not automatically unwrapped, and callers must pass the OCS -header argument. Adapter status settlement is simulated; server authorization -and OCS-level errors inside HTTP 200 are not tested. Basic auth is inspected as -Axios config, not a real on-wire Authorization header. PDF types are generated -as `File` although explicit arraybuffer transport returns bytes; callers must -reconcile those types. No live Nextcloud checks were rerun for this version; -real account success, binary download, subdirectory deployment and state-changing -signature requests remain unverified. Tests sample models, not runtime JSON -validation or numerical limits. No production SDK or frontend migration is -included. +OCS envelopes are not automatically unwrapped. Adapter status settlement is +simulated; server authorization and OCS-level errors inside HTTP 200 are not +tested. Basic auth is inspected as Axios config, not as a real on-wire header. +PDF types are generated as `File` although arraybuffer transport returns bytes. +Live Nextcloud checks in `live.test.ts` use a local stub; no real server was +exercised in this run. Tests sample models and do not validate runtime JSON or +numerical limits. No production SDK or frontend migration is included. ## Multipart limitations -The harness checks the generated signatures and requests, and the controller -source supplies the expected upload names: +The contract still has no `multipart/form-data` request body for the six +operations tracked in #9435, which is closed on GitHub although no generated +request body exists yet; the merged work (#9452, #9490) added runtime +validation and endpoint descriptions, not request bodies. Upstream extractor support is open +(`nextcloud/openapi-extractor` #343 and PR #401). The harness checks +signatures and requests; controller source supplies the expected upload names: | operationId | Runtime upload | Generated behavior | | --- | --- | --- | -| `account-upload-pfx` | `file` in `AccountController::uploadPfx` | No typed file parameter or request body; generated call sends no body. | -| `file-save` | `file` or `files` in `FileController::prepareFilesForSaving` | Typed JSON body supports `NewFile` representations, but exposes no typed multipart upload. | -| `admin-signature-background-save` | `image` in `AdminController::signatureBackgroundSave` | No typed image parameter or request body; generated call sends no body. | +| `account-upload-pfx` | `file` in `AccountController::uploadPfx` | No typed file parameter or request body; sends no body. | +| `file-save` | `file`, `files[]` or legacy `file[]` | Typed JSON body only; no typed multipart upload. | +| `file-validate-binary` | `file` | No typed file parameter or request body. | +| `file-add-file-to-envelope` | `files[]` plus optional `expectedFilesCount` | No typed files or request body. | +| `admin-signature-background-save` | `image` | No typed image parameter or request body. | +| `admin-save-certificate-policy` | `pdf` | No typed file parameter or request body. | -Generic Axios options may allow a caller to handcraft a request, but that is not -verified typed multipart support. An official SDK or frontend migration would -need a reviewed contract/extractor correction and regenerated serialization, or -another explicitly designed solution. Changes to PHP or OpenAPI extraction are -outside this evaluation. +Generic Axios options can carry a handcrafted `FormData`, but that is not +verified typed multipart support. An official SDK or frontend migration needs +the extractor support above (or another reviewed design) and a regeneration. ## Handoff Maintainers must choose among these options; this evaluation selects none: -1. Conditional Go with reviewed generator-input normalization, addressing the - remaining nullable and transport limitations before SDK infrastructure. -2. Correct the source contract/extractor to emit `oneOf` where semantically - valid, explicitly resolving overlapping alternatives rather than blindly - renaming keywords. +1. Conditional Go with a reviewed generator-input normalization of the 17 + `anyOf` constructs, documented as non-contractual. +2. Fix the generator's `anyOf` merge and type the extractor's implicit 401/403 + body upstream, and adjust LibreSign's own types or annotations where + their cause is confirmed to be in LibreSign, then regenerate. 3. Evaluate another generator against the same acceptance criteria. -Rerun the harness against the approved contract and toolchain. Multipart source -contract work belongs to #9435. No PHP controller, extractor, committed OpenAPI, -generated frontend type, CI job or permanent SDK is changed here. +Multipart needs the upstream extractor work in every option. Detailed +extractor/generator items and what remains unverified in this repository are +in [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). Rerun the harness against the +approved contract and toolchain before any decision. diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md new file mode 100644 index 0000000000..5183548c41 --- /dev/null +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -0,0 +1,271 @@ + + +# Extractor and generator follow-ups + +Items found while re-running the #9089 evaluation against `main` at +`40ee2280737e54ebf798bbc1f77bf4272cbe9320` (`openapi-full.json` SHA-256 +`64c52fa2…c405`; the LibreSign-side fixes below change it). The items here cannot +be fixed in LibreSign without a local workaround, which the epic (#9087) forbids. Nothing here has been filed upstream yet; the +"Upstream status" lines say only what was checked. Reproduce evidence with +`tests/sdk-generation/README.md` and the checks named per item. + +Toolchain: `nextcloud/openapi-extractor` 1.9.1 (pinned in +`vendor-bin/openapi-extractor/composer.lock`), OpenAPI Generator 7.27.0 +`typescript-axios`, `useSingleRequestParameter=true`. + +## nextcloud/openapi-extractor + +### E1. Multipart request bodies for uploads (blocks the SDK) + +Six operations read `IRequest::getUploadedFile()` and have no multipart body +in the contract. Five have no `requestBody` at all: `account-upload-pfx` +(`file`), `file-validate-binary` (`file`), `file-add-file-to-envelope` +(`files[]`, optional `expectedFilesCount`), `admin-signature-background-save` +(`image`) and `admin-save-certificate-policy` (`pdf`). `file-save` has only an +`application/json` body; its multipart `file`, `files[]` and legacy `file[]` +are missing. + +Needed from the extractor: a `multipart/form-data` body with binary parts, +repeated array parts, optional/required semantics, and coexistence with a JSON +alternative on `file-save`. + +Upstream status: `nextcloud/openapi-extractor#343` (issue) and `#401` (PR) are +open; #401 is awaiting review. LibreSign keeps direct `getUploadedFile()` +calls in `FileController::save()` to stay compatible with that detection. +After it lands: regenerate, then verify that the generated client serializes +single and repeated files (not yet testable, see G5). + +### E2. Unions of objects and arrays are emitted as `anyOf` + +As #9494 showed, the extractor emitted `oneOf` for the policy value once its +scalar branches became disjoint. Unions that include objects or arrays (the policy-override one pairs a value with +an array of values) are still emitted as `anyOf`, +and OpenAPI Generator mishandles them (G1). Affected schemas, 17 in total: + +- `FileListResponse.data[]` items: `FileSummary | DetailedFile`; +- `FileRuntimeMetadata`: `ValidateMetadata | array`; +- `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; +- 7 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, + notify-signer, request-signature, update-signature-request, `removeSigner`, + `file-save` and `file-add-file-to-envelope`). The union is real. The other + five get `{action, errors}` from `#[RequireManager]` (`canRequestSign()` runs + before the method; `afterException` serializes the `LibresignException`) and + `{message}` from a `DataResponse` built in their own `catch` blocks. The + notify endpoints have no `RequireManager`: `NotifyService` calls + `canRequestSign()` inside the action, `NotifyController::sendNotification()` + rethrows, and `afterException` serializes both bodies (a JSON message becomes + `{action, errors}`, a plain one `{message}`); +- 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` + whose second branch has an untyped `data: {}`. Cause confirmed: for every + non-public OCS method the extractor adds an implicit 401 with an untyped + `data`, and a 403 for admin methods (`ControllerMethod.php`, about lines + 414-440 in 1.9.1). The `anyOf` appears exactly when the controller also + declares that same status in its `@return` for a method that is not + `#[PublicPage]` (401) or not `#[NoAdminRequired]` (403). A scan of + `lib/Controller` finds exactly seven such methods, the same seven operations: + `AccountController::signatureGenerate`, + `AdminController::generateCertificateCfssl` and `generateCertificateOpenSsl`, + `FileController::deleteFile`, `FooterTemplateController::saveFooterTemplate` + (403), `RequestSignatureController::removeSigner` and `deleteSignatureRequest`. + Public methods that declare a 401 (for example `IdDocsController::delete`) + generate a single typed response, and the 82 other 401/403 responses have an + untyped `data: {}`, mostly the implicit ones (a few are explicit `list` + declarations, for example `FileController.php:138`). The explicit declarations describe what the code returns, so + removing them would only erase the typed body and leave `data: {}`. The + request to the extractor is therefore to give the implicit 401/403 a typed + body (or to let the controller refine it), not to let an explicit declaration + replace the implicit one: the implicit response models what the framework + sends (not verified here, Nextcloud's security middleware was not read), so + both bodies are plausible and `anyOf` is correct. The generator then produces + `data: any`, a faithful reading of `X | {}`. Separately, several of these + methods use 401 for failures that are not authentication failures, which is a + LibreSign decision (see "Left in LibreSign"). + +For the object unions, `anyOf` is semantically correct: without +`additionalProperties: false` an object carrying every key of two alternatives +matches both (a detailed file can match both `FileSummary` and `DetailedFile`), +so `oneOf` would be wrong. The defect is the generator's merge (G1), not the +extractor's choice. Evidence: `npm run test:anyof` (`union-defects.ts`) and +`npm run test:normalized`, which renames the 17 keywords in a disposable copy +and passes. + +### E3. `mixed` maps to `{ type: object }` + +`EffectivePolicyValue`'s object branch and `UserConfigValue` are emitted with +`additionalProperties: { type: object }`, `UserConfigValue`'s `list` +becomes `Array`, and `DynamicMetadataValue` (PHP `mixed`) is +`{ type: object }`. Generated types therefore reject scalar-valued entries that +the PHP type allows. This was already noted in #9494 as an open limitation. + +### E4. `nullable` on a composed schema + +`EffectivePolicyValue` is `nullable: true` plus `oneOf`, with no explicit +`null` alternative. The generator applies `| null` at properties that +reference it (`EffectivePolicyState.effectiveValue`) but not at array items +(`allowedValues: Array` and the `values` maps), and OpenAPI 3.0.3 defines +`nullable` only next to `type`. Decide whether the extractor should emit a +construct generators handle consistently. Not tested with another generator. + +### E5. Binary responses are typed `*/*` + +Thumbnails, signature element preview, the CRL and the admin background image +were all generated with the media type `*/*` and `format: binary`, while the PDF +operations use `application/pdf`. The CRL and the background have a fixed type +in the code and now declare it in LibreSign. Thumbnails and the element preview +depend on the previewed file; their `FileDisplayResponse` only states +`Content-Type: string`, so `*/*` remains. The extractor already accepts literal +`Content-Type` values (`ResponseType.php`, 1.9.1), so nothing is missing there: +the media type set of a previewed file is not closed, which is why LibreSign +keeps `string`. + +### E6. Every OCS operation repeats the header parameter + +`OCS-APIRequest` is a required header parameter with `default: true` on the +87 OCS operations (the 3 non-OCS ones have none). Generated clients make it +a required field of every request object (positional in the lower-level +functions). Consider whether the extractor can mark OCS operations through a +reusable component or security-like default so SDK generators can inject it +once. + +## OpenAPI Generator (`typescript-axios` 7.27.0) + +### G1. `anyOf` of objects becomes one merged interface + +The generated interface merges both alternatives and keeps required fields from +one of them: `FileListResponseDataInner` requires `files`, `size` and +`visibleElements` and narrows `nodeId` to `number`; `FileRuntimeMetadata` loses +its dynamic branch; the `RequestPolicyOverridesValue` union becomes an empty +interface; the seven 422 bodies such as `NotifySigners422ResponseOcsData` require +`action` and `errors`, and the seven envelope `anyOf` bodies become `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` +("`anyOf` creates same interface as `allOf`", reported against 5.0.1) is open +and matches the merged-interface cases (`FileListResponseDataInner` and the seven +422 bodies). It does not describe the lost dynamic branch of +`FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the seven +envelope cases, where the generator keeps `data: any`; those may need their own +reports. The fix was not tracked here. The earlier evaluation recorded the former `EffectivePolicyValue` defect, a different `anyOf` case, in both 7.15.0 and 7.27.0; the object cases above were checked only with 7.27.0. +A union of two arrays (`list|list` as `anyOf`) becomes an empty interface +(tested on a disposable spec copy). `oneOf` produces correct unions, so the choice is: fix the generator, add a +reviewed normalization step to the future SDK Generator, or pick another +generator. + +### G2. Error responses are not part of method return types + +Models for 4xx/5xx bodies exist, but method return types only describe the +success response. The SDK layer must expose typed access to +`error.response.data` itself (for example through a wrapper or documented type +guards). Do not assume this is unwrapped or typed automatically. The success +types can also carry misleading names: `notifySigners` returns +`AxiosPromise`, a model deduplicated +from a 401 body that shares the 200 `MessageResponse` shape. If this matters for +the public SDK surface, it needs naming control (for example +`inlineSchemaNameMapping`), which was not tested. + +### G3. The schema named `File` is renamed but its references become `any` + +`File` is renamed to `ModelFile` because it matches a global TypeScript type +(generator warning, repeated per usage), but the references to it are not +updated: `IdDocsListResponse.data` and `IdDocsApprovalListResponse.data` are +generated as `Array`, the only unbounded `any` in the model section. On a +disposable copy of the spec with the schema renamed to `IdDocFile` both become +`Array` and no `Array` remains, so the defect is the +generator's handling of reserved model names. LibreSign renamed its schema to +`IdDocFile` (decided by the maintainer, because the name was also too generic), +which removes the `any` from its contract; `anyof-defect.ts` guards it. The +generator defect itself is not fixed. + +Binary responses are typed as the DOM `File`, while transport with +`responseType: arraybuffer` yields bytes, so callers must reconcile types. To +evaluate in the generator configuration: `typeMappings` (for example +`file=Blob` or `ArrayBuffer`) and `modelNameMappings`. Neither was tested. + +### G4. Ergonomics + +- Header parameter name is `oCSAPIRequest`; `parameterNameMappings` may allow a + readable name (untested). +- Generated Markdown examples use positional arguments although + `useSingleRequestParameter=true` is set; real signatures take one object. +- The OCS envelope is not unwrapped: callers read `response.data.ocs.data`. +- `BASE_PATH` defaults to `http://localhost` and LibreSign's paths mix + `/ocs/v2.php/...` and `/index.php/...`; subdirectory installs work only + because callers pass the full base URL (tested), not through `servers`. + +### G5. Multipart serialization is unverified + +Because the contract has no multipart bodies (E1), serialization of single and +repeated file parts by `typescript-axios` (FormData in browsers and Node, +`files[]` naming, `expectedFilesCount`) could not be tested. Add these checks +to the harness once E1 is available and record any generator limitation +separately. + +## Left in LibreSign + +Rule for this work: packages (`vendor/`, `vendor-bin/`, the generator) are not +patched locally and no local extractor workaround is added; defects above are +reported upstream. Anything whose cause is in LibreSign's own code is adjusted +in LibreSign. Candidates, each needing its cause confirmed first: + +- the 7 error bodies with an untyped `data: {}` (E2): investigated; the + controllers' explicit 401/403 declarations describe what the code returns, so + the untyped body is the extractor's and needs no LibreSign change; +- annotations that did not match the data (done): `removeSigner`, `file-save` + and `file-add-file-to-envelope` now document `MessageResponse | + ActionErrorResponse` for 422 (their `catch` answers `{message}`, the + middleware answers `{action, errors}`); `identify-account/search` documents the + middleware 422 (`ActionErrorResponse`), it has no `try` block; and `nodeId` is + nullable in `DetailedFile`, `ValidatedFile` and `ValidatedChildFile` like the + database column. Guarded by + `tests/php/openapi/OpenApiErrorBodyContractTest.php`. The 422 documentation of + `request-signature`, `deleteFile` and `deleteSignatureRequest` was checked and + is correct: `#[RequireManager]` rejects a user without permission with an + `{action, errors}` 422 before the method runs. `SignFileController::signByFileId` + is public and documents `SignActionErrorResponse`, which accommodates that + payload; unchanged; +- **open maintainer decision**: several methods answer HTTP 401 for failures + that are not authentication failures. `AccountController::signatureGenerate`, + the `AdminController` certificate generators (`catch \Exception`), + `FileController::deleteFile` and + `RequestSignatureController::deleteSignatureRequest` (`catch \Throwable`) + return 401 for every caught failure; `removeSigner` returns 401 for a + `LibresignException` whose code is not 422. Moving business failures to + 422/400 is a compatibility-breaking change that needs its own change and + Behat updates; not done here; +- `DetailedFile.policySnapshotFrozen` is declared required, but + `formatSingleFileData` omits it without a user (`FileListService.php:273-275`) + while `formatFileWithChildren` always sets it (`:881`); not changed because it + was not established which builder feeds each typed OCS response; +- `src/services/validationDocument.ts` (`isValidatedChildFileRecord` and + `isValidationDocumentRecord`) treats a validation payload with a null + `nodeId` as invalid, although the backend can send it once the original file + was deleted (`FileService.php`, `EnvelopeAssembler.php`). Not changed here: it + is a frontend behavior decision, not an annotation; +- the three `anyOf` schemas in `lib/ResponseDefinitions.php` (E2/G1): + investigated, no change recommended. `FileSummary|DetailedFile` is a + per-item approximation, because `FileListService.php:99-103` makes the + `details` flag switch the whole list; the more faithful + `list|list` is still an `anyOf`, and on a + disposable copy of the spec `typescript-axios` turned it into an empty + interface (`FileListResponseData`), which is worse. `FileRuntimeMetadata` + (`ValidateMetadata|array`) and `RequestPolicyOverrides` + (`value|list`) are deliberate unions that the runtime treats as + `array`; no evidence was found that they are wrong. So the + defects are the generator's (G1) and the extractor's `mixed` mapping (E3); +- the schema `File` name (G3): done. `LibresignFile` became `LibresignIdDocFile` + (`lib/ResponseDefinitions.php`, imports in `FileController`, + `IdDocsController` and `AccountController`), the frontend alias in + `src/views/Documents/IdDocsValidation.vue` and its spec follow, the three + contracts and the TypeScript types were regenerated, and + `tests/php/openapi/OpenApiIdDocSchemaTest.php` guards the name; +- the `*/*` media types (E5): done where the type is fixed in the code. The CRL + now declares `application/pkix-crl` (`CrlController.php`) and the admin + background `image/png` (`AdminController.php`), with + `tests/php/openapi/OpenApiBinaryMediaTypesTest.php`. Thumbnails and the + signature element preview keep `*/*` because their media type depends on the + previewed file (`Content-Type: string` is accurate). +- **Go/No-Go**: see the handoff in [REPORT.md](REPORT.md). It must be re-run + after the toolchain or contract changes. +- **Not verified**: a real browser with the real XHR adapter and a real + Nextcloud server; state-changing signature requests; runtime JSON + validation against the contract. diff --git a/tests/sdk-generation/anyof-defect.ts b/tests/sdk-generation/anyof-defect.ts index e23577beb6..50563a4d23 100644 --- a/tests/sdk-generation/anyof-defect.ts +++ b/tests/sdk-generation/anyof-defect.ts @@ -2,8 +2,21 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ -import type { EffectivePolicyValue } from '../../build/sdk-generation/typescript/api' -// This defect-reproduction check passes only while invalid arrays are accepted. -// Missing generated output or a corrected union must fail compilation. -const accepted: EffectivePolicyValue = ['not a policy value'] -void accepted +import type { EffectivePolicyValue, EffectivePolicyState, IdDocFile, IdDocsListResponse } from '../../build/sdk-generation/typescript/api' +// Regression guard for the former EffectivePolicyValue defect (empty generated +// interface accepting arrays). Fixed by the disjoint oneOf contract; each +// ts-expect-error below fails compilation if the generated type widens again. +const accepted: EffectivePolicyValue[] = [true, 42, 1.5, 'value', { nested: {} }] +// @ts-expect-error arrays are not policy values +const invalidArray: EffectivePolicyValue = ['not a policy value'] +// @ts-expect-error undefined is not a policy value +const invalidUndefined: EffectivePolicyValue = undefined +// The nullable flag is applied where the schema is referenced as a property. +const nullableProperty: Pick = { effectiveValue: null } +// The ID document record schema was named File, which made the generator emit +// Array for both ID document lists. It is now IdDocFile and must stay typed. +declare const idDocs: IdDocsListResponse +const idDoc: IdDocFile = idDocs.data[0] +// @ts-expect-error a number is not an ID document record +const invalidIdDoc: IdDocsListResponse['data'][number] = 42 +void [accepted, invalidArray, invalidUndefined, nullableProperty, idDoc, invalidIdDoc] diff --git a/tests/sdk-generation/nextcloud-axios.test.ts b/tests/sdk-generation/nextcloud-axios.test.ts new file mode 100644 index 0000000000..974dac9b23 --- /dev/null +++ b/tests/sdk-generation/nextcloud-axios.test.ts @@ -0,0 +1,60 @@ +/* + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +// Injects the real, locked @nextcloud/axios instance into a generated client. +// The package needs browser globals, so a jsdom window is installed first. +// Only the network adapter is replaced; the package's own defaults and its CSRF +// interceptor run unmodified. No real Nextcloud server is contacted. +import * as assert from 'node:assert/strict' +import { test } from 'node:test' +import { AxiosError, type AxiosAdapter, type InternalAxiosRequestConfig } from 'axios' +import { JSDOM } from 'jsdom' +import { IdentityApi } from '../../build/sdk-generation/typescript/api' +import { Configuration } from '../../build/sdk-generation/typescript/configuration' + +const dom = new JSDOM('', { url: 'https://example.test/nextcloud/' }) +Object.assign(globalThis, { window: dom.window, document: dom.window.document, location: dom.window.location, localStorage: dom.window.localStorage, sessionStorage: dom.window.sessionStorage }) + +const okBody = { ocs: { meta: { status: 'ok', statuscode: 200 }, data: { account: { uid: 'test', emailAddress: 'test@example.test', displayName: 'Test' }, settings: { canRequestSign: true, hasSignatureFile: false, phoneNumber: '' } } } } + +test('generated client works with the real @nextcloud/axios instance and its CSRF retry', async () => { + const { default: nextcloudAxios } = await import('@nextcloud/axios') + const seen: InternalAxiosRequestConfig[] = [] + let calls = 0 + const adapter: AxiosAdapter = async config => { + seen.push(config) + calls++ + const reply = (status: number, data: unknown) => { + const response = { data, status, statusText: String(status), headers: {}, config } + if (config.validateStatus && !config.validateStatus(status)) { + throw new AxiosError('HTTP error', 'ERR_BAD_REQUEST', config, undefined, response) + } + return response + } + // First account request: simulate a stale token, as Nextcloud does. + return calls === 1 ? reply(412, { message: 'CSRF check failed' }) : reply(200, okBody) + } + // fetchRequestToken() uses the global fetch(), not Axios. + const fetched: string[] = [] + globalThis.fetch = (async (input: RequestInfo | URL) => { + fetched.push(String(input)) + return new Response(JSON.stringify({ token: 'refreshed-token' }), { status: 200, headers: { 'Content-Type': 'application/json' } }) + }) as typeof fetch + nextcloudAxios.defaults.adapter = adapter + + const api = new IdentityApi(new Configuration({ basePath: 'https://example.test/nextcloud' }), undefined, nextcloudAxios) + const account = await api.accountMe({ apiVersion: 'v1', oCSAPIRequest: true }) + + const first = seen[0] + assert.equal(first.url, 'https://example.test/nextcloud/ocs/v2.php/apps/libresign/api/v1/account/me') + assert.equal(first.headers.get('OCS-APIRequest'), 'true') + assert.equal(first.headers.get('requesttoken'), 'initial-token') + assert.equal(first.headers.get('X-Requested-With'), 'XMLHttpRequest') + const retry = seen[seen.length - 1] + assert.equal(retry.url, first.url) + assert.equal(retry.headers.get('requesttoken'), 'refreshed-token') + assert.equal(retry.headers.get('OCS-APIRequest'), 'true') + assert.deepEqual(fetched, ['/nextcloud/index.php/csrftoken']) + assert.equal(account.data.ocs.data.account.uid, 'test') +}) diff --git a/tests/sdk-generation/package-lock.json b/tests/sdk-generation/package-lock.json index b033d640d8..8845e2fba4 100644 --- a/tests/sdk-generation/package-lock.json +++ b/tests/sdk-generation/package-lock.json @@ -13,11 +13,142 @@ "axios": "1.20.0" }, "devDependencies": { + "@types/jsdom": "21.1.7", "@types/node": "22.15.21", + "jsdom": "26.1.0", "tsx": "4.19.4", "typescript": "5.8.3" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", @@ -542,6 +673,18 @@ "@types/sizzle": "*" } }, + "node_modules/@types/jsdom": { + "version": "21.1.7", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.7.tgz", + "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^7.0.0" + } + }, "node_modules/@types/node": { "version": "22.15.21", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz", @@ -564,6 +707,13 @@ "integrity": "sha512-TC0dmN0K8YcWEAEfiPi5gJP14eJe30TTGjkvek3iM/1NdHHsdCA/Td6GvNndMOo/iSnIsZ4HuuhrYPDAmbxzww==", "license": "MIT" }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true, + "license": "MIT" + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -619,6 +769,34 @@ "node": ">= 0.8" } }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -636,6 +814,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -659,6 +844,19 @@ "node": ">= 0.4" } }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -907,6 +1105,43 @@ "node": ">= 0.4" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/https-proxy-agent": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", @@ -920,6 +1155,97 @@ "node": ">= 6" } }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -956,6 +1282,26 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -965,6 +1311,16 @@ "node": ">=10" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -975,6 +1331,33 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/semver": { "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", @@ -987,6 +1370,59 @@ "node": ">=10" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tsx": { "version": "4.19.4", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.19.4.tgz", @@ -1027,6 +1463,106 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" } } } diff --git a/tests/sdk-generation/package.json b/tests/sdk-generation/package.json index f28958bec6..b877d2cd2e 100644 --- a/tests/sdk-generation/package.json +++ b/tests/sdk-generation/package.json @@ -4,9 +4,9 @@ "private": true, "license": "AGPL-3.0-or-later", "scripts": { - "compile": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/typescript/*.ts types.ts signing-contracts.ts transport.ts live.ts live.test.ts", - "test": "tsx transport.ts && node inventory.cjs && tsx --test live.test.ts && node --test generate.test.cjs", - "test:anyof": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node anyof-defect.ts", + "compile": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/typescript/*.ts types.ts signing-contracts.ts transport.ts live.ts live.test.ts nextcloud-axios.test.ts", + "test": "tsx transport.ts && node inventory.cjs && tsx --test live.test.ts && node --test generate.test.cjs && tsx --test nextcloud-axios.test.ts", + "test:anyof": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node anyof-defect.ts union-defects.ts", "test:live": "tsx live.ts", "test:nextcloud": "node nextcloud-import.mjs", "test:normalized": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/normalized/typescript/*.ts normalized-types.ts" @@ -16,7 +16,9 @@ "axios": "1.20.0" }, "devDependencies": { + "@types/jsdom": "21.1.7", "@types/node": "22.15.21", + "jsdom": "26.1.0", "tsx": "4.19.4", "typescript": "5.8.3" } diff --git a/tests/sdk-generation/types.ts b/tests/sdk-generation/types.ts index c6904e3ad8..024d3e6321 100644 --- a/tests/sdk-generation/types.ts +++ b/tests/sdk-generation/types.ts @@ -15,9 +15,9 @@ const signer: SignerDetail = { } // @ts-expect-error allOf requires inherited fields const badSigner: SignerDetail = { me: true, visibleElements: [] } -const request: RequestSignatureRequestSignatureRequest = { callback: null } -// @ts-expect-error callback must be a string or null -const badRequest: RequestSignatureRequestSignatureRequest = { callback: 2 } +const request: RequestSignatureRequestSignatureRequest = { status: null } +// @ts-expect-error status must be a number or null +const badRequest: RequestSignatureRequestSignatureRequest = { status: 'pending' } // @ts-expect-error status is a finite numeric enum const badStatus: SignerDetail['status'] = 99 function account(response: AccountMe200Response): string { return response.ocs.data.account.uid } diff --git a/tests/sdk-generation/union-defects.ts b/tests/sdk-generation/union-defects.ts new file mode 100644 index 0000000000..f510cfc98b --- /dev/null +++ b/tests/sdk-generation/union-defects.ts @@ -0,0 +1,24 @@ +/* + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import type { FileListResponseDataInner, FileRuntimeMetadata, FileSummary, RequestPolicyOverridesValue } from '../../build/sdk-generation/typescript/api' +// Reproductions of defects that remain in the generated output for the +// object-valued anyOf constructs. The file compiles only while the defects +// exist: a @ts-expect-error marks a contract-valid value that the generated +// type rejects (it fails with TS2578 once fixed), and a plain assignment marks +// a contract-invalid value that the generated type accepts (it fails with +// TS2322 once fixed). When either happens, reevaluate the handoff in +// REPORT.md and UPSTREAM-NOTES.md and invert the assertion. +declare const summary: FileSummary +// anyOf of FileSummary|DetailedFile is merged into one interface whose +// required fields come from DetailedFile (files, size, visibleElements). +// @ts-expect-error a valid FileSummary is not assignable to the generated item type +const item: FileListResponseDataInner = summary +// anyOf of ValidateMetadata|{[k]: DynamicMetadataValue}: the dynamic branch is lost. +// @ts-expect-error a dynamic metadata object without extension/p is valid by contract +const metadata: FileRuntimeMetadata = { custom: {} } +// anyOf of EffectivePolicyValue|array becomes an empty interface. A triple-nested +// array is invalid by contract (only a flat array of policy values is allowed) but is accepted. +const overrideAcceptsAnything: RequestPolicyOverridesValue = [[[1]]] +void [item, metadata, overrideAcceptsAnything]