Fix native OTP insertion and centre two-factor form controls

This commit is contained in:
Nick Beckley 2026-11-25 19:47:11 +00:00
parent e140a6c969
commit 9b1770d96d
8 changed files with 289 additions and 53 deletions

View File

@ -0,0 +1,17 @@
# Two-factor layout and native insertion correction — 2026-11-25
The owner confirmed Android Chrome pastes only the first digit; Windows desktop paste works. The old page handles the desktop `paste` event, but not native multi-character `beforeinput`. A trusted Chromium `keyboard.insertText("123456")` reproduced the failure: `beforeinput.data` contained six digits, then `maxlength="1"` reduced `input.data` to `1`. Manual typing and desktop Ctrl+V already worked.
The earlier acceptance used a constructed ClipboardEvent and prevented submission. It exercised the desktop handler but neither the mobile insertion path nor an actual POST. That evidence was insufficient for the reported mobile behaviour.
The existing component now captures paste and multi-character beforeinput at the form, validates exactly six ASCII digits after conventional space normalization, populates all six boxes and requests submission once. The submit latch also permits retries after client cancellation and page restoration. No server authentication, TOTP, recovery or database code changed. Component-only CSS centres the label, button group and recovery text; card dimensions and branding remain unchanged.
## Verification
`PlotLine.Tests/Browser/two-factor-otp.cjs` exercises the actual compiled Razor view and ordinary assets in Chromium. A private loopback fixture substitutes only the authentication service result with a controlled rejection: real MVC POST, antiforgery, model validation and error-page reload remain active. It never authenticates a real account and is not part of the deployed application.
At desktop, 390px and 320px, genuine clipboard writes followed by Ctrl+V pass for plain codes, surrounding whitespace, grouped digits, leading zero and nonbreaking spaces. All six boxes and the combined value are observed before exactly one actual POST. Trusted native insertion also passes. Malformed content makes no POST. Typing, backspace, corrections, keyboard navigation, manual submission, cancelled submission retry and rejected-code retry pass. The separate setup view retains its original single input.
The three after screenshots were visually inspected: compact horizontal boxes, centred label/actions/recovery text, natural mobile wrapping and no overflow. [Desktop](../Testing/TwoFactor-20261125/centred-1440.png), [390px](../Testing/TwoFactor-20261125/centred-390.png), [320px](../Testing/TwoFactor-20261125/centred-320.png). [Structured clipboard evidence](../Testing/TwoFactor-20261125/genuine-clipboard-results.json) uses synthetic codes only.
Physical Android Chrome confirmation remains an owner acceptance check; trusted native insertion reproduces the identified event mechanism but is not a physical Android test. Production deployment is not authorised for this correction.

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

View File

@ -0,0 +1,159 @@
{
"status": "passed",
"physical_android_device_tested": false,
"results": [
{
"width": 1440,
"case": "real-clipboard",
"synthetic_value": "\"123456\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 1440,
"case": "real-clipboard",
"synthetic_value": "\" \\t123456\\r\\n\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 1440,
"case": "real-clipboard",
"synthetic_value": "\"1 2 3 4 5 6\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 1440,
"case": "real-clipboard",
"synthetic_value": "\"012345\"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 1440,
"case": "real-clipboard",
"synthetic_value": "\" 012 345 \"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 1440,
"case": "trusted-native-insertion",
"submitted": "012345",
"posts": 1
},
{
"width": 390,
"case": "real-clipboard",
"synthetic_value": "\"123456\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 390,
"case": "real-clipboard",
"synthetic_value": "\" \\t123456\\r\\n\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 390,
"case": "real-clipboard",
"synthetic_value": "\"1 2 3 4 5 6\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 390,
"case": "real-clipboard",
"synthetic_value": "\"012345\"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 390,
"case": "real-clipboard",
"synthetic_value": "\" 012 345 \"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 390,
"case": "trusted-native-insertion",
"submitted": "012345",
"posts": 1
},
{
"width": 320,
"case": "real-clipboard",
"synthetic_value": "\"123456\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 320,
"case": "real-clipboard",
"synthetic_value": "\" \\t123456\\r\\n\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 320,
"case": "real-clipboard",
"synthetic_value": "\"1 2 3 4 5 6\"",
"submitted": "123456",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 320,
"case": "real-clipboard",
"synthetic_value": "\"012345\"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 320,
"case": "real-clipboard",
"synthetic_value": "\" 012 345 \"",
"submitted": "012345",
"posts": 1,
"all_six_populated_before_submit": true,
"trusted_paste": true
},
{
"width": 320,
"case": "trusted-native-insertion",
"submitted": "012345",
"posts": 1
}
]
}

