fix: decode WebP uploads through their inspected codec

This commit is contained in:
Nick Beckley 2026-11-04 06:02:39 +00:00
parent 6f61d7d382
commit 02a1ea99ab
10 changed files with 390 additions and 22 deletions

View File

@ -0,0 +1,29 @@
Workflow,Input,Execution,Verified,Limits
Character gallery,.png,Production service + real SQL/files,WebP image/thumbnail and Unicode metadata,HTTP/UI acceptance separate
Character main image,.png,Production service + real SQL/files,WebP image/thumbnail and gallery source,HTTP/UI acceptance separate
Asset image,.png,Production service + real SQL/files,WebP image and thumbnail,HTTP/UI acceptance separate
Book cover,.png,Production service + real SQL/files,WebP cover and thumbnail,HTTP/UI acceptance separate
Floor background,.png,Production service + real SQL/files,Exact original bytes and filename,Existing workflow preserves input format
Map reference,.png,Production service + real SQL,WebP embedded bytes and author boundary,HTTP/UI acceptance separate
Character avatar,.png,Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate
Character gallery,.jpg,Production service + real SQL/files,WebP image/thumbnail and Unicode metadata,HTTP/UI acceptance separate
Character main image,.jpg,Production service + real SQL/files,WebP image/thumbnail and gallery source,HTTP/UI acceptance separate
Asset image,.jpg,Production service + real SQL/files,WebP image and thumbnail,HTTP/UI acceptance separate
Book cover,.jpg,Production service + real SQL/files,WebP cover and thumbnail,HTTP/UI acceptance separate
Floor background,.jpg,Production service + real SQL/files,Exact original bytes and filename,Existing workflow preserves input format
Map reference,.jpg,Production service + real SQL,WebP embedded bytes and author boundary,HTTP/UI acceptance separate
Character avatar,.jpg,Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate
Character gallery,.jpeg,Production service + real SQL/files,WebP image/thumbnail and Unicode metadata,HTTP/UI acceptance separate
Character main image,.jpeg,Production service + real SQL/files,WebP image/thumbnail and gallery source,HTTP/UI acceptance separate
Asset image,.jpeg,Production service + real SQL/files,WebP image and thumbnail,HTTP/UI acceptance separate
Book cover,.jpeg,Production service + real SQL/files,WebP cover and thumbnail,HTTP/UI acceptance separate
Floor background,.jpeg,Production service + real SQL/files,Exact original bytes and filename,Existing workflow preserves input format
Map reference,.jpeg,Production service + real SQL,WebP embedded bytes and author boundary,HTTP/UI acceptance separate
Character avatar,.jpeg,Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate
Character gallery,.webp,Production service + real SQL/files,WebP image/thumbnail and Unicode metadata,HTTP/UI acceptance separate
Character main image,.webp,Production service + real SQL/files,WebP image/thumbnail and gallery source,HTTP/UI acceptance separate
Asset image,.webp,Production service + real SQL/files,WebP image and thumbnail,HTTP/UI acceptance separate
Book cover,.webp,Production service + real SQL/files,WebP cover and thumbnail,HTTP/UI acceptance separate
Floor background,.webp,Production service + real SQL/files,Exact original bytes and filename,Existing workflow preserves input format
Map reference,.webp,Production service + real SQL,WebP embedded bytes and author boundary,HTTP/UI acceptance separate
Character avatar,.webp,Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate
1 Workflow Input Execution Verified Limits
2 Character gallery .png Production service + real SQL/files WebP image/thumbnail and Unicode metadata HTTP/UI acceptance separate
3 Character main image .png Production service + real SQL/files WebP image/thumbnail and gallery source HTTP/UI acceptance separate
4 Asset image .png Production service + real SQL/files WebP image and thumbnail HTTP/UI acceptance separate
5 Book cover .png Production service + real SQL/files WebP cover and thumbnail HTTP/UI acceptance separate
6 Floor background .png Production service + real SQL/files Exact original bytes and filename Existing workflow preserves input format
7 Map reference .png Production service + real SQL WebP embedded bytes and author boundary HTTP/UI acceptance separate
8 Character avatar .png Production service + real SQL/files 256x256 WebP crop and gallery source identity Geometry clamping intentional; physical UI acceptance separate
9 Character gallery .jpg Production service + real SQL/files WebP image/thumbnail and Unicode metadata HTTP/UI acceptance separate
10 Character main image .jpg Production service + real SQL/files WebP image/thumbnail and gallery source HTTP/UI acceptance separate
11 Asset image .jpg Production service + real SQL/files WebP image and thumbnail HTTP/UI acceptance separate
12 Book cover .jpg Production service + real SQL/files WebP cover and thumbnail HTTP/UI acceptance separate
13 Floor background .jpg Production service + real SQL/files Exact original bytes and filename Existing workflow preserves input format
14 Map reference .jpg Production service + real SQL WebP embedded bytes and author boundary HTTP/UI acceptance separate
15 Character avatar .jpg Production service + real SQL/files 256x256 WebP crop and gallery source identity Geometry clamping intentional; physical UI acceptance separate
16 Character gallery .jpeg Production service + real SQL/files WebP image/thumbnail and Unicode metadata HTTP/UI acceptance separate
17 Character main image .jpeg Production service + real SQL/files WebP image/thumbnail and gallery source HTTP/UI acceptance separate
18 Asset image .jpeg Production service + real SQL/files WebP image and thumbnail HTTP/UI acceptance separate
19 Book cover .jpeg Production service + real SQL/files WebP cover and thumbnail HTTP/UI acceptance separate
20 Floor background .jpeg Production service + real SQL/files Exact original bytes and filename Existing workflow preserves input format
21 Map reference .jpeg Production service + real SQL WebP embedded bytes and author boundary HTTP/UI acceptance separate
22 Character avatar .jpeg Production service + real SQL/files 256x256 WebP crop and gallery source identity Geometry clamping intentional; physical UI acceptance separate
23 Character gallery .webp Production service + real SQL/files WebP image/thumbnail and Unicode metadata HTTP/UI acceptance separate
24 Character main image .webp Production service + real SQL/files WebP image/thumbnail and gallery source HTTP/UI acceptance separate
25 Asset image .webp Production service + real SQL/files WebP image and thumbnail HTTP/UI acceptance separate
26 Book cover .webp Production service + real SQL/files WebP cover and thumbnail HTTP/UI acceptance separate
27 Floor background .webp Production service + real SQL/files Exact original bytes and filename Existing workflow preserves input format
28 Map reference .webp Production service + real SQL WebP embedded bytes and author boundary HTTP/UI acceptance separate
29 Character avatar .webp Production service + real SQL/files 256x256 WebP crop and gallery source identity Geometry clamping intentional; physical UI acceptance separate

View File

