# knownprint in the browser

Part of the knownprint quickstart for AI coding agents, Step 5. Read
https://knownprint.com/quickstart.md first: it holds the rules that apply here (never read or print
secrets, ask before touching a live server, an unknown result is never a pass). This file covers the
script tag and the helper that gets a request id when the user submits.

Load the script once on every page that has a protected form, from the site's own origin, then the
helper below:

```html
<script src="/kp/agent.js" defer></script>
<script src="/js/knownprint.js" defer></script>
```

In Next.js, use `<Script src="/kp/agent.js" strategy="afterInteractive" />` from `next/script` in
the layout of those pages.

The helper starts the agent when the page opens, and gets a request id at the moment the user
submits (a request id is checked within 10 seconds, so never take it earlier). It never throws and
never holds the form for more than 3 seconds. As a classic script it defines two global functions;
in a bundled app (React, Vue, Next.js), put `export` before each and import them:

```js
// knownprint.js (browser). The public key is safe in the page.
const KNOWNPRINT_PUBLIC_KEY = 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // from the environment

/** Start the agent early, so the first submit is quick. Call it when the page opens. */
function knownprintStart() {
  window.knownprint?.load({ pk: KNOWNPRINT_PUBLIC_KEY }).catch(() => {});
}

/** A fresh request id, or null when the script is blocked, failed or was too slow. */
async function knownprintRequestId({ linkedId, timeoutMs = 3000 } = {}) {
  if (!window.knownprint) return null;
  try {
    const { requestId } = await Promise.race([
      window.knownprint
        .load({ pk: KNOWNPRINT_PUBLIC_KEY })
        .then((agent) => agent.identify(linkedId ? { linkedId: String(linkedId) } : {})),
      new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs)),
    ]);
    return requestId;
  } catch {
    return null;
  }
}
```

Call `knownprintStart()` once when the page opens (a `DOMContentLoaded` listener, or a
`useEffect` in the component with the form).

For a request sent with `fetch` (single page apps, React, Vue):

```js
const kpRequestId = await knownprintRequestId();
await fetch('/api/signup', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, password, kp_request_id: kpRequestId }),
});
```

For a plain HTML form, add `<input type="hidden" name="kp_request_id">` and fill it on submit,
once per submit even when the user clicks twice:

```js
document.addEventListener('DOMContentLoaded', () => {
  knownprintStart();
  const form = document.getElementById('signup');
  let passing = false;
  let inFlight = false;
  form.addEventListener('submit', async (event) => {
    if (passing) return; // our own resubmit below
    event.preventDefault();
    if (inFlight) return; // a second click while the first is being identified
    inFlight = true;
    const submitter = event.submitter;
    form.elements.kp_request_id.value = (await knownprintRequestId()) ?? '';
    inFlight = false;
    passing = true;
    try {
      form.requestSubmit(submitter);
    } finally {
      passing = false;
    }
  });
});
```

Where the user is already signed in (login, checkout, password change), pass the account id:
`knownprintRequestId({ linkedId: user.id })`. Use the app's own opaque id, never an email address
or a name. If the site sends a Content Security Policy, see the end of Step 6 of the quickstart.

Next: https://knownprint.com/quickstart.md, Step 6.