View File

@ -1,47 +1,73 @@
// Run against a loopback visual host rendering the real Account/TwoFactor view
// with a synthetic pending challenge. No real user, TOTP or database is needed.
// Actual Razor view in a loopback, database-free pending-auth fixture. Only
// synthetic codes are used. Clipboard cases use the browser clipboard + Ctrl+V;
// native insertion uses trusted CDP input (Android/IME-style), not value assignment.
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const base=process.env.OTP_VISUAL_URL||'http://127.0.0.1:5282';
assert(/^http:\/\/127\.0\.0\.1:\d+$/.test(base),'Loopback fixture required');
const output=process.env.OTP_SCREENSHOTS;
if(!/^http:\/\/127\.0\.0\.1:\d+$/.test(base))throw Error('Loopback visual fixture required');
(async()=>{const browser=await chromium.launch();try{
(async()=>{const browser=await chromium.launch();const results=[];try{
for(const width of [1440,390,320]){
const page=await browser.newPage({viewport:{width,height:950}});
await page.goto(base+'/Account/TwoFactor');
const digits=page.locator('[data-two-factor-digit]');assert.equal(await digits.count(),6);
const geometry=await digits.evaluateAll(xs=>xs.map(x=>{const r=x.getBoundingClientRect();return{x:r.x,y:r.y,w:r.width,h:r.height,align:getComputedStyle(x).textAlign}}));
assert(geometry.every(x=>Math.abs(x.y-geometry[0].y)<.1&&Math.abs(x.w-geometry[0].w)<.1&&Math.abs(x.w-x.h)<.1&&x.align==='center'));
assert(geometry[0].w<=56&&geometry[0].w>=24);
const gaps=geometry.slice(1).map((x,i)=>x.x-geometry[i].x-geometry[i].w);assert(gaps.every(x=>x>0&&Math.abs(x-gaps[0])<.1));
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
const action=await page.locator('.two-factor-actions').boundingBox();assert(action.y-geometry[0].y-geometry[0].h>=20);
const context=await browser.newContext({viewport:{width,height:950},permissions:['clipboard-read','clipboard-write']});
const page=await context.newPage();let submits=[],posts=[],pastes=[],insertions=[];
await page.exposeFunction('observeOtp',x=>{if(x.type==='submit')submits.push(x);else if(x.type==='paste')pastes.push(x);else insertions.push(x);});
await page.addInitScript(()=>{
document.addEventListener('paste',e=>{if(e.target.matches('[data-two-factor-digit]'))window.observeOtp({type:'paste',trusted:e.isTrusted});},true);
document.addEventListener('beforeinput',e=>{if(e.target.matches('[data-two-factor-digit]'))window.observeOtp({type:'beforeinput',trusted:e.isTrusted,inputType:e.inputType,data:e.data});},true);
document.addEventListener('submit',e=>{if(e.target.matches('[data-two-factor-form]'))window.observeOtp({type:'submit',values:Array.from(e.target.querySelectorAll('[data-two-factor-digit]'),x=>x.value),code:e.target.querySelector('[data-two-factor-code]').value});},true);
});
page.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/Account/TwoFactor')posts.push(new URLSearchParams(r.postData()).get('Code'));});
const digits=page.locator('[data-two-factor-digit]');
const fresh=async()=>{await page.goto(base+'/Account/TwoFactor');await digits.first().waitFor();submits=[];posts=[];pastes=[];insertions=[];};
const clipboard=async text=>{await digits.first().focus();await page.evaluate(text=>navigator.clipboard.writeText(text),text);await page.keyboard.press('Control+V');};
const rejected=async()=>{await page.getByText('Synthetic authenticator rejection. Try again.',{exact:true}).waitFor();await page.waitForTimeout(30);};
const assertSubmission=code=>{assert.deepEqual(posts,[code]);assert.equal(submits.length,1);assert.equal(submits[0].code,code);assert.deepEqual(submits[0].values,[...code]);};
await fresh();
const layout=await page.evaluate(()=>{
const box=x=>{const r=x.getBoundingClientRect();return{x:r.x,y:r.y,w:r.width,h:r.height,cx:r.x+r.width/2}};
const xs=Array.from(document.querySelectorAll('[data-two-factor-digit]'),box),label=document.querySelector('.two-factor-label'),help=document.querySelector('.two-factor-help');
return{xs,label:box(label),labelAlign:getComputedStyle(label).textAlign,buttons:Array.from(document.querySelector('.two-factor-actions').children,box),helpAlign:getComputedStyle(help).textAlign,overflow:document.documentElement.scrollWidth>innerWidth,card:box(document.querySelector('.two-factor-card'))};
});
assert.equal(layout.overflow,false);assert.equal(layout.labelAlign,'center');assert.equal(layout.helpAlign,'center');
assert(layout.xs.every(x=>Math.abs(x.y-layout.xs[0].y)<.1&&Math.abs(x.w-layout.xs[0].w)<.1&&Math.abs(x.w-x.h)<.1));
const rowCenter=(layout.xs[0].x+layout.xs[5].x+layout.xs[5].w)/2;
assert(Math.abs(rowCenter-layout.label.cx)<1);assert(Math.abs((layout.buttons[0].x+layout.buttons[1].x+layout.buttons[1].w)/2-rowCenter)<1);
assert(Math.abs(layout.buttons[0].y-layout.buttons[1].y)<1);assert(layout.buttons[0].y-layout.xs[0].y-layout.xs[0].h>=20);
for(let i=0;i<6;i++){
assert.equal(await digits.nth(i).getAttribute('aria-label'),`Digit ${i+1} of 6`);
assert.equal(await digits.nth(i).getAttribute('inputmode'),'numeric');assert.equal(await digits.nth(i).getAttribute('maxlength'),'1');
assert.equal(await digits.nth(i).getAttribute('autocomplete'),'one-time-code');assert.equal(await digits.nth(i).getAttribute('pattern'),'[0-9]*');
assert.equal(await digits.nth(i).getAttribute('aria-label'),`Digit ${i+1} of 6`);assert.equal(await digits.nth(i).getAttribute('autocomplete'),'one-time-code');
}
const focus=await digits.first().evaluate(x=>{const s=getComputedStyle(x);return s.outlineStyle!=='none'||s.boxShadow!=='none'});assert(focus);
await page.evaluate(()=>{window.otpSubmissions=[];document.querySelector('form[data-two-factor-form]').addEventListener('submit',e=>{e.preventDefault();window.otpSubmissions.push(document.querySelector('[data-two-factor-code]').value)});});
await digits.first().press('a');assert.equal(await digits.first().inputValue(),'');assert(await digits.first().evaluate(x=>x===document.activeElement));
for(let i=0;i<6;i++){await digits.nth(i).press(String(i+1));if(i<5)assert(await digits.nth(i+1).evaluate(x=>x===document.activeElement));}
assert.equal(await page.locator('[data-two-factor-code]').inputValue(),'123456');assert.deepEqual(await page.evaluate(()=>window.otpSubmissions),['123456']);
if(output)await page.screenshot({path:`${output}/after-${width}.png`,fullPage:true});
assert.equal(await page.locator('form[data-two-factor-form]').getAttribute('method'),'post');assert.equal(await page.locator('input[name=__RequestVerificationToken]').count(),1);
await page.reload();await page.evaluate(()=>{window.otpSubmissions=[];document.querySelector('[data-two-factor-form]').addEventListener('submit',e=>{e.preventDefault();window.otpSubmissions.push(document.querySelector('[data-two-factor-code]').value)});});
await digits.first().evaluate(x=>{const d=new DataTransfer();d.setData('text','12 34-56');x.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,cancelable:true,clipboardData:d}));});
assert.deepEqual(await digits.evaluateAll(xs=>xs.map(x=>x.value)),['1','2','3','4','5','6']);assert.deepEqual(await page.evaluate(()=>window.otpSubmissions),['123456']);
await page.reload();await digits.first().press('1');await digits.nth(1).press('2');await digits.nth(2).press('Backspace');
assert(await digits.nth(1).evaluate(x=>x===document.activeElement));assert.deepEqual((await digits.evaluateAll(xs=>xs.map(x=>x.value))).slice(0,3),['1','','']);
await digits.nth(1).press('Tab');assert(await digits.nth(2).evaluate(x=>x===document.activeElement));await digits.nth(2).press('Shift+Tab');assert(await digits.nth(1).evaluate(x=>x===document.activeElement));
await digits.nth(1).press('ArrowLeft');await digits.nth(1).press('ArrowRight');assert.deepEqual((await digits.evaluateAll(xs=>xs.map(x=>x.value))).slice(0,3),['1','','']);
assert.equal(await page.getByRole('link',{name:'Use a recovery code.'}).getAttribute('href'),'/Account/TwoFactorRecovery?returnUrl=%2F');
// Empty Code uses the existing server-side required validation, never TOTP.
await page.reload();const response=page.waitForResponse(r=>r.url().endsWith('/Account/TwoFactor')&&r.request().method()==='POST');
await page.getByRole('button',{name:'Continue',exact:true}).click();assert.equal((await response).status(),200);await page.waitForLoadState();
assert(await page.getByText('Enter the code from your authenticator app.',{exact:true}).isVisible());assert.equal(await page.locator('[data-two-factor-digit]').count(),6);
await page.close();
if(output)await page.screenshot({path:`${output}/centred-${width}.png`,fullPage:true});
for(const [text,expected] of [['123456','123456'],[' \t123456\r\n','123456'],['1 2 3 4 5 6','123456'],['012345','012345'],['\u00a0012\u202f345\u00a0','012345']]){
await fresh();await clipboard(text);await rejected();assertSubmission(expected);assert(pastes.some(x=>x.trusted));
results.push({width,case:'real-clipboard',synthetic_value:JSON.stringify(text),submitted:expected,posts:posts.length,all_six_populated_before_submit:true,trusted_paste:true});
}
for(const text of ['12345','1234567','abc123456','12-34-56','123\n456','123456']){
await fresh();await clipboard(text);await page.waitForTimeout(70);assert.equal(posts.length,0);assert.equal(submits.length,0);
assert.deepEqual(await digits.evaluateAll(xs=>xs.map(x=>x.value)),['','','','','','']);
}
// Browser-native insertion exposes the full value BEFORE maxlength truncation.
await fresh();await digits.first().focus();await page.keyboard.insertText('012345');await rejected();assertSubmission('012345');
assert(insertions.some(x=>x.trusted&&x.data==='012345'));results.push({width,case:'trusted-native-insertion',submitted:'012345',posts:posts.length});
// A real rejected response renders a new attempt; no cancellation/mock response.
submits=[];posts=[];pastes=[];await clipboard('654321');await rejected();assertSubmission('654321');
await fresh();for(let i=0;i<6;i++)await digits.nth(i).press(String(i+1));await rejected();assertSubmission('123456');
await fresh();await digits.first().press('1');await digits.nth(1).press('2');await digits.nth(2).press('3');await digits.nth(3).press('Backspace');
assert(await digits.nth(2).evaluate(x=>x===document.activeElement));assert.equal(await page.locator('[data-two-factor-code]').inputValue(),'12');
await digits.nth(2).press('4');await digits.first().focus();await digits.first().press('0');assert.equal(await page.locator('[data-two-factor-code]').inputValue(),'024');
await digits.first().press('Tab');assert(await digits.nth(1).evaluate(x=>x===document.activeElement));await digits.nth(1).press('Shift+Tab');assert(await digits.first().evaluate(x=>x===document.activeElement));
await digits.first().press('ArrowRight');await digits.first().press('ArrowLeft');assert.equal(await page.locator('[data-two-factor-code]').inputValue(),'024');
await page.getByRole('button',{name:'Continue',exact:true}).click();await rejected();assert.deepEqual(posts,['024']);
// A cancelled client validation must not permanently latch automatic submission.
await fresh();await page.evaluate(()=>document.querySelector('[data-two-factor-form]').addEventListener('submit',e=>e.preventDefault(),{once:true}));
await clipboard('123456');await page.waitForTimeout(50);assert.equal(posts.length,0);assert.equal(submits.length,1);
submits=[];await digits.first().focus();await digits.first().press('9');await rejected();assertSubmission('923456');
await fresh();await page.getByRole('button',{name:'Continue',exact:true}).click();await page.getByText('Enter the code from your authenticator app.',{exact:true}).waitFor();assert.deepEqual(posts,['']);
await page.goto(base+'/fixture/setup');assert.equal(await page.getByLabel('Verification code').count(),1);assert.equal(await page.locator('[data-two-factor-digit]').count(),0);
assert((await page.getByLabel('Verification code').boundingBox()).width>100);
await context.close();
}
console.log('PASS Chromium OTP: desktop/390/320 single row, equal squares/gaps, centred text, focus, no overflow, spacing, numeric input, advancement, paste, backspace, tab/arrows, accessibility, auto-POST payload/antiforgery and real required validation.');
if(output)fs.writeFileSync(`${output}/genuine-clipboard-results.json`,JSON.stringify({status:'passed',physical_android_device_tested:false,results},null,2));
console.log('PASS actual Razor/HTTP rejection: genuine Ctrl+V, whitespace/grouping/leading zero, malformed rejection, trusted native insertion, exactly one POST, typing/backspace/correction/navigation/manual submit, cancelled-submit retry, rejected-code retry; centred desktop/390/320 layout and separate setup field.');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});

View File

@ -68,25 +68,48 @@
const submitIfComplete = () => {
syncCode();
if (isComplete() && !hasSubmitted) {
hasSubmitted = true;
form.requestSubmit();
}
};
const fillFrom = (startIndex, value) => {
const numbers = value.replace(/\D/g, "").slice(0, digits.length - startIndex);
numbers.split("").forEach((number, offset) => {
digits[startIndex + offset].value = number;
});
const nextIndex = Math.min(startIndex + numbers.length, digits.length - 1);
digits[nextIndex].focus();
submitIfComplete();
const fullCode = value => {
// Only conventional digit grouping spaces are allowed internally.
const normalized = value.trim().replace(/[ \u00a0\u202f]/g, "");
return /^[0-9]{6}$/.test(normalized) ? normalized : null;
};
const fillCode = value => {
const code = fullCode(value);
if (!code) return false;
// Populate atomically: assignments do not dispatch input events.
digits.forEach((input, index) => input.value = code[index]);
syncCode();
digits[digits.length - 1].focus();
submitIfComplete();
return true;
};
const isDigit = target => digits.includes(target);
// Capture the original text before native maxlength processing. Use
// text/plain rather than relying on a browser's legacy "text" alias.
form.addEventListener("paste", event => {
if (!isDigit(event.target)) return;
const text = event.clipboardData?.getData("text/plain");
if (typeof text !== "string" || text === "") return;
event.preventDefault();
fillCode(text);
}, true);
// Native autofill and some browser/mobile insertion paths do not
// dispatch a ClipboardEvent. beforeinput still carries the full text.
form.addEventListener("beforeinput", event => {
if (!isDigit(event.target) || !event.inputType?.startsWith("insert")) return;
const text = event.dataTransfer?.getData("text/plain") || event.data;
if (typeof text !== "string" || text.length <= 1) return;
event.preventDefault();
fillCode(text);
}, true);
digits.forEach((input, index) => {
input.addEventListener("input", () => {
if (input.value.length > 1) {
fillFrom(index, input.value);
if (!fillCode(input.value)) { input.value = ""; syncCode(); }
return;
}
@ -108,16 +131,24 @@
}
});
input.addEventListener("paste", event => {
event.preventDefault();
fillFrom(index, event.clipboardData.getData("text"));
});
input.addEventListener("focus", () => input.select());
});
form.addEventListener("submit", () => {
form.addEventListener("submit", event => {
syncCode();
if (hasSubmitted) {
event.preventDefault();
return;
}
hasSubmitted = true;
// Client validation may cancel submission. Permit correction and
// retry once all submit listeners have finished.
queueMicrotask(() => {
if (event.defaultPrevented) hasSubmitted = false;
});
});
window.addEventListener("pageshow", event => {
if (event.persisted) hasSubmitted = false;
});
digits.forEach(input => {

View File

@ -231,6 +231,9 @@ html[data-site-theme="public"] {
.auth-help { margin-top: 20px; font-size: 13px; }
/* OTP geometry must not depend on the installed-window-only legacy theme. */
.two-factor-code-group { margin-bottom: 1.5rem; }
.two-factor-label { display: block; text-align: center; margin-bottom: 0; }
.two-factor-actions { display: flex; align-items: center; justify-content: center; gap: .75rem; }
.two-factor-help { text-align: center; margin-top: 1rem; }
.two-factor-inputs {
display: grid;
grid-template-columns: repeat(6, minmax(0, 3.5rem));