@ -0,0 +1,41 @@
Route,FileName,Actor,Antiforgery,SourceImageID,HTTP
"/Characters/UploadImage","HTTP café 雨.png","Owner","Present when authenticated","","302"
"/Characters/UploadImage","HTTP café 雨.jpg","Owner","Present when authenticated","","302"
"/Characters/UploadImage","HTTP café 雨.jpeg","Owner","Present when authenticated","","302"
"/Characters/UploadImage","HTTP café 雨.webp","Owner","Present when authenticated","","302"
"/Characters/UploadImage","foreign.png","Other author","Present when authenticated","","404"
"/Characters/UploadImage","anonymous.png","Anonymous","Present when authenticated","","401"
"/Characters/UploadImage","no-token.png","Owner","Absent","","400"
"/Characters/UploadImage","corrupt.png","Owner","Present when authenticated","","302"
"/Characters/UploadImage","missing.png","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","HTTP café 雨.png","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","HTTP café 雨.jpg","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","HTTP café 雨.jpeg","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","HTTP café 雨.webp","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","foreign.png","Other author","Present when authenticated","","404"
"/FloorPlans/UploadBackground","anonymous.png","Anonymous","Present when authenticated","","401"
"/FloorPlans/UploadBackground","no-token.png","Owner","Absent","","400"
"/FloorPlans/UploadBackground","corrupt.png","Owner","Present when authenticated","","302"
"/FloorPlans/UploadBackground","missing.png","Owner","Present when authenticated","","302"
"/Maps/UploadReference","HTTP café 雨.png","Owner","Present when authenticated","","200"
"/Maps/UploadReference","HTTP café 雨.jpg","Owner","Present when authenticated","","200"
"/Maps/UploadReference","HTTP café 雨.jpeg","Owner","Present when authenticated","","200"
"/Maps/UploadReference","HTTP café 雨.webp","Owner","Present when authenticated","","200"
"/Maps/UploadReference","foreign.png","Other author","Present when authenticated","","404"
"/Maps/UploadReference","anonymous.png","Anonymous","Present when authenticated","","401"
"/Maps/UploadReference","no-token.png","Owner","Absent","","400"
"/Maps/UploadReference","corrupt.png","Owner","Present when authenticated","","400"
"/Maps/UploadReference","missing.png","Owner","Present when authenticated","","400"
"/Characters/SaveAvatar","","Other author","Present when authenticated","32412","404"
"/Characters/SaveAvatar","","Anonymous","Present when authenticated","32412","401"
"/Characters/SaveAvatar","","Owner","Absent","32412","400"
"/Characters/DeleteImage","","Other author","Present when authenticated","","404"
"/Characters/DeleteImage","","Anonymous","Present when authenticated","","401"
"/Characters/DeleteImage","","Owner","Absent","","400"
"/Characters/RemoveAvatar","","Other author","Present when authenticated","","404"
"/Characters/RemoveAvatar","","Anonymous","Present when authenticated","","401"
"/Characters/RemoveAvatar","","Owner","Absent","","400"
"/Characters/SaveAvatar","","Owner","Present when authenticated","32412","302"
"/Characters/SaveAvatar","","Owner","Present when authenticated","0","302"
"/Characters/DeleteImage","","Owner","Present when authenticated","","302"
"/Characters/RemoveAvatar","","Owner","Present when authenticated","","302"
1 Route FileName Actor Antiforgery SourceImageID HTTP
2 /Characters/UploadImage HTTP café 雨.png Owner Present when authenticated 302
3 /Characters/UploadImage HTTP café 雨.jpg Owner Present when authenticated 302
4 /Characters/UploadImage HTTP café 雨.jpeg Owner Present when authenticated 302
5 /Characters/UploadImage HTTP café 雨.webp Owner Present when authenticated 302
6 /Characters/UploadImage foreign.png Other author Present when authenticated 404
7 /Characters/UploadImage anonymous.png Anonymous Present when authenticated 401
8 /Characters/UploadImage no-token.png Owner Absent 400
9 /Characters/UploadImage corrupt.png Owner Present when authenticated 302
10 /Characters/UploadImage missing.png Owner Present when authenticated 302
11 /FloorPlans/UploadBackground HTTP café 雨.png Owner Present when authenticated 302
12 /FloorPlans/UploadBackground HTTP café 雨.jpg Owner Present when authenticated 302
13 /FloorPlans/UploadBackground HTTP café 雨.jpeg Owner Present when authenticated 302
14 /FloorPlans/UploadBackground HTTP café 雨.webp Owner Present when authenticated 302
15 /FloorPlans/UploadBackground foreign.png Other author Present when authenticated 404
16 /FloorPlans/UploadBackground anonymous.png Anonymous Present when authenticated 401
17 /FloorPlans/UploadBackground no-token.png Owner Absent 400
18 /FloorPlans/UploadBackground corrupt.png Owner Present when authenticated 302
19 /FloorPlans/UploadBackground missing.png Owner Present when authenticated 302
20 /Maps/UploadReference HTTP café 雨.png Owner Present when authenticated 200
21 /Maps/UploadReference HTTP café 雨.jpg Owner Present when authenticated 200
22 /Maps/UploadReference HTTP café 雨.jpeg Owner Present when authenticated 200
23 /Maps/UploadReference HTTP café 雨.webp Owner Present when authenticated 200
24 /Maps/UploadReference foreign.png Other author Present when authenticated 404
25 /Maps/UploadReference anonymous.png Anonymous Present when authenticated 401
26 /Maps/UploadReference no-token.png Owner Absent 400
27 /Maps/UploadReference corrupt.png Owner Present when authenticated 400
28 /Maps/UploadReference missing.png Owner Present when authenticated 400
29 /Characters/SaveAvatar Other author Present when authenticated 32412 404
30 /Characters/SaveAvatar Anonymous Present when authenticated 32412 401
31 /Characters/SaveAvatar Owner Absent 32412 400
32 /Characters/DeleteImage Other author Present when authenticated 404
33 /Characters/DeleteImage Anonymous Present when authenticated 401
34 /Characters/DeleteImage Owner Absent 400
35 /Characters/RemoveAvatar Other author Present when authenticated 404
36 /Characters/RemoveAvatar Anonymous Present when authenticated 401
37 /Characters/RemoveAvatar Owner Absent 400
38 /Characters/SaveAvatar Owner Present when authenticated 32412 302
39 /Characters/SaveAvatar Owner Present when authenticated 0 302
40 /Characters/DeleteImage Owner Present when authenticated 302
41 /Characters/RemoveAvatar Owner Present when authenticated 302

View File

