gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf5-styles9ced53c3|||PR ident#33 ident#35 every component's styles live in its own Style block; styles.hl keeps the page-wide rest; the account bar is phone first (min-width: 60rem block); the avatar preview is hidden with the hidden attribute (ident#34 in part)mref5-styles/tests/invites.mjs

16.2 KB

  1. // tests/invites.mjs — THE GATE OF THE INVITE SERVICE (ticket ident#22): an app invites people
  2. // by link through ident. Real headless Chrome (tests/cdp.mjs, --disable-gpu) opens the links;
  3. // the API parts run over HTTP. Own servers only, NEVER the dev server, NEVER real mail:
  4. // ident :8700 (IDENT_MAIL_SINK, a "day" of 3 s so an invite expires within the run),
  5. // test app :8701 (the app of the invites, against ident :8700).
  6. // Own storage: .scratch/invites-gate/ (wiped at start). Chrome debug ports 8706-8709.
  7. //
  8. // Run: node tests/invites.mjs (exit 0 = all passed)
  9. import { spawn } from 'node:child_process';
  10. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';
  11. import { dirname, join } from 'node:path';
  12. import { fileURLToPath } from 'node:url';
  13. import { launchBrowser, sleep } from './cdp.mjs';
  14. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  15. const G = join(APP, '.scratch/invites-gate');
  16. const P0 = Number(process.env.INVITES_GATE_PORT || 8700); // ident = P0, test app = P0+1, Chrome INVITES_GATE_CHROME (default 8706-8709)
  17. const ID = 'http://127.0.0.1:' + P0, TA = 'http://127.0.0.1:' + (P0 + 1);
  18. let passed = 0, failed = 0;
  19. const check = (name, ok, detail = '') => {
  20. if (ok) { passed++; console.log(' ok ' + name); }
  21. else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  22. };
  23. const procs = [];
  24. function start(cwd, env, log) {
  25. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  26. let out = '';
  27. p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  28. p.on('exit', () => writeFileSync(join(G, log), out));
  29. procs.push(p);
  30. }
  31. async function up(url) {
  32. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); Date.now() < end;) { try { await fetch(url + "/", { redirect: "manual" }); return; } catch {} await sleep(250); }
  33. throw new Error('server did not come up: ' + url);
  34. }
  35. const stopAll = () => { for (const p of procs) { try { p.kill(); } catch {} } };
  36. rmSync(G, { recursive: true, force: true });
  37. mkdirSync(join(G, 'ident'), { recursive: true });
  38. start(APP, { IDENT_PORT: String(P0), IDENT_STORAGE: join(G, 'ident'), IDENT_SESSIONS: join(G, 'sess') + '/', IDENT_MAIL_SINK: join(G, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_INVITE_DAY_MS: '3000', IDENT_INVITE_MAIL_LIMIT: '3' }, 'ident.log');
  39. await up(ID);
  40. const lastCode = (email) => {
  41. const f = join(G, 'mail.txt');
  42. const lines = existsSync(f) ? readFileSync(f, 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' ')) : [];
  43. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  44. };
  45. const inviteMails = () => { const f = join(G, 'mail.txt.invites'); return existsSync(f) ? readFileSync(f, 'utf8').trim().split('\n').filter(Boolean) : []; };
  46. let emitI = 0;
  47. async function emit(event, payload, cookie) {
  48. const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: JSON.stringify({ t: 'emit', i: ++emitI, event, payload }) });
  49. const t = await r.text();
  50. let j = null; try { j = JSON.parse(t); } catch {}
  51. return { cookie: (r.headers.get('set-cookie') || '').split(';')[0], value: j && j.value, raw: t };
  52. }
  53. async function post(path, body, base = ID) {
  54. const r = await fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: typeof body === 'string' ? body : JSON.stringify(body) });
  55. const t = await r.text();
  56. let j = null; try { j = JSON.parse(t); } catch {}
  57. return { status: r.status, j, t };
  58. }
  59. // the app's owner: an ident account + the app (over the faces)
  60. await post('/api/code', { email: '[email protected]' });
  61. const own = await emit('verifyCode', ['[email protected]', lastCode('[email protected]'), 'UTC']);
  62. const created = (await emit('appCreate', [{ name: 'Demo tickets', origins: [TA] }], own.cookie)).value;
  63. const KEY = created.app.apiKey, SECRET = created.secret;
  64. writeFileSync(join(G, 'testapp.json'), JSON.stringify({ key: KEY, secret: SECRET, users: {}, count: 0, sessions: {} }));
  65. start(join(APP, 'testapp'), { TESTAPP_PORT: String(P0 + 1), TESTAPP_URL: TA, IDENT_URL: ID, TESTAPP_STORE: join(G, 'testapp.json') }, 'testapp.log');
  66. await up(TA);
  67. const A = { key: KEY, secret: SECRET };
  68. const mk = (extra = {}) => post('/api/invites', { ...A, project: 'Website', role: 'editor', return: TA + '/callback', ...extra });
  69. const idOf = (invId) => post('/api/invites/get', { ...A, id: invId });
  70. let br;
  71. try {
  72. // ---- the API: negatives -----------------------------------------------------------------
  73. console.log('API');
  74. let r = await post('/api/invites', { ...A, key: 'pk_' + '0'.repeat(32), project: 'p', role: 'r', return: TA + '/callback' });
  75. check('unknown key → 401', r.status === 401, r.t);
  76. r = await post('/api/invites', { ...A, secret: 'sk_' + '0'.repeat(48), project: 'p', role: 'r', return: TA + '/callback' });
  77. check('wrong secret → 401', r.status === 401, r.t);
  78. r = await mk({ bogus: 1 });
  79. check('unknown field → 400 naming it', r.status === 400 && /unknown field: bogus/.test(r.j.error), r.t);
  80. r = await post('/api/invites', { ...A, project: 'p', role: 'r' });
  81. check('missing return → 400 naming it', r.status === 400 && /missing field: return/.test(r.j.error), r.t);
  82. r = await mk({ return: 'http://evil.example/cb' });
  83. check('return outside the app origins → 400', r.status === 400 && /not one of the origins/.test(r.j.error), r.t);
  84. r = await mk({ uses: 0 });
  85. check('uses 0 → 400', r.status === 400 && /uses/.test(r.j.error), r.t);
  86. r = await mk({ days: 1.5 });
  87. check('days 1.5 → 400', r.status === 400 && /days/.test(r.j.error), r.t);
  88. r = await mk({ email: 'nope' });
  89. check('bad email → 400', r.status === 400 && /email/.test(r.j.error), r.t);
  90. r = await mk({ role: '' });
  91. check('empty role → 400', r.status === 400 && /role/.test(r.j.error), r.t);
  92. r = await fetch(ID + '/api/invites');
  93. check('GET on the create call → 405', r.status === 405);
  94. r = await fetch(ID + '/invite/' + '0'.repeat(32), { redirect: 'manual' });
  95. check('unknown link → 404 error page', r.status === 404 && /not valid/.test(await r.text()));
  96. // ---- 1. a new address: email → code → back in the app ------------------------------------
  97. console.log('new person, private window');
  98. r = await mk({ days: 90 });
  99. check('create → 200 with link, single use, open', r.status === 200 && /\/invite\/[0-9a-f]{32}$/.test(r.j.url) && r.j.uses === 1 && r.j.state === 'open' && r.j.url.startsWith(ID), r.t);
  100. const inv1 = r.j;
  101. br = await launchBrowser({ debugPortRange: (process.env.INVITES_GATE_CHROME || '8706-8709').split('-').map(Number) });
  102. const p = await br.newPage();
  103. await p.send('Emulation.setTimezoneOverride', { timezoneId: 'Europe/Vienna' });
  104. await p.goto(inv1.url);
  105. await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated' });
  106. check('link → ident sign-in for the app, worded as an invitation', /You are invited to\s*Demo tickets/.test(await p.text('#apprequest')), await p.text('#apprequest'));
  107. await p.type('#email', '[email protected]');
  108. await p.click('#sendcode');
  109. await p.waitFor('!!document.querySelector("#code")', { label: 'code form' });
  110. // the code page is server-rendered after a navigation: wait for hydration, or the click is a native GET submit (?code=…) and the field stays empty
  111. await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'code page hydrated' });
  112. await p.type('#code', lastCode('[email protected]'));
  113. await p.click('#verify');
  114. await p.waitFor('!!document.querySelector("#skip")', { label: 'welcome form' });
  115. await p.click('#skip');
  116. await p.waitFor('!!document.querySelector("#chooselist .choose")', { label: 'choose list' });
  117. await p.click('#chooselist .choose');
  118. await p.waitFor('!!document.querySelector("#invite")', { label: 'back in the app', timeout: 15000 });
  119. check('back in the app: invite reports used, accepted by the logged-in identity', (await p.text('#invitestate')) === 'used' && (await p.text('#invitewho')) === 'this identity', await p.text('#invite'));
  120. check('the invite carries its project and role', (await p.text('#inviteproject')) === 'Website' && (await p.text('#inviterole')) === 'editor');
  121. const g = await idOf(inv1.id);
  122. check('get: used 1 of 1, one identity, state used', g.j.invite.state === 'used' && g.j.invite.used === 1 && g.j.invite.identities.length === 1 && /^[2-9a-hj-km-np-z]{5}$/.test(g.j.invite.identities[0]), g.t);
  123. check('the answer never contains the link or an email', !/newbie|invite\//.test(g.t));
  124. // ---- 2. the same link again --------------------------------------------------------------
  125. console.log('used, revoked, expired');
  126. const again = await fetch(inv1.url, { redirect: 'manual' });
  127. const againText = await again.text();
  128. check('the same link again → "already used"', again.status === 410 && /already used/.test(againText), again.status + againText.slice(0, 80));
  129. r = await mk();
  130. const inv2 = r.j;
  131. r = await post('/api/invites/revoke', { ...A, id: inv2.id });
  132. check('revoke an open invite → revoked', r.status === 200 && r.j.invite.state === 'revoked', r.t);
  133. const rv = await fetch(inv2.url, { redirect: 'manual' });
  134. check('a revoked link → "withdrawn"', rv.status === 410 && /withdrawn/.test(await rv.text()));
  135. r = await post('/api/invites/revoke', { ...A, id: inv1.id });
  136. check('revoking a used invite is refused (409)', r.status === 409, r.t);
  137. r = await mk({ days: 1 });
  138. const inv3 = r.j;
  139. await sleep(3300);
  140. const ex = await fetch(inv3.url, { redirect: 'manual' });
  141. check('an expired link → "expired"', ex.status === 410 && /expired/.test(await ex.text()));
  142. check('get: state expired', (await idOf(inv3.id)).j.invite.state === 'expired');
  143. // ---- 3. already logged in to ident: one click --------------------------------------------
  144. console.log('logged in to ident already');
  145. r = await mk({ days: 90 });
  146. const inv4 = r.j;
  147. await p.goto(inv4.url);
  148. await p.waitFor('!!document.querySelector("#chooselist .choose")', { label: 'choose list (signed in)' });
  149. check('signed in: no email step, only the identity choice', !(await p.evaluate('!!document.querySelector("#email")')));
  150. await p.click('#chooselist .choose');
  151. await p.waitFor('!!document.querySelector("#invite")', { label: 'back in the app', timeout: 15000 });
  152. check('one click → back in the app, invite used', (await p.text('#invitestate')) === 'used');
  153. const g4 = await idOf(inv4.id);
  154. check('the same identity accepted both invites (one id per app)', g4.j.invite.identities[0] === g.j.invite.identities[0]);
  155. // ---- 4. several uses, list ---------------------------------------------------------------
  156. console.log('two uses, list');
  157. r = await mk({ uses: 2, project: 'Docs', days: 90 });
  158. const inv5 = r.j;
  159. const accept = async () => {
  160. const q = await fetch(inv5.url, { redirect: 'manual' });
  161. const rid = (q.headers.get('location') || '').split('/').pop();
  162. return { q, rid };
  163. };
  164. const a1 = await accept();
  165. check('open invite → 302 to the sign-in of the app', a1.q.status === 302 && /^\/signin\/[0-9a-f]{32}$/.test(a1.q.headers.get('location')));
  166. // two different people accept it over the faces
  167. const people = [];
  168. for (const e of ['[email protected]', '[email protected]', '[email protected]']) {
  169. await post('/api/code', { email: e });
  170. const v = await emit('verifyCode', [e, lastCode(e), 'UTC']);
  171. people.push({ cookie: v.cookie, ident: v.value.identities[0].id });
  172. }
  173. const choose = async (who, rid) => (await emit('chooseIdentity', [rid, who.ident], who.cookie)).value;
  174. let c1 = await choose(people[0], a1.rid);
  175. check('first person accepts → return URL with ident_code and invite', !!c1.url && c1.url.includes('ident_code=') && c1.url.includes('invite=' + inv5.id), JSON.stringify(c1));
  176. const a2 = await accept();
  177. let c2 = await choose(people[1], a2.rid);
  178. check('second person accepts', !!c2.url, JSON.stringify(c2));
  179. const a3 = await fetch(inv5.url, { redirect: 'manual' });
  180. check('third opening: used up → "already used"', a3.status === 410 && /already used/.test(await a3.text()));
  181. const g5 = await idOf(inv5.id);
  182. check('get: used 2 of 2 with two different identities', g5.j.invite.used === 2 && g5.j.invite.uses === 2 && g5.j.invite.identities[0] !== g5.j.invite.identities[1], g5.t);
  183. // a request parked BEFORE the last use, accepted AFTER it, is refused with a clear message
  184. r = await mk({ uses: 1, days: 90 });
  185. const inv6 = r.j;
  186. const early = (await fetch(inv6.url, { redirect: 'manual' })).headers.get('location').split('/').pop();
  187. const early2 = (await fetch(inv6.url, { redirect: 'manual' })).headers.get('location').split('/').pop();
  188. const ok1 = await choose(people[0], early);
  189. const bad = await choose(people[2], early2);
  190. check('two parked requests, one use: first wins, second told "already used"', !!ok1.url && bad.error && /already used/.test(bad.error), JSON.stringify([ok1, bad]));
  191. r = await post('/api/invites/list', { ...A });
  192. check('list: all invites of the app with states', r.status === 200 && r.j.invites.length === 6 && r.j.invites.some(i => i.state === 'revoked') && r.j.invites.some(i => i.state === 'expired') && r.j.invites.some(i => i.state === 'used'), r.t);
  193. r = await post('/api/invites/list', { ...A, project: 'Docs' });
  194. check('list narrowed to a project', r.j.invites.length === 1 && r.j.invites[0].project === 'Docs');
  195. const other = await post('/api/invites/get', { ...A, id: 'nonexistent1' });
  196. check('get an unknown id → 404', other.status === 404);
  197. // ---- 5. mail through ident's mailer ------------------------------------------------------
  198. console.log('mail');
  199. r = await mk({ email: '[email protected]', days: 90 });
  200. check('create with an address → mailed', r.status === 200 && r.j.mailed === true, r.t);
  201. const mails = inviteMails();
  202. check('the mail (sink) holds the address and the very link', mails.length === 1 && mails[0] === '[email protected] ' + r.j.url, JSON.stringify(mails));
  203. const mailedLink = r.j.url;
  204. await mk({ email: '[email protected]', days: 90 }); await mk({ email: '[email protected]', days: 90 });
  205. r = await mk({ email: '[email protected]', days: 90 });
  206. check('a 4th mail within the day is refused (429), nothing sent', r.status === 429 && inviteMails().length === 3, r.t);
  207. const p2 = await br.newPage();
  208. await p2.goto(mailedLink);
  209. await p2.waitFor('!!document.querySelector("#apprequest")', { label: 'sign-in from the mailed link' });
  210. check('the mailed link opens ident sign-in', /invited to\s*Demo tickets/.test(await p2.text('#apprequest')));
  211. // ---- 6. the test app page ----------------------------------------------------------------
  212. console.log('the app page');
  213. await p2.goto(TA + '/invites');
  214. await p2.waitFor('!!document.querySelector("#invites")', { label: 'invites page' });
  215. check('the app lists its invites with their state', (await p2.evaluate('document.querySelectorAll("#invites li").length')) >= 9);
  216. await p2.type('#iproject', 'FromForm', { clear: true });
  217. await p2.click('#create');
  218. await p2.waitFor('!!document.querySelector("#link")', { label: 'link shown' });
  219. const link = await p2.evaluate('document.querySelector("#link").value');
  220. check('the app shows the link and a share link', /\/invite\/[0-9a-f]{32}$/.test(link) && /^mailto:/.test(await p2.evaluate('document.querySelector("#share").getAttribute("href")')), link);
  221. check('the new invite is listed ONCE', (await p2.evaluate('[...document.querySelectorAll("#invites li strong")].filter(e => e.textContent === "FromForm").length')) === 1, await p2.text('#invites'));
  222. await p2.click('#invites li:last-child .revoke');
  223. await p2.waitFor('/revoked/.test(document.querySelector("#invites li:last-child .state")?.textContent || "")', { label: 'revoked in the list' });
  224. check('the app revokes it from the list', /revoked/.test(await p2.text('#invites li:last-child .state')), await p2.text('#invites li:last-child'));
  225. r = await post('/api/invites/list', { ...A, project: 'FromForm' });
  226. check('ident agrees: revoked', r.j.invites.length === 1 && r.j.invites[0].state === 'revoked', r.t);
  227. } catch (e) {
  228. failed++; console.log(' FAIL exception — ' + (e && e.stack || e));
  229. } finally {
  230. if (br) await br.close();
  231. stopAll();
  232. console.log(`\n${passed} passed, ${failed} failed`);
  233. process.exit(failed ? 1 : 0);
  234. }

