# Embedding the DWG browser SDK

> Cross-product identity, entitlement, billing, key, lease, and portal
> boundaries are canonical in
> `../licensing/docs/LICENSING_ARCHITECTURE.md`. This file owns only DWH SDK
> integration details.

> **Licence.** This SDK is proprietary and is licensed, not sold. Downloading it
> grants no right to use it — a valid key does. You may serve it from the
> origins registered to your key and embed it in your application. You may not
> redistribute it, reverse engineer it, extract the engine from its encrypted
> distribution, or interfere with its licence checks. Full terms:
> [LICENSE.txt](./LICENSE.txt), published alongside these files and at
> <https://dmytro-prototypes.net/docs/sdk-licence.txt>. The same notice is
> compiled into the binaries and returned by `licenseNotice()`.

Four files, served from your own site. The engine ships **encrypted** and is
inert until a signed, origin-checked lease unlocks it — which is why a public
download URL gives nothing away.

Download them from the public distribution point — no account, no token:

```
https://stdwhsdkdist.blob.core.windows.net/sdk/v<version>/
```

Always fetch from there rather than from a copy someone passed you, and verify
what you got:

```bash
base=https://stdwhsdkdist.blob.core.windows.net/sdk/v0.2.0
curl -O $base/SHA256SUMS
while read -r _ f; do curl -sO $base/$f; done < SHA256SUMS
sha256sum -c SHA256SUMS
```

The same digests are published on <https://dmytro-prototypes.net/products/dwg-apis>,
on a different host and under different credentials. That is the point of them:
a checksum stored beside the file it describes only catches a corrupted
download, because whoever can replace one can replace the other. Compare the
two.

| file | what it is | secret? |
|---|---|---|
| `dwg_loader.js`, `dwg_loader_bg.wasm` | public loader: verifies the lease, decrypts the engine | no |
| `dwg_wasm.js` | wasm-bindgen glue, fed the decrypted engine at runtime | no |
| `engine.enc` | the engine, AES-256-GCM encrypted | no — inert without a lease |

The plaintext engine is never published. If you ever find a `dwg_wasm_bg.wasm`
in a release, that is a bug and it should be reported, not used.

## Why you host these yourself

Serve all four from your own static hosting, next to your bundle. Your site then
has no runtime dependency on ours: if our CDN is down, your product still works.
Nothing here is secret, so self-hosting costs you nothing in protection.

Pin a version. Copy the assets of one `sdk-v*` release and record which one — a
newer engine may be encrypted under a rotated key, and mixing files across
releases produces a blob that cannot be opened.

## How the lock actually works

```
your page ──POST /api/activate {key}──▶ licence server
                                        ├── is the key live?
                                        └── is the Origin header registered to it?
          ◀────── signed lease, containing the engine's decryption key ──────┘
your page ── verifyAndUnwrap(lease, engine.enc) ──▶ plaintext engine, in memory only
```

Three things are worth being precise about, because they decide what you can and
cannot do with the key:

**Your publishable key is not a secret.** It ships in your bundle. Anyone can
read it. That is by design.

**The `Origin` header is the real gate.** A browser sets it and a page cannot
forge it, so the key is useless from a site you have not registered. This is why
the key can be public at all.

**The engine is only ever decrypted in memory.** The lease carries the key in
its `k` claim; the loader unwraps the engine and hands the bytes straight to
`wasm-bindgen`. Nothing writes the plaintext engine to disk, and you should not
either.

A consequence worth planning around: **the lease is per origin, so every domain
that serves your page needs registering** — apex and `www` are two different
origins, and so are your staging and production hosts.

## Origins per plan

| plan | registered origins | localhost |
|---|---|---|
| Free | 2 | always allowed, never counted |
| Basic | 4 | always allowed, never counted |
| Pro | unlimited | always allowed, never counted |

`localhost` is enabled per key and does not spend a slot, so local development
never costs you an origin. Add and remove origins on the Keys page of the
portal; a key issued with a higher ceiling keeps it.

## The whole integration

