@cosmicdrift/kumiko-bundled-features 0.417.0 → 0.418.0

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.
Files changed (41) hide show
  1. package/dist/agent-tools/api-docs/schema-fields.js +9 -0
  2. package/dist/auth-email-password/index.d.ts +2 -1
  3. package/dist/auth-email-password/index.js +2 -1
  4. package/dist/auth-email-password/signup-activation.js +2 -1
  5. package/dist/auth-email-password/signup-token-store.d.ts +1 -6
  6. package/dist/auth-email-password/signup-token-store.js +0 -5
  7. package/dist/cap-counter/stock-cap-guard.d.ts +9 -2
  8. package/dist/cap-counter/stock-cap-guard.js +9 -11
  9. package/dist/document-ingest-foundation/feature.js +5 -1
  10. package/dist/document-ingest-foundation/report-ingest-progress.js +19 -6
  11. package/dist/signature/entity.d.ts +8 -6
  12. package/dist/signature/entity.js +3 -1
  13. package/dist/signature/feature.js +11 -4
  14. package/dist/signature/handlers/lifecycle.write.d.ts +9 -0
  15. package/dist/signature/handlers/lifecycle.write.js +23 -1
  16. package/dist/signature/handlers/request.write.d.ts +1 -1
  17. package/dist/signature/i18n.js +1 -0
  18. package/dist/signature/list-cursor-seal.d.ts +3 -0
  19. package/dist/signature/list-cursor-seal.js +44 -0
  20. package/dist/signature/options.d.ts +2 -2
  21. package/dist/signature/payloads.d.ts +17 -1
  22. package/dist/signature/payloads.js +11 -2
  23. package/dist/signature/png.js +23 -3
  24. package/dist/signature/subject-queries.d.ts +1 -1
  25. package/dist/signature/subject-queries.js +30 -8
  26. package/dist/signature/sweep.js +26 -9
  27. package/dist/signature/web/constants.d.ts +9 -0
  28. package/dist/signature/web/constants.js +8 -0
  29. package/dist/subscription-stripe/plugin-methods.js +2 -0
  30. package/dist/subscription-stripe/verify-webhook.js +17 -16
  31. package/dist/tenant-inactivity/handlers/keep-account.write.js +5 -2
  32. package/dist/tenant-lifecycle/run-tenant-destroy.js +65 -33
  33. package/package.json +11 -11
  34. package/src/agent-tools/changes.json +6 -0
  35. package/src/cap-counter/changes.json +6 -0
  36. package/src/channel-whatsapp/changes.json +1 -1
  37. package/src/document-ingest-foundation/changes.json +6 -0
  38. package/src/signature/changes.json +18 -0
  39. package/src/subscription-paddle/changes.json +1 -1
  40. package/src/subscription-stripe/changes.json +6 -0
  41. package/src/tenant-lifecycle/changes.json +6 -0
