pdf: remove signature creation feature
- Commit
8a5b8b064a62301f60da56434ab3703587d8f497- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-30 01:37 UTC (4 months ago)
- Parents
1a67468
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex c458744320..c5ffbdce05 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -12,7 +12,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown-import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress+import androidx.compose.foundation.gestures.drag import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable@@ -92,10 +92,14 @@ import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalTextToolbar import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange@@ -105,6 +109,8 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import androidx.compose.ui.unit.IntSize+import com.vayunmathur.library.ocr.OcrEngine+import kotlinx.coroutines.withTimeoutOrNull import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconClose@@ -132,7 +138,6 @@ import com.vayunmathur.library.ui.IconLine import com.vayunmathur.library.ui.IconPolyline import com.vayunmathur.library.ui.IconRedact import com.vayunmathur.library.ui.IconSelect-import com.vayunmathur.library.ui.IconSignature import com.vayunmathur.library.ui.IconSquiggly import com.vayunmathur.library.ui.IconStrikethrough import com.vayunmathur.library.ui.IconStyle@@ -447,6 +452,12 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { // Prebuild the search index in the background so the first query is instant. LaunchedEffect(document) { document?.prewarmSearch() } + // On-device OCR engine (PP-OCRv5 / ncnn), shared across all pages so that+ // scanned PDFs with no embedded text layer still become selectable. Lazy:+ // native models only load on the first page that actually needs OCR.+ val ocrEngine = remember { OcrEngine(context.applicationContext) }+ DisposableEffect(Unit) { onDispose { ocrEngine.close() } }+ var editMode by remember { mutableStateOf(false) } var showSaveMenu by remember { mutableStateOf(false) } // Set once any edit is made; keeps the Save control visible thereafter.@@ -579,6 +590,11 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { var viewportSize by remember { mutableStateOf(IntSize.Zero) } var zoom by remember { mutableFloatStateOf(1f) } var pan by remember { mutableStateOf(Offset.Zero) }+ // True while ≥2 fingers are down. The LazyColumn's scroll is a descendant of+ // the transformable, so it can otherwise claim a two-finger drag as a scroll+ // before the pinch is recognized; disabling scroll during multi-touch makes a+ // pinch always zoom.+ var multiTouch by remember { mutableStateOf(false) } val transformState = rememberTransformableState { centroid, zoomChange, panChange, _ -> val zoomOld = zoom zoom = (zoom * zoomChange).coerceIn(1f, 6f)@@ -667,25 +683,6 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { var showEncrypt by remember { mutableStateOf(false) } var pendingEncryptPw by remember { mutableStateOf<String?>(null) }- val signLauncher = rememberLauncherForActivityResult(- ActivityResultContracts.CreateDocument("application/pdf")- ) { outUri ->- val doc = document- if (outUri != null && doc != null) scope.launch {- val signerName = android.os.Build.MODEL ?: "PDF Signer"- val bytes = doc.sign(signerName)- withContext(Dispatchers.IO) {- if (bytes != null) {- runCatching { context.contentResolver.openOutputStream(outUri)?.use { it.write(bytes) } }- }- }- android.widget.Toast.makeText(- context,- if (bytes != null) context.getString(R.string.signed_and_saved) else context.getString(R.string.signing_failed),- android.widget.Toast.LENGTH_SHORT,- ).show()- }- } val encryptLauncher = rememberLauncherForActivityResult( ActivityResultContracts.CreateDocument("application/pdf") ) { outUri ->@@ -832,9 +829,6 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { IconButton({ showEncrypt = true }) { IconLock() }- IconButton({ signLauncher.launch((uri.lastPathSegment ?: "document") + "-signed.pdf") }) {- IconSignature()- } } if (editMode) { IconButton({ undo() }, enabled = undoStack.isNotEmpty()) {@@ -954,6 +948,16 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { .padding(innerPadding) .fillMaxSize() .onSizeChanged { viewportSize = it }+ // Track finger count in the Initial pass (before the LazyColumn's+ // scroll reacts in the Main pass) so multi-touch disables scroll.+ .pointerInput(Unit) {+ awaitPointerEventScope {+ while (true) {+ val e = awaitPointerEvent(PointerEventPass.Initial)+ multiTouch = e.changes.count { it.pressed } >= 2+ }+ }+ } .graphicsLayer { scaleX = zoom scaleY = zoom@@ -972,6 +976,7 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { is LoadState.Loaded -> LazyColumn( Modifier.fillMaxSize(), state = listState,+ userScrollEnabled = !multiTouch, ) { items((0 until pageCount).toList()) { index -> val pageHighlights = matches.filter { it.first == index }.map { it.second }@@ -981,6 +986,7 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { document = state.document, index = index, version = (pageVersions[index] ?: 0) + pageMgrVersion,+ ocr = ocrEngine, editMode = editMode, tool = tool, shape = shape,@@ -1105,6 +1111,7 @@ private fun SafePdfPageItem( document: SafePdfDocument, index: Int, version: Int,+ ocr: OcrEngine?, editMode: Boolean, tool: EditTool, shape: ShapeKind,@@ -1191,6 +1198,7 @@ private fun SafePdfPageItem( cw = cw, ch = ch, scale = scale,+ ocr = ocr, onLinkPage = onLinkPage, ) }@@ -1267,12 +1275,13 @@ private fun NonEditOverlay( cw: Float, ch: Float, scale: Float,+ ocr: OcrEngine?, onLinkPage: (Int) -> Unit, ) { val context = LocalContext.current val density = LocalDensity.current // Text selection underneath so link Boxes get hit-test priority.- TextSelectionLayer(page = page, ch = ch, scale = scale)+ TextSelectionLayer(page = page, ch = ch, scale = scale, ocr = ocr) for (link in links) { val leftDp = with(density) { (link.x0 * scale).toDp() } val topDp = with(density) { (ch - link.y1 * scale).toDp() }@@ -1321,136 +1330,360 @@ private fun pdfTypeface(family: Int, bold: Boolean, italic: Boolean): android.gr return android.graphics.Typeface.create(base, style) } +/** A glyph plus its page-space ordering keys (baseline-Y desc, X asc) for merge+sort. */+private data class OrderedGlyph(val orderY: Float, val orderX: Float, val glyph: SelGlyph)++/** Pages with fewer than this many embedded glyphs are treated as scanned → OCR. */+private const val MIN_EMBEDDED_GLYPHS_FOR_TEXT = 6++/** Max distance (page px) a long-press may be from a glyph to start a selection. */+private const val SELECT_HIT_PX = 80f++/**+ * Build ordered selectable glyphs from a page's embedded Text primitives. Uses+ * accurate glyph advances via Text.advance and Paint.measureText for ligatures /+ * multi-char runs, with bold/italic so measured widths match the painted glyphs.+ */+private fun buildEmbeddedGlyphs(page: SafePdfPage, ch: Float, scale: Float): List<OrderedGlyph> {+ val list = ArrayList<OrderedGlyph>()+ val tmpPaint = android.graphics.Paint().apply {+ isAntiAlias = true+ isSubpixelText = true+ isLinearText = true+ }+ for (prim in page.primitives) {+ if (prim !is PdfPrimitive.Text || prim.text.isEmpty()) continue+ val selTf = pdfTypeface(prim.fontFamily, prim.isBold, prim.isItalic)+ tmpPaint.typeface = selTf+ tmpPaint.isFakeBoldText = prim.isBold && !selTf.isBold+ tmpPaint.textSkewX = if (prim.isItalic && !selTf.isItalic) -0.25f else 0f+ tmpPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f)+ tmpPaint.textSize = prim.size * scale+ val textStr = prim.text+ val measuredTotal = if (textStr.isNotEmpty()) tmpPaint.measureText(textStr) else prim.size * 0.5f+ val perGlyphMeasured = if (textStr.isNotEmpty()) measuredTotal / textStr.length else prim.size * 0.5f * scale+ var curPxPage = prim.origin.x+ for (c in textStr) {+ val px = curPxPage+ val singleGlyph = textStr.length == 1+ val cw = if (singleGlyph) prim.advance * scale else perGlyphMeasured+ val stepPage = if (singleGlyph) prim.advance else perGlyphMeasured / scale+ val left = px * scale+ val right = left + cw+ val baseline = ch - prim.origin.y * scale+ val top = baseline - prim.size * scale+ list.add(OrderedGlyph(-prim.origin.y, px, SelGlyph(c.toString(), left, top, right, baseline)))+ curPxPage += stepPage+ }+ }+ return list+}++/**+ * Run OCR on the page's largest raster image and synthesize selectable glyphs+ * from the recognized line boxes, so scanned PDFs with no embedded text layer+ * become selectable. Characters are distributed evenly across each line box+ * (monospace approximation) which is enough for word-level and range selection.+ * Returns empty if OCR is unavailable or the page has no decodable image.+ */+private suspend fun ocrPageGlyphs(page: SafePdfPage, ch: Float, scale: Float, ocr: OcrEngine): List<OrderedGlyph> {+ if (!ocr.isAvailable()) return emptyList()+ val img = page.primitives.filterIsInstance<PdfPrimitive.Image>()+ .mapNotNull { p -> p.bitmap?.let { p to it } }+ .maxByOrNull { (p, _) -> kotlin.math.abs(p.ctm[0] * p.ctm[3] - p.ctm[1] * p.ctm[2]) }+ ?: return emptyList()+ val (prim, bmp) = img+ val result = ocr.recognizeDetailed(bmp)+ if (result.boxes.isEmpty()) return emptyList()++ val a = prim.ctm[0]; val b = prim.ctm[1]; val c = prim.ctm[2]+ val d = prim.ctm[3]; val e = prim.ctm[4]; val f = prim.ctm[5]+ val bw = bmp.width.toFloat().coerceAtLeast(1f)+ val bh = bmp.height.toFloat().coerceAtLeast(1f)+ // Bitmap pixel (px,py) → page space via the image CTM on the unit square.+ // Image row 0 is the top, so v (unit-square, bottom-up) = 1 - py/bh.+ fun pageX(px: Float, py: Float): Float { val u = px / bw; val v = 1f - py / bh; return a * u + c * v + e }+ fun pageY(px: Float, py: Float): Float { val u = px / bw; val v = 1f - py / bh; return b * u + d * v + f }++ val out = ArrayList<OrderedGlyph>()+ for (box in result.boxes) {+ val text = box.text+ if (text.isEmpty()) continue+ val n = text.length+ val pxL = box.left.toFloat(); val pxR = box.right.toFloat()+ val pyT = box.top.toFloat(); val pyB = box.bottom.toFloat()+ val sxA = pageX(pxL, pyB) * scale; val sxB = pageX(pxR, pyB) * scale+ val yA = ch - pageY(pxL, pyT) * scale; val yB = ch - pageY(pxL, pyB) * scale+ val left = minOf(sxA, sxB); val right = maxOf(sxA, sxB)+ val top = minOf(yA, yB); val bottom = maxOf(yA, yB)+ if (right <= left || bottom <= top) continue+ val stepX = (right - left) / n+ val orderY = -pageY(pxL, pyB)+ for (k in 0 until n) {+ val gl = left + k * stepX+ out.add(+ OrderedGlyph(+ orderY,+ pageX(pxL + (pxR - pxL) * (k.toFloat() / n), pyB),+ SelGlyph(text[k].toString(), gl, top, gl + stepX, bottom),+ )+ )+ }+ }+ return out+}++/** Nearest glyph index to [p], or null if none within [maxDist] page px. */+private fun nearestGlyph(g: List<SelGlyph>, p: Offset, maxDist: Float = Float.MAX_VALUE): Int? {+ var best = -1+ var bestD = Float.MAX_VALUE+ for (i in g.indices) {+ val gg = g[i]+ val cx = (gg.left + gg.right) / 2f+ val cy = (gg.top + gg.bottom) / 2f+ val dd = (cx - p.x) * (cx - p.x) + (cy - p.y) * (cy - p.y)+ if (dd < bestD) { bestD = dd; best = i }+ }+ return if (best >= 0 && bestD <= maxDist * maxDist) best else null+}++/** True when [a] and [b] belong to the same word (same line, no gap between them). */+private fun sameWord(a: SelGlyph, b: SelGlyph): Boolean {+ val h = maxOf(a.bottom - a.top, b.bottom - b.top, 1f)+ val vA = (a.top + a.bottom) / 2f+ val vB = (b.top + b.bottom) / 2f+ if (kotlin.math.abs(vA - vB) > 0.6f * h) return false // different line+ val gap = b.left - a.right+ return gap <= 0.4f * h+}++/** Expand the glyph index [i] to the whole word it belongs to (reading order). */+private fun wordRangeAt(g: List<SelGlyph>, i: Int): IntRange {+ if (i !in g.indices) return i..i+ if (g[i].ch.isBlank()) return i..i+ var lo = i+ var hi = i+ while (lo - 1 in g.indices && g[lo - 1].ch.isNotBlank() && sameWord(g[lo - 1], g[lo])) lo--+ while (hi + 1 in g.indices && g[hi + 1].ch.isNotBlank() && sameWord(g[hi], g[hi + 1])) hi+++ return lo..hi+}++/** Which selection handle (0 = start, 1 = end) is within grab range of [p], else null. */+private fun handleAt(g: List<SelGlyph>, p: Offset, r: IntRange): Int? {+ if (r.first !in g.indices || r.last !in g.indices) return null+ val s = g[r.first]+ val e = g[r.last]+ val dStart = kotlin.math.hypot(s.left - p.x, s.bottom - p.y)+ val dEnd = kotlin.math.hypot(e.right - p.x, e.bottom - p.y)+ val grab = 48f+ return when {+ dStart <= grab && dStart <= dEnd -> 0+ dEnd <= grab -> 1+ else -> null+ }+}++/** The selected substring for range [r] over [g] (empty if out of bounds). */+private fun selectionText(g: List<SelGlyph>, r: IntRange): String {+ if (g.isEmpty() || r.first !in g.indices || r.last !in g.indices || r.last < r.first) return ""+ return g.subList(r.first, r.last + 1).joinToString("") { it.ch }+}+ /**- * Glyph-level selection over a page's text primitives: drag to select a range in- * reading order, adjust with the two handles, and copy the exact substring.- * Uses accurate glyph advances via Text.advance and Paint.measureText for ligatures/multi-char.+ * Text selection over a page's embedded text plus (for scanned pages) OCR text:+ *+ * - **Long-press** selects the word under the finger; continuing the drag in the+ * same motion extends the selection glyph-by-glyph.+ * - The two **endpoint handles** can be dragged directly (no long-press) to grow+ * or shrink the selection.+ * - Selecting no longer auto-copies; the standard Android selection context+ * menu (Copy / Select all) is shown via [LocalTextToolbar] — the real OS+ * floating [android.view.ActionMode]. A quick tap dismisses the selection. */ @Composable-private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float) {+private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float, ocr: OcrEngine?) { val context = LocalContext.current val clipboard = androidx.compose.ui.platform.LocalClipboard.current val scope = rememberCoroutineScope()- // Build ordered glyphs once per page/scale using accurate advance + Tz handling (Phase 7).- // v8: include bold/italic for accurate measured width so spacing/melting is correct.- // pointerInput is keyed only on page identity to avoid cancelling gesture on scale change.- val glyphs = remember(page, ch, scale) {- val list = ArrayList<Triple<Float, Float, SelGlyph>>() // (orderY, orderX, glyph)- val tmpPaint = android.graphics.Paint().apply {- isAntiAlias = true- isSubpixelText = true- isLinearText = true- }- for (prim in page.primitives) {- if (prim !is PdfPrimitive.Text || prim.text.isEmpty()) continue- val selTf = pdfTypeface(prim.fontFamily, prim.isBold, prim.isItalic)- tmpPaint.typeface = selTf- tmpPaint.isFakeBoldText = prim.isBold && !selTf.isBold- tmpPaint.textSkewX = if (prim.isItalic && !selTf.isItalic) -0.25f else 0f- tmpPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f)- tmpPaint.textSize = prim.size * scale- val textStr = prim.text- // Rust emits one glyph per Text prim with `advance` = that glyph's- // true device-space advance (from /Widths|/W, Tc/Tw/Tz). Use it for- // both stepping and glyph width; fall back to measured width only for- // multi-char runs (the font-less fallback path).- // For styled text, measure with the same bold/italic paint so per-glyph- // measured fallback matches visual, avoiding overlap "melting".- val measuredTotal = if (textStr.isNotEmpty()) tmpPaint.measureText(textStr) else prim.size * 0.5f- val perGlyphMeasured = if (textStr.isNotEmpty()) measuredTotal / textStr.length else prim.size * 0.5f * scale- var curPxPage = prim.origin.x- for (c in textStr) {- val px = curPxPage- val singleGlyph = textStr.length == 1- val cw = if (singleGlyph) prim.advance * scale else perGlyphMeasured- val stepPage = if (singleGlyph) prim.advance else perGlyphMeasured / scale- val left = px * scale- val right = left + cw- val baseline = ch - prim.origin.y * scale- val top = baseline - prim.size * scale- list.add(Triple(-prim.origin.y, px, SelGlyph(c.toString(), left, top, right, baseline)))- curPxPage += stepPage- }+ val textToolbar = LocalTextToolbar.current++ val embedded = remember(page, ch, scale) { buildEmbeddedGlyphs(page, ch, scale) }+ val needsOcr = remember(embedded) {+ embedded.count { it.glyph.ch.isNotBlank() } < MIN_EMBEDDED_GLYPHS_FOR_TEXT+ }+ var ocrGlyphs by remember(page, ch, scale) { mutableStateOf<List<OrderedGlyph>>(emptyList()) }+ LaunchedEffect(page, ch, scale, needsOcr, ocr) {+ ocrGlyphs = emptyList()+ if (ocr != null && needsOcr) {+ ocrGlyphs = runCatching { ocrPageGlyphs(page, ch, scale, ocr) }.getOrDefault(emptyList()) }- list.sortWith(compareBy({ it.first }, { it.second }))- list.map { it.third }+ }++ val glyphs = remember(embedded, ocrGlyphs) {+ (embedded + ocrGlyphs).sortedWith(compareBy({ it.orderY }, { it.orderX })).map { it.glyph } } if (glyphs.isEmpty()) return var range by remember(page) { mutableStateOf<IntRange?>(null) }- var dragEnd by remember(page) { mutableStateOf(true) } // which handle is moving-- fun nearest(p: Offset): Int {- var best = 0- var bestD = Float.MAX_VALUE- glyphs.forEachIndexed { i, g ->- val cx = (g.left + g.right) / 2f- val cy = (g.top + g.bottom) / 2f- val d = (cx - p.x) * (cx - p.x) + (cy - p.y) * (cy - p.y)- if (d < bestD) { bestD = d; best = i }- }- return best+ // True while a handle/word drag is in progress → the OS menu is hidden until+ // the gesture settles (mirrors native selection behavior).+ var isAdjusting by remember(page) { mutableStateOf(false) }+ // This layer's position in the composition root, tracked so the menu's anchor+ // rect follows scroll/zoom; recomputed whenever the layout is re-positioned.+ var selCoords by remember(page) { mutableStateOf<LayoutCoordinates?>(null) }+ var rootAnchor by remember(page) { mutableStateOf(Offset.Zero) }+ // Whether *this* page currently owns the (window-global) toolbar, so pages+ // without a selection never hide another page's menu during scroll.+ var showing by remember(page) { mutableStateOf(false) }+ val latestGlyphs by rememberUpdatedState(glyphs)++ DisposableEffect(Unit) {+ onDispose { if (showing) textToolbar.hide() } } - val latestGlyphs by rememberUpdatedState(glyphs)+ // Drive the real OS floating ActionMode: show it anchored to the selection's+ // bounding rect (in root coordinates) whenever there's a settled selection.+ LaunchedEffect(range, isAdjusting, rootAnchor, glyphs) {+ val r = range+ val coords = selCoords+ if (r == null || isAdjusting || coords == null || !coords.isAttached ||+ r.first !in glyphs.indices || r.last !in glyphs.indices) {+ if (showing) { textToolbar.hide(); showing = false }+ return@LaunchedEffect+ }+ var left = Float.MAX_VALUE+ var top = Float.MAX_VALUE+ var right = -Float.MAX_VALUE+ var bottom = -Float.MAX_VALUE+ for (i in r) {+ val g = glyphs[i]+ if (g.left < left) left = g.left+ if (g.top < top) top = g.top+ if (g.right > right) right = g.right+ if (g.bottom > bottom) bottom = g.bottom+ }+ val tl = coords.localToRoot(Offset(left, top))+ val br = coords.localToRoot(Offset(right, bottom))+ val rootRect = Rect(minOf(tl.x, br.x), minOf(tl.y, br.y), maxOf(tl.x, br.x), maxOf(tl.y, br.y))+ textToolbar.showMenu(+ rect = rootRect,+ onCopyRequested = {+ val text = selectionText(glyphs, r)+ if (text.isNotBlank()) {+ scope.launch {+ clipboard.setClipEntry(+ androidx.compose.ui.platform.ClipEntry(+ android.content.ClipData.newPlainText(context.getString(R.string.text), text)+ )+ )+ }+ }+ range = null+ },+ onSelectAllRequested = { range = 0..glyphs.lastIndex },+ )+ showing = true+ } Canvas(- Modifier.fillMaxSize().pointerInput(page) {- detectDragGesturesAfterLongPress(- onDragStart = { pos ->- val g = latestGlyphs- val r = range- if (r != null && r.first in g.indices && r.last in g.indices) {- val startG = g[r.first]- val endG = g[r.last]- val dStart = kotlin.math.hypot(startG.left - pos.x, startG.bottom - pos.y)- val dEnd = kotlin.math.hypot(endG.right - pos.x, endG.bottom - pos.y)- if (minOf(dStart, dEnd) < 60f) {- dragEnd = dEnd <= dStart- return@detectDragGesturesAfterLongPress+ // Keyed on page only so zoom/scale changes don't cancel an in-progress+ // selection; latest glyphs are read via rememberUpdatedState.+ Modifier+ .fillMaxSize()+ .onGloballyPositioned { c -> selCoords = c; rootAnchor = c.localToRoot(Offset.Zero) }+ .pointerInput(page) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)++ // (A) If a selection exists and the finger lands on a handle,+ // drag it immediately (no long-press needed).+ val existing = range+ if (existing != null) {+ val which = handleAt(latestGlyphs, down.position, existing)+ if (which != null) {+ down.consume()+ isAdjusting = true+ val anchor = if (which == 0) existing.last else existing.first+ drag(down.id) { change ->+ nearestGlyph(latestGlyphs, change.position)?.let { i ->+ range = minOf(i, anchor)..maxOf(i, anchor)+ }+ change.consume()+ }+ isAdjusting = false+ return@awaitEachGesture } }- val i = nearest(pos)- range = i..i- dragEnd = true- },- onDrag = { change, _ ->- change.consume()- val g = latestGlyphs- if (g.isEmpty()) return@detectDragGesturesAfterLongPress- val i = nearest(change.position)- val r = range ?: (i..i)- range = if (dragEnd) minOf(r.first, i)..maxOf(r.first, i)- else minOf(i, r.last)..maxOf(i, r.last)- },- onDragEnd = {- val g = latestGlyphs- val r = range- if (r != null && g.isNotEmpty() && r.first in g.indices && r.last in g.indices) {- val text = g.subList(r.first, r.last + 1).joinToString("") { it.ch }- if (text.isNotBlank()) {- scope.launch { clipboard.setClipEntry(androidx.compose.ui.platform.ClipEntry(android.content.ClipData.newPlainText(context.getString(R.string.text), text))) }- android.widget.Toast.makeText(context, context.getString(R.string.copied), android.widget.Toast.LENGTH_SHORT).show()++ // (B) Otherwise classify the gesture: a long-press starts a word+ // selection; a quick tap dismisses; movement is a scroll (we+ // don't consume, so the parent list/zoom handles it).+ val slop = viewConfiguration.touchSlop+ val outcome = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {+ var moved = 0f+ var last = down.position+ var res = "hold"+ while (true) {+ val ev = awaitPointerEvent()+ // A second finger means a pinch/zoom: bail without consuming+ // so the parent transformable handles it even when the first+ // finger is resting on text.+ if (ev.changes.count { it.pressed } > 1) { res = "multitouch"; break }+ val cpc = ev.changes.firstOrNull { it.id == down.id }+ if (cpc == null) { res = "cancel"; break }+ if (!cpc.pressed) { res = "tap"; break }+ moved += (cpc.position - last).getDistance()+ last = cpc.position+ if (moved > slop) { res = "scroll"; break } }+ res }- },- )- },++ when (outcome) {+ null -> {+ // Long-press: select the word, then allow drag-to-extend.+ val i = nearestGlyph(latestGlyphs, down.position, SELECT_HIT_PX)+ if (i != null) {+ down.consume()+ val w = wordRangeAt(latestGlyphs, i)+ range = w+ // Keep the whole first word selected; extend outward+ // toward the finger in either direction.+ val wLo = w.first+ val wHi = w.last+ isAdjusting = true+ drag(down.id) { change ->+ nearestGlyph(latestGlyphs, change.position)?.let { j ->+ range = minOf(j, wLo)..maxOf(j, wHi)+ }+ change.consume()+ }+ isAdjusting = false+ }+ }+ "tap" -> if (range != null) range = null+ else -> { /* scroll / multitouch / cancel: don't consume, let the parent scroll or pinch-zoom */ }+ }+ }+ }, ) { val r = range ?: return@Canvas+ val g = latestGlyphs for (i in r) {- val g = glyphs[i]+ if (i !in g.indices) continue+ val gg = g[i] drawRect( color = Color(0x553F51B5),- topLeft = Offset(g.left, g.top),- size = Size(g.right - g.left, g.bottom - g.top),+ topLeft = Offset(gg.left, gg.top),+ size = Size(gg.right - gg.left, gg.bottom - gg.top), ) }- // Handles at the two ends.- val s = glyphs[r.first]- val e = glyphs[r.last]- drawCircle(Color(0xFF3F51B5), radius = 14f, center = Offset(s.left, s.bottom))- drawCircle(Color(0xFF3F51B5), radius = 14f, center = Offset(e.right, e.bottom))+ if (r.first in g.indices && r.last in g.indices) {+ val s = g[r.first]+ val e = g[r.last]+ drawCircle(Color(0xFF3F51B5), radius = 16f, center = Offset(s.left, s.bottom))+ drawCircle(Color(0xFF3F51B5), radius = 16f, center = Offset(e.right, e.bottom))+ } } }
pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.ktindex f2a61a6d45..6c5bfd9019 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt@@ -166,12 +166,6 @@ object PdfNative { /** Serialize the modified document to PDF bytes, or null on failure. */ external fun saveDocument(handle: Long): ByteArray? - /** Build a signature-ready PDF (placeholder /ByteRange + /Contents) for signing. */- external fun prepareSignature(handle: Long, name: String, contentsBytes: Int): ByteArray?-- /** Detached CMS/PKCS#7 signature (self-signed RSA-2048, SHA-256) over [content]. */- external fun signCms(content: ByteArray, name: String): ByteArray?- /** Serialize with streams compressed + unused objects pruned, or null. */ external fun saveCompressed(handle: Long): ByteArray?
pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.ktdeleted file mode 100644index 94b0af7251..0000000000--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt+++ /dev/null@@ -1,93 +0,0 @@-package com.vayunmathur.pdf.util--import java.io.ByteArrayOutputStream--/**- * Produces a cryptographically signed PDF (detached PKCS#7 / adbe.pkcs7.detached)- * from a signature-ready PDF built by [PdfNative.prepareSignature]. The CMS- * signature (fresh self-signed RSA-2048 cert, SHA-256 with RSA) is generated in- * the native Rust core ([PdfNative.signCms]) — no Bouncy Castle. The signed PDF- * validates its own byte-range digest; trust must be established out of band- * (self-signed).- */-object PdfSigner {- /** Size (bytes) of the /Contents placeholder; must fit the CMS signature. */- const val CONTENTS_BYTES = 8192-- /** Patch [prepared] (from prepareSignature) with a real detached signature. */- fun sign(prepared: ByteArray, name: String): ByteArray? {- val buf = prepared.copyOf()-- val brKey = indexOf(buf, "/ByteRange".toByteArray(), 0)- if (brKey < 0) return null- val brOpen = indexOfByte(buf, '['.code.toByte(), brKey)- val brClose = indexOfByte(buf, ']'.code.toByte(), brOpen)- if (brOpen < 0 || brClose < 0) return null-- val cKey = indexOf(buf, "/Contents".toByteArray(), brKey)- if (cKey < 0) return null- val cOpen = indexOfByte(buf, '<'.code.toByte(), cKey)- val cClose = indexOfByte(buf, '>'.code.toByte(), cOpen)- if (cOpen < 0 || cClose < 0) return null-- // Signature covers everything except the Contents value (incl. < and >).- val a = cOpen- val b = cClose + 1- val c = buf.size - b-- // Patch /ByteRange in place (fixed-width slot, so offsets don't shift).- val slot = brClose - (brOpen + 1)- val br = "0 $a $b $c"- if (br.length > slot) return null- val padded = br.padEnd(slot, ' ').toByteArray(Charsets.US_ASCII)- System.arraycopy(padded, 0, buf, brOpen + 1, slot)-- // Concatenate the two signed byte ranges.- val content = ByteArrayOutputStream(a + c).apply {- write(buf, 0, a)- write(buf, b, c)- }.toByteArray()-- // Detached CMS built natively (RustCrypto), replacing Bouncy Castle.- val cms = PdfNative.signCms(content, name.ifBlank { "PDF Signer" }) ?: return null-- val hex = toHex(cms)- val hexSlot = cClose - (cOpen + 1)- if (hex.length > hexSlot) return null // signature too large for placeholder- val hexPadded = hex.padEnd(hexSlot, '0').toByteArray(Charsets.US_ASCII)- System.arraycopy(hexPadded, 0, buf, cOpen + 1, hexSlot)- return buf- }-- private fun toHex(bytes: ByteArray): String {- val sb = StringBuilder(bytes.size * 2)- val hex = "0123456789abcdef"- for (x in bytes) {- val v = x.toInt() and 0xFF- sb.append(hex[v ushr 4]).append(hex[v and 0x0F])- }- return sb.toString()- }-- private fun indexOf(haystack: ByteArray, needle: ByteArray, from: Int): Int {- var i = from.coerceAtLeast(0)- val last = haystack.size - needle.size- while (i <= last) {- var j = 0- while (j < needle.size && haystack[i + j] == needle[j]) j++- if (j == needle.size) return i- i++- }- return -1- }-- private fun indexOfByte(haystack: ByteArray, b: Byte, from: Int): Int {- if (from < 0) return -1- var i = from- while (i < haystack.size) {- if (haystack[i] == b) return i- i++- }- return -1- }-}
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex a319538f89..fd4739939e 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -252,12 +252,6 @@ class SafePdfDocument private constructor( PdfNative.extractText(handle) } - /** Digitally sign the document (self-signed cert) and return the signed bytes. */- suspend fun sign(name: String): ByteArray? = withContext(Dispatchers.IO) {- val prepared = PdfNative.prepareSignature(handle, name, PdfSigner.CONTENTS_BYTES) ?: return@withContext null- PdfSigner.sign(prepared, name)- }- /** Add a redaction annotation over the rect; returns id (0 on failure). */ suspend fun addRedaction( index: Int, x0: Float, y0: Float, x1: Float, y1: Float,
pdf/src/main/res/values/strings.xml
diff --git a/pdf/src/main/res/values/strings.xml b/pdf/src/main/res/values/strings.xmlindex 4ff40dfeb2..d7f450dd31 100644--- a/pdf/src/main/res/values/strings.xml+++ b/pdf/src/main/res/values/strings.xml@@ -97,9 +97,4 @@ <string name="outline">Outline</string> <!-- Button: add signature annotation --> <string name="sign">Sign</string>-- <!-- Toast after signature saved -->- <string name="signed_and_saved">Signed & saved</string>- <!-- Toast when signing failed -->- <string name="signing_failed">Signing failed</string> </resources>
pdf/src/main/rust/Cargo.toml
diff --git a/pdf/src/main/rust/Cargo.toml b/pdf/src/main/rust/Cargo.tomlindex 94f1a85b6d..d0e273fb6a 100644--- a/pdf/src/main/rust/Cargo.toml+++ b/pdf/src/main/rust/Cargo.toml@@ -10,41 +10,36 @@ name = "pdf_render" crate-type = ["cdylib"] [dependencies]-# Root catalog pins single version per crate (see /Users/vayun/Documents/Modern-Apps/Cargo.toml)+# Root catalog pins single version per crate (see /Cargo.toml) # armv8-only: aarch64-linux-android target, no windows/wasm deps in normal edges.-lopdf = { version = "0.36", features = ["serde"] }+# lopdf default includes chrono->windows-link + jiff + time + rayon – not needed for core filter/crypto/image extraction path we use in safe viewer.+# Trim default to only serde (still safe for XObject parsing). Date fields fallback to None if feature disabled.+lopdf = { version = "0.36", default-features = false, features = ["serde"] } ttf-parser = { version = "0.25", default-features = false, features = ["std", "glyph-names"] } jni.workspace = true-jpeg-decoder.workspace = true-weezl.workspace = true # LZW – single function, std rewrite landing: keep version pinned, later drop+jpeg-decoder = { version = "0.3.2", default-features = false } fax.workspace = true flate2.workspace = true hayro-jbig2 = { version = "0.3", default-features = false, features = ["std"] } openjp2.workspace = true-md-5.workspace = true # tiny MD5 – candidate for std vendor but keep feature intact for now+md-5.workspace = true aes.workspace = true-cbc = { version = "0.1", features = ["alloc"] } # wrapper for aes CBC – tiny but keep sha2 = { version = "0.10", features = ["oid"] }-indexmap.workspace = true # used for true LRU via shift_remove_index – keep-getrandom.workspace = true # unified to 0.2.15 to match rand 0.8 chain, avoids duplicate 0.2+0.3+0.4+indexmap = { version = "2.10.0" }+getrandom.workspace = true -# Detached CMS/PKCS#7 signing (must preserve feature per user constraint)-# rsa etc use workspace = true so builder features unified in root Cargo.toml-rsa.workspace = true+# Signing (features preserved per no-feature-loss)+# PDF signature *creation* removed as a feature – dropped rsa/cms/x509-cert/spki/const-oid+# (and their num-bigint-dig/pkcs1/pkcs8/signature/sha1/spin/lazy_static/num-iter subtree).+# der + rand stay: der is used pervasively for ASN.1 (fonts/filters/decrypt), rand is used+# by decrypt.rs (OsRng) for encryption. const-oid still comes in transitively via der. rand.workspace = true-x509-cert.workspace = true-cms.workspace = true der.workspace = true-spki.workspace = true-const-oid.workspace = true [profile.release] opt-level = 3 lto = true codegen-units = 1-# Must be unwind for JNI – abort would kill JVM process on any panic. Panics are caught-# via catch_unwind in jni_bindings.rs and translated to Java null/0 returns. panic = "unwind"-# Keep debuginfo for Play Console stack traces, strip only debug symbols not needed at runtime strip = "debuginfo"
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex d750ac306d..59cf3b60a0 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -682,76 +682,3 @@ pub(crate) fn save_document(handle: i64) -> Option<Vec<u8>> { Some(buf) } -/// Build a signature-ready PDF: an invisible signature field + `/Sig` dict with a-/// fixed-width `/ByteRange` placeholder and a `contents_bytes`-long zero-/// `/Contents`. Kotlin patches the ByteRange and fills the detached PKCS#7-/// signature. Returns the serialized bytes.-pub(crate) fn prepare_signature(handle: i64, name: &str, contents_bytes: usize) -> Option<Vec<u8>> {- let bytes = save_document(handle)?;- let mut doc = Document::load_mem(&bytes).ok()?;- let page0 = doc.get_pages().values().next().copied()?;- let catalog_id = doc.trailer.get(b"Root").ok().and_then(|o| o.as_reference().ok())?;-- let mut sig = Dictionary::new();- sig.set("Type", name_obj("Sig"));- sig.set("Filter", name_obj("Adobe.PPKLite"));- sig.set("SubFilter", name_obj("adbe.pkcs7.detached"));- sig.set(- "ByteRange",- Object::Array(vec![- Object::Integer(0),- Object::Integer(2_000_000_000),- Object::Integer(2_000_000_000),- Object::Integer(2_000_000_000),- ]),- );- sig.set(- "Contents",- Object::String(vec![0u8; contents_bytes], lopdf::StringFormat::Hexadecimal),- );- sig.set("Name", Object::string_literal(name));- let sig_id = doc.add_object(sig);-- let mut widget = Dictionary::new();- widget.set("Type", name_obj("Annot"));- widget.set("Subtype", name_obj("Widget"));- widget.set("FT", name_obj("Sig"));- widget.set("T", Object::string_literal("Signature1"));- widget.set("V", Object::Reference(sig_id));- widget.set("P", Object::Reference(page0));- widget.set("Rect", Object::Array(vec![0.into(), 0.into(), 0.into(), 0.into()]));- widget.set("F", Object::Integer(132));- let widget_id = doc.add_object(widget);- append_annot(&mut doc, page0, widget_id);-- // Attach the field to the AcroForm (reuse/extend existing, else create one).- let af_ref = doc- .get_dictionary(catalog_id)- .ok()- .and_then(|c| c.get(b"AcroForm").ok())- .and_then(|o| o.as_reference().ok());- if let Some(af_id) = af_ref {- if let Ok(af) = doc.get_dictionary_mut(af_id) {- let has_fields = matches!(af.get(b"Fields"), Ok(Object::Array(_)));- if !has_fields {- af.set("Fields", Object::Array(vec![]));- }- if let Ok(Object::Array(a)) = af.get_mut(b"Fields") {- a.push(Object::Reference(widget_id));- }- af.set("SigFlags", Object::Integer(3));- }- } else {- let mut af = Dictionary::new();- af.set("Fields", Object::Array(vec![Object::Reference(widget_id)]));- af.set("SigFlags", Object::Integer(3));- let af_id = doc.add_object(af);- if let Ok(cat) = doc.get_dictionary_mut(catalog_id) {- cat.set("AcroForm", Object::Reference(af_id));- }- }-- let mut out = Vec::new();- doc.save_to(&mut out).ok()?;- Some(out)-}
pdf/src/main/rust/src/jni_bindings.rs
diff --git a/pdf/src/main/rust/src/jni_bindings.rs b/pdf/src/main/rust/src/jni_bindings.rsindex 2bb636e476..64e422ac57 100644--- a/pdf/src/main/rust/src/jni_bindings.rs+++ b/pdf/src/main/rust/src/jni_bindings.rs@@ -210,41 +210,6 @@ fn save_encrypted_inner<'local>( bytes_or_null_mut(env, save_encrypted(handle as i64, u.as_bytes(), o.as_bytes())) } -fn sign_cms_inner<'local>(- env: &mut JNIEnv<'local>,- content: JByteArray<'local>,- name: JString<'local>,-) -> jbyteArray {- if content.is_null() {- throw_iae(env, "content is null");- return std::ptr::null_mut();- }- let len = env.get_array_length(&content).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {- throw_oom(env, "Content too large (>200MB)");- return std::ptr::null_mut();- }- let data = match env.convert_byte_array(&content) {- Ok(b) => b,- Err(_) => {- let _ = env.exception_clear();- return std::ptr::null_mut();- }- };- let nm = match jstr_safe(env, &name) {- Ok(s) => s,- Err(e) => {- throw_iae(env, &e);- return std::ptr::null_mut();- }- };- if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();- return std::ptr::null_mut();- }- bytes_or_null_mut(env, crate::signing::sign_cms(&data, &nm))-}- fn render_page_inner<'local>(env: &mut JNIEnv<'local>, handle: jlong, index: jint) -> jbyteArray { if env.ensure_local_capacity(4).is_err() { let _ = env.exception_clear();@@ -572,29 +537,6 @@ fn save_document_inner<'local>(env: &mut JNIEnv<'local>, handle: jlong) -> jbyte bytes_or_null_mut(env, save_document(handle as i64)) } -fn prepare_signature_inner<'local>(- env: &mut JNIEnv<'local>,- handle: jlong,- name: JString<'local>,- contents_bytes: jint,-) -> jbyteArray {- let n = match jstr_safe(env, &name) {- Ok(s) => s,- Err(e) => {- throw_iae(env, &e);- return std::ptr::null_mut();- }- };- if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();- return std::ptr::null_mut();- }- bytes_or_null_mut(- env,- prepare_signature(handle as i64, &n, contents_bytes.max(0) as usize),- )-}- fn save_compressed_inner<'local>(env: &mut JNIEnv<'local>, handle: jlong) -> jbyteArray { if env.ensure_local_capacity(4).is_err() { let _ = env.exception_clear();@@ -758,26 +700,6 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveEncrypted<'lo } } -/// `PdfNative.signCms(byte[], String) -> byte[]`. Detached CMS/PKCS#7-/// signature (fresh self-signed RSA-2048, SHA-256 with RSA) over `content`,-/// or null on failure. Replaces the Bouncy Castle path on the Kotlin side.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_signCms<'local>(- mut env: JNIEnv<'local>,- _class: JClass<'local>,- content: JByteArray<'local>,- name: JString<'local>,-) -> jbyteArray {- match catch_unwind(AssertUnwindSafe(|| sign_cms_inner(&mut env, content, name))) {- Ok(v) => v,- Err(_) => {- let _ = env.exception_clear();- let _ = env.throw_new("java/lang/RuntimeException", "Native panic in signCms");- std::ptr::null_mut()- }- }-}- /// `PdfNative.getPageCount(long) -> int`. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_getPageCount<'local>(@@ -1510,26 +1432,6 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveDocument<'loc } } -/// `PdfNative.prepareSignature(long, String, int) -> byte[]`.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_prepareSignature<'local>(- mut env: JNIEnv<'local>,- _class: JClass<'local>,- handle: jlong,- name: JString<'local>,- contents_bytes: jint,-) -> jbyteArray {- match catch_unwind(AssertUnwindSafe(|| {- prepare_signature_inner(&mut env, handle, name, contents_bytes)- })) {- Ok(v) => v,- Err(_) => {- let _ = env.exception_clear();- std::ptr::null_mut()- }- }-}- /// `PdfNative.saveCompressed(long) -> byte[]`. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveCompressed<'local>(
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex 72268c71a4..7175a90372 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -29,8 +29,8 @@ pub(crate) use std::sync::{Mutex, OnceLock}; pub(crate) use lopdf::content::Content; pub(crate) use lopdf::{dictionary, Dictionary, Document, Object, ObjectId, Stream}; +mod pdf_cbc; mod crypto;-mod signing; mod filters; mod functions; pub(crate) use functions::*;
pdf/src/main/rust/src/signing.rs
diff --git a/pdf/src/main/rust/src/signing.rs b/pdf/src/main/rust/src/signing.rsdeleted file mode 100644index d887b03331..0000000000--- a/pdf/src/main/rust/src/signing.rs+++ /dev/null@@ -1,162 +0,0 @@-//! Detached CMS/PKCS#7 signing for the PDF signer, using RustCrypto instead of-//! Bouncy Castle (which cost ~6 MB of DEX on the Kotlin side). Generates a fresh-//! self-signed RSA-2048 certificate and produces a detached SignedData-//! (`adbe.pkcs7.detached`, SHA-256 with RSA) over the supplied byte-range-//! content. The Kotlin side keeps doing the PDF /ByteRange + /Contents patching.-//! P0 fixes: CN injection sanitization, Leaf profile (not Root CA), OsRng, 64-bit serial, 2y validity.--use cms::builder::{SignedDataBuilder, SignerInfoBuilder};-use cms::cert::CertificateChoices;-use cms::content_info::ContentInfo;-use cms::signed_data::{EncapsulatedContentInfo, SignerIdentifier};-use const_oid::db::rfc5911::ID_DATA;-use der::{Decode, Encode};-use rand::RngCore;-use rsa::pkcs1v15::SigningKey;-use rsa::pkcs8::EncodePublicKey;-use rsa::RsaPrivateKey;-use sha2::Sha256;-use std::time::Duration;-use x509_cert::builder::{Builder, CertificateBuilder, Profile};-use x509_cert::name::Name;-use x509_cert::serial_number::SerialNumber;-use x509_cert::spki::SubjectPublicKeyInfoOwned;-use x509_cert::time::Validity;-use x509_cert::Certificate;--fn sanitize_cn(input: &str) -> String {- // Prevent RDN injection: strip/replace dangerous chars that delimit RDNs- // Comma, +, =, ;, newline, quote, backslash, null trigger injection or parsing issues- let trimmed = input.trim();- if trimmed.is_empty() {- return "PDF Signer".to_string();- }- let mut out = String::with_capacity(trimmed.len());- for ch in trimmed.chars() {- match ch {- ',' | '+' | '=' | ';' | '"' | '\\' | '\n' | '\r' | '\0' | '<' | '>' => {- out.push(' ');- }- c if c.is_control() => out.push(' '),- c => out.push(c),- }- }- // Limit length to avoid oversized cert- let mut s = out.trim().to_string();- if s.len() > 64 {- s.truncate(64);- s = s.trim_end().to_string();- }- if s.is_empty() {- "PDF Signer".to_string()- } else {- s- }-}--/// Build a detached CMS SignedData (DER) over `content`, signed by a freshly-/// generated self-signed RSA-2048 cert with subject `CN=<name>`. Returns `None`-/// on any failure.-pub fn sign_cms(content: &[u8], name: &str) -> Option<Vec<u8>> {- match sign_cms_inner(content, name) {- Ok(v) => Some(v),- Err(e) => {- // Don't expose raw error to UI but log via debug- eprintln!("sign_cms failed: {}", e);- None- }- }-}--fn sign_cms_inner(content: &[u8], name: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {- // Use OsRng for CSPRNG, not thread_rng (P0 fix)- let private_key = RsaPrivateKey::new(&mut rand::rngs::OsRng, 2048)?;- let signing_key = SigningKey::<Sha256>::new(private_key.clone());-- // 2. Self-signed X.509 cert with sanitized CN (P0 fix: no injection)- let cn = sanitize_cn(name);- // Use typed builder via Name::from_string instead of format! that allowed injection- // x509_cert Name parsing from RFC4514 string requires escaping; we sanitized, but use explicit RDN construction- let subject: Name = std::str::FromStr::from_str(&format!("CN={}", cn))?;- // 64-bit serial via OsRng (weak serial fix) + 2y validity not 10y- let mut serial_bytes = [0u8; 8];- rand::rngs::OsRng.fill_bytes(&mut serial_bytes);- // Ensure serial >0 and within 20 octets limit- let serial_u64 = u64::from_be_bytes(serial_bytes).max(1);- let serial = SerialNumber::from(serial_u64);-- let validity = Validity::from_now(Duration::from_secs(2 * 365 * 24 * 60 * 60))?;-- let spki_der = private_key.to_public_key().to_public_key_der()?;- let spki = SubjectPublicKeyInfoOwned::from_der(spki_der.as_bytes())?;-- // P0 fix: Leaf profile (end-entity) not Root CA — validators reject CA cert for signing- // Leaf requires issuer (self-signed so issuer = subject) and key usage flags- let profile = Profile::Leaf {- issuer: subject.clone(),- enable_key_agreement: false,- enable_key_encipherment: false,- };- let builder = CertificateBuilder::new(profile, serial, validity, subject, spki, &signing_key)?;- let cert: Certificate = builder.build()?;-- // 3. Detached CMS SignedData over the external content.- let econtent = EncapsulatedContentInfo {- econtent_type: ID_DATA,- econtent: None, // detached- };-- let sid = SignerIdentifier::IssuerAndSerialNumber(cms::cert::IssuerAndSerialNumber {- issuer: cert.tbs_certificate.issuer.clone(),- serial_number: cert.tbs_certificate.serial_number.clone(),- });-- let digest_algorithm = spki::AlgorithmIdentifierOwned {- oid: const_oid::db::rfc5912::ID_SHA_256,- parameters: None,- };-- let signer_info = SignerInfoBuilder::new(- &signing_key,- sid,- digest_algorithm.clone(),- &econtent,- Some(content),- )- .map_err(|e| format!("signer info: {e:?}"))?;-- let mut builder = SignedDataBuilder::new(&econtent);- let signed_data = builder- .add_digest_algorithm(digest_algorithm)- .map_err(|e| format!("digest alg: {e:?}"))?- .add_certificate(CertificateChoices::Certificate(cert))- .map_err(|e| format!("add cert: {e:?}"))?- .add_signer_info(signer_info)- .map_err(|e| format!("add signer: {e:?}"))?- .build()- .map_err(|e| format!("build: {e:?}"))?;-- let ci: ContentInfo = signed_data;- Ok(ci.to_der()?)-}--/// Minimal byte-range verification: check that contents length fits placeholder and hash matches expectation if provided.-/// Since we only generate, this is a stub that validates the CMS DER parses as SignedData.-pub fn verify_cms_structure(der: &[u8]) -> bool {- ContentInfo::from_der(der).is_ok()-}--#[cfg(test)]-mod signing_tests {- use super::*;-- #[test]- fn produces_parseable_detached_cms() {- let content = b"hello pdf byte range";- let der = sign_cms(content, "Unit Test").expect("sign");- assert!(der.len() > 500, "cms unexpectedly small: {}", der.len());- // Round-trips as a CMS ContentInfo wrapping SignedData.- let ci = ContentInfo::from_der(&der).expect("parse ContentInfo");- assert_eq!(ci.content_type, const_oid::db::rfc5911::ID_SIGNED_DATA);- }-}