```js
import initLoader, { verifyAndUnwrap } from "./sdk/dwg_loader.js";
import initEngine, { DwgDoc, setLicense } from "./sdk/dwg_wasm.js";

const LICENCE = "https://<your-licence-host>";
const KEY = "pk_…"; // publishable; safe in your bundle

await initLoader();

// Activation is a CORS "simple request" — text/plain, so there is no preflight.
const res = await fetch(`${LICENCE}/api/activate`, {
  method: "POST",
  headers: { "content-type": "text/plain" },
  body: JSON.stringify({ key: KEY }),
});
if (!res.ok) throw new Error(`activation failed (${res.status})`);
const { lease } = await res.json();

const encrypted = new Uint8Array(await (await fetch("./sdk/engine.enc")).arrayBuffer());
const engine = verifyAndUnwrap(lease, encrypted);

await initEngine({ module_or_path: engine });
setLicense(lease);

const doc = new DwgDoc(new Uint8Array(await file.arrayBuffer()));
const report = JSON.parse(doc.report());
const sheets = JSON.parse(doc.layouts());        // model space first, handle null
const drawn = JSON.parse(doc.renderSvg(1600, 1000, false, null, sheets[1]?.handle));
doc.free();                                       // the WASM heap is yours to free
```

Run it in a **Web Worker**. Parsing a large drawing will otherwise block the
page for seconds.

## Fonts

A browser has no filesystem to search and no OS font database to query, so a
drawing's own fonts can never be found here. Nothing is silently lost to that:
anything you do not supply is drawn in a **bundled open stroke face**, and every
render tells you what it used.

```js
// What this drawing asks for. Read it before the first render.
const wanted = JSON.parse(doc.fonts());
// [{ id: "romans", name: "romans.shx", symbol: false,
//    substitute: "hershey-roman", styles: ["Standard"], … }]

// Supply the real thing under the id you were given. Once, not per render:
// the face is parsed here and reused by every later draw.
doc.addFont("arial.ttf", new Uint8Array(await (await fetch("/fonts/Arimo.ttf")).arrayBuffer()));

// After a render, what actually happened, font by font.
const drawn = JSON.parse(doc.renderSvg(1600, 1000, false, null, null));
for (const f of drawn.fonts) {
  // f.outcome: authored | supplied | substituted | builtin | notSubstituted | missing
  // f.id is what to pass to addFont to override it; f.drawn says whether any
  // glyph reached the page at all.
}

JSON.parse(builtinFonts());   // the bundled faces, for a picker
fontAcknowledgement();        // must be displayed — see below
```

`doc.fonts()` is what the STYLE table declares — enough to pre-fetch against.
It is not quite the whole list: an MTEXT run can name a font inline, and those
are only known once the text is laid out. They are substituted like any other
and do appear in the render's `fonts`, which is the complete account.

**Ids are stable and case-insensitive**, with or without an extension: a style
naming `ROMANS.SHX` and one naming `romans` are one id, `romans`, and one font
to supply. SHX and TrueType are both accepted and told apart by their content,
not their name.

**A supplied font beats everything else**, so this is also how you let someone
point at a font on their own machine — an `<input type="file">` straight into
`addFont`. Reading a font a person has already licensed, on their own device, is
what AutoCAD does at runtime; it is redistributing Autodesk's SHX files that you
must not do, and this does not.

**Symbol and shape sets are never substituted.** `ltypeshp` carries the shapes
drawn *inside linetypes*; `gdt`/`amgdt` are geometric-tolerancing marks; and
TrueType has its own (`CommercialPi BT`, Wingdings). Standing an alphabet in for
one of those strings letters along every dashed line — confident nonsense, worse
than an honest gap. They come back `outcome: "notSubstituted"` with
`drawn: false`, so you can say so in your UI.

**The bundled faces are Hershey**, and carry one obligation: the acknowledgement
returned by `fontAcknowledgement()` must be displayed wherever they are used.
That is the whole licence cost — they are otherwise free for commercial use.

## When it does not work

| symptom | cause |
|---|---|
| `origin_mismatch` | the page's origin is not registered on that key |
| `licence is not valid` | the lease was signed by a different keypair, or has expired |
| `licence is for a different product` | a lease for another product — leases do not cross products |
| a version-mismatch error from `dwg_wasm.js` | `dwg_wasm.js` and `engine.enc` came from different releases |
| text is in the wrong typeface | nothing was supplied for it, so a bundled face stood in — check `fonts` on the render result |
| some text is missing entirely | a symbol or shape set, which is never substituted (`outcome: "notSubstituted"`) |
| `addFont` throws | the bytes are not an SHX or TrueType this build can read — a failed download usually |

## What we can see

Activation is logged: which key, which origin, when. The drawing is not
uploaded, is not seen, and cannot be — parsing happens entirely in the visitor's
browser.