@ -7,23 +7,23 @@ ChapterBrief,Export,html; markdown/md; text/txt,Chapter goal and scene brief,Exp
WritingSession,Export,html; markdown/md; text/txt,Scene writing-session brief,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
ResearchPack,Export,html; markdown/md; text/txt,Research notes and attachment links,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
Search,Export,html; markdown/md; text/txt,Project-scoped search results,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
Project backup download/import-as-new,Export + import,PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2,Portable serialized project data and active uploaded files,ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson,65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download,Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply
Saved restore point create/download/restore,Export + restore,Same versioned project backup JSON,Recover a prior state inside the same project,ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController,Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership,Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care
Project backup download/import-as-new,Export + import,PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2,Portable serialized project data and active uploaded files,ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson,103 populated persistent collections; 108 entities/1388 fields; independent 183-owned-row census; exact uploaded/map bytes; reference/actor/source identity copy; real SQL rollback; HTTP download,Shared administrator illustration catalogue/files excluded with explicit warnings and inactive copied associations; no historical backup fixture; existing request/proxy limits still apply
Saved restore point create/download/restore,Export + restore,Same versioned project backup JSON,Recover a prior state inside the same project,ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController,Actual SQL safety/rollback; 103 populated collections; exact files; HTTP download/ownership; old snapshot/active work guards; retained account authority,Shared catalogue/files remain external; older points cannot recreate absent bytes; active jobs/imports/analysis/illustration generation refuse restore
Legacy structured JSON package,Import,PackageVersion 1.0 JSON,Create planning entities from explicitly structured external data,ImportsController; ImportService; ImportRepository,Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing,One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
Word manuscript structure API,Import + sync,Word Companion JSON structure/binding protocol,Create or sync Word-linked chapters/scenes and word counts,WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs,Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions,Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
Core Import from current Word document,Import,Chunked paragraph scan + approved structure/marker protocol,Retain source paragraphs and materialize approved canonical book structure,WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository,Existing 405-check parser/review/source coverage; real isolated SQL build/source protocol; canonical mapping and retry; exact long Unicode/CRLF/empty text; completed provenance restore; copy ownership and inactive bindings,External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
Story Intelligence reviewed Characters,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Locations,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Assets,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Relationships,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Knowledge,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Narrative,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Character/gallery images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Asset images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Book covers,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; BookCoverService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Floor-plan backgrounds,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; FloorPlanBackgroundImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Map reference images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; MapReferenceImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Character avatar crop,Image operation,Existing gallery raster -> WebP,Crop an avatar from a selected gallery image,VisualIdentityImageService,Avatar/gallery identity remap and file independence verified in backup SQL matrix,Crop UI/geometry is not a new acceptance claim
Story Intelligence reviewed Characters,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Story Intelligence reviewed Locations,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Story Intelligence reviewed Assets,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Story Intelligence reviewed Relationships,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Story Intelligence reviewed Knowledge,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Story Intelligence reviewed Narrative,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events,Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
Character/gallery images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,Four formats through production gallery and main-image services/SQL/files; real gallery HTTP binding/persistence; WebP fix; metadata; owner byte ledger; invalid/quota refusal; gallery tombstone/removal,Synthetic HTTP/service fixture; live browser acceptance unavailable; character main edit-form HTTP is not newly covered; 10 MiB source limit
Asset images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,PNG/JPG/JPEG/WebP production upload service with actual SQL/files; WebP output/thumbnail; owner byte ledger; invalid/quota refusal; removal; existing portable backup coverage,Service/SQL fixture; asset edit-form HTTP and live UI not newly covered; normalized WebP; 10 MiB source limit
Book covers,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; BookCoverService,PNG/JPG/JPEG/WebP production cover service with actual SQL/files; WebP cover/thumbnail; owner byte ledger; invalid/quota refusal; existing portable backup coverage,Service/SQL fixture; book edit-form HTTP and live UI not newly covered; normalized WebP; 10 MiB source limit
Floor-plan backgrounds,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; FloorPlanBackgroundImageService,Four formats through production service and actual HTTP/SQL/files; exact original encoded bytes; Unicode filename/path; invalid/missing and author/CSRF refusal without mutation,Preserves original PNG/JPG/JPEG/WebP; 10 MiB source limit; existing background workflow has no new quota/ledger claim; no live UI acceptance
Map reference images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; MapReferenceImageService,Four formats through production service and actual HTTP/SQL; real normalized WebP embedded bytes; owner boundary; invalid/missing input; quota and anti-forgery refusal,Synthetic HTTP/service fixture; no new live UI acceptance; 10 MiB source / 8 MiB stored and existing pixel limits
Character avatar crop,Image operation,Existing gallery raster -> WebP,Crop an avatar from a selected gallery image,VisualIdentityImageService,Four source formats/clamped/default crop geometry; real 256x256 WebP and source IDs; HTTP save/invalid source/remove; source gallery deletion clears avatar; denied requests unchanged,Production service/SQL and HTTP fixtures; physical crop gestures/live browser UI not new acceptance claims
Scene attachments,Upload/link,Uploaded file bytes or external URL,Scene-associated reference material,ScenesController; writer workspace/storage services,Empty and long Unicode attachments; external link metadata; exact backup bytes and storage ledger,External URLs are metadata; remote content is not downloaded or embedded
Solver review record,Export,JSON diagnostic record,Download one solver review record,WritingSolverReviewController,Existing solver review harness; no new HTTP data-transfer claim,Diagnostic workflow; not project backup or manuscript transfer
Admin full-chapter test text,Diagnostic input,Text upload,Administrator analysis preflight/test input,AdminController; full chapter test service,Not executed during this programme,Not a project import; paid analysis/generation deliberately not invoked

1 Workflow Direction Formats IntendedPurpose Implementation Verification Limits
7 WritingSession Export html; markdown/md; text/txt Scene writing-session brief ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
8 ResearchPack Export html; markdown/md; text/txt Research notes and attachment links ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
9 Search Export html; markdown/md; text/txt Project-scoped search results ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
10 Project backup download/import-as-new Export + import PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2 Portable serialized project data and active uploaded files ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson 65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download 103 populated persistent collections; 108 entities/1388 fields; independent 183-owned-row census; exact uploaded/map bytes; reference/actor/source identity copy; real SQL rollback; HTTP download Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply Shared administrator illustration catalogue/files excluded with explicit warnings and inactive copied associations; no historical backup fixture; existing request/proxy limits still apply
11 Saved restore point create/download/restore Export + restore Same versioned project backup JSON Recover a prior state inside the same project ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership Actual SQL safety/rollback; 103 populated collections; exact files; HTTP download/ownership; old snapshot/active work guards; retained account authority Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care Shared catalogue/files remain external; older points cannot recreate absent bytes; active jobs/imports/analysis/illustration generation refuse restore
12 Legacy structured JSON package Import PackageVersion 1.0 JSON Create planning entities from explicitly structured external data ImportsController; ImportService; ImportRepository Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
13 Word manuscript structure API Import + sync Word Companion JSON structure/binding protocol Create or sync Word-linked chapters/scenes and word counts WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
14 Core Import from current Word document Import Chunked paragraph scan + approved structure/marker protocol Retain source paragraphs and materialize approved canonical book structure WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository Existing 405-check parser/review/source coverage; real isolated SQL build/source protocol; canonical mapping and retry; exact long Unicode/CRLF/empty text; completed provenance restore; copy ownership and inactive bindings External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
15 Story Intelligence reviewed Characters Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
16 Story Intelligence reviewed Locations Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
17 Story Intelligence reviewed Assets Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
18 Story Intelligence reviewed Relationships Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
19 Story Intelligence reviewed Knowledge Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
20 Story Intelligence reviewed Narrative Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Existing focused review harness; persisted generation/candidate/evidence backup SQL round trips; production readers; canonical idempotence for Relationship/Knowledge and Narrative events Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work Review materialization is not an interchange file format; no new end-to-end acceptance of every module review action; raw provider JSON remains historical audit
21 Character/gallery images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; VisualIdentityImageService Active file bytes and portable backup paths verified; map normalization is covered separately Four formats through production gallery and main-image services/SQL/files; real gallery HTTP binding/persistence; WebP fix; metadata; owner byte ledger; invalid/quota refusal; gallery tombstone/removal Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit Synthetic HTTP/service fixture; live browser acceptance unavailable; character main edit-form HTTP is not newly covered; 10 MiB source limit
22 Asset images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; VisualIdentityImageService Active file bytes and portable backup paths verified; map normalization is covered separately PNG/JPG/JPEG/WebP production upload service with actual SQL/files; WebP output/thumbnail; owner byte ledger; invalid/quota refusal; removal; existing portable backup coverage Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit Service/SQL fixture; asset edit-form HTTP and live UI not newly covered; normalized WebP; 10 MiB source limit
23 Book covers Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; BookCoverService Active file bytes and portable backup paths verified; map normalization is covered separately PNG/JPG/JPEG/WebP production cover service with actual SQL/files; WebP cover/thumbnail; owner byte ledger; invalid/quota refusal; existing portable backup coverage Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit Service/SQL fixture; book edit-form HTTP and live UI not newly covered; normalized WebP; 10 MiB source limit
24 Floor-plan backgrounds Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; FloorPlanBackgroundImageService Active file bytes and portable backup paths verified; map normalization is covered separately Four formats through production service and actual HTTP/SQL/files; exact original encoded bytes; Unicode filename/path; invalid/missing and author/CSRF refusal without mutation Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit Preserves original PNG/JPG/JPEG/WebP; 10 MiB source limit; existing background workflow has no new quota/ledger claim; no live UI acceptance
25 Map reference images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; MapReferenceImageService Active file bytes and portable backup paths verified; map normalization is covered separately Four formats through production service and actual HTTP/SQL; real normalized WebP embedded bytes; owner boundary; invalid/missing input; quota and anti-forgery refusal Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit Synthetic HTTP/service fixture; no new live UI acceptance; 10 MiB source / 8 MiB stored and existing pixel limits
26 Character avatar crop Image operation Existing gallery raster -> WebP Crop an avatar from a selected gallery image VisualIdentityImageService Avatar/gallery identity remap and file independence verified in backup SQL matrix Four source formats/clamped/default crop geometry; real 256x256 WebP and source IDs; HTTP save/invalid source/remove; source gallery deletion clears avatar; denied requests unchanged Crop UI/geometry is not a new acceptance claim Production service/SQL and HTTP fixtures; physical crop gestures/live browser UI not new acceptance claims
27 Scene attachments Upload/link Uploaded file bytes or external URL Scene-associated reference material ScenesController; writer workspace/storage services Empty and long Unicode attachments; external link metadata; exact backup bytes and storage ledger External URLs are metadata; remote content is not downloaded or embedded
28 Solver review record Export JSON diagnostic record Download one solver review record WritingSolverReviewController Existing solver review harness; no new HTTP data-transfer claim Diagnostic workflow; not project backup or manuscript transfer
29 Admin full-chapter test text Diagnostic input Text upload Administrator analysis preflight/test input AdminController; full chapter test service Not executed during this programme Not a project import; paid analysis/generation deliberately not invoked