Branches

Latest commits

  • 9ced53c3|||PR ident#33 ident#35 every component's styles live in its own Style block; styles.hl keeps the page-wide rest; the account bar is phone first (min-width: 60rem block); the avatar preview is hidden with the hidden attribute (ident#34 in part)mre
  • f28333e4ident#33 ident#35: styles.hl keeps only the accent, the page column and the shared patterns; the account bar is written phone first (base rule + one min-width: 60rem block) instead of a max-width overridemre
  • 5b4541fcident#33: the selector sign-in frame's rules move into embed.hl's Stylemre
  • 00235f21ident#33: the per-app notification switches move into appsettings.hl's Stylemre
  • 2249945cident#33: the inbox and connection list rules move into inbox.hl's Stylemre
  • f2d9f79fident#33: the apps list and the secret box move into apps.hl's Stylemre
  • 8370b748ident#33: the app request box moves into home.hl's Stylemre
  • 40bf3b97ident#33: the 404 page's home link rule moves into notfound.hlmre
  • 40627a89ident#33: the time zone section's spacing moves into timezone.hlmre
  • d389db08ident#33: the identity page's rules and the Notif. chip move into identity.hl's Stylemre
  • ddda0b5bident#33: the identity row's parts move into identitylist.hl's Stylemre
  • 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
  • 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
  • f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
  • c512fb96Merge branch 'f4-homesplit' into mainIdent
  • 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
  • 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
  • e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
  • e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
  • 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre