: asapien/signet

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
// Real browser/API/worker regression; run against the isolated Alpine dev stack.
// PLAYWRIGHT_MODULE=/path/to/playwright-core/index.mjs node test/signing-flow.mjs
import assert from 'node:assert/strict';
import { mkdir, readFile } from 'node:fs/promises';
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright-core');
const base = process.env.SIGNET_URL || 'http://localhost:8080';
const output = process.env.SIGNET_EVIDENCE || '/tmp/signet-ticket11-browser';
await mkdir(output, { recursive: true });
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true });
let page;
const errors = [];
try {
  const context = await browser.newContext({ viewport: { width: 1440, height: 1700 } });
  page = await context.newPage();
  page.on('pageerror', (e) => errors.push(e.message));
  async function identity(user, groups) {
    await context.setExtraHTTPHeaders({ 'Remote-User': user, 'Remote-Groups': groups, 'X-Requested-With': 'signet' });
    if (page.url().startsWith(base)) await page.reload();
  }
  await identity('root', 'signet-admins');
  for (const [key, type, value] of [['gstin', 'text', '33AAAAA0000A1Z5'], ['seal', 'image', 'seals/agency_seal.png'], ['logo', 'image', 'seals/agency_image.jpg']]) {
    assert((await context.request.post(base + '/pim-api/attrs', { multipart: { org: 'BROWSER11', key, type, value } })).ok());
  }
  await identity('asha', 'clerks');
  const upload = await context.request.post(base + '/api/docs', { multipart: { file: { name: 'letter.pdf', mimeType: 'application/pdf', buffer: await readFile(new URL('fixtures/letter.pdf', import.meta.url)) } } });
  const { id } = await upload.json();
  const finalSigner = 'browser_' + Date.now();
  const layout = { title: 'Browser sequential signing', org_code: 'BROWSER11', route: { parties: [{ name: 'Manager', signer: 'manager' }, { name: 'Audit', signer: 'auditor' }, { name: 'Partner', signer: finalSigner }] }, layout: { reference_width: 1000, reference_height: 1414, imprints: [
    { type: 'pim_text', page: 1, ref: 'gstin', prefix: 'GSTIN: ', coords: [120, 150, 520, 180], font: 'fonts/DejaVuSans.ttf' },
    { type: 'signature_zone', page: 1, party: 'Manager', coords: [120, 550, 500, 700], min_w: 50, min_h: 20 },
    { type: 'pim_image', page: 2, ref: 'seal', shape: 'circle', coords: [300, 1100, 90] },
    { type: 'pim_image', page: 2, ref: 'logo', shape: 'rect', coords: [120, 1250, 320, 1350] },
    { type: 'signature_zone', page: 2, party: 'Partner', coords: [400, 1000, 850, 1200], min_w: 70, min_h: 25 },
  ] } };
  assert((await context.request.post(base + `/api/docs/${id}/save`, { multipart: { json: JSON.stringify(layout) } })).ok());
  async function open() {
    await page.goto(base + '/#/doc/' + id);
    await page.reload();
    await page.locator('.page').nth(1).waitFor();
    await page.waitForFunction(() => [...document.querySelectorAll('.page img')].every((i) => i.complete && i.naturalWidth));
    await page.evaluate(() => document.fonts.ready);
    await page.waitForTimeout(200);
  }
  async function capture(label) {
    for (let i = 0; i < 2; i++) await page.locator('.page').nth(i).screenshot({ path: `${output}/${label}-${i + 1}.png` });
  }
  async function signOff() {
    const [response] = await Promise.all([page.waitForResponse((r) => r.url().endsWith('/decide') && r.request().method() === 'POST'), page.getByRole('button', { name: 'Sign off', exact: true }).click()]);
    assert(response.ok(), await response.text());
  }
  async function ready() {
    for (let i = 0; i < 120; i++) {
      const r = await context.request.get(base + '/api/docs/' + id), d = await r.json();
      assert(r.ok(), JSON.stringify(d));
      assert.equal(d.render_error, null);
      if (!d.rendering) return d;
      await page.waitForTimeout(100);
    }
    throw Error('worker timeout');
  }
  await open();
  const textBox = await page.locator('.overlay .box.t-pim_text').evaluate((b) => ({
    height: b.getBoundingClientRect().height,
    content: b.clientHeight,
    size: parseFloat(getComputedStyle(b).fontSize),
  }));
  assert(Math.abs(textBox.height - textBox.content) < 1, 'overlay decoration must not consume the renderer box');
  assert(Math.abs(textBox.size - textBox.height * .7) < .75, 'editor text must use 70% of the full imprint height');
  await page.locator('#f-title').fill('');
  assert(await page.getByRole('button', { name: 'Submit', exact: true }).isDisabled());
  await page.locator('#f-title').fill(layout.title);
  await page.getByRole('button', { name: 'Save draft', exact: true }).click();
  await page.getByText('Saved', { exact: true }).waitFor();
  const saved = await (await context.request.get(base + '/api/docs/' + id)).json();
  assert.equal(saved.org_code, 'BROWSER11');
  assert.equal(saved.layout.imprints.find((i) => i.party === 'Manager').min_w, 50);
  assert.equal(saved.layout.imprints.find((i) => i.party === 'Partner').min_h, 25);
  await capture('edit');
  await Promise.all([page.waitForResponse((r) => r.url().endsWith('/submit') && r.request().method() === 'POST'), page.getByRole('button', { name: 'Submit', exact: true }).click()]);
  await ready();
  await open();
  await capture('proof');

  await identity(finalSigner, 'management');
  assert.equal((await context.request.get(base + `/api/docs/${id}`)).status(), 404);
  await identity('manager', 'management');
  const originalSignature = (await (await context.request.get(base + '/api/me')).json()).facsimile;
  await page.getByRole('link', { name: 'My signatures', exact: true }).click();
  await page.getByRole('heading', { name: 'My signatures', exact: true }).waitFor();
  const alternateLabel = 'Browser alternate ' + Date.now();
  await page.getByLabel('Signature label', { exact: true }).fill(alternateLabel);
  await page.getByLabel('Or upload PNG', { exact: true }).setInputFiles(new URL('fixtures/seal.png', import.meta.url).pathname);
  await page.getByRole('button', { name: 'Enrol signature', exact: true }).click();
  await page.getByText(alternateLabel, { exact: true }).waitFor();
  let collection = await (await context.request.get(base + '/api/me')).json();
  const alternate = collection.facsimiles.find((f) => f.label === alternateLabel);
  assert(alternate.enrolled);
  assert.equal(collection.facsimile.id, originalSignature.id, 'adding a variant must not replace the default');
  await page.locator('.row').filter({ has: page.getByText(alternateLabel, { exact: true }) }).getByRole('button', { name: /as default$/ }).click();
  await page.getByText('Default updated', { exact: true }).waitFor();
  assert.equal((await (await context.request.get(base + '/api/me')).json()).facsimile.id, alternate.id);
  await page.locator('.row').filter({ has: page.getByText(originalSignature.label, { exact: true }) }).getByRole('button', { name: /as default$/ }).click();
  await page.waitForFunction((name) => [...document.querySelectorAll('.card .row')].some((r) => r.textContent.includes(name) && r.textContent.includes('Default')), originalSignature.label);
  await page.screenshot({ path: output + '/signature-collection.png', fullPage: true });
  await open();
  await page.getByLabel('Signature to use', { exact: true }).selectOption(alternate.id);
  let shape = await page.locator('area[data-placement]').getAttribute('data-coords');
  let bounds = shape.split(',').map(Number);
  assert(Math.abs((bounds[2] - bounds[0]) / (bounds[3] - bounds[1]) - 1) < .01, 'picker must refit to selected dimensions');
  assert.equal(await page.locator('area[data-placement]').count(), 1);
  await page.screenshot({ path: output + '/signature-picker.png', fullPage: true });
  await page.getByLabel('Signature to use', { exact: true }).selectOption(originalSignature.id);
  let placement = page.locator('.placement');
  await placement.waitFor();
  let coords = await page.locator('area[data-placement]').getAttribute('data-coords');
  await placement.focus();
  await placement.press('Shift+ArrowLeft');
  assert.notEqual(await page.locator('area[data-placement]').getAttribute('data-coords'), coords);
  coords = await page.locator('area[data-placement]').getAttribute('data-coords');
  await placement.press('ArrowRight');
  assert.notEqual(await page.locator('area[data-placement]').getAttribute('data-coords'), coords);
  const grip = await page.locator('.placement .grip').boundingBox();
  await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
  await page.mouse.down();
  await page.mouse.move(grip.x - 40, grip.y - 15, { steps: 5 });
  await page.mouse.up();
  const chosen = JSON.parse(await page.locator('area[data-placement]').evaluate((a) => JSON.stringify(a.dataset.coords.split(',').map(Number))));
  assert(chosen[0] >= 120 && chosen[1] >= 550 && chosen[2] <= 500 && chosen[3] <= 700);
  assert(chosen[2] - chosen[0] >= 50 && chosen[3] - chosen[1] >= 20);
  await signOff();
  assert.equal((await ready()).decisions[0].facsimile_id, originalSignature.id, 'browser choice must be recorded');
  await open();
  await capture('stamped');
  await identity('auditor', 'management');
  await open();
  assert.equal(await page.locator('.placement').count(), 0, 'check-only party needs no placement');
  await signOff();
  await identity(finalSigner, 'management');
  await open();
  await page.getByRole('heading', { name: 'Enrol your signature', exact: true }).waitFor();
  await page.locator('input[type=file]').setInputFiles(new URL('fixtures/sig.png', import.meta.url).pathname);
  await page.getByRole('button', { name: 'Enrol signature', exact: true }).click();
  await page.locator('.placement').waitFor({ timeout: 15000 });
  await page.locator('textarea').fill('Browser final sign-off');
  await signOff();
  const released = await ready();
  assert.equal(released.status, 'RELEASED');
  assert.equal(released.decisions.length, 3);
  assert(released.events.some((e) => e.action === 'RELEASED'));
  await open();
  await page.getByRole('button', { name: 'Open print copy (PDF)', exact: true }).waitFor();
  await page.getByRole('heading', { name: 'Event log', exact: true }).waitFor();
  await capture('final');
  await page.locator('.page').nth(2).screenshot({ path: output + '/audit.png' });
  assert.equal((await context.request.get(base + `/api/docs/${id}/file/stamped`)).status(), 404);
  // A full collection must remain usable, including long labels and the form below it.
  const listContext = await browser.newContext({ viewport: { width: 800, height: 700 }, extraHTTPHeaders: {
    'Remote-User': 'collection_ui_' + Date.now(), 'Remote-Groups': 'management', 'X-Requested-With': 'signet'
  } });
  const sample = await readFile(new URL('fixtures/sig.png', import.meta.url));
  for (let i = 0; i < 32; i++) {
    assert((await listContext.request.post(base + '/api/me/facsimile', { multipart: {
      label: i ? 'Variant ' + i : 'W'.repeat(80), file: { name: 'sig.png', mimeType: 'image/png', buffer: sample }
    } })).ok());
  }
  const listPage = await listContext.newPage();
  listPage.on('pageerror', (e) => errors.push(e.message));
  await listPage.goto(base + '/#/signatures');
  await listPage.getByRole('heading', { name: 'My signatures', exact: true }).waitFor();
  await listPage.getByRole('button', { name: 'Enrol signature', exact: true }).scrollIntoViewIfNeeded();
  assert(await listPage.locator('.signature-collection').evaluate((el) => el.scrollTop > 0));
  assert(await listPage.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
  await listPage.screenshot({ path: output + '/signature-collection-scroll.png' });
  await listContext.close();
  assert.deepEqual(errors, []);
  console.log('signing flow: edit/save, two-page proof, constrained keyboard/pointer placement, check-only, enrolment, final release and event log passed; id=' + id);
} catch (error) {
  console.error('Browser errors:', errors);
  if (page) {
    console.error(await page.locator('#view').innerText());
    await page.screenshot({ path: output + '/failure.png', fullPage: true });
  }
  throw error;
} finally {
  await browser.close();
}