@@ -1,6 +1,7 @@
1
- import { DEFAULT_LIST_LIMIT, entityListSchema, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { DEFAULT_LIST_LIMIT, entityListSchema, isUuid, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import { requestExecutor } from "./entity.js";
4
+ import { openListCursor, sealListCursor } from "./list-cursor-seal.js";
4
5
  function allFilters(payload) {
5
6
  return [...(payload.filter === undefined ? [] : [payload.filter]), ...(payload.filters ?? [])];
6
7
  }
@@ -23,7 +24,26 @@ function subjectKey(subject) {
23
24
  const MAX_BASE_PAGES_PER_ANSWER = 10;
24
25
  // authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
25
26
  const SUBJECT_CHECKS_IN_PARALLEL = 10;
26
- export function scopeRequestList(base, scope) {
27
+ async function openFirstQuery(query, payload, user, cursorSecret) {
28
+ const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
29
+ if (sealedCursor === undefined)
30
+ return query;
31
+ const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
32
+ if (openedCursor === null)
33
+ throw new AccessDeniedError();
34
+ return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
35
+ }
36
+ async function sealedPage(page, visibleRows, nextCursor, user, cursorSecret) {
37
+ // `total` would count requests of foreign subjects. The base cursor names the last base row,
38
+ // which may belong to a foreign subject, so the user only gets it sealed.
39
+ const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
40
+ return {
41
+ ...rest,
42
+ rows: visibleRows,
43
+ nextCursor: typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
44
+ };
45
+ }
46
+ export function scopeRequestList(base, scope, cursorSecret) {
27
47
  return {
28
48
  ...base,
29
49
  handler: async (query, ctx) => {
@@ -32,14 +52,16 @@ export function scopeRequestList(base, scope) {
32
52
  return base.handler(query, ctx);
33
53
  const payload = entityListSchema.parse(query.payload);
34
54
  // Group counts would include requests of foreign subjects, and an offset counts base rows,
35
- // not the rows this user sees; the screen pages by cursor.
36
- if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0) {
55
+ // not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
56
+ // without checking a row.
57
+ if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
37
58
  throw new AccessDeniedError();
38
59
  }
39
60
  const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
40
61
  const verdicts = new Map();
41
62
  const visibleRows = [];
42
- let page = await base.handler(query, ctx);
63
+ const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
64
+ let page = await base.handler(firstQuery, ctx);
43
65
  for (let fetched = 1;; fetched++) {
44
66
  if (!isRowsPage(page))
45
67
  throw new Error("signature request list did not return a rows page");
@@ -58,9 +80,7 @@ export function scopeRequestList(base, scope) {
58
80
  typeof nextCursor !== "string" ||
59
81
  fetched >= MAX_BASE_PAGES_PER_ANSWER ||
60
82
  verdicts.size >= MAX_LIST_LIMIT) {
61
- // `total` would count requests of foreign subjects; the cursor continues after the last base page.
62
- const { total: _total, rows: _rows, ...rest } = page;
63
- return { ...rest, rows: visibleRows };
83
+ return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
64
84
  }
65
85
  page = await base.handler({
66
86
  ...query,
@@ -103,6 +123,8 @@ export function scopeSignerList(base, scope) {
103
123
  typeof requestFilter.value !== "string") {
104
124
  throw new AccessDeniedError();
105
125
  }
126
+ if (!isUuid(requestFilter.value))
127
+ return emptyPage(payload);
106
128
  const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
107
129
  if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
108
130
  return emptyPage(payload);
@@ -4,7 +4,7 @@ import { requestExecutor } from "./entity.js";
4
4
  import { discardGeneratedFile, PDF_MIME_TYPE, readTenantFile, sha256Hex, storeGeneratedFile, } from "./files.js";
5
5
  import { instantOrNull, isPastInstant, listSigners, } from "./lib.js";
6
6
  import { appendPdfPages, buildSignaturePageHtml, DEFAULT_SIGNATURE_PAGE_LABELS, } from "./signature-page.js";
7
- import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
7
+ import { SIGNATURE_FAILURE_REASON, SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
8
8
  // Equals the executor's MAX_LIST_LIMIT.
9
9
  const SWEEP_PAGE_SIZE = 200;
10
10
  // Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
@@ -47,21 +47,38 @@ async function signaturePageEntries(ctx, signers) {
47
47
  }
48
48
  return entries;
49
49
  }
50
- // Appends the signature page to the unchanged original. A renderer outage throws, the request
51
- // stays all-signed and the next run tries again.
50
+ async function failRequest(ctx, request, reason) {
51
+ const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
52
+ requestId: request.id,
53
+ reason,
54
+ });
55
+ if (!failed.isSuccess) {
56
+ ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
57
+ requestId: request.id,
58
+ reason,
59
+ error: failed.error,
60
+ });
61
+ return;
62
+ }
63
+ if (propertyOf(failed.data, "failed") === true) {
64
+ ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
65
+ requestId: request.id,
66
+ reason,
67
+ });
68
+ }
69
+ }
70
+ // Appends the signature page to the unchanged original. A missing or changed original or a
71
+ // missing signature image can never heal and ends the request as failed. A renderer outage
72
+ // throws, the request stays all-signed and the next run tries again.
52
73
  async function finalizeRequest(ctx, opts, request) {
53
74
  const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
54
75
  if (original === null || sha256Hex(original.content) !== request.documentSha256) {
55
- ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
56
- requestId: request.id,
57
- });
76
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
58
77
  return;
59
78
  }
60
79
  const entries = await signaturePageEntries(ctx, await listSigners(ctx, ctx.systemUser, request.id));
61
80
  if (entries === null) {
62
- ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
63
- requestId: request.id,
64
- });
81
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
65
82
  return;
66
83
  }
67
84
  const html = buildSignaturePageHtml({
@@ -11,6 +11,7 @@ export declare const SIGNATURE_REQUEST_STATUS: {
11
11
  readonly Completed: "completed";
12
12
  readonly Declined: "declined";
13
13
  readonly Expired: "expired";
14
+ readonly Failed: "failed";
14
15
  readonly Cancelled: "cancelled";
15
16
  };
16
17
  export type SignatureRequestStatus = (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
@@ -48,11 +49,18 @@ export declare const SIGNATURE_EVENT_SHORT: {
48
49
  readonly completed: "completed";
49
50
  readonly declined: "declined";
50
51
  readonly expired: "expired";
52
+ readonly failed: "failed";
51
53
  };
54
+ export declare const SIGNATURE_FAILURE_REASON: {
55
+ readonly DocumentChanged: "document-changed";
56
+ readonly SignatureImageMissing: "signature-image-missing";
57
+ };
58
+ export type SignatureFailureReason = (typeof SIGNATURE_FAILURE_REASON)[keyof typeof SIGNATURE_FAILURE_REASON];
52
59
  export declare const SignatureEvents: {
53
60
  readonly completed: "signature:event:completed";
54
61
  readonly declined: "signature:event:declined";
55
62
  readonly expired: "signature:event:expired";
63
+ readonly failed: "signature:event:failed";
56
64
  };
57
65
  export declare const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
58
66
  export declare const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
@@ -65,5 +73,6 @@ export declare const SignatureInternalHandlers: {
65
73
  readonly linkDecline: "signature:write:link-decline";
66
74
  readonly finish: "signature:write:finish";
67
75
  readonly expire: "signature:write:expire";
76
+ readonly fail: "signature:write:fail";
68
77
  readonly reconcile: "signature:write:reconcile";
69
78
  };
@@ -11,6 +11,7 @@ export const SIGNATURE_REQUEST_STATUS = {
11
11
  Completed: "completed",
12
12
  Declined: "declined",
13
13
  Expired: "expired",
14
+ Failed: "failed",
14
15
  Cancelled: "cancelled",
15
16
  };
16
17
  export const SIGNATURE_SIGNER_STATUS = {
@@ -45,11 +46,17 @@ export const SIGNATURE_EVENT_SHORT = {
45
46
  completed: "completed",
46
47
  declined: "declined",
47
48
  expired: "expired",
49
+ failed: "failed",
50
+ };
51
+ export const SIGNATURE_FAILURE_REASON = {
52
+ DocumentChanged: "document-changed",
53
+ SignatureImageMissing: "signature-image-missing",
48
54
  };
49
55
  export const SignatureEvents = {
50
56
  completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
51
57
  declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
52
58
  expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
59
+ failed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.failed}`,
53
60
  };
54
61
  // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
55
62
  // a caller cannot tell the cases apart.
@@ -64,5 +71,6 @@ export const SignatureInternalHandlers = {
64
71
  linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
65
72
  finish: `${SIGNATURE_FEATURE}:write:finish`,
66
73
  expire: `${SIGNATURE_FEATURE}:write:expire`,
74
+ fail: `${SIGNATURE_FEATURE}:write:fail`,
67
75
  reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
68
76
  };
@@ -111,6 +111,8 @@ export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation =
111
111
  ...(mode === "subscription"
112
112
  ? { subscription_data: { metadata } }
113
113
  : {
114
+ // Session metadata too: a 100% promotion code completes without a PaymentIntent.
115
+ metadata,
114
116
  payment_intent_data: { metadata },
115
117
  invoice_creation: { enabled: paymentInvoiceCreation },
116
118
  // Without a customer, Stripe's default "if_required" makes a guest
@@ -300,9 +300,11 @@ function dropPaidSession(event, session, reason) {
300
300
  async function parsePaymentEvent(event, stripe) {
301
301
  const session = event.data.object; // @cast-boundary engine-bridge
302
302
  // mode !== "payment" excludes subscription-checkout sessions (same event types);
303
- // payment_status !== "paid" excludes an unpaid/expired session. Null here — not an
304
- // error — maps to foundation's 200 "ignored", same as the subscription-path's filters.
305
- if (session.mode !== "payment" || session.payment_status !== "paid") {
303
+ // any status but paid / no_payment_required (a 100% promotion code) excludes an
304
+ // unpaid/expired session. Null here — not an error — maps to foundation's 200 "ignored",
305
+ // same as the subscription-path's filters.
306
+ if (session.mode !== "payment" ||
307
+ (session.payment_status !== "paid" && session.payment_status !== "no_payment_required")) {
306
308
  return null;
307
309
  }
308
310
  // Lazy-fetch with expand: the raw webhook payload carries neither
@@ -321,21 +323,20 @@ async function parsePaymentEvent(event, stripe) {
321
323
  return null;
322
324
  throw transientProviderRejection(error);
323
325
  }
324
- // Tenant-resolution: mode:"payment" checkout sessions carry tenantId on
325
- // the PaymentIntent's OWN metadata (plugin-methods.ts sets it via
326
- // payment_intent_data.metadata), NOT on session-level metadata —
327
- // session.metadata is unset for this mode. Reading it off the expanded,
328
- // Stripe-verified PaymentIntent (not a freely-choosable payload field) is
329
- // what keeps tenant-attribution trustworthy: the webhook signature proves
330
- // this whole object chain came from Stripe, and the metadata itself was
331
- // set by our own backend at checkout-creation time.
326
+ // Tenant-resolution: plugin-methods.ts sets tenantId on the PaymentIntent metadata and on the
327
+ // session metadata. A 100% promotion code creates no PaymentIntent, so the session metadata
328
+ // is only read then. Both are set by our own backend at checkout-creation time and reach us
329
+ // through the signature-verified webhook chain, not as a freely-choosable payload field.
332
330
  const paymentIntent = expanded.payment_intent;
333
- if (!paymentIntent || typeof paymentIntent === "string") {
334
- // Not expanded (Stripe-API-drift) or absent — no verified tenant-claim
331
+ if (typeof paymentIntent === "string" ||
332
+ (paymentIntent === null && session.payment_status === "paid")) {
333
+ // Not expanded (Stripe-API-drift) or absent on a paid session — no verified tenant-claim
335
334
  // to trust.
336
335
  return dropPaidSession(event, session, "payment_intent_not_expanded");
337
336
  }
338
- const tenantId = paymentIntent.metadata?.["tenantId"];
337
+ const tenantId = paymentIntent
338
+ ? paymentIntent.metadata?.["tenantId"]
339
+ : expanded.metadata?.["tenantId"];
339
340
  if (!tenantId || tenantId.length === 0) {
340
341
  return dropPaidSession(event, session, "missing_tenant_id");
341
342
  }
@@ -348,9 +349,9 @@ async function parsePaymentEvent(event, stripe) {
348
349
  // customer, which Stripe sets independently of the session-level field.
349
350
  const sessionCustomer = expanded.customer;
350
351
  const providerCustomerId = (typeof sessionCustomer === "string" ? sessionCustomer : sessionCustomer?.id) ??
351
- (typeof paymentIntent.customer === "string"
352
+ (typeof paymentIntent?.customer === "string"
352
353
  ? paymentIntent.customer
353
- : paymentIntent.customer?.id);
354
+ : paymentIntent?.customer?.id);
354
355
  if (!providerCustomerId) {
355
356
  return dropPaidSession(event, session, "missing_customer");
356
357
  }
@@ -6,6 +6,7 @@ import { tenantTable } from "../../tenant/index.js";
6
6
  import { redeemKeepAccountToken } from "../keep-token.js";
7
7
  import { lockInactivityCycle } from "../state-store.js";
8
8
  import { tenantInactivityStateTable } from "../state-table.js";
9
+ const KEEPABLE_TENANT_STATUS = "active";
9
10
  const KEEP_ACCOUNT_ESCAPE_HATCH_REASON = "the anonymous link holder has no tenant scope; the tenant comes from the signed token and every statement filters by that tenantId";
10
11
  export function createKeepAccountHandler(opts) {
11
12
  return defineWriteHandler({
@@ -37,8 +38,10 @@ export function createKeepAccountHandler(opts) {
37
38
  commitKeep: async (tenantId, cycleId) => {
38
39
  await lockInactivityCycle(runner, tenantId);
39
40
  // A destruction request that won the lock owns the tenant now; reporting "kept" would be a lie.
40
- const tenant = await fetchOne(runner, tenantTable, { id: tenantId });
41
- if (tenant?.status !== "active")
41
+ const tenant = await fetchOne(runner, tenantTable, {
42
+ id: tenantId,
43
+ });
44
+ if (tenant?.status !== KEEPABLE_TENANT_STATUS)
42
45
  return false;
43
46
  const updated = await updateMany(runner, tenantInactivityStateTable, {
44
47
  lastActivityAt: now,
@@ -1,4 +1,4 @@
1
- import { createEventStoreExecutor, createTenantDb, fetchOne, selectMany, WritePurposes, } from "@cosmicdrift/kumiko-framework/db";
1
+ import { createEventStoreExecutor, createTenantDb, fetchOne, selectMany, tryWithSessionAdvisoryLock, WritePurposes, } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { createSystemUser, SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { append, loadAggregate, VersionConflictError, } from "@cosmicdrift/kumiko-framework/event-store";
4
4
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
@@ -9,6 +9,19 @@ import { invalidateTenantLifecycleGate, TEARDOWN_GATE_SETTLE_MS } from "./lifecy
9
9
  import { isDestructionPipelineComplete, pickNextStage, } from "./stages.js";
10
10
  const tenantCrud = createEventStoreExecutor(tenantTable, tenantEntity, { entityName: "tenant" });
11
11
  const FEATURE_PREFIX = "tenant-lifecycle:event:";
12
+ const TENANT_DESTRUCTION_LOCK_NAMESPACE = 0x74_64_65_73; // 'tdes'
13
+ const FNV32_OFFSET = 0x81_1c_9d_c5;
14
+ const FNV32_PRIME = 0x01_00_01_93;
15
+ // Cron ticks of the destruction job overlap (concurrency:"skip" does not hold across ticks),
16
+ // and two sweeps on one tenant make the loser's version conflict count as a failed stage
17
+ // attempt. A hash collision between tenants only skips one tick for the other tenant.
18
+ function tenantDestructionLockKey(tenantId) {
19
+ let hash = FNV32_OFFSET;
20
+ for (let i = 0; i < tenantId.length; i++) {
21
+ hash = Math.imul(hash ^ tenantId.charCodeAt(i), FNV32_PRIME);
22
+ }
23
+ return (hash ^ TENANT_DESTRUCTION_LOCK_NAMESPACE) | 0;
24
+ }
12
25
  function qualified(short) {
13
26
  return `${FEATURE_PREFIX}${short}`;
14
27
  }
@@ -150,6 +163,7 @@ async function tenantOwnsRetentionHeldRows(args) {
150
163
  return await tenantHasBlockDeleteRows(args);
151
164
  }
152
165
  async function haltPipelineOnAbandon(args) {
166
+ args.log?.(`[tenant-lifecycle] destruction halted: tenant ${args.tenantId} stage "${args.stage}" abandoned after ${args.attempts} attempt(s): ${args.error}`);
153
167
  const T = getTemporal();
154
168
  const failedAt = T.Now.instant();
155
169
  // Reload fresh instead of trusting a caller-supplied version: the failed
@@ -179,6 +193,7 @@ async function maybeAppendDestructionCompleted(db, tenantId, completed) {
179
193
  // `version` differs per caller: the catch path appends against the pre-run
180
194
  // version, the no-progress path against the version reloaded after run().
181
195
  async function recordFailedStageAttempt(args) {
196
+ args.log?.(`[tenant-lifecycle] stage attempt failed: tenant ${args.tenantId} stage "${args.stage.name}" attempt ${args.attempt}/${args.stage.maxAttempts}: ${args.error}`);
182
197
  if (args.attempt >= args.stage.maxAttempts) {
183
198
  await haltPipelineOnAbandon({
184
199
  db: args.db,
@@ -186,6 +201,7 @@ async function recordFailedStageAttempt(args) {
186
201
  stage: args.stage.name,
187
202
  attempts: args.attempt,
188
203
  error: args.error,
204
+ log: args.log,
189
205
  });
190
206
  return { done: false, error: args.error, halted: true };
191
207
  }
@@ -216,6 +232,7 @@ async function recordIdleStageTick(args) {
216
232
  ? `stage "${args.stage.name}" still pending after ${DESTRUCTION_STAGE_MAX_PENDING_MS / 60_000} min`
217
233
  : `stage "${args.stage.name}" made no progress`,
218
234
  version: lastEventVersion(args.events),
235
+ log: args.log,
219
236
  });
220
237
  }
221
238
  export async function runNextDestructionStage(args) {
@@ -276,6 +293,7 @@ export async function runNextDestructionStage(args) {
276
293
  pending: outcome.pending === true,
277
294
  events: eventsAfterRun,
278
295
  now,
296
+ log: args.log,
279
297
  });
280
298
  }
281
299
  if (!outcome.done) {
@@ -295,6 +313,7 @@ export async function runNextDestructionStage(args) {
295
313
  attempt,
296
314
  error: err instanceof Error ? err.message : String(err),
297
315
  version,
316
+ log: args.log,
298
317
  });
299
318
  }
300
319
  }
@@ -339,26 +358,33 @@ export async function runTenantDestructionSweep(args) {
339
358
  let triggered = 0;
340
359
  for (const row of due) {
341
360
  const tenantId = row.id;
342
- const events = await loadAggregate(args.db, tenantId, SYSTEM_TENANT_ID);
343
- const version = lastEventVersion(events);
344
- const user = createSystemUser(tenantId);
345
- const scopedDb = createTenantDb({
346
- db: args.db,
347
- tenantId,
348
- mode: "system",
349
- reason: "tenant destruction updates the tenant being destroyed, outside its request scope",
361
+ const locked = await tryWithSessionAdvisoryLock(args.db, tenantDestructionLockKey(tenantId), async () => {
362
+ // A peer sweep may have started this tenant after our `due` select.
363
+ if ((await tenantStatusOf(args.db, tenantId)) !== "destroyRequested")
364
+ return false;
365
+ const events = await loadAggregate(args.db, tenantId, SYSTEM_TENANT_ID);
366
+ const version = lastEventVersion(events);
367
+ const user = createSystemUser(tenantId);
368
+ const scopedDb = createTenantDb({
369
+ db: args.db,
370
+ tenantId,
371
+ mode: "system",
372
+ reason: "tenant destruction updates the tenant being destroyed, outside its request scope",
373
+ });
374
+ // Version-guarded (no skipOptimisticLock): a concurrent cancel-destruction
375
+ // between the `due` select above and this write also appends to the same
376
+ // tenant stream, so an unguarded overwrite here would silently revert the
377
+ // cancellation. A version conflict means we lost that race — skip, the
378
+ // tenant is no longer due and the next tick re-evaluates it.
379
+ const result = await tenantCrud.update({ id: tenantId, version, changes: { status: "destroying", destroyStartedAt: now } }, user, scopedDb, { writePurpose: WritePurposes.erasure });
380
+ if (!result.isSuccess)
381
+ return false;
382
+ invalidateTenantLifecycleGate(tenantId);
383
+ await appendTenantStageEvent(args.db, tenantId, qualified(TENANT_DESTRUCTION_STARTED_EVENT_SHORT), { startedAt: now.toString() }, version + 1);
384
+ return true;
350
385
  });
351
- // Version-guarded (no skipOptimisticLock): a concurrent cancel-destruction
352
- // between the `due` select above and this write also appends to the same
353
- // tenant stream, so an unguarded overwrite here would silently revert the
354
- // cancellation. A version conflict means we lost that race — skip, the
355
- // tenant is no longer due and the next tick re-evaluates it.
356
- const result = await tenantCrud.update({ id: tenantId, version, changes: { status: "destroying", destroyStartedAt: now } }, user, scopedDb, { writePurpose: WritePurposes.erasure });
357
- if (!result.isSuccess)
358
- continue;
359
- invalidateTenantLifecycleGate(tenantId);
360
- await appendTenantStageEvent(args.db, tenantId, qualified(TENANT_DESTRUCTION_STARTED_EVENT_SHORT), { startedAt: now.toString() }, version + 1);
361
- triggered++;
386
+ if (locked.acquired && locked.value)
387
+ triggered++;
362
388
  }
363
389
  let advanced = 0;
364
390
  const destroying = await selectMany(args.db, tenantTable, destroyingWhere);
@@ -370,20 +396,26 @@ export async function runTenantDestructionSweep(args) {
370
396
  for (const row of destroying) {
371
397
  const tenantDeadlineAt = Date.now() + sliceMs;
372
398
  try {
373
- const result = await runNextDestructionStage({
374
- deadlineAt: tenantDeadlineAt,
375
- now,
376
- db: args.db,
377
- registry: args.registry,
378
- tenantId: row.id,
379
- log: args.log,
380
- fileProviderResolver: args.fileProviderResolver,
381
- searchAdapter: args.searchAdapter,
382
- escapeHatchAuditSink: args.escapeHatchAuditSink,
383
- escapeHatchAuditLog: args.escapeHatchAuditLog,
384
- actor: args.actor,
399
+ const locked = await tryWithSessionAdvisoryLock(args.db, tenantDestructionLockKey(row.id), async () => {
400
+ // A peer sweep may have finished or halted this tenant after our `destroying` select.
401
+ if ((await tenantStatusOf(args.db, row.id)) !== "destroying")
402
+ return undefined;
403
+ return await runNextDestructionStage({
404
+ deadlineAt: tenantDeadlineAt,
405
+ now,
406
+ db: args.db,
407
+ registry: args.registry,
408
+ tenantId: row.id,
409
+ log: args.log,
410
+ fileProviderResolver: args.fileProviderResolver,
411
+ searchAdapter: args.searchAdapter,
412
+ escapeHatchAuditSink: args.escapeHatchAuditSink,
413
+ escapeHatchAuditLog: args.escapeHatchAuditLog,
414
+ actor: args.actor,
415
+ });
385
416
  });
386
- if (!result.error && !result.halted && !result.held)
417
+ const result = locked.acquired ? locked.value : undefined;
418
+ if (result && !result.error && !result.halted && !result.held)
387
419
  advanced++;
388
420
  }
389
421
  catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.417.0",
3
+ "version": "0.418.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -642,9 +642,9 @@
642
642
  }
643
643
  },
644
644
  "dependencies": {
645
- "@cosmicdrift/kumiko-framework": "0.417.0",
646
- "@cosmicdrift/kumiko-renderer": "0.417.0",
647
- "@cosmicdrift/kumiko-types": "0.417.0",
645
+ "@cosmicdrift/kumiko-framework": "0.418.0",
646
+ "@cosmicdrift/kumiko-renderer": "0.418.0",
647
+ "@cosmicdrift/kumiko-types": "0.418.0",
648
648
  "@mollie/api-client": "^4.6.0",
649
649
  "@node-rs/argon2": "^2.2.2",
650
650
  "@tiptap/core": "^3.32.2",
@@ -1310,19 +1310,19 @@
1310
1310
  "LICENSE"
1311
1311
  ],
1312
1312
  "devDependencies": {
1313
- "@cosmicdrift/kumiko-locale-de": "0.417.0",
1314
- "@cosmicdrift/kumiko-locale-es": "0.417.0",
1315
- "@cosmicdrift/kumiko-locale-fr": "0.417.0",
1316
- "@cosmicdrift/kumiko-locale-it": "0.417.0",
1317
- "@cosmicdrift/kumiko-renderer-mail-html": "0.417.0",
1318
- "@cosmicdrift/kumiko-testing": "0.417.0",
1313
+ "@cosmicdrift/kumiko-locale-de": "0.418.0",
1314
+ "@cosmicdrift/kumiko-locale-es": "0.418.0",
1315
+ "@cosmicdrift/kumiko-locale-fr": "0.418.0",
1316
+ "@cosmicdrift/kumiko-locale-it": "0.418.0",
1317
+ "@cosmicdrift/kumiko-renderer-mail-html": "0.418.0",
1318
+ "@cosmicdrift/kumiko-testing": "0.418.0",
1319
1319
  "@testing-library/user-event": "^14.6.8",
1320
1320
  "@types/sanitize-html": "^2.16.2",
1321
1321
  "jsqr": "^1.4.0",
1322
1322
  "unpdf": "^1.9.1"
1323
1323
  },
1324
1324
  "peerDependencies": {
1325
- "@cosmicdrift/kumiko-testing": "0.417.0"
1325
+ "@cosmicdrift/kumiko-testing": "0.418.0"
1326
1326
  },
1327
1327
  "peerDependenciesMeta": {
1328
1328
  "@cosmicdrift/kumiko-testing": {
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "API docs label nullable types",
6
+ "detail": "A JSON Schema type array such as `[\"string\", \"null\"]` (Zod nullable) was labelled `any` in the generated API docs. Each element is now labelled (string keeps its format) and joined with ` | `, with null last, e.g. `string | null`."
7
+ },
2
8
  {
3
9
  "version": "0.416.0",
4
10
  "type": "improvement",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "withStockCap keeps the handler type",
6
+ "detail": "`withStockCap` is generic over the write handler definition and returns the type it received, so a `defineWriteHandler` result passes in without an `as unknown as WriteHandlerDef` cast. Callers passing a `WriteHandlerDef` compile unchanged."
7
+ },
2
8
  {
3
9
  "version": "0.414.0",
4
10
  "type": "fix",
@@ -15,7 +15,7 @@
15
15
  "version": "0.415.0",
16
16
  "type": "fix",
17
17
  "title": "WhatsApp webhook skips oversized ids and survives absurd timestamps",
18
- "detail": "An entry with a wamid or phone number id above its limit is counted as skipped instead of failing the whole delivery with a 5xx. Overlong context ids, media ids and mime types are clipped, and a timestamp beyond the Temporal range falls back to the receive time."
18
+ "detail": "An entry with a wamid or phone number id above its limit is counted as skipped instead of failing the whole delivery with a 5xx. Overlong context ids and media ids are dropped to null and overlong mime types are clipped, and a timestamp beyond the Temporal range falls back to the receive time."
19
19
  },
20
20
  {
21
21
  "version": "0.415.0",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "Ingest progress only moves forward",
6
+ "detail": "Parallel `reportIngestProgress` calls for one file can land in any order; the progress row now keeps the highest `pagesDone`, a report whose progress is already stored stops early, and after 10 version conflicts the call throws instead of returning silently."
7
+ },
2
8
  {
3
9
  "version": "0.415.0",
4
10
  "type": "fix",
@@ -1,4 +1,22 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "List cursor of subject-scoped users is sealed",
6
+ "detail": "The request list returned the plain cursor of the last base page, which could name a request of a foreign subject. Scoped users now get an encrypted cursor bound to their user and tenant, a plain or foreign cursor is answered with access denied, and `authorizeSubject` now requires a non-empty `linkSecret` because the cursor key is derived from it. A scoped user asking for `limit: 0` is refused like `offset`."
7
+ },
8
+ {
9
+ "version": "0.418.0",
10
+ "type": "fix",
11
+ "title": "Unrecoverable finalisation ends in status failed",
12
+ "detail": "A request whose original PDF changed or went missing, or whose signature image is missing, used to stay `all-signed` forever while the sweep warned every five minutes. It now ends in the status `failed` with the event `signature:event:failed` and a reason (`document-changed` or `signature-image-missing`). Renderer outages and storage errors still retry on the next run."
13
+ },
14
+ {
15
+ "version": "0.418.0",
16
+ "type": "fix",
17
+ "title": "Empty signatures are rejected on every background",
18
+ "detail": "The ink check treats an image as having a solid background only when all four corners are opaque and identical; a lone opaque pixel no longer counts the whole image as ink, and signer emails must be valid addresses."
19
+ },
2
20
  {
3
21
  "version": "0.417.0",
4
22
  "type": "breaking",
@@ -3,7 +3,7 @@
3
3
  "version": "0.415.0",
4
4
  "type": "fix",
5
5
  "title": "unreadable ledger backfill marker no longer causes endless 503",
6
- "detail": "shouldRedeliverLegacyCheckout answers 200 and logs when the marker dispatch fails, because custom_data.tenantBinding is client-settable."
6
+ "detail": "shouldRedeliverLegacyCheckout answers 200 and logs only when the marker dispatch fails with a configuration error (access_denied, not_found, feature_disabled), because custom_data.tenantBinding is client-settable; other dispatch failures still answer 503 so Paddle redelivers a bounded number of times."
7
7
  },
8
8
  {
9
9
  "version": "0.414.0",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "One-off checkouts with a 100% promo code are booked",
6
+ "detail": "A Stripe checkout session in payment mode that a 100% promo code makes free is now booked like a paid one: the handler reads the session metadata in payment mode. Sessions created before the upgrade carry no session metadata and are still discarded."
7
+ },
2
8
  {
3
9
  "version": "0.416.0",
4
10
  "type": "improvement",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "The tenant destruction sweep locks per tenant",
6
+ "detail": "Overlapping sweeps no longer push a tenant into `destroyFailed`. Each sweep takes a session advisory lock per tenant and skips tenants another sweep holds for that tick; failed stage attempts and abandoned stages are now logged with tenant and stage."
7
+ },
2
8
  {
3
9
  "version": "0.415.0",
4
10
  "type": "fix",