@huaqiu/hardware-artifacts 0.7.13 → 0.7.15

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/src/routes.ts CHANGED
@@ -1,10 +1,23 @@
1
1
  /** Read-only HTTP surface for the Hardware Engineering client. */
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http'
3
3
  import { readFileSync } from 'node:fs'
4
- import type { ArtifactKind, DiscoveryResult, HardwareArtifactService, NativeApplication } from './service.js'
4
+ import type { ArtifactKind, HardwareArtifactService, NativeApplication } from './service.js'
5
5
 
6
6
  export const HARDWARE_ROUTE_PREFIX = '/api/v1/hardware'
7
7
 
8
+ /**
9
+ * Resolve the workspace root of one DSH session, host-side.
10
+ *
11
+ * Supplied by the plugin from the `sessions` service, so the base for an
12
+ * authorization check comes from the session header rather than from a value
13
+ * the browser sent — and never from whichever session discovered last.
14
+ */
15
+ export type WorkspaceResolver = (sessionId: string) => Promise<string | undefined> | string | undefined
16
+
17
+ export interface HardwareHandlerOptions {
18
+ readonly resolveWorkspace?: WorkspaceResolver
19
+ }
20
+
8
21
  function sendJson(res: ServerResponse, status: number, body: unknown): void {
9
22
  const text = JSON.stringify(body)
10
23
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text) })
@@ -48,8 +61,53 @@ function rootsOf(body: unknown): string[] {
48
61
  return [cwd, workspace].filter((value): value is string => value !== undefined)
49
62
  }
50
63
 