View File

@ -336,3 +336,17 @@ Illustration checkpoint: build zero warnings/errors; full 405-check regression h
Expanded the real production MapRepository fixture from two marker/area features to four features, including a connected Path, endpoint markers, an unplaced locked marker with hidden label/offsets and opaque geometry properties. The source map links to an actual FloorPlan, and its journey references the connected route. Copy checks verify route endpoints, journey identity, remapped floor-plan identity, exact geometry and label/placement/lock state; the independent stored-field matrix also covers in-place restore. Added three malformed preview cases: area used as a journey route, foreign route endpoint and foreign floor-plan reference. Total malformed previews now 53, all before allocation.
Build zero warnings/errors; complete 103-collection copy/in-place SQL run passed (`/tmp/plotdirector-phase2-map-routes.log`). This is a specialist fixture expansion, with no application change. Last full 405 regression gate remains the illustration commit. No standalone label geometry is claimed: the application's declared geometries are Marker, Area and Path; label settings are attached to those features.
## Ordinary image workflows and WebP stream lifecycle — 4 November
Added an explicit synthetic-only `--image-transfer-only` specialist mode, using production gallery/main-image/asset/cover/background/map upload and avatar crop services, repositories and actual files. Four extensions (PNG, JPG, JPEG, WebP) cover 28 upload/crop cases. Gallery/main/asset/book outputs are normalized WebP; floor backgrounds instead preserve the exact original encoded bytes and Unicode filename. Map references remain embedded normalized WebP with existing limits and author-scoped access.
Confirmed a real WebP upload exception in production gallery code: codec creation can close the managed input stream, then the uploader rewinds that closed stream to decode a second time. PNG/JPG/JPEG passed; WebP failed at MemoryStream.set_Position / VisualIdentityImageService line 316. The same pattern existed in asset and book cover uploads. All three paths now decode through the already format-validated codec. No new raster formats, limits or decoding policy introduced. Reproduction `/tmp/plotdirector-phase2-image-webp-repro.log`; repaired format matrix `/tmp/plotdirector-phase2-image-webp-fixed.log`.
The expanded HTTP fixture passed 40 actual MVC requests across gallery/background/map uploads, avatar save/remove and gallery delete, including persisted rows/encoded bytes, Unicode filename binding, source identity, crop clamping, tombstones and avatar cleanup. Other-author, anonymous and missing anti-forgery requests are refused without SQL/file mutation. Five invalid inputs across five upload paths (25 cases), including renamed GIF, are refused with exact source SQL/ledger/file-byte equality. Five quota-refusal cases exercise service handling of the quota decision without mutation; this is not a new end-to-end subscription calculation claim. Active ledger rows use the actual project owner and stored file lengths, with no repeated active fixed paths. Floor's existing original-file workflow is separate and no quota/ledger change is claimed.
Final prior-to-capture HTTP run passed `/tmp/plotdirector-phase2-image-avatar-http.log`; final actual-upload backup capture and generated HTTP inventory are being checked next. Physical UI crop gestures, live browser acceptance and book/asset edit-form HTTP are explicitly outside these new service/HTTP claims. No provider calls or Development/Production writes.
Image checkpoint: final production service/SQL and 40-case HTTP fixture passed, including backup capture of 27 owned files and four embedded map images (`/tmp/plotdirector-phase2-image-capture.log`). The initial capture assertion incorrectly disallowed the fixture's legitimate empty text attachment; corrected to exact physical-byte and SHA-256 comparison, including zero length. No application defect was inferred from that fixture mistake. Build zero warnings/errors (`/tmp/plotdirector-phase2-build-image-capture.log`); full 405 regression checks passed, exit 0 (`/tmp/plotdirector-phase2-tests-image-workflows.log`). Per-case inventories: `2026-11-03-phase2-image-coverage.csv` and `2026-11-03-phase2-image-http-coverage.csv`.
Next independent check: concurrent author edits between the separate core/map/source/metadata backup reads. Current repository has no encompassing read transaction; test for a mixed-version snapshot before choosing a repair. Do not infer an atomic filesystem snapshot from a consistent SQL read.

View File

