@abelxiaoxing/cadence 2.2.0 → 2.2.2

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.
@@ -33,6 +33,7 @@ import {
33
33
  type PreflightRequest,
34
34
  parseWireJson,
35
35
  type ReadCursor,
36
+ type Reply,
36
37
  type Scope,
37
38
  utf8Bytes,
38
39
  } from "./service-contract.ts";
@@ -40,8 +41,10 @@ import {
40
41
  decodeHttpInput,
41
42
  decodeHttpOutput,
42
43
  decodeSocketOutput,
44
+ HISTORY_CSRF_HEADER,
43
45
  type HttpOperation,
44
46
  httpOutputLimit,
47
+ retainedHistoryBody,
45
48
  type SocketOutput,
46
49
  WS_PATH,
47
50
  wireRequest,
@@ -63,6 +66,8 @@ export interface ReadSocket {
63
66
  export class HttpServiceTransport implements ServiceTransport {
64
67
  private attachment: string | undefined;
65
68
  private csrf: string | null = null;
69
+ private historyCsrf?: string;
70
+ private bootstrapRevision = 0;
66
71
  private readonly fetcher: typeof fetch;
67
72
  private readonly origin: string;
68
73
  constructor(
@@ -70,6 +75,8 @@ export class HttpServiceTransport implements ServiceTransport {
70
75
  origin: string;
71
76
  /** Authenticated same-origin project routing; never an arbitrary URL. */
72
77
  project?: string;
78
+ /** Dedicated retained reader: never allocates an attachment or sends work. */
79
+ retainedHistory?: boolean;
73
80
  /** Diagnostic metadata only; authentication never depends on a build. */
74
81
  build?: ClientBuild;
75
82
  fetch?: typeof fetch;
@@ -91,6 +98,8 @@ export class HttpServiceTransport implements ServiceTransport {
91
98
  !/^[a-f0-9]{64}$/.test(options.project)
92
99
  )
93
100
  throw new ContractError("invalid");
101
+ if (options.retainedHistory && options.localCapability)
102
+ throw new ContractError("invalid");
94
103
  this.origin = options.origin;
95
104
  if (options.build) options.build = decodeClientBuild(options.build);
96
105
  // Native browser fetch requires its Window receiver. Node/injected arrow
@@ -127,6 +136,12 @@ export class HttpServiceTransport implements ServiceTransport {
127
136
  value: unknown,
128
137
  signal?: AbortSignal,
129
138
  ): Promise<unknown> {
139
+ if (
140
+ this.options.retainedHistory &&
141
+ operation !== "workspace" &&
142
+ !retainedHistoryBody(operation)
143
+ )
144
+ throw new ContractError("forbidden");
130
145
  const input = decodeHttpInput(operation, value),
131
146
  wire = wireRequest(operation, input),
132
147
  write = wire.method === "POST";
@@ -142,11 +157,26 @@ export class HttpServiceTransport implements ServiceTransport {
142
157
  // One client-chosen observation ID survives a lost header/body. Repeating
143
158
  // session reuses that slot and recovers CSRF, never a command or grant.
144
159
  if (operation === "session") this.attachment ??= crypto.randomUUID();
160
+ const bootstrap =
161
+ this.options.retainedHistory && operation === "workspace"
162
+ ? ++this.bootstrapRevision
163
+ : undefined;
164
+ if (bootstrap !== undefined) this.historyCsrf = undefined;
165
+ const historyBody = this.options.retainedHistory && write;
166
+ const headers = this.headers(
167
+ write && !historyBody,
168
+ operation === "session",
169
+ );
170
+ if (historyBody) {
171
+ if (!this.historyCsrf) throw new ContractError("stale");
172
+ headers[HISTORY_CSRF_HEADER] = this.historyCsrf;
173
+ headers["Content-Type"] = "application/json";
174
+ }
145
175
  const response = await this.fetcher(
146
176
  `${this.origin}${this.options.project ? `/projects/${this.options.project}` : ""}${wire.path}`,
147
177
  {
148
178
  method: wire.method,
149
- headers: this.headers(write, operation === "session"),
179
+ headers,
150
180
  credentials: "same-origin",
151
181
  redirect: "error",
152
182
  signal: requestSignal,
@@ -175,6 +205,15 @@ export class HttpServiceTransport implements ServiceTransport {
175
205
  if (utf8Bytes(source) > httpOutputLimit(operation, parsed))
176
206
  throw new ContractError("oversize");
177
207
  const result = decodeHttpOutput(operation, parsed);
208
+ if (
209
+ bootstrap !== undefined &&
210
+ response.ok &&
211
+ Object.getOwnPropertyDescriptor(result ?? {}, "kind")?.value === "ok"
212
+ ) {
213
+ if (requestSignal?.aborted || this.bootstrapRevision !== bootstrap)
214
+ throw new ContractError("stale");
215
+ this.historyCsrf = decodeId(response.headers.get(HISTORY_CSRF_HEADER));
216
+ }
178
217
  if (operation === "session") {
179
218
  const reply = decodeReply(result, decodeSessionBootstrap);
180
219
  if (reply.kind === "ok") {
@@ -183,9 +222,14 @@ export class HttpServiceTransport implements ServiceTransport {
183
222
  !!this.options.localCapability
184
223
  )
185
224
  throw new ContractError("forbidden");
186
- this.attachment =
187
- sessionAttachment ??
188
- decodeId(response.headers.get("x-cadence-attachment"));
225
+ // The body can finish after this viewer was retired (even after the
226
+ // header matched). Never reinstall the old allocation or its CSRF.
227
+ if (
228
+ requestSignal?.aborted ||
229
+ sessionAttachment !== this.attachment ||
230
+ !sessionAttachment
231
+ )
232
+ throw new ContractError("stale");
189
233
  this.csrf = reply.value.csrf;
190
234
  }
191
235
  }
@@ -278,54 +322,68 @@ export class HttpServiceTransport implements ServiceTransport {
278
322
  search(input: ReadCursor, signal?: AbortSignal) {
279
323
  return this.request("search", input, signal);
280
324
  }
281
- async detach(): Promise<unknown> {
325
+ async detach(): Promise<Reply<null> | undefined> {
282
326
  const attachment = this.attachment;
283
327
  if (!attachment) return;
284
- // A lost session body may leave the exact allocation without its CSRF.
285
- // Read that same ID again so departure/reconnection can release it instead
286
- // of blocking forever or abandoning a slot. This cannot submit work.
287
- if (!this.options.localCapability && !this.csrf) {
288
- const session = decodeReply(await this.session(), decodeSessionBootstrap);
289
- if (session.kind === "error") {
290
- if (!["stale", "unauthenticated"].includes(session.error.code))
291
- throw new ContractError(session.error.code);
292
- if (this.attachment === attachment) this.attachment = undefined;
293
- return session;
328
+ // A lost session body may leave this allocation without its CSRF. A
329
+ // restarted owner may also refuse the old CSRF on detach. In either case
330
+ // read the SAME ID at most once. No command or grant is renewed.
331
+ let checked = false;
332
+ for (;;) {
333
+ if (!this.options.localCapability && !this.csrf) {
334
+ checked = true;
335
+ const session = decodeReply(
336
+ await this.session(),
337
+ decodeSessionBootstrap,
338
+ );
339
+ if (session.kind === "error") {
340
+ if (session.error.code === "forbidden") return session;
341
+ if (!["stale", "unauthenticated"].includes(session.error.code))
342
+ throw new ContractError(session.error.code);
343
+ if (this.attachment === attachment) this.attachment = undefined;
344
+ return session;
345
+ }
294
346
  }
295
- }
296
- const result = decodeReply(await this.request("detach", null), (value) => {
297
- if (value !== null) throw new ContractError("invalid");
298
- return null;
299
- });
300
- // A lost reply does not prove release. Retain the exact attachment for a
301
- // later detach rather than allocating another of the 16 slots.
302
- // Stale means the server no longer owns this ID; rotation also revokes it.
303
- if (
304
- result.kind === "error" &&
305
- result.error.code !== "stale" &&
306
- result.error.code !== "unauthenticated"
307
- ) {
308
- // A restarted direct owner can keep the access token but replace CSRF.
309
- // The next detach recovers it by reading the same allocation, rather than
310
- // repeatedly sending this refused challenge. No work command is retried.
347
+ if (this.attachment !== attachment) throw new ContractError("stale");
348
+ const result = decodeReply(
349
+ await this.request("detach", null),
350
+ (value) => {
351
+ if (value !== null) throw new ContractError("invalid");
352
+ return null;
353
+ },
354
+ );
355
+ // Only acknowledgement, stale (no longer owned) or rotation proves the
356
+ // slot released. An uncertain reply retains the exact ID for later.
311
357
  if (
312
- result.error.code === "forbidden" &&
313
- !this.options.localCapability &&
314
- this.attachment === attachment
315
- )
358
+ result.kind === "error" &&
359
+ result.error.code !== "stale" &&
360
+ result.error.code !== "unauthenticated"
361
+ ) {
362
+ if (
363
+ result.error.code === "forbidden" &&
364
+ !this.options.localCapability &&
365
+ this.attachment === attachment
366
+ ) {
367
+ this.csrf = null;
368
+ if (!checked) continue;
369
+ // Still forbidden with the freshly observed challenge: stop, without
370
+ // claiming release or allocating a new viewer.
371
+ return result;
372
+ }
373
+ throw new ContractError(result.error.code);
374
+ }
375
+ if (this.attachment === attachment) {
376
+ this.attachment = undefined;
316
377
  this.csrf = null;
317
- throw new ContractError(result.error.code);
318
- }
319
- if (this.attachment === attachment) {
320
- this.attachment = undefined;
321
- this.csrf = null;
378
+ }
379
+ return result;
322
380
  }
323
- return result;
324
381
  }
325
382
  async *export(
326
383
  input: ExportRequest,
327
384
  signal: AbortSignal,
328
385
  ): AsyncGenerator<unknown> {
386
+ if (this.options.retainedHistory) throw new ContractError("forbidden");
329
387
  const request = decodeExportRequest(input),
330
388
  wire = wireRequest("export", request);
331
389
  const response = await this.fetcher(
@@ -388,7 +446,7 @@ export class HttpServiceTransport implements ServiceTransport {
388
446
  subscribe(
389
447
  scopeInput: Scope,
390
448
  receive: (value: SocketOutput) => void,
391
- status: (state: "current" | "stale" | "closed") => void,
449
+ status: (state: "stale" | "closed") => void,
392
450
  ): () => void {
393
451
  const scope = decodeScope(scopeInput);
394
452
  if (!this.attachment || !this.options.socket)
@@ -412,7 +470,7 @@ export class HttpServiceTransport implements ServiceTransport {
412
470
  }
413
471
  notify("closed");
414
472
  };
415
- const notify = (value: "current" | "stale" | "closed") => {
473
+ const notify = (value: "stale" | "closed") => {
416
474
  try {
417
475
  status(value);
418
476
  } catch {
@@ -420,8 +478,14 @@ export class HttpServiceTransport implements ServiceTransport {
420
478
  }
421
479
  };
422
480
  const timer = setInterval(() => {
423
- if (!active) return;
424
- if (Date.now() - last >= LIMITS.staleMs) notify("stale");
481
+ const silent = Date.now() - last;
482
+ if (silent >= LIMITS.staleMs) {
483
+ notify("stale");
484
+ // A hanging handshake can't ping. An open but silent connection gets
485
+ // one reconcile period to answer; don't wait indefinitely for close.
486
+ if (!active || silent > LIMITS.reconcileMs) return stop();
487
+ }
488
+ if (!active || closed) return;
425
489
  try {
426
490
  if (Date.now() - reconciled >= LIMITS.reconcileMs) {
427
491
  socket.send(canonicalJson({ kind: "resync", scope }));
@@ -434,6 +498,7 @@ export class HttpServiceTransport implements ServiceTransport {
434
498
  socket.addEventListener("open", () => {
435
499
  if (closed) return;
436
500
  active = true;
501
+ last = reconciled = Date.now();
437
502
  try {
438
503
  socket.send(canonicalJson({ kind: "subscribe", scope }));
439
504
  } catch {
@@ -441,14 +506,15 @@ export class HttpServiceTransport implements ServiceTransport {
441
506
  }
442
507
  });
443
508
  socket.addEventListener("message", (event) => {
444
- if (closed) return;
509
+ if (closed || !active) return;
445
510
  try {
446
511
  if (typeof event.data !== "string") throw new ContractError("invalid");
447
512
  const value = decodeSocketOutput(
448
513
  parseWireJson(event.data, LIMITS.viewerBytes),
449
514
  );
450
515
  last = Date.now();
451
- notify("current");
516
+ // Only the observer knows whether the frame advances the selected
517
+ // attachment/epoch/projection. A resync request isn't current data.
452
518
  receive(value);
453
519
  } catch {
454
520
  stop();
@@ -93,6 +93,21 @@ const pageReaders = [
93
93
  "changes",
94
94
  "reviews",
95
95
  ] as const;
96
+ /** Only bounded original history readers, never live state, archives or work.
97
+ * A separate CSRF challenge for these bodies does not authorize other POSTs. */
98
+ export const HISTORY_CSRF_HEADER = "x-cadence-history-csrf";
99
+ const retainedReaders = [
100
+ ...pageReaders,
101
+ "entity",
102
+ "graph",
103
+ "detail",
104
+ "search",
105
+ ] as const;
106
+ export function retainedHistoryBody(
107
+ operation: HttpOperation,
108
+ ): operation is (typeof retainedReaders)[number] {
109
+ return (retainedReaders as readonly HttpOperation[]).includes(operation);
110
+ }
96
111
  /** Encoded HTTP Reply category, including wire whitespace/escaping. Graph data
97
112
  * is a control document; only its proof-only branch shares the page ceiling. */
98
113
  export function httpOutputLimit(
@@ -245,16 +260,12 @@ export function decodeHttpOutput(
245
260
  /** Body transport and POST security are independent of execution semantics. */
246
261
  export function readonlyBody(operation: HttpOperation): boolean {
247
262
  const operations: readonly HttpOperation[] = [
248
- ...pageReaders,
263
+ ...retainedReaders,
249
264
  "workbenchRead",
250
265
  "current",
251
266
  "currentChanges",
252
267
  "checkObligations",
253
- "entity",
254
- "graph",
255
268
  "snapshot",
256
- "detail",
257
- "search",
258
269
  "export",
259
270
  "download",
260
271
  "receipt",
@@ -268,7 +279,10 @@ function queryUrl(operation: HttpOperation, input: unknown): string {
268
279
  : `${path}?request=${encodeURIComponent(canonicalJson(input))}`;
269
280
  }
270
281
  export function wireUrl(operation: HttpOperation, value: unknown): string {
271
- const result = queryUrl(operation, decodeHttpInput(operation, value));
282
+ const input = decodeHttpInput(operation, value);
283
+ if (input && typeof input === "object" && Object.hasOwn(input, "navigation"))
284
+ throw new ContractError("invalid"); // Navigation travels only in the request body.
285
+ const result = queryUrl(operation, input);
272
286
  if (utf8Bytes(result) > LIMITS.headerBytes)
273
287
  throw new ContractError("oversize");
274
288
  return result;
@@ -234,6 +234,14 @@ export function decodeId(v) {
234
234
  invalid();
235
235
  return s;
236
236
  }
237
+ /** Scalar bounds shared by model input and the (independently closed) owner read. */
238
+ export const knowledgeFields = Object.freeze({
239
+ checkout: (v) => list(v, 8, (entry) => text(entry, 1024, true)),
240
+ path: (v) => text(v, 1024, true),
241
+ section: (v) => text(v, 512, true),
242
+ match: (v) => text(v, 256, true),
243
+ investigation: decodeId,
244
+ });
237
245
  export function decodeHash(v) {
238
246
  const s = text(v, 64);
239
247
  if (!/^[0-9a-f]{64}$/.test(s)) invalid();