51
- export function createHardwareHandler(service: HardwareArtifactService): (req: IncomingMessage, res: ServerResponse) => void {
52
- let lastDiscovery: DiscoveryResult | undefined
64
+ /** The DSH session a request belongs to: a query field for reads, a body field for writes. */
65
+ function sessionOf(url: URL, body?: unknown): string | undefined {
66
+ const fromBody = body === null || typeof body !== 'object'
67
+ ? undefined
68
+ : asString((body as Record<string, unknown>).session)
69
+ return fromBody ?? asString(url.searchParams.get('session') ?? undefined)
70
+ }
71
+
72
+ /**
73
+ * Everything one request may read: the roots it named plus the workspace of the
74
+ * session it belongs to.
75
+ *
76
+ * The session's workspace is resolved here, not taken from `cwd`: the browser
77
+ * sends whichever cwd its session hook held at render time, and a viewer that
78
+ * stayed mounted across a workspace switch would otherwise authorize against a
79
+ * workspace it no longer shows.
80
+ */
81
+ async function authorizeRequest(
82
+ options: HardwareHandlerOptions,
83
+ url: URL,
84
+ body?: unknown,
85
+ ): Promise<{ roots: string[]; sessionId?: string }> {
86
+ const sessionId = sessionOf(url, body)
87
+ const roots = rootsOf(body)
88
+ // Reads carry theirs in the query string; writes in the body. Either way they
89
+ // only add to the session's workspace, never replace it.
90
+ for (const key of ['cwd', 'workspace']) {
91
+ const value = asString(url.searchParams.get(key) ?? undefined)
92
+ if (value !== undefined && !roots.includes(value)) roots.push(value)
93
+ }
94
+ if (sessionId === undefined || options.resolveWorkspace === undefined) {
95
+ return { roots }
96
+ }
97
+ try {
98
+ const workspace = await options.resolveWorkspace(sessionId)
99
+ if (workspace !== undefined && workspace !== '') roots.push(workspace)
100
+ } catch {
101
+ // An unresolvable session is not a reason to fail a local read: the caller's
102
+ // own roots still apply, and they can only come from this machine.
103
+ }
104
+ return { roots, sessionId }
105
+ }
106
+
107
+ export function createHardwareHandler(
108
+ service: HardwareArtifactService,
109
+ options: HardwareHandlerOptions = {},
110
+ ): (req: IncomingMessage, res: ServerResponse) => void {
53
111
  return (req, res) => {
54
112
  if (!isTrustedRequest(req)) {
55
113
  sendJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
@@ -60,8 +118,22 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
60
118
  const url = new URL(req.url ?? '/', 'http://dsh.internal')
61
119
  const p = url.pathname
62
120
  if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/projects`) {
63
- const result = service.discover(asString(url.searchParams.get('cwd') ?? undefined) ?? process.cwd(), asString(url.searchParams.get('project') ?? undefined))
64
- lastDiscovery = result
121
+ const sessionId = asString(url.searchParams.get('session') ?? undefined)
122
+ let workspace = asString(url.searchParams.get('cwd') ?? undefined)
123
+ if (workspace === undefined && sessionId !== undefined && options.resolveWorkspace !== undefined) {
124
+ try {
125
+ workspace = await options.resolveWorkspace(sessionId)
126
+ } catch {
127
+ workspace = undefined
128
+ }
129
+ }
130
+ // The workspace the session declares is the default; `process.cwd()`
131
+ // is only a last resort for an embed with no session at all.
132
+ const result = service.discover(
133
+ workspace ?? process.cwd(),
134
+ asString(url.searchParams.get('project') ?? undefined),
135
+ sessionId,
136
+ )
65
137
  sendJson(res, 200, { ok: true, ...result })
66
138
  return
67
139
  }
@@ -70,7 +142,12 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
70
142
  return
71
143
  }
72
144
  if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/environment`) {
73
- sendJson(res, 200, { ok: true, text: service.environmentText(lastDiscovery ?? service.discovery()), childEnv: service.childEnvironment() })
145
+ const sessionId = asString(url.searchParams.get('session') ?? undefined)
146
+ sendJson(res, 200, {
147
+ ok: true,
148
+ text: service.environmentText(service.discovery(sessionId)),
149
+ childEnv: service.childEnvironment(),
150
+ })
74
151
  return
75
152
  }
76
153
  if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/source`) {
@@ -79,13 +156,14 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
79
156
  sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
80
157
  return
81
158
  }
82
- const cwd = asString(url.searchParams.get('cwd') ?? undefined)
83
159
  const revision = asString(url.searchParams.get('revision') ?? undefined)
160
+ const { roots, sessionId } = await authorizeRequest(options, url)
84
161
  try {
85
162
  const source = await service.readSource({
86
163
  artifactPath,
87
164
  ...(revision === undefined ? {} : { expectedRevision: revision }),
88
- ...(cwd === undefined ? {} : { roots: [cwd] }),
165
+ roots,
166
+ ...(sessionId === undefined ? {} : { sessionId }),
89
167
  })
90
168
  sendJson(res, 200, { ok: true, ...source })
91
169
  } catch (error) {
@@ -94,6 +172,129 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
94
172
  }
95
173
  return
96
174
  }
175
+ if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/order`) {
176
+ sendJson(res, 200, { ok: true, ...await service.orderConfig() })
177
+ return
178
+ }
179
+ if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/fabrication`) {
180
+ const body = await readJson(req) as Record<string, unknown>
181
+ const artifactPath = asString(body.path)
182
+ if (artifactPath === undefined) {
183
+ sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
184
+ return
185
+ }
186
+ const schematic = asString(body.schematic)
187
+ const { roots, sessionId } = await authorizeRequest(options, url, body)
188
+ try {
189
+ const prepared = await service.fabricate({
190
+ boardPath: artifactPath,
191
+ ...(schematic === undefined ? {} : { schematicPath: schematic }),
192
+ roots,
193
+ ...(sessionId === undefined ? {} : { sessionId }),
194
+ })
195
+ sendJson(res, 200, {
196
+ ok: true,
197
+ boardPath: prepared.boardPath,
198
+ revision: prepared.revision,
199
+ generatedAt: prepared.generatedAt,
200
+ facts: prepared.facts,
201
+ archive: prepared.archive,
202
+ ...(prepared.assembly === undefined ? {} : { assembly: prepared.assembly }),
203
+ })
204
+ } catch (error) {
205
+ const { status, body: failureBody } = failure(error)
206
+ sendJson(res, status, failureBody)
207
+ }
208
+ return
209
+ }
210
+ if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/order/pcb`) {
211
+ const body = await readJson(req) as Record<string, unknown>
212
+ if (body.confirm !== true) {
213
+ sendJson(res, 400, {
214
+ ok: false,
215
+ error: {
216
+ code: 'confirmation-required',
217
+ message: 'placing an order uploads the board files and requires explicit confirmation',
218
+ },
219
+ })
220
+ return
221
+ }
222
+ const artifactPath = asString(body.path)
223
+ if (artifactPath === undefined) {
224
+ sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
225
+ return
226
+ }
227
+ const schematic = asString(body.schematic)
228
+ const { roots, sessionId } = await authorizeRequest(options, url, body)
229
+ try {
230
+ const placed = await service.placeOrder({
231
+ kind: 'pcb',
232
+ boardPath: artifactPath,
233
+ ...(schematic === undefined ? {} : { schematicPath: schematic }),
234
+ roots,
235
+ ...(sessionId === undefined ? {} : { sessionId }),
236
+ ...(typeof body.quantity === 'number' ? { quantity: body.quantity } : {}),
237
+ ...(body.launch === false ? { launch: false } : {}),
238
+ })
239
+ sendJson(res, 200, { ok: true, ...placed })
240
+ } catch (error) {
241
+ const { status, body: failureBody } = failure(error)
242
+ sendJson(res, status, failureBody)
243
+ }
244
+ return
245
+ }
246
+ if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/order/smt`) {
247
+ const body = await readJson(req) as Record<string, unknown>
248
+ if (body.confirm !== true) {
249
+ sendJson(res, 400, {
250
+ ok: false,
251
+ error: {
252
+ code: 'confirmation-required',
253
+ message: 'placing an assembly order uploads the board, BOM and positions and requires explicit confirmation',
254
+ },
255
+ })
256
+ return
257
+ }
258
+ const artifactPath = asString(body.path)
259
+ if (artifactPath === undefined) {
260
+ sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
261
+ return
262
+ }
263
+ const schematic = asString(body.schematic)
264
+ const { roots, sessionId } = await authorizeRequest(options, url, body)
265
+ try {
266
+ const placed = await service.placeOrder({
267
+ kind: 'smt',
268
+ boardPath: artifactPath,
269
+ ...(schematic === undefined ? {} : { schematicPath: schematic }),
270
+ roots,
271
+ ...(sessionId === undefined ? {} : { sessionId }),
272
+ ...(typeof body.quantity === 'number' ? { quantity: body.quantity } : {}),
273
+ ...(body.launch === false ? { launch: false } : {}),
274
+ })
275
+ sendJson(res, 200, { ok: true, ...placed })
276
+ } catch (error) {
277
+ const { status, body: failureBody } = failure(error)
278
+ sendJson(res, status, failureBody)
279
+ }
280
+ return
281
+ }
282
+ if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/order/open`) {
283
+ const body = await readJson(req) as Record<string, unknown>
284
+ const orderUrl = asString(body.url)
285
+ if (orderUrl === undefined) {
286
+ sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'url is required' } })
287
+ return
288
+ }
289
+ try {
290
+ const opened = service.openOrderUrl(orderUrl)
291
+ sendJson(res, 200, { ok: true, ...opened })
292
+ } catch (error) {
293
+ const { status, body: failureBody } = failure(error)
294
+ sendJson(res, status, failureBody)
295
+ }
296
+ return
297
+ }
97
298
  if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/bom`) {
98
299
  const body = await readJson(req) as Record<string, unknown>
99
300
  const artifactPath = asString(body.path)
@@ -101,8 +302,13 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
101
302
  sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
102
303
  return
103
304
  }
305
+ const { roots, sessionId } = await authorizeRequest(options, url, body)
104
306
  try {
105
- const bom = await service.exportBom({ artifactPath, roots: rootsOf(body) })
307
+ const bom = await service.exportBom({
308
+ artifactPath,
309
+ roots,
310
+ ...(sessionId === undefined ? {} : { sessionId }),
311
+ })
106
312
  sendJson(res, 200, { ok: true, ...bom })
107
313
  } catch (error) {
108
314
  const { status, body } = failure(error)
@@ -117,8 +323,13 @@ export function createHardwareHandler(service: HardwareArtifactService): (req: I
117
323
  sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
118
324
  return
119
325
  }
326
+ const { roots, sessionId } = await authorizeRequest(options, url, body)
120
327
  try {
121
- const glb = await service.exportGlb({ artifactPath, roots: rootsOf(body) })
328
+ const glb = await service.exportGlb({
329
+ artifactPath,
330
+ roots,
331
+ ...(sessionId === undefined ? {} : { sessionId }),
332
+ })
122
333
  const query = new URLSearchParams({ path: glb.path, revision: glb.revision })
123
334
  sendJson(res, 200, {
124
335
  ok: true,