-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
440 lines (368 loc) · 11.4 KB
/
script.js
File metadata and controls
440 lines (368 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/**
* CADit Embed Example
*
* This script demonstrates how to communicate with an embedded CADit instance
* using the postMessage API.
*/
// Configuration
// IMPORTANT: This must match the origin of your CADit iframe
// For local development, use 'http://localhost:5175'
// For production, use 'https://app.cadit.app'
const CADIT_ORIGIN = 'https://app.cadit.app';
const PARTNER_NAME = 'MyApp';
// Auth configuration — replace these with your real values
const PARTNER_ISSUER = 'https://myapp.com';
const PARTNER_AUDIENCE = 'https://cookiecad.com';
const PARTNER_TEST_USER_ID = 'user-123';
const PARTNER_TEST_EMAIL = 'user@myapp.com';
let testPrivateKey = null; // CryptoKey, loaded on init
/**
* Load the test RSA private key for JWT signing
*/
async function loadTestKey() {
try {
const response = await fetch('./test-private-key.jwk.json');
const jwk = await response.json();
testPrivateKey = await crypto.subtle.importKey(
'jwk',
jwk,
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
false,
['sign']
);
console.log('Test signing key loaded');
logEvent('key-loaded', 'sent', { info: 'Test RSA signing key loaded' });
} catch (error) {
console.error('Failed to load test key:', error);
logEvent('key-error', 'sent', { error: error.message });
}
}
/**
* Create a signed JWT for testing
*/
async function createTestJWT(nonce) {
if (!testPrivateKey) {
throw new Error('Test signing key not loaded');
}
const now = Math.floor(Date.now() / 1000);
const jti = crypto.randomUUID();
const header = {
alg: 'RS256',
typ: 'JWT',
kid: 'test-key-1'
};
const payload = {
iss: PARTNER_ISSUER,
aud: PARTNER_AUDIENCE,
sub: PARTNER_TEST_USER_ID,
email: PARTNER_TEST_EMAIL,
iat: now,
exp: now + 300, // 5 minutes
jti: jti,
nonce: nonce
};
// Base64url encode
const encode = (obj) => {
const json = JSON.stringify(obj);
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const headerB64 = encode(header);
const payloadB64 = encode(payload);
const signingInput = `${headerB64}.${payloadB64}`;
// Sign with RSA-SHA256
const signature = await crypto.subtle.sign(
'RSASSA-PKCS1-v1_5',
testPrivateKey,
new TextEncoder().encode(signingInput)
);
// Base64url encode signature
const sigB64 = btoa(String.fromCharCode(...new Uint8Array(signature)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
return `${signingInput}.${sigB64}`;
}
// DOM Elements
const caditFrame = document.getElementById('caditFrame');
const getStlBtn = document.getElementById('getStlBtn');
const downloadBtn = document.getElementById('downloadBtn');
const statusText = document.getElementById('statusText');
const eventLog = document.getElementById('eventLog');
const previewContainer = document.getElementById('previewContainer');
const stlViewerContainer = document.getElementById('stlViewer');
// State
let isReady = false;
let currentBlob = null;
let currentFilename = null;
// Three.js viewer state
let scene, camera, renderer, controls, mesh;
/**
* Initialize the Three.js STL viewer
*/
function initViewer() {
const width = stlViewerContainer.clientWidth || 300;
const height = 400;
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf8f8f8);
// Camera
camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
camera.position.set(100, 100, 100);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.setPixelRatio(window.devicePixelRatio);
stlViewerContainer.appendChild(renderer.domElement);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Lights
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
directionalLight2.position.set(-1, -1, -1);
scene.add(directionalLight2);
// Animation loop
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
// Handle resize
window.addEventListener('resize', () => {
const newWidth = stlViewerContainer.clientWidth || 300;
camera.aspect = newWidth / height;
camera.updateProjectionMatrix();
renderer.setSize(newWidth, height);
});
}
/**
* Load STL from blob into viewer
*/
function loadSTL(blob) {
const loader = new THREE.STLLoader();
blob.arrayBuffer().then(buffer => {
const geometry = loader.parse(buffer);
// Remove old mesh if exists
if (mesh) {
scene.remove(mesh);
mesh.geometry.dispose();
mesh.material.dispose();
}
// Create material with pastel color
const material = new THREE.MeshPhongMaterial({
color: 0xa8c5da,
specular: 0x111111,
shininess: 30,
flatShading: false
});
mesh = new THREE.Mesh(geometry, material);
// Center the model
geometry.computeBoundingBox();
const center = new THREE.Vector3();
geometry.boundingBox.getCenter(center);
mesh.position.sub(center);
scene.add(mesh);
// Fit camera to model
const box = new THREE.Box3().setFromObject(mesh);
const size = box.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180);
const cameraDistance = maxDim / (2 * Math.tan(fov / 2)) * 1.5;
camera.position.set(cameraDistance, cameraDistance, cameraDistance);
camera.lookAt(0, 0, 0);
controls.target.set(0, 0, 0);
controls.update();
});
}
/**
* Log an event to the event log panel
*/
function logEvent(type, direction, data) {
const time = new Date().toLocaleTimeString();
const entry = document.createElement('div');
entry.className = 'log-entry';
// For blobs, show metadata instead of the full object
let displayData = data;
if (data && data.blob instanceof Blob) {
displayData = { ...data, blob: `Blob(${data.blob.size} bytes, ${data.blob.type})` };
}
const timeSpan = document.createElement('span');
timeSpan.className = 'log-time';
timeSpan.textContent = time;
entry.appendChild(timeSpan);
const text1 = document.createTextNode(' ');
entry.appendChild(text1);
const typeSpan = document.createElement('span');
typeSpan.className = `log-type ${direction}`;
typeSpan.textContent = direction === 'received' ? 'RECV' : 'SENT';
entry.appendChild(typeSpan);
const text2 = document.createTextNode(' ');
entry.appendChild(text2);
const msgSpan = document.createElement('span');
msgSpan.className = 'log-message';
msgSpan.textContent = type;
entry.appendChild(msgSpan);
if (displayData) {
const pre = document.createElement('pre');
pre.textContent = JSON.stringify(displayData, null, 2);
entry.appendChild(pre);
}
eventLog.insertBefore(entry, eventLog.firstChild);
}
/**
* Send a message to the CADit iframe
*/
function sendMessage(type, payload) {
if (!caditFrame.contentWindow) {
console.error('CADit iframe not available');
return;
}
const message = { type, payload };
caditFrame.contentWindow.postMessage(message, CADIT_ORIGIN);
logEvent(type, 'sent', payload);
}
/**
* Handle messages received from CADit
*/
function handleMessage(event) {
// Security: Verify the message origin
if (event.origin !== CADIT_ORIGIN) {
// Log ignored messages for debugging (but don't show in event log for security)
if (event.data && event.data.type) {
console.log(`Ignored message from origin: ${event.origin} (expected: ${CADIT_ORIGIN})`);
}
return;
}
const { type, payload } = event.data;
if (!type) {
return;
}
console.log(`Received message: ${type}`, payload);
logEvent(type, 'received', payload);
switch (type) {
case 'ready':
handleReady(payload);
break;
case 'export-stl':
handleExportStl(payload);
break;
case 'cadit-auth-request':
handleAuthRequest(payload);
break;
default:
console.log('Unknown message type:', type);
}
}
/**
* Handle the 'ready' message from CADit
*/
function handleReady(payload) {
isReady = true;
statusText.textContent = `CADit ready (v${payload?.version || 'unknown'})`;
getStlBtn.disabled = false;
// Auto-initialize when CADit is ready
sendInit();
}
/**
* Handle the 'export-stl' message from CADit
*/
function handleExportStl(payload) {
if (!payload?.blob) {
console.error('No blob in export-stl payload');
statusText.textContent = 'Error: No STL data received';
return;
}
// Store for download
currentBlob = payload.blob;
currentFilename = payload.filename || 'design.stl';
// Enable download button
downloadBtn.disabled = false;
// Show preview container and initialize viewer if needed
previewContainer.style.display = 'block';
if (!renderer) {
initViewer();
}
// Load STL into viewer
loadSTL(payload.blob);
statusText.textContent = `Received: ${currentFilename} (${Math.round(payload.blob.size / 1024)} KB)`;
}
/**
* Handle auth request from CADit iframe
*/
async function handleAuthRequest(payload) {
const { nonce, version } = payload || {};
logEvent('cadit-auth-request', 'received', { nonce, version });
if (!testPrivateKey) {
logEvent('auth-error', 'sent', { error: 'Signing key not loaded yet' });
return;
}
try {
statusText.textContent = 'Signing auth token...';
const token = await createTestJWT(nonce);
// Send the signed token back to CADit
sendMessage('partner-auth-token', { token, nonce });
statusText.textContent = 'Auth token sent to CADit';
logEvent('auth-token-sent', 'sent', {
nonce,
claims: { sub: PARTNER_TEST_USER_ID, email: PARTNER_TEST_EMAIL, iss: PARTNER_ISSUER }
});
} catch (error) {
console.error('Failed to create auth token:', error);
statusText.textContent = 'Auth error: ' + error.message;
logEvent('auth-error', 'sent', { error: error.message });
}
}
/**
* Download the current STL file
*/
function downloadStl() {
if (!currentBlob) {
alert('No STL file available. Request an export first.');
return;
}
const url = URL.createObjectURL(currentBlob);
const a = document.createElement('a');
a.href = url;
a.download = currentFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
statusText.textContent = `Downloaded: ${currentFilename}`;
}
/**
* Send the init message to CADit
*/
function sendInit() {
sendMessage('init', {
partnerName: PARTNER_NAME,
features: ['export']
});
statusText.textContent = 'Initialized with partner name: ' + PARTNER_NAME;
}
/**
* Request STL export from CADit
*/
function requestStl() {
if (!isReady) {
alert('CADit is not ready yet. Please wait for it to load.');
return;
}
sendMessage('get-stl', null);
statusText.textContent = 'Requesting STL export...';
}
// Event Listeners
window.addEventListener('message', handleMessage);
getStlBtn.addEventListener('click', requestStl);
downloadBtn.addEventListener('click', downloadStl);
// Log initial state
logEvent('page-loaded', 'sent', {
info: 'Waiting for CADit to send ready message...'
});
// Load test signing key
loadTestKey();