@ -0,0 +1,138 @@
using System.Reflection;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using System.Security.Cryptography;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
using SkiaSharp;
// Explicit specialist fixture. Uses production upload/crop services, stored procedures and synthetic-only files/SQL.
internal static class ImageTransferDatabaseTests
{
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class
{var result=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)result).Handler=handler;return result;}
private static IFormFile Upload(byte[] bytes,string name)=>new FormFile(new MemoryStream(bytes),0,bytes.Length,"image",name){Headers=new HeaderDictionary(),ContentType="application/octet-stream"};
private static byte[] Raster(SKEncodedImageFormat format)
{
using var bitmap=new SKBitmap(96,64);
for(var y=0;y<bitmap.Height;y++)for(var x=0;x<bitmap.Width;x++)bitmap.SetPixel(x,y,new SKColor((byte)(x*2),(byte)(y*3),(byte)(x+y)));
using var image=SKImage.FromBitmap(bitmap);using var data=image.Encode(format,90);return data.ToArray();
}
internal static async Task RunAsync(ISqlConnectionFactory factory,IUploadStorageService uploads,int owner,int other,int project,int bookID,int characterID,int assetID,int planID)
{
using var db=factory.CreateConnection();
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305"
&& await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Image fixtures require verified synthetic database.");
var allowQuota=true;
var quotas=Proxy<ISubscriptionService>((name,args)=>name=="CanUploadFileAsync" ? Task.FromResult(allowQuota ? StorageLimitResult.AllowedResult(0,1_000_000_000) : StorageLimitResult.Blocked(100,100,(long)args![1]!)) : throw new NotSupportedException(name));
var activity=Proxy<IProjectActivityService>((name,args)=>name=="RecordAsync" ? Task.CompletedTask : throw new NotSupportedException(name));
var projects=new ProjectRepository(factory);var characters=new CharacterRepository(factory);var assets=new AssetRepository(factory);var books=new BookRepository(factory);var plans=new FloorPlanRepository(factory);var maps=new MapRepository(factory);
var files=new UserFileRepository(factory);var collaboration=new ProjectCollaborationRepository(factory);
var visual=new VisualIdentityImageService(uploads,collaboration,quotas,files,characters,assets,NullLogger<VisualIdentityImageService>.Instance);
var covers=new BookCoverService(uploads,collaboration,quotas,files,books,NullLogger<BookCoverService>.Instance);
var backgrounds=new FloorPlanBackgroundImageService(uploads,NullLogger<FloorPlanBackgroundImageService>.Instance);
var floors=new FloorPlanService(projects,new SceneRepository(factory),new SceneFloorPlanOccupancyRepository(factory),plans,new LocationRepository(factory),characters,backgrounds,activity);
var references=new MapReferenceImageService(maps,quotas);
var currentUser=Proxy<ICurrentUserService>((name,args)=>name=="get_UserId" ? (int?)owner : throw new NotSupportedException(name));
var characterService=new CharacterService(projects,books,characters,collaboration,quotas,activity,currentUser,visual,
Proxy<ICharacterEnrichmentService>((name,args)=>throw new NotSupportedException(name)),Proxy<ITimelineRepository>((name,args)=>throw new NotSupportedException(name)));
var floorID=await db.ExecuteScalarAsync<int>("SELECT TOP(1) FloorPlanFloorID FROM dbo.FloorPlanFloors WHERE FloorPlanID=@planID ORDER BY FloorPlanFloorID",new{planID});
async Task<Character> Character()=>await db.QuerySingleAsync<Character>("SELECT * FROM dbo.Characters WHERE CharacterID=@characterID AND ProjectID=@project",new{characterID,project});
async Task<StoryAsset> Asset()=>await db.QuerySingleAsync<StoryAsset>("SELECT * FROM dbo.StoryAssets WHERE StoryAssetID=@assetID AND ProjectID=@project",new{assetID,project});
async Task<Book> Book()=>await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID AND ProjectID=@project",new{bookID,project});
string Physical(string path)=>uploads.TryResolvePublicPath(path,"uploads") ?? throw new InvalidOperationException("Invalid synthetic upload path.");
void Webp(string? path,int? width=null,int? height=null)
{
Check(path is not null && path.EndsWith(".webp"),"Normalized output is WebP.");
using var codec=SKCodec.Create(Physical(path!));Check(codec is not null && codec.EncodedFormat==SKEncodedImageFormat.Webp,"Output has actual WebP encoding.");
if(width.HasValue)Check(codec!.Info.Width==width && codec.Info.Height==height,"Avatar has expected dimensions.");
}
var coverage=new List<string>{"Workflow,Input,Execution,Verified,Limits"};
var inputs=new[]{(".png",SKEncodedImageFormat.Png),(".jpg",SKEncodedImageFormat.Jpeg),(".jpeg",SKEncodedImageFormat.Jpeg),(".webp",SKEncodedImageFormat.Webp)};
foreach(var (extension,format) in inputs)
{
var bytes=Raster(format);var name="Synthetic 雨 café"+extension.ToUpperInvariant();
var gallery=await characterService.UploadCharacterImageAsync(new CharacterImageUploadViewModel{CharacterID=characterID,ImageUpload=Upload(bytes,name),Caption="Caption Ω 🖋"});
Check(gallery.Succeeded && gallery.CharacterImageID.HasValue,"Gallery accepts "+extension);
var image=await characters.GetCharacterImageAsync(gallery.CharacterImageID!.Value);Check(image is not null && image.Caption=="Caption Ω 🖋","Gallery metadata retained.");Webp(image!.ImagePath);Webp(image.ThumbnailPath);
coverage.Add($"Character gallery,{extension},Production service + real SQL/files,WebP image/thumbnail and Unicode metadata,HTTP/UI acceptance separate");
Check((await visual.UploadCharacterImageAsync(await Character(),Upload(bytes,name))).Succeeded,"Legacy character image accepts "+extension);var character=await Character();Webp(character.ImagePath);Webp(character.ThumbnailPath);
coverage.Add($"Character main image,{extension},Production service + real SQL/files,WebP image/thumbnail and gallery source,HTTP/UI acceptance separate");
Check((await visual.UploadAssetImageAsync(await Asset(),Upload(bytes,name))).Succeeded,"Asset accepts "+extension);var asset=await Asset();Webp(asset.ImagePath);Webp(asset.ThumbnailPath);
coverage.Add($"Asset image,{extension},Production service + real SQL/files,WebP image and thumbnail,HTTP/UI acceptance separate");
Check((await covers.UploadCoverAsync(await Book(),Upload(bytes,name))).Succeeded,"Book cover accepts "+extension);var book=await Book();Webp(book.CoverStandardPath);Webp(book.CoverThumbnailPath);
coverage.Add($"Book cover,{extension},Production service + real SQL/files,WebP cover and thumbnail,HTTP/UI acceptance separate");
var background=await floors.UploadBackgroundAsync(planID,floorID,Upload(bytes,name));Check(background.Succeeded && background.StoragePath is not null,"Floor background accepts "+extension);
var storedBackground=await File.ReadAllBytesAsync(Physical(background.StoragePath!));
Check(bytes.SequenceEqual(storedBackground),"Floor background preserves original encoded bytes.");
var floor=await plans.GetFloorAsync(floorID);Check(floor!.BackgroundImagePath==background.StoragePath && floor.BackgroundImageOriginalFileName==name,"Floor background path/name persisted.");
coverage.Add($"Floor background,{extension},Production service + real SQL/files,Exact original bytes and filename,Existing workflow preserves input format");
var reference=await references.UploadAsync(project,owner,Upload(bytes,name));var saved=(await maps.GetImageAsync(project,owner,reference.ImageID))!;
Check(saved.ContentType=="image/webp" && MapReferenceImageService.ValidBackupImage(saved),"Map reference normalizes and stores valid encoded bytes.");
try{var foreign=await maps.GetImageAsync(project,other,reference.ImageID);Check(foreign is null,"Map reference bytes respect author boundary.");}
catch(SqlException ex) when(ex.Number==51000){}
coverage.Add($"Map reference,{extension},Production service + real SQL,WebP embedded bytes and author boundary,HTTP/UI acceptance separate");
var crop=extension switch {".png"=>(0,0,32),".jpg"=>(20,12,40),".jpeg"=>(-100,10000,10000),_=>(0,0,0)};
var avatar=await visual.CreateCharacterAvatarAsync(await Character(),image,crop.Item1,crop.Item2,crop.Item3);Check(avatar.Succeeded,"Avatar crop accepts supported source/clamped bounds/default size.");
character=await Character();Check(character.AvatarSourceCharacterImageID==image.CharacterImageID,"Avatar retains gallery source identity.");Webp(character.AvatarImagePath,256,256);
Console.WriteLine("PASS supported image/crop source "+extension);
coverage.Add($"Character avatar,{extension},Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate");
}
var tracked=(await db.QueryAsync<UserFile>("SELECT * FROM dbo.UserFile WHERE ProjectID=@project AND IsDeleted=0",new{project})).ToList();
foreach(var file in tracked.Where(x=>x.EntityType!="MapReferenceImage"))
Check(file.UserID==owner && File.Exists(Physical(file.StoragePath)) && new FileInfo(Physical(file.StoragePath)).Length==file.FileSizeBytes,"Active ledger uses project owner and actual stored bytes: "+file.StoragePath);
Check(tracked.GroupBy(x=>x.StoragePath).All(group=>group.Count()==1),"Replaced fixed image paths have one active ledger row.");
async Task<string> StateAsync()
{
var state="";
foreach(var table in new[]{"Characters","CharacterImages","StoryAssets","Books","UserFile","MapReferenceImages"})
state+=await db.ExecuteScalarAsync<string>($"SELECT * FROM dbo.[{table}] WHERE ProjectID=@project ORDER BY 1 FOR JSON PATH,INCLUDE_NULL_VALUES",new{project});
state+=await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.FloorPlanFloors WHERE FloorPlanID=@planID ORDER BY FloorPlanFloorID FOR JSON PATH,INCLUDE_NULL_VALUES",new{planID});
return state+string.Join('|',Directory.GetFiles(uploads.UploadsRootPath,"*",SearchOption.AllDirectories).Order().Select(path=>path+":"+Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))));
}
var beforeInvalid=await StateAsync();
var invalids=new[]{("empty.png",Array.Empty<byte>()),("corrupt.png",new byte[]{1,2,3,4}),("unsupported.gif",Raster(SKEncodedImageFormat.Png)),("oversize.png",new byte[10*1024*1024+1]),("renamed.png",Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"))};
foreach(var (name,bytes) in invalids)
{
Check(!(await visual.UploadCharacterGalleryImageAsync(await Character(),Upload(bytes,name),null)).Succeeded,"Gallery refuses "+name);
Check(!(await visual.UploadAssetImageAsync(await Asset(),Upload(bytes,name))).Succeeded,"Asset refuses "+name);
Check(!(await covers.UploadCoverAsync(await Book(),Upload(bytes,name))).Succeeded,"Cover refuses "+name);
Check(!(await floors.UploadBackgroundAsync(planID,floorID,Upload(bytes,name))).Succeeded,"Background refuses "+name);
try{await references.UploadAsync(project,owner,Upload(bytes,name));throw new InvalidOperationException("Map accepted "+name);}catch(InvalidDataException){}
}
Check(beforeInvalid==await StateAsync(),"Rejected upload inputs preserve all SQL fields/ledger and every existing file byte without orphan files.");
allowQuota=false;
var png=Raster(SKEncodedImageFormat.Png);
Check(!(await visual.UploadCharacterGalleryImageAsync(await Character(),Upload(png,"quota.png"),null)).Succeeded,"Gallery quota refused.");
Check(!(await visual.UploadAssetImageAsync(await Asset(),Upload(png,"quota.png"))).Succeeded,"Asset quota refused.");
Check(!(await covers.UploadCoverAsync(await Book(),Upload(png,"quota.png"))).Succeeded,"Cover quota refused.");
Check(!(await visual.CreateCharacterAvatarAsync(await Character(),(await characters.GetCharacterImageAsync((await Character()).AvatarSourceCharacterImageID!.Value))!,0,0,32)).Succeeded,"Avatar quota refused.");
// Use a new raster to avoid intentional map content deduplication bypassing an additional quota allocation.
var distinct=png.ToArray();using(var bitmap=new SKBitmap(12,13)){bitmap.Erase(SKColors.Red);using var image=SKImage.FromBitmap(bitmap);using var data=image.Encode(SKEncodedImageFormat.Png,100);distinct=data.ToArray();}
try{await references.UploadAsync(project,owner,Upload(distinct,"quota.png"));throw new InvalidOperationException("Map quota accepted.");}catch(InvalidDataException){}
Check(beforeInvalid==await StateAsync(),"Quota refusals preserve all SQL fields/ledger and every existing file byte without orphan files.");
allowQuota=true;
await ImageUploadHttpTests.RunAsync(factory,uploads,characterService,floors,references,owner,other,project,characterID,planID,floorID,inputs.Select(input=>(input.Item1,Raster(input.Item2))).ToArray(),StateAsync);
var characterBefore=await Character();
var foreignImage=new CharacterImage{CharacterID=characterID+1,ImagePath=characterBefore.ImagePath!};
Check(!(await visual.CreateCharacterAvatarAsync(characterBefore,foreignImage,0,0,32)).Succeeded,"Cross-character crop source refused.");
await visual.RemoveCharacterAvatarAsync(characterBefore);Check((await Character()).AvatarImagePath is null,"Avatar removal persists.");
var recent=(await db.QueryAsync<CharacterImage>("SELECT * FROM dbo.CharacterImages WHERE CharacterID=@characterID AND ImagePath=@path AND IsDeleted=0 ORDER BY CharacterImageID DESC",new{characterID,path=(await Character()).ImagePath})).First();
await characterService.DeleteCharacterImageAsync(recent.CharacterImageID);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterImageID=@id AND IsDeleted=1",new{id=recent.CharacterImageID})==1,"Gallery deletion retains tombstone.");
Check((await Character()).ImagePath is null,"Deleting the current main gallery image clears its canonical reference before deleting bytes.");
await visual.RemoveAssetImageAsync(await Asset());Check((await Asset()).ImagePath is null,"Asset image removal persists.");
var backup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,owner))!;
await new ProjectBackupFiles(uploads).CaptureAsync(backup);
Check(backup.Files.Count>0,"Actual upload/crop/removal output includes owned files.");
foreach(var file in backup.Files)
Check(file.Data.SequenceEqual(File.ReadAllBytes(Physical(file.Path))) && file.Sha256==Convert.ToHexString(SHA256.HashData(file.Data)),"Actual image lifecycle backup retains exact file bytes/checksums including valid empty attachments.");
Console.WriteLine($"PASS actual image lifecycle backup capture: {backup.Files.Count} owned files plus {backup.Data.MapReferenceImages.Count} embedded map images.");
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-image-coverage.csv",coverage);
Console.WriteLine($"PASS image workflows: {coverage.Count-1} supported format/crop cases; 25 invalid uploads; five quota refusals; owner byte ledger; cross-character crop; removal/tombstones. Service/SQL and HTTP fixtures only; no live UI acceptance claim.");
}
}

