~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
265 lines · 11.5 KB Raw History
// OAuth sign-in and consent behavior. Every action also works as a plain form
// post or link; this adds passkeys, inline reveals and the details dialog.
(() => {
  const $ = (selector) => document.querySelector(selector);
  const requestUri = $('input[name="request_uri"]')?.value;
  const status = $('[data-status]');
  const say = (text) => {
    if (!status) return;
    status.querySelector('span').textContent = text;
    status.hidden = !text;
  };

  // Replace an artwork fallback with the account's avatar or the app's icon
  // only once the image has loaded, so a missing image never shows broken.
  for (const box of document.querySelectorAll('[data-image]')) {
    const image = new Image();
    image.alt = '';
    image.className = box.dataset.imageFit === 'logo' ? 'logo' : 'photo';
    image.onload = () => {
      if (box.dataset.imageFit !== 'logo') return box.replaceChildren(image);
      box.classList.add('has-logo');
      // App icons fill the tile. An icon that is an opaque tile inside
      // transparent margins is cropped to the tile. A mark on a transparent
      // background could vanish on one theme, so it sits inset on a surface
      // chosen by the mark itself: a dark mark on the paper tile, a light one
      // on a dark tile. The icon is served from this origin, so its pixels can
      // be read.
      try {
        const size = 64;
        const canvas = document.createElement('canvas');
        canvas.width = canvas.height = size;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, size, size);
        const pixels = context.getImageData(0, 0, size, size).data;
        // An opaque corner means a full-bleed icon: it fills the tile as it is.
        if (pixels[3] > 230) return box.replaceChildren(image);
        let left = size, top = size, right = -1, bottom = -1, opaque = 0, weight = 0, light = 0;
        for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
          const i = (y * size + x) * 4, alpha = pixels[i + 3] / 255;
          weight += alpha;
          light += alpha * (0.2126 * pixels[i] + 0.7152 * pixels[i + 1] + 0.0722 * pixels[i + 2]) / 255;
          if (alpha < 0.5) continue;
          opaque++;
          left = Math.min(left, x); right = Math.max(right, x); top = Math.min(top, y); bottom = Math.max(bottom, y);
        }
        const area = (right - left + 1) * (bottom - top + 1);
        if (right >= 0 && opaque / area > 0.8) {
          if (area < size * size * 0.9) {
            const scaleX = image.naturalWidth / size, scaleY = image.naturalHeight / size;
            const crop = document.createElement('canvas');
            crop.width = Math.max(1, Math.round((right - left + 1) * scaleX));
            crop.height = Math.max(1, Math.round((bottom - top + 1) * scaleY));
            crop.getContext('2d').drawImage(image, left * scaleX, top * scaleY, crop.width, crop.height, 0, 0, crop.width, crop.height);
            const cropped = new Image();
            cropped.alt = '';
            cropped.className = 'logo';
            cropped.onload = () => box.replaceChildren(cropped);
            cropped.src = crop.toDataURL();
            return;
          }
        } else if (opaque < size * size * 0.75) {
          box.classList.add('inset-logo', weight && light / weight > 0.6 ? 'light-mark' : 'dark-mark');
        }
      } catch {}
      box.replaceChildren(image);
    };
    image.src = box.dataset.image;
  }

  const reveal = $('[data-reveal-password]');
  reveal?.addEventListener('click', (event) => {
    event.preventDefault();
    $('#password-step').hidden = false;
    reveal.hidden = true;
    $('#password').focus();
  });

  const details = $('#details');
  const opener = $('[data-details]');
  if (details && opener && typeof details.showModal === 'function') {
    opener.addEventListener('click', () => {
      details.showModal();
      details.querySelector('.sb').scrollTop = 0;
    });
    details.addEventListener('close', () => opener.focus());
    details.addEventListener('click', (event) => { if (event.target === details) details.close(); });
  }

  // "Copy raw scopes" copies the exact scope string the app sent.
  const copy = $('[data-copy]');
  copy?.addEventListener('click', async () => {
    const status = copy.nextElementSibling;
    try {
      await navigator.clipboard.writeText(copy.dataset.copy);
    } catch {
      const field = document.createElement('textarea');
      field.value = copy.dataset.copy;
      field.setAttribute('readonly', '');
      field.className = 'offscreen';
      copy.after(field);
      field.select();
      document.execCommand('copy');
      field.remove();
    }
    status.textContent = 'Copied';
    clearTimeout(copy.timer);
    copy.timer = setTimeout(() => { status.textContent = ''; }, 2000);
  });

  // The return page navigates to the app on load, with no tap behind it.
  const back = $('[data-return]');
  const revealContinue = (link) => setTimeout(() => { link.hidden = false; }, 5000);
  if (back) {
    revealContinue(back);
    location.replace(back.href);
    return;
  }

  // Buttons that hand the browser back to the app (Authorize, Deny, Cancel)
  // post over fetch and then load a return page, which navigates to the app.
  // A navigation that follows a tap, even from script shortly after it, onto
  // a domain an installed app claims as a universal link opens that app
  // instead of loading the page, so the client never receives its code
  // (stream.place claims all of its URLs). Anything unexpected falls back to
  // the plain form post.
  const leavesForApp = (button) => button &&
    ((button.name === 'browser_action' && button.value === 'continue') || button.name === 'deny');
  const returning = (form, url) => {
    for (const button of form.querySelectorAll('button')) button.disabled = true;
    const note = document.createElement('p');
    note.className = 'returning';
    note.setAttribute('role', 'status');
    note.textContent = 'Returning to the app…';
    const link = document.createElement('a');
    link.className = 'btn';
    link.href = url;
    link.textContent = 'Continue';
    link.hidden = true;
    link.addEventListener('click', (event) => { event.preventDefault(); location.replace(url); });
    form.append(note, link);
    revealContinue(link);
  };

  // One submission per form; the clicked button keeps its name and value.
  for (const form of document.querySelectorAll('form[method="post"]')) {
    form.addEventListener('submit', async (event) => {
      if (form.dataset.busy) { event.preventDefault(); return; }
      form.dataset.busy = '1';
      const button = event.submitter;
      if (form.dataset.native || !leavesForApp(button) || !window.fetch) return;
      event.preventDefault();
      const body = new URLSearchParams(new FormData(form));
      body.append(button.name, button.value);
      body.append('via', 'page');
      try {
        const response = await fetch(form.action, {
          method: 'POST',
          headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
          body,
          credentials: 'same-origin',
        });
        const url = response.ok ? (await response.json()).redirect_uri : null;
        if (typeof url !== 'string') throw new Error('no redirect');
        returning(form, url);
        location.replace(url);
      } catch {
        delete form.dataset.busy;
        form.dataset.native = '1';
        form.requestSubmit(button);
      }
    });
  }
  addEventListener('pageshow', () => {
    for (const form of document.querySelectorAll('form[data-busy]')) delete form.dataset.busy;
  });

  const passkeyButtons = document.querySelectorAll('[data-passkey]');
  if (!requestUri || !passkeyButtons.length) return;
  if (!window.PublicKeyCredential || !navigator.credentials) {
    for (const button of passkeyButtons) button.hidden = true;
    $('.or')?.setAttribute('hidden', '');
    return;
  }

  const fromBase64 = (value) => {
    const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
    const binary = atob(base64 + '==='.slice((base64.length + 3) % 4));
    return Uint8Array.from(binary, (c) => c.charCodeAt(0)).buffer;
  };
  const toBase64 = (buffer) => btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  const publicKey = (options) => {
    const key = structuredClone(options.publicKey);
    key.challenge = fromBase64(key.challenge);
    key.allowCredentials = (key.allowCredentials || []).map((c) => ({ ...c, id: fromBase64(c.id) }));
    return key;
  };
  const post = async (url, body) => {
    const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
    const data = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(data.error || 'Passkey sign-in failed.');
    return data;
  };
  const finish = async (credential) => {
    const response = credential.response;
    const result = await post('/oauth/passkey/finish', {
      request_uri: requestUri,
      credential: {
        id: credential.id,
        rawId: toBase64(credential.rawId),
        type: credential.type,
        response: {
          clientDataJSON: toBase64(response.clientDataJSON),
          authenticatorData: toBase64(response.authenticatorData),
          signature: toBase64(response.signature),
          userHandle: response.userHandle ? toBase64(response.userHandle) : null,
        },
      },
    });
    location.assign(result.redirect_uri);
  };

  // Conditional mediation offers saved passkeys from the username field's
  // autofill. Its challenge is reused if the person presses the button instead.
  let conditional = null;
  let discoverable = null;
  const username = $('#username[autocomplete~="webauthn"]');
  const startConditional = async () => {
    if (!username || !PublicKeyCredential.isConditionalMediationAvailable) return;
    if (!(await PublicKeyCredential.isConditionalMediationAvailable())) return;
    discoverable = await post('/oauth/passkey/options', { request_uri: requestUri, conditional: true });
    conditional = new AbortController();
    const credential = await navigator.credentials.get({ publicKey: publicKey(discoverable), mediation: 'conditional', signal: conditional.signal });
    conditional = null;
    await finish(credential);
  };
  // Autofill is an optional shortcut: when it is unavailable or refused the
  // form and the explicit button still work, so its failures stay quiet.
  startConditional().catch(() => { conditional = null; });

  for (const button of passkeyButtons) {
    const label = button.querySelector('.label');
    const resting = label.textContent;
    button.addEventListener('click', async () => {
      conditional?.abort();
      conditional = null;
      button.disabled = true;
      label.textContent = 'Waiting for your passkey…';
      say('');
      try {
        const identifier = button.dataset.identifier;
        const options = identifier
          ? await post('/oauth/passkey/options', { request_uri: requestUri, identifier })
          : discoverable ?? await post('/oauth/passkey/options', { request_uri: requestUri, conditional: true });
        const credential = await navigator.credentials.get({ publicKey: publicKey(options) });
        label.textContent = 'Signing in…';
        await finish(credential);
      } catch (error) {
        button.disabled = false;
        label.textContent = resting;
        if (error.name === 'NotAllowedError' || error.name === 'AbortError') say('Passkey sign-in was cancelled or timed out.');
        else say(error.message);
      }
    });
  }
})();