slicer-studio 0.1.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,130 +4,377 @@ A 3D printing studio you add to any website with one HTML tag. Customers upload
4
4
  it costs to print. Staff can slice models and inspect the G-code.
5
5
 
6
6
  ```html
7
- <slicer-studio api-url="https://api.example.com"></slicer-studio>
7
+ <slicer-studio
8
+ api-url="https://api.example.com"
9
+ config='{"realtime":{"key":"your-public-key","host":"ws.example.com"}}'
10
+ ></slicer-studio>
8
11
  ```
9
12
 
10
13
  It is a standard custom element, so it works on any stack. It brings its own React, and a shadow root keeps its styles
11
14
  and your page's apart.
12
15
 
16
+ The studio is the interface only. It needs a [slicer backend](#slicer-backend) that you run: an API in front of headless
17
+ OrcaSlicer, which does the slicing and holds your printers and prices.
18
+
13
19
  **The price page** (`mode="quote"`, the default) takes up to 10 models at once and shows each one in 3D. Customers choose
14
- the material, finish, strength and number of copies, then see the price, weight and print time. SLA and SLS jobs get an
15
- email button to your lab instead of a price.
20
+ the material, finish, strength and number of copies, then see the price, weight and print time. Every price uses your
21
+ default printer. SLA and SLS jobs get an email button to your lab instead of a price.
16
22
 
17
- **Advanced** (`mode="advanced"`) is for staff. It offers every OrcaSlicer printer and preset, slices models, and shows the
18
- G-code layer by layer. It also opens G-code and sliced 3MF files in the browser, with no upload.
23
+ **Advanced** (`mode="advanced"`) is for staff. It offers your printers first, then every printer and preset your backend
24
+ lists, slices models, and shows the G-code layer by layer. Slicing needs your [staff routes](#staff-routes), which run on
25
+ your own login. It also opens G-code and sliced 3MF files in the browser, with no upload. You can
26
+ [limit it to people your own servers approve](#staff-access).
19
27
 
20
- ## Contents
21
28
 
22
- - [How it works](#how-it-works)
23
- - [Setup](#setup)
24
- - [Frameworks](#frameworks)
25
- - [Attributes](#attributes)
26
- - [Options](#options)
27
- - [Events and methods](#events-and-methods)
28
- - [Layout and styling](#layout-and-styling)
29
- - [Taking orders](#taking-orders)
30
- - [Staff access](#staff-access)
31
- - [Content Security Policy](#content-security-policy)
32
- - [Troubleshooting](#troubleshooting)
33
- - [Good to know](#good-to-know)
29
+ ## Slicer backend
34
30
 
35
- ## How it works
31
+ The backend is a headless OrcaSlicer setup behind a small API. The studio does no slicing itself, so it can't price
32
+ anything without a backend.
36
33
 
37
- ```text
38
- Your website Your server
39
- +---------------------------+ +-----------------------------+
40
- | <slicer-studio> | model | slicer-api (Docker) |
41
- | upload, choices, | ----------> | OrcaSlicer |
42
- | 3D view, price | <---------- | your printers and prices |
43
- +---------------------------+ weight, +-----------------------------+
44
- print time
45
- ```
46
-
47
- - **This package is the interface.** Slicing is done by
48
- [slicer-api](https://github.com/kerala-startup-mission/slicer-api), which you run yourself. Each API has one set of
49
- printers and prices, so a lab runs one API.
50
- - **Models go only to your API.** The studio makes no other network calls.
51
- - **Prices are worked out in the browser.** The API returns weight and time, and the studio multiplies the weight by
52
- your price per gram. So you can change prices from your page, but you must not trust them when you charge
53
- (see [Taking orders](#taking-orders)).
54
- - **The package is already built.** You get ready-made JavaScript in `dist/`, and `npm install` adds no other packages.
34
+ A slice can take minutes, so no request stays open for it. The browser asks for a quote, sends the file straight to your
35
+ storage, then waits for a websocket event. That takes four parts:
55
36
 
56
- ## Setup
37
+ | Part | What it does |
38
+ |---|---|
39
+ | API | Answers the [public routes](#public-routes), and the [staff routes](#staff-routes) if Advanced slices. Any language works |
40
+ | S3-compatible storage | Takes each upload through a signed form, and can hold the G-code |
41
+ | Pusher-compatible websocket server | Tells the page when a quote is done |
42
+ | Worker | Takes quotes from a queue and slices them, see [Headless OrcaSlicer](#headless-orcaslicer) |
57
43
 
58
- You need Docker on the server that runs the API. On your website you need either npm or a page whose HTML you can edit.
44
+ ### What each feature needs
59
45
 
60
- ### 1. Run slicer-api
46
+ | To use | The backend needs |
47
+ |---|---|
48
+ | Price page | The public routes, storage and a worker. Instant estimates from the model's shape are fine. Without the websocket each price can take up to a minute |
49
+ | Advanced slicing | The staff routes on your page's own origin, and a real slicer |
50
+ | Opening G-code files in Advanced | Nothing. They stay in the browser |
61
51
 
62
- ```bash
63
- git clone https://github.com/kerala-startup-mission/slicer-api.git
64
- cd slicer-api
65
- docker compose up --build -d
52
+ ### How a quote runs
53
+
54
+ 1. The studio sends `POST /quotes` with the file's details and settings, but not the file. Your API answers with an
55
+ `id`, a websocket `channel` and a signed upload form.
56
+ 2. It subscribes to the channel. This comes first because an estimate can finish about a second after the start, and the
57
+ event would be missed.
58
+ 3. It sends the file straight to your storage with the upload form.
59
+ 4. It sends `POST /quotes/{id}/start`, and your API queues the quote.
60
+ 5. Your worker slices the quote, then your backend publishes `quote.updated` on the channel.
61
+ 6. The studio reads the result once, with `GET /quotes/{id}`.
62
+
63
+ If no event comes, the studio checks once a minute, and once after the websocket reconnects. It gives up after 90
64
+ minutes, so every quote must reach `done` or `failed` before then.
65
+
66
+ ### Public routes
67
+
68
+ Give `api-url` the address these share. There is no login, because customers use them.
69
+
70
+ | Route | Used for |
71
+ |---|---|
72
+ | [`GET /config`](#get-config) | Your printers and prices |
73
+ | [`GET /options`](#get-options) | The materials for one printer |
74
+ | [`POST /quotes`](#post-quotes) | A new quote and its upload form |
75
+ | [`POST /quotes/{id}/start`](#post-quotesidstart) | Queue it once the file has arrived |
76
+ | [`GET /quotes/{id}`](#get-quotesid) | Its result |
77
+
78
+ Every answer is JSON. If something fails, answer with an error status and a message, which the studio shows as it is:
79
+
80
+ ```json
81
+ { "message": "This model is too big for the printer's bed" }
66
82
  ```
67
83
 
68
- The first build downloads OrcaSlicer (about 150 MB) and takes a few minutes. Then check that it is running:
84
+ #### `GET /config`
69
85
 
70
- ```bash
71
- curl http://localhost:3000/health
86
+ ```json
87
+ {
88
+ "printers": ["Bambu Lab A1 0.4 nozzle", "Bambu Lab P1S 0.4 nozzle"],
89
+ "defaultPrinter": "Bambu Lab A1 0.4 nozzle",
90
+ "pricing": { "currency": "INR", "perGram": { "PLA": 6, "PETG": 7, "ABS": 8, "TPU": 7 }, "range": 20 },
91
+ "regularMode": { "supports": true, "mode": "estimate" }
92
+ }
72
93
  ```
73
94
 
74
- You should get `{"ok":true,"slicer":true}`.
95
+ | Key | Meaning |
96
+ |---|---|
97
+ | `printers` | Your printers, listed first in Advanced |
98
+ | `defaultPrinter` | The printer every price uses. If it's blank, the first of `printers` |
99
+ | `pricing.range` | How far weight and time run above the figure on the page, in percent. `0` shows exact figures |
100
+ | `regularMode.supports` | Whether prices include supports, for the details popup |
101
+
102
+ The studio doesn't send `mode` or `supports` on these routes, so they are yours to decide. Your page can only override
103
+ `defaultPrinter`, see [Options](#options).
75
104
 
76
- ### 2. Set your printers and prices
105
+ #### `GET /options`
77
106
 
78
- Edit `config/printers.json` in slicer-api. Changes apply on the next page load, with no restart.
107
+ The studio asks this with `?printer=Bambu%20Lab%20A1%200.4%20nozzle`.
108
+
109
+ ```json
110
+ { "printer": "Bambu Lab A1 0.4 nozzle", "materials": ["ABS", "PETG", "PLA", "TPU"] }
111
+ ```
112
+
113
+ List only the materials you price, because the studio offers no others. Answer `503` while the slicer is down, and the
114
+ price page says so before anyone uploads.
115
+
116
+ #### `POST /quotes`
117
+
118
+ The studio sends one request per file, as JSON:
79
119
 
80
120
  ```json
81
121
  {
82
- "currency": "INR",
83
- "pricePerGram": { "PLA": 6, "PETG": 7, "ABS": 8, "TPU": 7 },
84
- "priceRange": 20,
85
- "printers": [
86
- { "name": "Bambu Lab A1 0.4 nozzle", "default": true },
87
- { "name": "Bambu Lab P1S 0.4 nozzle" }
88
- ],
89
- "regularMode": { "supports": true, "mode": "estimate" },
90
- "contact": { "name": "Acme Labs", "email": "hello@example.com" }
122
+ "filename": "bracket.stl",
123
+ "size": 48210,
124
+ "printer": "Bambu Lab A1 0.4 nozzle",
125
+ "material": "PLA",
126
+ "quality": "standard",
127
+ "infill": 15,
128
+ "walls": 3
91
129
  }
92
130
  ```
93
131
 
94
- Printer names must match OrcaSlicer's exactly. To find yours:
132
+ | Field | Value |
133
+ |---|---|
134
+ | `filename` | Ends in `.stl`, `.3mf`, `.obj`, `.step`, `.stp`, `.iges` or `.igs`, in any case |
135
+ | `size` | The file's size in bytes, up to 52428800 (50 MB) |
136
+ | `printer` | Your default printer |
137
+ | `material` | One of the materials from `/options` |
138
+ | `quality` | `standard` (0.2 mm), `medium` (0.15 mm) or `high` (0.1 mm) |
139
+ | `infill` | `10`, `15`, `20`, `30`, `40`, `50`, `60`, `70`, `80` or `90` |
140
+ | `walls` | `1` to `6` |
141
+
142
+ Answer `201`:
95
143
 
96
- ```bash
97
- curl "http://localhost:3000/api/printers?q=bambu"
144
+ ```json
145
+ {
146
+ "id": "01m688sadqy04j83nhtswgrdtt",
147
+ "status": "awaiting_upload",
148
+ "channel": "quotes.01m688sadqy04j83nhtswgrdtt",
149
+ "upload": {
150
+ "url": "https://storage.example.com/slicer",
151
+ "fields": { "key": "uploads/01m688sadqy04j83nhtswgrdtt.stl", "Policy": "...", "X-Amz-Signature": "..." }
152
+ }
153
+ }
98
154
  ```
99
155
 
100
- [Options](#options) explains each value. Your page can override all of them except `printers`.
156
+ The studio sends `upload.fields` as they are to `upload.url`, in a multipart `POST`, with the file last as `file`. Any
157
+ `2xx` means it arrived. Sign the form for this one file, and limit its size in the policy.
101
158
 
102
- ### 3. Allow your website
159
+ **Limits:** answer `429` or `503` with `Retry-After` when you're busy. If that's 60 seconds or less, the studio shows
160
+ `Waiting for a free slot`, waits, and tries once more. So 10 files can pass a limit of 6 a minute. With a longer wait, or
161
+ no `Retry-After`, your message shows on that file.
162
+
163
+ #### `POST /quotes/{id}/start`
164
+
165
+ No body. Answer `202` and queue the quote. The studio treats `409` as already started, and shows any other error's
166
+ message, such as a file that hasn't arrived.
167
+
168
+ #### The `quote.updated` event
169
+
170
+ Publish this on the quote's public channel once, when it reaches `done` or `failed`. Its data doesn't matter, because the
171
+ studio only reads the result after it.
172
+
173
+ #### `GET /quotes/{id}`
103
174
 
104
- Browsers block calls to the API from other sites until you allow them. Set these in slicer-api's `docker-compose.yml`:
175
+ ```json
176
+ {
177
+ "id": "01m688sadqy04j83nhtswgrdtt",
178
+ "status": "done",
179
+ "error": null,
180
+ "stats": { "weightG": 4.63, "seconds": 662, "sizeMm": [20, 20, 20], "watertight": true, "estimated": true },
181
+ "used": { "printer": "Bambu Lab A1 0.4 nozzle", "process": "0.20mm Standard", "filament": "Generic PLA" },
182
+ "price": { "currency": "INR", "perGram": 6, "min": 28, "max": 33 }
183
+ }
184
+ ```
185
+
186
+ A failed quote has a message for the customer:
105
187
 
106
- ```yaml
107
- services:
108
- print-quote-api:
109
- environment:
110
- ALLOWED_ORIGINS: "https://www.example.com,https://example.com"
111
- RATE_LIMIT_PER_MIN: "30"
112
- TRUST_PROXY: "1"
188
+ ```json
189
+ { "id": "01m688pmr3gg4465kyb4t8ska2", "status": "failed", "error": "This model could not be sliced", "stats": null, "used": null, "price": null }
113
190
  ```
114
191
 
115
- | Setting | What it does |
192
+ | Key | Meaning |
193
+ |---|---|
194
+ | `status` | `awaiting_upload`, `queued` or `processing` until it finishes as `done` or `failed` |
195
+ | `error` | Why it failed, shown on that file's card |
196
+ | `stats.weightG` | Weight in grams, for one copy |
197
+ | `stats.seconds` | Print time in seconds, for one copy |
198
+ | `stats.sizeMm` | Width, depth and height in millimetres |
199
+ | `stats.estimated` | `true` if this came from the model's shape, not a slicer. The page then says it's a quick estimate. Leave it out otherwise |
200
+ | `stats.watertight` | `false` warns that the model has holes |
201
+ | `used` | Optional. What was really used |
202
+ | `price` | `min` and `max` for one copy, in whole units of `currency`. The same number in both shows one price |
203
+
204
+ The page multiplies `price` by the copies. It works out no prices of its own, so your backend's rounding is what
205
+ customers see.
206
+
207
+ Answer `404` for a quote that has gone, and the studio asks the customer to try again.
208
+
209
+ ### Staff routes
210
+
211
+ These let Advanced slice. They are the quote routes above with more options, plus what only staff should have, and your
212
+ own login protects them. Name them with [`staffApi`](#options). Without it, Advanced only opens G-code files.
213
+
214
+ - **They must be on your page's own origin.** The studio relies on the page's cookies, so a page on another site can't use
215
+ them.
216
+ - **Every `POST` carries your CSRF token,** as `X-CSRF-TOKEN`, from `staffApi.csrfToken`.
217
+ - **Refusals explain themselves.** `401` shows `Sign in to slice`, `403` shows `Your account can't slice models`, and
218
+ `419` shows `Your session has expired. Reload the page`. Each stops the rest of the files.
219
+
220
+ | Route | Answer |
221
+ |---|---|
222
+ | [`GET /health`](#get-health) | Can it slice? |
223
+ | [`GET /printers`](#get-printers) | Every printer you can slice for |
224
+ | [`GET /options`](#staff-get-options) | What one printer offers, with presets |
225
+ | `POST /quotes` | As above, with [more fields](#staff-post-quotes) |
226
+ | `POST /quotes/{id}/start` | As above |
227
+ | `GET /quotes/{id}` | As above, with `hasGcode: true` once the G-code is ready. An optional `errorDetail` shows to staff in place of `error`, and `price` can be `null` for a material you don't price |
228
+ | `GET /quotes/{id}/gcode` | The G-code, or a redirect to a signed storage address |
229
+
230
+ G-code on another origin, such as a storage redirect, must allow your page's origin for `GET`. Comment lines such as
231
+ `;TYPE:Outer wall` and `;LAYER_CHANGE`, as OrcaSlicer writes them, let the view colour features and split layers.
232
+
233
+ #### `GET /health`
234
+
235
+ ```json
236
+ { "ok": true, "slicer": true }
237
+ ```
238
+
239
+ Set `slicer` to `false`, or answer `503`, if it can't slice right now. G-code files still open.
240
+
241
+ #### `GET /printers`
242
+
243
+ ```json
244
+ {
245
+ "printers": [{ "name": "Bambu Lab A1 0.4 nozzle", "vendor": "Bambu Lab", "model": "Bambu Lab A1", "nozzleMm": 0.4 }]
246
+ }
247
+ ```
248
+
249
+ Advanced groups these by brand, model and nozzle, after your `printers` from `/config`. If this fails, it offers only
250
+ those.
251
+
252
+ #### Staff `GET /options`
253
+
254
+ The studio asks this with `?printer=Bambu%20Lab%20A1%200.4%20nozzle&material=PLA`.
255
+
256
+ ```json
257
+ {
258
+ "printer": "Bambu Lab A1 0.4 nozzle",
259
+ "defaultProcess": "0.20mm Standard",
260
+ "materials": ["PLA", "PETG", "ABS", "TPU"],
261
+ "processes": ["0.20mm Standard", "0.16mm High Quality"],
262
+ "filaments": [{ "name": "Bambu PLA Basic", "material": "PLA" }]
263
+ }
264
+ ```
265
+
266
+ `filaments` lists the presets for the requested material.
267
+
268
+ #### Staff `POST /quotes`
269
+
270
+ The same JSON, where anything set to Default is left out, so the printer's own profile decides. `printer` can be any
271
+ printer. It always adds the first two of these:
272
+
273
+ | Field | Value |
274
+ |---|---|
275
+ | `mode` | `exact`: slice for real, because an estimate has no G-code |
276
+ | `gcode` | `true`: keep the G-code. A real boolean |
277
+ | `supports` | `true` or `false`, a real boolean. Left out, your own setting applies |
278
+ | `process`, `filament` | A preset's name, from `/options` |
279
+ | `rotX`, `rotY`, `rotZ` | `90`, `180` or `270`, the degrees to turn the model around each axis, in that order |
280
+
281
+ ### Headless OrcaSlicer
282
+
283
+ OrcaSlicer is a desktop app, but it can also slice from the command line. On a server with no screen, the setup has four
284
+ parts:
285
+
286
+ | Part | What it does |
116
287
  |---|---|
117
- | `ALLOWED_ORIGINS` | The sites that embed the studio, comma-separated. An origin is the scheme, host and port, with no path, such as `http://localhost:5173`. |
118
- | `RATE_LIMIT_PER_MIN` | Quotes per minute per visitor. Slices run one at a time, so turn this on for any public API. Each file is one request and a customer can send 10 at once, so 30 is a fair start. |
119
- | `TRUST_PROXY` | How many proxies sit in front of the API. Without it, all visitors behind a proxy share one rate limit. |
288
+ | OrcaSlicer | Slices the model. Use the Linux AppImage, unpacked so it doesn't need FUSE |
289
+ | System libraries | What OrcaSlicer needs to start, such as GTK and OpenGL |
290
+ | Xvfb | A virtual display, because OrcaSlicer needs one on Linux even from the command line |
291
+ | Your worker | Takes a quote from the queue, runs OrcaSlicer on it, and reads the result |
292
+
293
+ A container keeps these together. This installs everything except your worker, on x86-64. For arm64, use the file
294
+ with `aarch64` before the version in its name.
295
+
296
+ ```dockerfile
297
+ FROM ubuntu:24.04
298
+
299
+ RUN apt-get update && apt-get install -y --no-install-recommends \
300
+ ca-certificates curl xvfb xauth \
301
+ libgtk-3-0t64 libwebkit2gtk-4.1-0 libgl1 libglu1-mesa libegl1 libosmesa6 \
302
+ libxkbcommon0 libdbus-1-3 libsecret-1-0 libnss3
303
+
304
+ RUN curl -fL https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.4.2/OrcaSlicer_Linux_AppImage_Ubuntu2404_V2.4.2.AppImage -o /tmp/orca.AppImage \
305
+ && chmod +x /tmp/orca.AppImage \
306
+ && cd /tmp && ./orca.AppImage --appimage-extract >/dev/null \
307
+ && mv /tmp/squashfs-root /opt/orca \
308
+ && rm /tmp/orca.AppImage
309
+ ```
310
+
311
+ **To slice a model,** start from a 3MF project saved in OrcaSlicer's desktop app. A 3MF is a zip, so for each quote copy
312
+ that template, put the customer's mesh in it, and run this in a new folder. `HOME` must be a writable folder.
313
+
314
+ ```bash
315
+ HOME=/tmp/orca-home xvfb-run -a /opt/orca/AppRun --slice 1 --outputdir /tmp/job --export-3mf out.gcode.3mf \
316
+ --sparse-infill-density=15% --layer-height=0.2 --wall-loops=3 --enable-support=1 \
317
+ /tmp/job/job.3mf
318
+ ```
319
+
320
+ That writes `plate_1.gcode` to the output folder, with a `result.json` whose `error_string` says why if it fails. Inside
321
+ the 3MF, the mesh is in `3D/Objects/`, its position is in `3D/3dmodel.model` and `Metadata/model_settings.config`, and
322
+ the printer and presets are in `Metadata/project_settings.config`.
323
+
324
+
325
+ **To keep it reliable:**
326
+
327
+ - **Slice one at a time.** OrcaSlicer is heavy, so let quotes wait their turn in the queue.
328
+ - **Stop a slice that runs too long.** Kill it after a limit, such as 3 minutes, and fail the quote.
329
+ - **Delete each job's folder** afterwards.
330
+ - **Check the model fits first.** `printable_area` and `printable_height` in the `machine` preset give the printer's size.
331
+ - **Expect a few bad presets.** Some vendor presets fail OrcaSlicer's own checks. Its log names the value, so you can
332
+ correct it and try again.
333
+
334
+ ## Setup
120
335
 
121
- Then apply the changes:
336
+ You need a server to run the backend. On your website you need either npm or a page whose HTML you can edit.
337
+
338
+ ### 1. Run a slicer backend
339
+
340
+ Set up the [four parts](#slicer-backend), with [headless OrcaSlicer](#headless-orcaslicer) behind your API, then check that
341
+ it answers:
122
342
 
123
343
  ```bash
124
- docker compose up -d
344
+ curl https://api.example.com/config
125
345
  ```
126
346
 
127
- ### 4. Serve the API over HTTPS
347
+ You should get your printers and prices.
348
+
349
+ ### 2. Set your printers and prices
350
+
351
+ Make [`/config`](#get-config) answer with your own printers and prices. The studio reads this each time a page loads, so
352
+ changes need no update to your site.
353
+
354
+ ### 3. Allow your website
355
+
356
+ Browsers block calls to other sites until those sites allow them. Have your public routes answer with your site's exact
357
+ origin, which is its scheme, host and port, with no path. Answer `OPTIONS` requests too, because `POST /quotes` sends JSON:
358
+
359
+ ```text
360
+ Access-Control-Allow-Origin: https://www.example.com
361
+ Access-Control-Allow-Methods: GET, POST
362
+ Access-Control-Allow-Headers: content-type
363
+ Access-Control-Expose-Headers: Retry-After
364
+ Vary: Origin
365
+ ```
366
+
367
+ `Retry-After` must be exposed, or the studio can't see it and won't wait.
368
+
369
+ Your storage needs CORS as well: `POST` from your site's origin, and `GET` if Advanced downloads G-code from it.
128
370
 
129
- A page on `https://` can't call an `http://` API, so a live site needs HTTPS on the API too. Put a proxy in front of it.
130
- With nginx:
371
+ You can skip this for the routes by serving them from your own domain, with a path such as `api-url="/slicer"`. Storage
372
+ still needs it, because uploads go straight there.
373
+
374
+ ### 4. Serve it over HTTPS
375
+
376
+ A page on `https://` can't call `http://` or `ws://`, so a live site needs HTTPS on the API and storage, and `wss://` on
377
+ the websocket. Put a proxy in front of each. With nginx:
131
378
 
132
379
  ```nginx
133
380
  server {
@@ -135,30 +382,39 @@ server {
135
382
  server_name api.example.com;
136
383
  # ssl_certificate and ssl_certificate_key go here
137
384
 
138
- client_max_body_size 55m; # models can be up to 50 MB
139
-
140
385
  location / {
141
- proxy_pass http://127.0.0.1:3000;
386
+ proxy_pass http://127.0.0.1:3000; # your API
142
387
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
143
- proxy_read_timeout 300s; # a slice can wait for others in the queue
144
- proxy_send_timeout 300s;
145
388
  }
146
389
  }
147
390
  ```
148
391
 
149
- You can also forward `/api/` and `/health` from your own domain. The studio then calls your site's own origin, so leave
150
- out `api-url` and `ALLOWED_ORIGINS`.
392
+ ### 5. Set its limits
393
+
394
+ Slicing is heavy, and anyone can call your public routes, so set these however your server does:
395
+
396
+ | Limit | Why |
397
+ |---|---|
398
+ | New quotes per visitor | Each file is one quote and a customer can send 10 at once. Above the limit, answer `429` with `Retry-After` |
399
+ | Quotes running per visitor | The studio runs one at a time, so a low limit is fine. Count abandoned uploads out after a while |
400
+ | Quotes running in total | A worker slices one at a time. Above the limit, answer `503` with `Retry-After` |
401
+ | 50 MB per upload | The studio won't send more. Enforce it in the upload form's policy |
151
402
 
152
- ### 5. Add the studio to your page
403
+ ### 6. Add the studio to your page
153
404
 
154
405
  ```bash
155
406
  npm install slicer-studio
156
407
  ```
157
408
 
158
- Import it once, anywhere in your JavaScript, then put the tag on your page:
409
+ Import it once, anywhere in your JavaScript, then put the tag on your page and name your websocket. Its key is public, so
410
+ it's safe in your page's source.
159
411
 
160
412
  ```js
161
413
  import 'slicer-studio';
414
+
415
+ document.querySelector('slicer-studio').config = {
416
+ realtime: { key: 'your-public-key', host: 'ws.example.com' },
417
+ };
162
418
  ```
163
419
 
164
420
  ```html
@@ -167,7 +423,7 @@ import 'slicer-studio';
167
423
 
168
424
  [Frameworks](#frameworks) shows this for your stack, including how to use it without npm.
169
425
 
170
- ### 6. Check that it works
426
+ ### 7. Check that it works
171
427
 
172
428
  1. Open your page. The studio should appear.
173
429
  2. Drop an STL file on it.
@@ -175,9 +431,16 @@ import 'slicer-studio';
175
431
 
176
432
  If it doesn't, see [Troubleshooting](#troubleshooting). Your browser's console usually names the problem.
177
433
 
434
+ ### 8. Set up Advanced
435
+
436
+ This step is optional. To slice in Advanced, add your [staff routes](#staff-routes) and name them in `staffApi`. Until you
437
+ limit it, anyone who sets `mode="advanced"` can open Advanced, but only your login lets them slice. See
438
+ [Staff access](#staff-access).
439
+
178
440
  ## Frameworks
179
441
 
180
- Every example sets the same two options and logs the price. Replace `https://api.example.com` with your API.
442
+ Every example names your websocket and logs the price. Replace `https://api.example.com` with your backend, and
443
+ `realtime` with your own.
181
444
 
182
445
  Tested on Vite 8, React 18.3 and 19.3, Next.js 16, Vue 3.5, Nuxt 4, Angular 20, Svelte 5 and Laravel 13.
183
446
 
@@ -186,13 +449,13 @@ Tested on Vite 8, React 18.3 and 19.3, Next.js 16, Vue 3.5, Nuxt 4, Angular 20,
186
449
  No npm or build step. Load it from a CDN:
187
450
 
188
451
  ```html
189
- <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio@0.1.0/dist/slicer-studio.js"></script>
452
+ <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio@0.3.0/dist/slicer-studio.js"></script>
190
453
 
191
454
  <slicer-studio api-url="https://api.example.com"></slicer-studio>
192
455
 
193
456
  <script>
194
457
  const studio = document.querySelector('slicer-studio');
195
- studio.config = { priceRange: 15, pricePerGram: { PLA: 5 } };
458
+ studio.config = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
196
459
  studio.addEventListener('estimate', e => console.log(e.detail));
197
460
  </script>
198
461
  ```
@@ -208,7 +471,7 @@ To host it yourself, copy the whole `node_modules/slicer-studio/dist` folder to
208
471
  import 'slicer-studio';
209
472
 
210
473
  const studio = document.querySelector('slicer-studio');
211
- studio.config = { priceRange: 15, pricePerGram: { PLA: 5 } };
474
+ studio.config = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
212
475
  studio.addEventListener('estimate', e => console.log(e.detail));
213
476
  ```
214
477
 
@@ -223,7 +486,7 @@ This works on React 18 and 19. Set `config` and listen for events in an effect:
223
486
  import { useEffect, useRef } from 'react';
224
487
  import 'slicer-studio';
225
488
 
226
- const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
489
+ const options = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
227
490
 
228
491
  export default function PrintPrices() {
229
492
  const studio = useRef(null);
@@ -284,7 +547,7 @@ Then pass `config` as a property, with `.prop`:
284
547
  <script setup>
285
548
  import 'slicer-studio';
286
549
 
287
- const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
550
+ const options = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
288
551
  const onEstimate = e => console.log(e.detail);
289
552
  </script>
290
553
 
@@ -315,7 +578,7 @@ Then keep the tag out of server rendering with `<ClientOnly>`:
315
578
 
316
579
  ```vue
317
580
  <script setup>
318
- const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
581
+ const options = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
319
582
  const onEstimate = e => console.log(e.detail);
320
583
  </script>
321
584
 
@@ -342,7 +605,7 @@ import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
342
605
  `,
343
606
  })
344
607
  export class App {
345
- options = { priceRange: 15, pricePerGram: { PLA: 5 } };
608
+ options = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
346
609
 
347
610
  constructor() {
348
611
  import('slicer-studio');
@@ -368,7 +631,7 @@ This is for Svelte 5:
368
631
  <script>
369
632
  import 'slicer-studio';
370
633
 
371
- const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
634
+ const options = { realtime: { key: 'your-public-key', host: 'ws.example.com' } };
372
635
  const onEstimate = e => console.log(e.detail);
373
636
  </script>
374
637
 
@@ -385,7 +648,7 @@ import 'slicer-studio';
385
648
  document.querySelector('slicer-studio')?.addEventListener('estimate', e => console.log(e.detail));
386
649
  ```
387
650
 
388
- Add the API's address to `.env`, and read it in `config/services.php`:
651
+ Add the backend's address to `.env`, and read it in `config/services.php`:
389
652
 
390
653
  ```dotenv
391
654
  SLICER_API_URL=https://api.example.com
@@ -399,7 +662,7 @@ Pass the options from a route or controller:
399
662
 
400
663
  ```php
401
664
  Route::get('/prices', fn () => view('prices', [
402
- 'studio' => ['priceRange' => 15, 'pricePerGram' => ['PLA' => 5]],
665
+ 'studio' => ['realtime' => ['key' => 'your-public-key', 'host' => 'ws.example.com']],
403
666
  ]));
404
667
  ```
405
668
 
@@ -411,12 +674,23 @@ And in the Blade template:
411
674
  <slicer-studio api-url="{{ config('services.slicer.url') }}" config='@json($studio)'></slicer-studio>
412
675
  ```
413
676
 
677
+ If this app also serves your [staff routes](#staff-routes), add them for signed-in staff:
678
+
679
+ ```php
680
+ Route::get('/slicer', fn () => view('prices', [
681
+ 'studio' => [
682
+ 'realtime' => ['key' => 'your-public-key', 'host' => 'ws.example.com'],
683
+ 'staffApi' => ['url' => '/admin/slicer', 'csrfToken' => csrf_token()],
684
+ ],
685
+ ]))->middleware('auth');
686
+ ```
687
+
414
688
  ### Other server templates
415
689
 
416
690
  Write `config` as JSON in the attribute, inside single quotes, and escape any `'` in the values as `&#39;`:
417
691
 
418
692
  ```html
419
- <slicer-studio api-url="https://api.example.com" config='{"priceRange":15,"pricePerGram":{"PLA":5}}'></slicer-studio>
693
+ <slicer-studio api-url="https://api.example.com" config='{"realtime":{"key":"your-public-key","host":"ws.example.com"}}'></slicer-studio>
420
694
  ```
421
695
 
422
696
  ### TypeScript
@@ -459,7 +733,7 @@ const studio = useRef<SlicerStudioElement>(null);
459
733
 
460
734
  | Attribute | Values | Default |
461
735
  |---|---|---|
462
- | `api-url` | The address of your slicer-api | Your page's own origin |
736
+ | `api-url` | The address of your [public routes](#public-routes) | Your page's own origin |
463
737
  | `mode` | `quote` (the price page) or `advanced` (the staff tools) | `quote` |
464
738
  | `theme` | `light`, `dark` or `system`. Setting it hides the theme switch | Follows the device, and visitors can switch |
465
739
  | `config` | JSON of the [options](#options) | Nothing overridden |
@@ -468,17 +742,23 @@ You can change any of them at any time. Changing `api-url` or `mode` clears the
468
742
 
469
743
  ## Options
470
744
 
471
- Options override slicer-api's `printers.json` for this page. Every key is optional. Set them as a property, which is
472
- easiest from JavaScript, or as JSON in the `config` attribute, which suits server templates.
745
+ Every key is optional, but without `realtime` each price can take up to a minute. Set them as a property, which is easiest
746
+ from JavaScript, or as JSON in the `config` attribute, which suits server templates.
747
+
748
+ Prices aren't an option. They come from your backend, so a page can't show one it doesn't hold.
473
749
 
474
750
  ```js
475
751
  document.querySelector('slicer-studio').config = {
476
- // the same names as printers.json, and they win over it
477
- currency: 'INR',
478
- pricePerGram: { PLA: 5, PETG: 6 },
479
- priceRange: 15,
480
- regularMode: { supports: false, mode: 'estimate' },
752
+ // the websocket that says when a quote is done
753
+ realtime: { key: 'your-public-key', host: 'ws.example.com' },
754
+
755
+ // where Advanced slices, on your page's own origin
756
+ staffApi: { url: '/admin/slicer', csrfToken: 'your-pages-token' },
757
+
758
+ // your lab, for SLA and SLS enquiries
481
759
  contact: { name: 'Acme Labs', email: 'hello@example.com' },
760
+
761
+ // the printer for prices, in place of your backend's default
482
762
  defaultPrinter: 'Bambu Lab P1S 0.4 nozzle',
483
763
 
484
764
  // the choices a customer starts with
@@ -486,30 +766,39 @@ document.querySelector('slicer-studio').config = {
486
766
 
487
767
  // the cards to show; all of them when left out
488
768
  cards: ['model', 'files', 'material', 'cost'],
769
+
770
+ // the servers that approve Advanced; anyone can open it when left out
771
+ advanced: {
772
+ authUrl: 'https://www.example.com/slicer-token',
773
+ verifyUrl: 'https://www.example.com/slicer-verify',
774
+ },
489
775
  };
490
776
  ```
491
777
 
492
778
  | Key | Meaning |
493
779
  |---|---|
494
- | `currency` | A three-letter code such as `INR` or `USD` |
495
- | `pricePerGram` | Price per gram by material. Only the materials you list change |
496
- | `priceRange` | Shows cost, weight and time as a range, from the calculated figure up to this percent more. `0` shows exact figures |
497
- | `regularMode.supports` | `true` if estimates include supports |
498
- | `regularMode.mode` | `estimate` is instant, from the model's shape. `exact` is sliced by OrcaSlicer, and takes seconds to minutes per file. `auto` uses `exact` when the server has OrcaSlicer |
780
+ | `realtime.key` | Your websocket server's public key. Required for `realtime` |
781
+ | `realtime.host` | Its host. Left out, Pusher's own servers for the `cluster` |
782
+ | `realtime.port` | Its port. `443` when left out |
783
+ | `realtime.cluster` | Its cluster. `mt1` when left out |
784
+ | `realtime.tls` | `false` for `ws://`, for local testing. `true` when left out |
785
+ | `staffApi.url` | The address of your [staff routes](#staff-routes), on your page's own origin |
786
+ | `staffApi.csrfToken` | The token for your page's session, sent on each `POST` |
499
787
  | `contact` | Your lab's `name`, and the `email` that SLA and SLS enquiries go to. The email button hides while no email is set |
500
- | `defaultPrinter` | The printer for estimates, which must be one the API has profiles for |
788
+ | `defaultPrinter` | The printer for prices, which must be one your backend allows |
501
789
  | `defaults.material` | `PLA`, `PETG`, `ABS` or `TPU`. If the printer doesn't offer it, the first one it does offer is used |
502
790
  | `defaults.quality` | `standard` (0.2 mm), `medium` (0.15 mm) or `high` (0.1 mm) |
503
791
  | `defaults.infill` | `10`, `15`, `20`, `30`, `40`, `50`, `60`, `70`, `80` or `90` |
504
792
  | `defaults.walls` | `1` to `6` |
505
793
  | `cards` | Which [cards](#cards) to show |
794
+ | `advanced` | The two servers that approve Advanced, see [Staff access](#staff-access) |
506
795
 
507
796
  - Setting `config` replaces the whole object, so include everything you want each time.
508
- - `pricePerGram`, `regularMode` and `contact` merge with the API's values key by key.
509
797
  - `defaults` apply to files added after they are set.
510
- - Anything invalid is left out, with a `slicer-studio:` warning in the console.
511
- - In `advanced` mode, only `defaultPrinter` has an effect, and only until someone picks a printer. The studio then
512
- remembers their choice.
798
+ - Anything invalid is left out, with a `slicer-studio:` warning in the console. The exception is `advanced`: if it's
799
+ there without both URLs, Advanced stays closed.
800
+ - In `advanced` mode, only `realtime`, `staffApi`, `defaultPrinter` and `advanced` have an effect, and `defaultPrinter`
801
+ only until someone picks a printer. The studio then remembers their choice.
513
802
 
514
803
  ### Cards
515
804
 
@@ -546,7 +835,7 @@ the copies. It doesn't fire for SLA or SLS, or in `advanced` mode. A typical `e.
546
835
  ```js
547
836
  {
548
837
  currency: 'INR',
549
- range: { low: 61, high: 71 }, // total cost; null if a material has no price
838
+ range: { low: 61, high: 71 }, // total cost; null if a file has no price
550
839
  gramsRange: { low: 12, high: 15 }, // total weight
551
840
  secondsRange: { low: 1380, high: 1680 }, // total print time, with prints run one after another
552
841
  unpriced: [], // materials with no price
@@ -554,6 +843,7 @@ the copies. It doesn't fire for SLA or SLS, or in `advanced` mode. A typical `e.
554
843
  files: [{
555
844
  name: 'bracket.stl',
556
845
  file: File, // the customer's File object
846
+ quoteId: '01m688sadqy04j83nhtswgrdtt', // to read the real price from your backend
557
847
  copies: 1,
558
848
  settings: { printer: '', material: 'PLA', quality: 'standard', infill: 15, walls: 3 },
559
849
  range: { low: 61, high: 71 }, // these three are for all of this file's copies
@@ -563,18 +853,25 @@ the copies. It doesn't fire for SLA or SLS, or in `advanced` mode. A typical `e.
563
853
  }
564
854
  ```
565
855
 
566
- With `priceRange` at `0`, `low` and `high` are the same exact figure. Otherwise they are whole numbers.
856
+ `range` is your backend's `price` times the copies. Weight and time are whole numbers, or the exact figure with
857
+ `pricing.range` at `0`.
567
858
 
568
859
  ### `modechange`
569
860
 
570
- Fires when someone uses the Simple / Advanced switch, with `{ mode }` in `detail`. The switch only appears in `advanced`
571
- mode, and setting the attribute yourself doesn't fire the event.
861
+ Fires when someone uses the Simple / Advanced switch, or a refused visitor is sent back to the price page, with `{ mode }`
862
+ in `detail`. The switch only appears in `advanced` mode, and setting the attribute yourself doesn't fire the event.
863
+
864
+ ### `advanceddenied`
865
+
866
+ Fires when your servers don't approve a visitor for Advanced, just before the studio returns to the price page. Use it to
867
+ show your own sign-in. `e.detail.reason` is `refused`, `unreachable` or `not-set-up`, see
868
+ [When the check fails](#when-the-check-fails).
572
869
 
573
870
  ### `getPrice()`
574
871
 
575
872
  Prices every file that needs it, and `estimate` fires when it's done. If everything is already priced, `estimate` fires
576
873
  again. It does nothing while there are no files, while SLA or SLS is selected, while a price is being worked out, or
577
- when the API can't be reached.
874
+ when the backend can't be reached.
578
875
 
579
876
  The element needs to be loaded first, so wait for it if your code might run earlier:
580
877
 
@@ -613,10 +910,11 @@ slicer-studio {
613
910
 
614
911
  ## Taking orders
615
912
 
616
- **Work the price out again on your server before you charge for it.** Everything in a browser can be changed, including
617
- the `estimate` event and your `pricePerGram`.
913
+ **Read the price from your backend before you charge for it.** Everything in a browser can be changed, including the
914
+ `estimate` event.
618
915
 
619
- The event includes each customer's `File`, so you can send the order to your server:
916
+ Each file in the event has a `quoteId`, so send those to your server. The event also has each customer's `File`, for the
917
+ model itself:
620
918
 
621
919
  ```js
622
920
  let order = null;
@@ -624,43 +922,199 @@ studio.addEventListener('estimate', e => { order = e.detail; });
624
922
 
625
923
  orderButton.addEventListener('click', async () => {
626
924
  const form = new FormData();
627
- for (const { file, copies, settings } of order.files) {
925
+ for (const { file, quoteId, copies } of order.files) {
628
926
  form.append('models', file);
629
- form.append('lines', JSON.stringify({ copies, settings }));
927
+ form.append('lines', JSON.stringify({ quoteId, copies }));
630
928
  }
631
929
  await fetch('/orders', { method: 'POST', body: form });
632
930
  });
633
931
  ```
634
932
 
635
- Then have your server ask slicer-api for each file's weight, with the same settings:
933
+ Then have your server read each quote:
636
934
 
637
935
  ```bash
638
- curl https://api.example.com/api/quote \
639
- -F model=@bracket.stl \
640
- -F "printer=Bambu Lab A1 0.4 nozzle" \
641
- -F material=PLA -F quality=standard -F infill=15 -F walls=3 \
642
- -F supports=true \
643
- -F mode=estimate
936
+ curl https://api.example.com/quotes/01m688sadqy04j83nhtswgrdtt
644
937
  ```
645
938
 
646
939
  ```json
647
- { "stats": { "weightG": 12.33, "seconds": 1437, "sizeMm": [30, 30, 30], "volumeCm3": 27, "watertight": true, "estimated": true } }
940
+ { "status": "done", "price": { "currency": "INR", "perGram": 6, "min": 28, "max": 33 } }
648
941
  ```
649
942
 
650
- - The studio's `settings` leave out the printer, supports and mode. Send your `defaultPrinter`, `regularMode.supports` and
651
- `regularMode.mode` for those.
652
- - The cost is `weightG × copies × price per gram`. The page shows that rounded down as `low`, and
653
- `cost × (1 + priceRange / 100)` rounded up as `high`.
943
+ - Check that `status` is `done`. Reject a quote that has gone, and send the customer back for a new price.
944
+ - `min` and `max` are for one copy, so multiply by `copies`.
945
+ - Read it when the order comes in, because your backend decides how long a quote lasts.
654
946
 
655
947
  ## Staff access
656
948
 
657
- `mode="advanced"` is not a lock. Anyone can change an attribute in their browser's tools, so put staff pages behind your
658
- own login.
949
+ Two options control Advanced, and they do different jobs:
950
+
951
+ - **`staffApi` says where it slices.** Your login protects those [routes](#staff-routes), so only your staff can slice,
952
+ whatever happens in the browser.
953
+ - **`advanced` says who can open it.** Anyone can open Advanced until you set it, though they can only open G-code files
954
+ without a login. With it set, the studio asks your own servers before it shows Advanced to a visitor.
955
+
956
+ **`advanced` only controls what the studio shows.** A visitor can change the config in their browser's tools and open
957
+ Advanced anyway. It keeps the page tidy for customers, and your login on the staff routes keeps slicing private.
958
+
959
+ ### How it works
960
+
961
+ Your site decides who gets in. The studio only asks it and acts on the answer, and your slicer backend takes no part.
962
+
963
+ ```text
964
+ Staff member signs in to your site (your login, your cookie)
965
+ |
966
+ Your page sets mode="advanced"
967
+ |
968
+ Studio shows "Checking your access…" (Advanced isn't loaded yet)
969
+ |
970
+ 1. POST authUrl, with cookies, body {}
971
+ | Your server checks the login
972
+ | Staff: 200 { "token": "..." }, signed with your private key
973
+ | Not staff: 403
974
+ |
975
+ 2. POST verifyUrl, no cookies, body { "token": "..." }
976
+ | Your server checks the signature and expiry with your public key
977
+ | Valid: 200 { "valid": true }
978
+ | Not valid: 403
979
+ |
980
+ 3. Both passed: Advanced opens
981
+ Anything else: back to the price page
982
+ ```
983
+
984
+ | Who | Holds |
985
+ |---|---|
986
+ | Your page | The two URLs |
987
+ | Your servers | Your login, the private key and the public key |
988
+ | The studio | No keys. It passes the token along, then forgets it |
989
+ | Your slicer backend | Nothing. It never sees the token |
990
+
991
+ Once Advanced is open, slicing goes to your staff routes as usual. Nothing checks again while it stays open, even after the
992
+ token expires. When someone leaves Advanced and comes back the whole check runs again, which is automatic if they're
993
+ still signed in.
994
+
995
+ ### When the check fails
996
+
997
+ The visitor sees a toast and goes back to the price page, and [`advanceddenied`](#advanceddenied) fires with the reason.
998
+ To try again, set `mode="advanced"` again.
999
+
1000
+ | Reason | What happened | Toast |
1001
+ |---|---|---|
1002
+ | `refused` | A server said no, or gave a bad answer | `Advanced is for staff. Sign in and try again.` |
1003
+ | `unreachable` | A server was down or blocked, or took over 8 seconds | `We couldn’t check your access. Please try again.` |
1004
+ | `not-set-up` | `advanced` is missing a URL | `Advanced isn’t set up on this page.` |
1005
+
1006
+ ### Set it up
1007
+
1008
+ Name your two servers, then set `mode`. They can be the same server, and either can be a path on your own site, such as
1009
+ `/slicer-token`.
1010
+
1011
+ ```js
1012
+ studio.config = {
1013
+ advanced: {
1014
+ authUrl: 'https://www.example.com/slicer-token',
1015
+ verifyUrl: 'https://www.example.com/slicer-verify',
1016
+ },
1017
+ };
1018
+ studio.setAttribute('mode', 'advanced');
1019
+ ```
1020
+
1021
+ Set `config` first, or use the JSON attribute. If `mode` comes first, Advanced can show for a moment before the check
1022
+ starts.
1023
+
1024
+ Then add two routes. Any other answer refuses the visitor, and each call has 8 seconds.
1025
+
1026
+ | Route | The studio sends | Your answer to approve |
1027
+ |---|---|---|
1028
+ | `authUrl` | `POST` with cookies, body `{}` | `200` with `{ "token": "..." }` |
1029
+ | `verifyUrl` | `POST` without cookies, body `{ "token": "..." }` | `200` with `{ "valid": true }` |
1030
+
1031
+ The token's format is up to you. The studio only passes it along, and doesn't keep it. A short signed JWT works well, so
1032
+ make a key pair and keep both keys on your servers:
1033
+
1034
+ ```bash
1035
+ openssl ecparam -name prime256v1 -genkey -noout -out slicer-private.pem
1036
+ ```
1037
+
1038
+ ```bash
1039
+ openssl ec -in slicer-private.pem -pubout -out slicer-public.pem
1040
+ ```
1041
+
1042
+ In these examples, replace the staff check with your own.
1043
+
1044
+ **Laravel,** with `firebase/php-jwt`, in `routes/web.php`:
1045
+
1046
+ ```php
1047
+ use Firebase\JWT\JWT;
1048
+ use Firebase\JWT\Key;
1049
+ use Illuminate\Http\Request;
1050
+
1051
+ Route::post('/slicer-token', function (Request $request) {
1052
+ abort_unless($request->user()?->is_staff, 403);
1053
+
1054
+ $token = JWT::encode(
1055
+ ['sub' => (string) $request->user()->id, 'iat' => time(), 'exp' => time() + 900],
1056
+ file_get_contents(storage_path('slicer-private.pem')),
1057
+ 'ES256',
1058
+ );
1059
+
1060
+ return response()->json(['token' => $token])->header('Cache-Control', 'no-store');
1061
+ });
1062
+
1063
+ Route::post('/slicer-verify', function (Request $request) {
1064
+ try {
1065
+ JWT::decode((string) $request->input('token'), new Key(file_get_contents(storage_path('slicer-public.pem')), 'ES256'));
1066
+ } catch (Throwable) {
1067
+ return response()->json(['valid' => false], 403);
1068
+ }
1069
+
1070
+ return response()->json(['valid' => true]);
1071
+ });
1072
+ ```
1073
+
1074
+ The studio can't send a CSRF token, so exempt both routes in `bootstrap/app.php`:
1075
+
1076
+ ```php
1077
+ ->withMiddleware(function (Middleware $middleware) {
1078
+ $middleware->validateCsrfTokens(except: ['slicer-token', 'slicer-verify']);
1079
+ })
1080
+ ```
1081
+
1082
+ **Node,** with `express` and `jsonwebtoken`:
1083
+
1084
+ ```js
1085
+ import fs from 'node:fs';
1086
+ import express from 'express';
1087
+ import jwt from 'jsonwebtoken';
1088
+
1089
+ const privateKey = fs.readFileSync('slicer-private.pem');
1090
+ const publicKey = fs.readFileSync('slicer-public.pem');
1091
+
1092
+ app.post('/slicer-token', requireStaff, (req, res) => {
1093
+ const token = jwt.sign({ sub: String(req.user.id) }, privateKey, { algorithm: 'ES256', expiresIn: 900 });
1094
+ res.set('Cache-Control', 'no-store').json({ token });
1095
+ });
1096
+
1097
+ app.post('/slicer-verify', express.json(), (req, res) => {
1098
+ try {
1099
+ jwt.verify(req.body.token, publicKey, { algorithms: ['ES256'] });
1100
+ res.json({ valid: true });
1101
+ } catch {
1102
+ res.status(403).json({ valid: false });
1103
+ }
1104
+ });
1105
+ ```
1106
+
1107
+ ### Keep `authUrl` safe
1108
+
1109
+ - **Only answer `POST`,** with `Cache-Control: no-store`.
1110
+ - **On another origin, allow your page's exact origin.** Send `Access-Control-Allow-Credentials: true`, and allow the
1111
+ `content-type` header. Never echo the request's `Origin` back, or any site could get a token for your signed-in staff.
1112
+ - **Use `SameSite=Lax` cookies,** and keep `authUrl` on the same site as the page. In a cross-site iframe the browser sends
1113
+ no cookies, so staff are refused.
1114
+ - **Keep tokens short.** 15 minutes is plenty. The studio checks each time someone enters Advanced, and doesn't close it
1115
+ when a token expires.
659
1116
 
660
- - **Don't use `API_KEY` on an API that serves a public price page.** The studio could load but not price anything, and a
661
- key in a page's source isn't secret. That is why there is no attribute for one.
662
- - **`API_KEY` does suit a staff-only API.** Advanced shows a key button, and keeps the key in that browser.
663
- - **`ALLOWED_ORIGINS` limits browsers, not scripts,** so a public API still needs `RATE_LIMIT_PER_MIN`.
1117
+ `verifyUrl` on another origin only needs your page's origin and the `content-type` header.
664
1118
 
665
1119
  ## Content Security Policy
666
1120
 
@@ -668,7 +1122,7 @@ If your site sends a CSP header, it needs these:
668
1122
 
669
1123
  ```text
670
1124
  script-src 'self';
671
- connect-src https://api.example.com;
1125
+ connect-src https://api.example.com https://storage.example.com wss://ws.example.com;
672
1126
  img-src 'self' data: blob:;
673
1127
  font-src data:;
674
1128
  worker-src blob:;
@@ -677,7 +1131,7 @@ worker-src blob:;
677
1131
  | Directive | Why |
678
1132
  |---|---|
679
1133
  | `script-src` | Add `https://cdn.jsdelivr.net` if you load the package from the CDN |
680
- | `connect-src` | Your API. Leave it as `'self'` if the API is on your own origin |
1134
+ | `connect-src` | Your API, your storage and your websocket, plus `authUrl` and `verifyUrl` if you set them. Use `'self'` for anything on your own origin |
681
1135
  | `img-src` | Model pictures on the file cards |
682
1136
  | `font-src` | The fonts are built in as data URIs. Without this the studio uses system fonts |
683
1137
  | `worker-src` | Advanced's G-code reader. Without this it shows `Could not read this G-code: parser failed` |
@@ -690,13 +1144,23 @@ from the toast library. They are harmless, because the studio's styles don't dep
690
1144
  | What you see | Cause | Fix |
691
1145
  |---|---|---|
692
1146
  | Nothing on the page, and the tag has no size | The package didn't load | Run `customElements.get('slicer-studio')` in the console. If it's `undefined`, check your import or script tag |
693
- | `The server can't be reached.` and `blocked by CORS policy` in the console | Your site isn't allowed | Add its exact origin to `ALLOWED_ORIGINS`, then run `docker compose up -d` |
694
- | `The server can't be reached.` and `ERR_CONNECTION_REFUSED` in the console | Wrong `api-url`, or the API is down | Check `https://your-api/health` in a browser |
695
- | `The server can't be reached.` and `Mixed Content` in the console | An `https://` page is calling an `http://` API | [Serve the API over HTTPS](#4-serve-the-api-over-https) |
696
- | `No price set for PLA yet` | That material has no price | Add it to `pricePerGram` |
697
- | `Missing or wrong x-api-key` | The API has `API_KEY` set | Remove it from a public API, see [Staff access](#staff-access) |
698
- | `Too many requests. Try again in a minute.` | The rate limit was reached | Raise `RATE_LIMIT_PER_MIN` |
699
- | A large file fails, with status 413 in the browser's Network tab | Your proxy's upload limit is too low | Raise `client_max_body_size` in nginx |
1147
+ | `The server can't be reached.` and `blocked by CORS policy` in the console | Your site isn't allowed | Have the backend send your exact origin, see [Allow your website](#3-allow-your-website) |
1148
+ | `The server can't be reached.` and `ERR_CONNECTION_REFUSED` in the console | Wrong `api-url`, or the backend is down | Check `https://your-backend/config` in a browser |
1149
+ | `The server can't be reached.` and `Mixed Content` in the console | An `https://` page is calling an `http://` backend | [Serve it over HTTPS](#4-serve-it-over-https) |
1150
+ | `Prices can't be worked out right now.` | `/options` answered `503` | Fix the slicer, then reload the page |
1151
+ | `The file could not be uploaded, please try again` | Storage refused the form, or blocked your origin | Check its CORS, see [Allow your website](#3-allow-your-website), and that the form hasn't expired |
1152
+ | A price takes a minute, and `live updates are off` in the console | The websocket didn't connect | Check `realtime`, your `connect-src`, and that the server is up |
1153
+ | `No price set for PLA yet` | `/options` listed a material with no price | List only the materials you price |
1154
+ | `Slicing isn't set up on this page` in Advanced | `staffApi` isn't set | Set it, see [Staff routes](#staff-routes). G-code files still open |
1155
+ | `Slicing is off on this server` in Advanced | `/health` says `slicer: false`, or answered `503` | Fix the slicer. G-code files still open |
1156
+ | `Sign in to slice` | A staff route answered `401` | Sign in on this site. The routes must be on the page's own origin |
1157
+ | `Your account can't slice models` | A staff route answered `403` | Give that account access |
1158
+ | `Your session has expired. Reload the page` | The CSRF token is out of date | Reload, and check that `staffApi.csrfToken` comes from the current session |
1159
+ | `The G-code could not be downloaded` | The G-code route or storage refused it | Check that storage allows `GET` from your page's origin |
1160
+ | `Advanced is for staff. Sign in and try again.` for someone who is signed in | `authUrl` got no cookie, or a server said no | Check both calls in the Network tab, and see [Keep `authUrl` safe](#keep-authurl-safe) |
1161
+ | `We couldn't check your access. Please try again.` | CORS, CSP, a wrong URL, or a server took over 8 seconds | The console names it. Check the CORS headers and `connect-src` |
1162
+ | `Advanced isn't set up on this page.` | `advanced` is missing a URL | Set both, see [Staff access](#staff-access) |
1163
+ | Your backend's own message about too many requests | Your limit per visitor is too low | Raise it. Each file is one quote |
700
1164
  | `slicer-studio: config is not valid JSON` | An object reached the `config` attribute as `[object Object]` | Set the `config` property in an effect, or use `JSON.stringify` |
701
1165
  | `slicer-studio: unknown config key` | A typo in an option's name | Check it against [Options](#options) |
702
1166
  | Your options and events do nothing, with no error | React 19's short form after server rendering | Use the [effect](#react) instead |
@@ -708,9 +1172,10 @@ from the toast library. They are harmless, because the studio's styles don't dep
708
1172
  ## Good to know
709
1173
 
710
1174
  - **Browsers:** Chrome and Edge 111+, Firefox 128+, Safari 16.4+. The 3D views need WebGL.
711
- - **Files:** STL, 3MF, OBJ, STEP and IGES, up to 10 at once and 50 MB each, with at most 500,000 triangles. STEP and IGES
712
- are priced but have no 3D preview. A model too big for the printer's bed gets an error on its card.
713
- - **Size:** about 210 kB gzipped to start, with the 3D view (about 250 kB) and the fonts (about 240 kB) loading after.
1175
+ - **Files:** STL, 3MF, OBJ, STEP and IGES, up to 10 at once and 50 MB each. STEP and IGES are priced but have no 3D
1176
+ preview. If your backend refuses a file, its message shows on that file's card.
1177
+ - **Size:** about 215 kB gzipped to start, with the 3D view (about 250 kB) and the fonts (about 240 kB) loading after. The
1178
+ websocket client (about 18 kB) loads with the first quote.
714
1179
  - **Server rendering:** importing the package on a server is safe, and does nothing. The studio has no server-rendered
715
1180
  content, so set `config` and listeners in browser code, or give `config` as a JSON attribute.
716
1181
  - **One studio per page:** a second one works, but both show every toast.
@@ -718,9 +1183,9 @@ from the toast library. They are harmless, because the studio's styles don't dep
718
1183
  - **What it adds to your page:** its fonts, some CSS `@property` rules, and one `<style>` for toasts. Nothing else touches
719
1184
  your page.
720
1185
  - **What it stores:** in `localStorage`, the visitor's theme (`print-preview.theme`) and, in Advanced, the last printer
721
- (`print-preview.printer`) and the API key (`gcode-viewer.api-key`).
1186
+ (`print-preview.printer`).
722
1187
  - **Updating:** run `npm update slicer-studio`, or change the version in your CDN link. Price and printer changes need no
723
- update, because the studio reads them from the API.
1188
+ update, because the studio reads them from your backend.
724
1189
 
725
1190
  ## License
726
1191