View File

@ -0,0 +1,137 @@
using System.Collections.Concurrent;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using SkiaSharp;
using PlotLine.Models;
using Dapper;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Services;
// Real MVC binding, anti-forgery and project-access filters; header identities exist only in this synthetic host.
internal static class ImageUploadHttpTests
{
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
internal static async Task RunAsync(ISqlConnectionFactory factory,IUploadStorageService uploads,ICharacterService characters,IFloorPlanService floors,MapReferenceImageService images,int owner,int other,int project,int character,int plan,int floor,(string Extension,byte[] Bytes)[] inputs,Func<Task<string>> state)
{
using(var db=factory.CreateConnection())
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"HTTP image fixtures require verified synthetic database.");
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});
builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();
builder.Services.AddAuthentication("ImageFixture").AddCookie("ImageFixture",options=>options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;return Task.CompletedTask;});
builder.Services.AddAuthorization();builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(factory);builder.Services.AddSingleton(characters);builder.Services.AddSingleton(floors);builder.Services.AddSingleton(images);
builder.Services.AddScoped<ICurrentUserService,CurrentUserService>();builder.Services.AddScoped<IProjectAccessRepository,ProjectAccessRepository>();builder.Services.AddScoped<IProjectAccessService,ProjectAccessService>();
builder.Services.AddScoped<IProjectRepository,ProjectRepository>();builder.Services.AddScoped<ILocationRepository,LocationRepository>();builder.Services.AddScoped<IFloorPlanRepository,FloorPlanRepository>();builder.Services.AddScoped<MapRepository>();builder.Services.AddScoped<ProjectAccessFilter>();
builder.Services.AddControllersWithViews(options=>options.Filters.Add<ProjectAccessFilter>()).AddApplicationPart(typeof(CharactersController).Assembly);
await using var app=builder.Build();var errors=new ConcurrentQueue<string>();
app.Use(async(context,next)=>
{
if(int.TryParse(context.Request.Headers["X-Synthetic-Actor"],out var actor) && (actor==owner || actor==other))context.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,actor.ToString())],"ImageFixture"));
try{await next();}catch(Exception ex){errors.Enqueue(ex.GetType().Name+": "+ex.Message);context.Response.StatusCode=500;await context.Response.WriteAsync("Synthetic image fixture failed.");}
});
app.UseAuthorization();app.MapGet("/fixture/token",(IAntiforgery antiforgery,HttpContext context)=>antiforgery.GetAndStoreTokens(context).RequestToken!);
app.MapControllerRoute("default","{controller=Characters}/{action=Details}/{id?}");await app.StartAsync();
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
using var client=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(address)};
async Task<string> Token(int actor)
{
using var request=new HttpRequestMessage(HttpMethod.Get,"/fixture/token");request.Headers.Add("X-Synthetic-Actor",actor.ToString());
using var response=await client.SendAsync(request);Check(response.IsSuccessStatusCode,"Anti-forgery fixture token available.");return await response.Content.ReadAsStringAsync();
}
var endpoints=new[]{
(Route:"/Characters/UploadImage",Field:"ImageUpload",Fields:new Dictionary<string,string>{{"CharacterID",character.ToString()},{"Caption","HTTP caption Ω 🖋"}},Success:HttpStatusCode.Redirect),
(Route:"/FloorPlans/UploadBackground",Field:"backgroundImage",Fields:new Dictionary<string,string>{{"floorPlanId",plan.ToString()},{"floorPlanFloorId",floor.ToString()}},Success:HttpStatusCode.Redirect),
(Route:"/Maps/UploadReference",Field:"referenceImage",Fields:new Dictionary<string,string>{{"projectId",project.ToString()}},Success:HttpStatusCode.OK)
};
var coverage=new List<string>{"Route,FileName,Actor,Antiforgery,SourceImageID,HTTP"};
static string Csv(string value)=>"\""+value.Replace("\"","\"\"")+"\"";
async Task<HttpResponseMessage> Post(string route,string field,Dictionary<string,string> fields,byte[]? bytes,string name,int? actor,bool includeToken=true)
{
var token=actor.HasValue && includeToken ? await Token(actor.Value) : null;
using var request=new HttpRequestMessage(HttpMethod.Post,route);if(actor.HasValue)request.Headers.Add("X-Synthetic-Actor",actor.Value.ToString());
using var body=new MultipartFormDataContent();foreach(var pair in fields)body.Add(new StringContent(pair.Value,Encoding.UTF8),pair.Key);
if(token is not null)body.Add(new StringContent(token),"__RequestVerificationToken");
if(bytes is not null)body.Add(new ByteArrayContent(bytes),field,name);request.Content=body;var response=await client.SendAsync(request);
coverage.Add(string.Join(',',new[]{route,name,actor==owner?"Owner":actor==other?"Other author":"Anonymous",includeToken?"Present when authenticated":"Absent",fields.GetValueOrDefault("CharacterImageID",""),((int)response.StatusCode).ToString()}.Select(Csv)));
return response;
}
var cases=0;
foreach(var endpoint in endpoints)
{
foreach(var input in inputs)
{
using var verify=factory.CreateConnection();
var galleryCount=await verify.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterID=@character AND IsDeleted=0",new{character});
using var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,input.Bytes,"HTTP café 雨"+input.Extension,owner);
Check(response.StatusCode==endpoint.Success,$"HTTP image {endpoint.Route} {input.Extension}: {(int)response.StatusCode}; {string.Join(" | ",errors)}");cases++;
if(endpoint.Field=="ImageUpload")
{
Check(await verify.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterID=@character AND IsDeleted=0",new{character})==galleryCount+1,"HTTP gallery upload creates a real persisted image.");
var path=await verify.ExecuteScalarAsync<string>("SELECT TOP(1) ImagePath FROM dbo.CharacterImages WHERE CharacterID=@character AND Caption=N'HTTP caption Ω 🖋' ORDER BY CharacterImageID DESC",new{character});
using var codec=SKCodec.Create(uploads.TryResolvePublicPath(path,"uploads/characters")!);Check(codec is not null && codec.EncodedFormat==SKEncodedImageFormat.Webp,"HTTP gallery stores actual WebP output.");
}
else if(endpoint.Field=="backgroundImage")
{
var saved=await verify.QuerySingleAsync<FloorPlanFloor>("SELECT * FROM dbo.FloorPlanFloors WHERE FloorPlanFloorID=@floor",new{floor});
var bytes=await File.ReadAllBytesAsync(uploads.TryResolvePublicPath(saved.BackgroundImagePath,"uploads/floor-plans")!);
Check(input.Bytes.SequenceEqual(bytes) && saved.BackgroundImageOriginalFileName=="HTTP café 雨"+input.Extension,"HTTP floor preserves bytes and bound Unicode filename.");
}
else
{
var result=JsonSerializer.Deserialize<MapReferenceImage>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true});
var saved=result is null ? null : await new MapRepository(factory).GetImageAsync(project,owner,result.ImageID);
Check(saved is not null && MapReferenceImageService.ValidBackupImage(saved),"HTTP map response resolves to actual valid persisted image bytes.");
}
}
var before=await state();
using(var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,inputs[0].Bytes,"foreign.png",other))Check(response.StatusCode==HttpStatusCode.NotFound,"Other author cannot upload to "+endpoint.Route);
using(var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,inputs[0].Bytes,"anonymous.png",null))Check(response.StatusCode==HttpStatusCode.Unauthorized,"Anonymous image upload refused.");
using(var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,inputs[0].Bytes,"no-token.png",owner,false))Check(response.StatusCode==HttpStatusCode.BadRequest,"Image upload requires anti-forgery token.");
Check(before==await state(),"Denied HTTP image uploads preserve SQL/file state.");cases+=3;
using(var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,new byte[]{1,2,3},"corrupt.png",owner))Check(response.StatusCode==(endpoint.Success==HttpStatusCode.OK ? HttpStatusCode.BadRequest : HttpStatusCode.Redirect),"Corrupt image produces normal validation response.");
using(var response=await Post(endpoint.Route,endpoint.Field,endpoint.Fields,null,"missing.png",owner))Check(response.StatusCode==(endpoint.Success==HttpStatusCode.OK ? HttpStatusCode.BadRequest : HttpStatusCode.Redirect),"Missing image produces normal validation response.");
Check(before==await state(),"Invalid/missing HTTP images preserve SQL/file state.");cases+=2;
}
using(var verify=factory.CreateConnection())
{
var source=await verify.QueryFirstAsync<CharacterImage>("SELECT * FROM dbo.CharacterImages WHERE CharacterID=@character AND Caption=N'HTTP caption Ω 🖋' AND IsDeleted=0 ORDER BY CharacterImageID DESC",new{character});
var cropFields=new Dictionary<string,string>{{"CharacterID",character.ToString()},{"CharacterImageID",source.CharacterImageID.ToString()},{"CropX","-100"},{"CropY","10000"},{"CropSize","10000"}};
var operations=new[]{(Route:"/Characters/SaveAvatar",Fields:cropFields),(Route:"/Characters/DeleteImage",Fields:new Dictionary<string,string>{{"imageId",source.CharacterImageID.ToString()},{"characterId",character.ToString()}}),(Route:"/Characters/RemoveAvatar",Fields:new Dictionary<string,string>{{"id",character.ToString()}})};
foreach(var operation in operations)
{
var before=await state();
using(var response=await Post(operation.Route,"",operation.Fields,null,"",other))Check(response.StatusCode==HttpStatusCode.NotFound,"Avatar/gallery change denies other author.");
using(var response=await Post(operation.Route,"",operation.Fields,null,"",null))Check(response.StatusCode==HttpStatusCode.Unauthorized,"Avatar/gallery change requires authentication.");
using(var response=await Post(operation.Route,"",operation.Fields,null,"",owner,false))Check(response.StatusCode==HttpStatusCode.BadRequest,"Avatar/gallery change requires anti-forgery.");
Check(before==await state(),"Denied avatar/gallery changes preserve SQL/files.");cases+=3;
}
using(var response=await Post("/Characters/SaveAvatar","",cropFields,null,"",owner))Check(response.StatusCode==HttpStatusCode.Redirect && response.Headers.Location!.OriginalString.Contains("/Characters/Details"),"HTTP avatar saves through production model/service.");cases++;
var saved=await verify.QuerySingleAsync<Character>("SELECT * FROM dbo.Characters WHERE CharacterID=@character",new{character});
using(var codec=SKCodec.Create(uploads.TryResolvePublicPath(saved.AvatarImagePath,"uploads/characters")!))Check(codec is not null && codec.EncodedFormat==SKEncodedImageFormat.Webp && codec.Info.Width==256 && codec.Info.Height==256 && saved.AvatarSourceCharacterImageID==source.CharacterImageID,"HTTP avatar stores crop and source identity.");
var beforeInvalidCrop=await state();var invalidCrop=new Dictionary<string,string>(cropFields);invalidCrop["CharacterImageID"]="0";
using(var response=await Post("/Characters/SaveAvatar","",invalidCrop,null,"",owner))Check(response.StatusCode==HttpStatusCode.Redirect && response.Headers.Location!.OriginalString.Contains("/Characters/CropAvatar"),"HTTP invalid crop source returns validation navigation.");
Check(beforeInvalidCrop==await state(),"Invalid avatar source preserves SQL/files.");cases++;
using(var response=await Post(operations[1].Route,"",operations[1].Fields,null,"",owner))Check(response.StatusCode==HttpStatusCode.Redirect,"HTTP gallery deletion completes.");cases++;
saved=await verify.QuerySingleAsync<Character>("SELECT * FROM dbo.Characters WHERE CharacterID=@character",new{character});
Check(saved.AvatarImagePath is null && saved.AvatarSourceCharacterImageID is null && await verify.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterImageID=@id AND IsDeleted=1",new{id=source.CharacterImageID})==1,"HTTP deleting current avatar source clears avatar and retains gallery tombstone.");
Check(!File.Exists(uploads.TryResolvePublicPath(source.ImagePath,"uploads/characters")),"HTTP gallery deletion removes source bytes.");
using(var response=await Post(operations[2].Route,"",operations[2].Fields,null,"",owner))Check(response.StatusCode==HttpStatusCode.Redirect,"HTTP avatar removal completes.");cases++;
}
Check(errors.IsEmpty,"No HTTP image fixture exceptions: "+string.Join(" | ",errors));
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-image-http-coverage.csv",coverage);
await app.StopAsync();Console.WriteLine($"PASS {cases} actual HTTP image cases: four formats across gallery/background/map; avatar save/remove and gallery deletion; real MVC/anti-forgery/access filters; invalid inputs; no denied-request mutation.");
}
}

View File

@ -73,7 +73,7 @@ if (args.Contains("--maps-story-dev-fixture"))
if(args.Contains("--project-transfer-database"))
{
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only"), args.Contains("--core-import-only")); }
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only"), args.Contains("--core-import-only"), args.Contains("--image-transfer-only")); }
catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; }
return;
}

View File

@ -18,7 +18,7 @@ internal static class ProjectTransferDatabaseTests
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
static T Proxy<T>(Func<string, object?[]?, object?> handler) where T : class
{ var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; }
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false)
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false, bool imagesOnly = false)
{
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
@ -158,6 +158,12 @@ internal static class ProjectTransferDatabaseTests
await db.ExecuteAsync("UPDATE dbo.SceneAttachments SET FilePath=@attachment WHERE SceneID=@scene;INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,FilePath) SELECT @scene,MIN(SceneAttachmentTypeID),N'Empty text attachment',@emptyAttachment FROM dbo.SceneAttachmentTypes",new{scene,attachment,emptyAttachment});
async Task<string> AccountStateAsync()=>await db.ExecuteScalarAsync<string>("SELECT (SELECT * FROM dbo.UserOnboardingState WHERE UserID=@user FOR JSON PATH) AS Onboarding,(SELECT * FROM dbo.StoryIntelligenceConsents WHERE ProjectID=@project FOR JSON PATH) AS Consents,(SELECT * FROM dbo.StoryIntelligenceJobs WHERE ProjectID=@project FOR JSON PATH) AS Jobs,(SELECT * FROM dbo.ProjectActivity WHERE ProjectID=@project ORDER BY ProjectActivityID FOR JSON PATH) AS Activity FOR JSON PATH,WITHOUT_ARRAY_WRAPPER",new{user,project}) ?? throw new InvalidOperationException("Account state snapshot missing.");
var originalAccountState=await AccountStateAsync();
if(imagesOnly)
{
try{await ImageTransferDatabaseTests.RunAsync(factory,uploads,user,importingUser,project,book,character,asset,floorPlan);}
catch(Exception error){Console.Error.WriteLine(error.StackTrace);throw;}
return;
}
var before=(await backups.GetProjectBackupAsync(project,user))!;
await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported.");
var retainedRun=before.Data.StoryIntelligenceRuns.Single();

View File

@ -85,8 +85,9 @@ public sealed class BookCoverService(
return new(false, "Cover image must be a valid JPG, PNG or WebP file.");
}
memory.Position = 0;
bitmap = SKBitmap.Decode(memory) ?? throw new InvalidDataException();
// WebP codecs can release the managed input stream; decode through the inspected codec.
bitmap = SKBitmap.Decode(codec) ?? throw new InvalidDataException();
}
catch (Exception ex) when (ex is InvalidDataException or ArgumentException)
{

View File

@ -215,8 +215,9 @@ public sealed class VisualIdentityImageService(
return new(false, "Image must be a valid JPG, PNG or WebP file.");
}
memory.Position = 0;
bitmap = SKBitmap.Decode(memory) ?? throw new InvalidDataException();
// WebP codecs can release the managed input stream; decode through the inspected codec.
bitmap = SKBitmap.Decode(codec) ?? throw new InvalidDataException();
}
catch (Exception ex) when (ex is InvalidDataException or ArgumentException)
{
@ -313,8 +314,9 @@ public sealed class VisualIdentityImageService(
return new(false, "Image must be a valid JPG, PNG or WebP file.");
}
memory.Position = 0;
bitmap = SKBitmap.Decode(memory) ?? throw new InvalidDataException();
// WebP codecs can release the managed input stream; decode through the inspected codec.
bitmap = SKBitmap.Decode(codec) ?? throw new InvalidDataException();
}
catch (Exception ex) when (ex is InvalidDataException or ArgumentException)
{