@substrat-run/adapter-cloudflare 0.240.0 → 0.242.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 (72) hide show
  1. package/dist/connection-sweep-do.d.ts +12 -0
  2. package/dist/connection-sweep-do.d.ts.map +1 -1
  3. package/dist/connection-sweep-do.js +28 -6
  4. package/dist/connection-sweep-do.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +22 -0
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +60 -13
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/control-plane-object.d.ts +23 -0
  10. package/dist/control-plane-object.d.ts.map +1 -0
  11. package/dist/control-plane-object.js +92 -0
  12. package/dist/control-plane-object.js.map +1 -0
  13. package/dist/delivery-broker-supervisor-do.d.ts +19 -0
  14. package/dist/delivery-broker-supervisor-do.d.ts.map +1 -1
  15. package/dist/delivery-broker-supervisor-do.js +27 -0
  16. package/dist/delivery-broker-supervisor-do.js.map +1 -1
  17. package/dist/directory-placement.d.ts.map +1 -1
  18. package/dist/directory-placement.js +7 -0
  19. package/dist/directory-placement.js.map +1 -1
  20. package/dist/egress-gate.d.ts +71 -0
  21. package/dist/egress-gate.d.ts.map +1 -0
  22. package/dist/egress-gate.js +80 -0
  23. package/dist/egress-gate.js.map +1 -0
  24. package/dist/host.d.ts +1058 -18
  25. package/dist/host.d.ts.map +1 -1
  26. package/dist/host.js +135 -29
  27. package/dist/host.js.map +1 -1
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +5 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/listed-object.d.ts +24 -0
  33. package/dist/listed-object.d.ts.map +1 -0
  34. package/dist/listed-object.js +43 -0
  35. package/dist/listed-object.js.map +1 -0
  36. package/dist/peer-read-evidence.d.ts +31 -31
  37. package/dist/peer-read-evidence.d.ts.map +1 -1
  38. package/dist/peer-read-evidence.js +75 -0
  39. package/dist/peer-read-evidence.js.map +1 -1
  40. package/dist/route-resolver.d.ts +22 -1
  41. package/dist/route-resolver.d.ts.map +1 -1
  42. package/dist/route-resolver.js +1 -1
  43. package/dist/route-resolver.js.map +1 -1
  44. package/dist/scope-do.d.ts +5 -0
  45. package/dist/scope-do.d.ts.map +1 -1
  46. package/dist/scope-do.js +32 -10
  47. package/dist/scope-do.js.map +1 -1
  48. package/dist/scope-facets.d.ts +15 -4
  49. package/dist/scope-facets.d.ts.map +1 -1
  50. package/dist/scope-facets.js +66 -13
  51. package/dist/scope-facets.js.map +1 -1
  52. package/dist/scope-object.d.ts +28 -0
  53. package/dist/scope-object.d.ts.map +1 -0
  54. package/dist/scope-object.js +13 -0
  55. package/dist/scope-object.js.map +1 -0
  56. package/dist/scope-supervisor-do.d.ts +3 -1
  57. package/dist/scope-supervisor-do.d.ts.map +1 -1
  58. package/dist/scope-supervisor-do.js +24 -5
  59. package/dist/scope-supervisor-do.js.map +1 -1
  60. package/dist/supplied-pass-box.d.ts +16 -2
  61. package/dist/supplied-pass-box.d.ts.map +1 -1
  62. package/dist/supplied-pass-box.js +92 -28
  63. package/dist/supplied-pass-box.js.map +1 -1
  64. package/dist/tenant-due-index-do.d.ts +33 -0
  65. package/dist/tenant-due-index-do.d.ts.map +1 -1
  66. package/dist/tenant-due-index-do.js +47 -0
  67. package/dist/tenant-due-index-do.js.map +1 -1
  68. package/dist/tenant-due-work-do.d.ts +18 -0
  69. package/dist/tenant-due-work-do.d.ts.map +1 -1
  70. package/dist/tenant-due-work-do.js +21 -0
  71. package/dist/tenant-due-work-do.js.map +1 -1
  72. package/package.json +13 -12
package/dist/host.js CHANGED
@@ -14,7 +14,7 @@ import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink,
14
14
  // #2995: the parent link a provision-child writes, and the doors it decides.
15
15
  childDoorRefusal, childScopeRefusal, claimsHome, directAccessRefusal, parentlessScopeRefusal, provisionedParent,
16
16
  // #2993 part 3: the modules (and seats) a scope of each declared type has.
17
- HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, declaredJobsOf, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, sealingKeysForReach, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, loadedFromScopeNote, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
17
+ HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, guardSecretBox, secretBoxCanaryPreflight, secretBoxCanaryReceipt, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, declaredJobsOf, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, sealingKeysForReach, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, loadedFromScopeNote, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
18
18
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
19
19
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
20
20
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
@@ -62,6 +62,21 @@ export const TENANT_UNRECORDED_PER_PASS = 50;
62
62
  * looks again a minute on, then on the directory's back-off.
63
63
  */
64
64
  export const LIFECYCLE_RETRY_FIRST_LOOK_MS = 60_000;
65
+ /**
66
+ * K-69 (#3540), #2016: with a {@link LifecycleRetryOwner}, how long after a tenant-record ask the
67
+ * next one is due while the deployment answers without the record. The sweep's rotation reaches each
68
+ * such scope once a pass while fewer than {@link TENANT_UNRECORDED_PER_PASS} are owed one, so this is
69
+ * the pass's period: the cadence the sweep asks at. An ask that fails waits on the directory's
70
+ * back-off (#3119) instead, as any failed delivery does.
71
+ */
72
+ export const LIFECYCLE_TENANT_ASK_RELOOK_MS = 15 * 60_000;
73
+ /**
74
+ * #2016: whether the scope's deployment has not answered that it holds a record of the scope's
75
+ * tenant: no receipt, or one without the record. The sweep's tenant-record walk reads the same.
76
+ */
77
+ function owedTenantAsk(t) {
78
+ return t.tenant_recorded !== 1;
79
+ }
65
80
  /**
66
81
  * K-69 (#3540): whether a scope is owed its first lifecycle delivery after a directory restore. The
67
82
  * restore minted an epoch (`epoch > 0`), and the deployment has acknowledged nothing in it: no
@@ -442,6 +457,8 @@ export class CloudflareScopeHost {
442
457
  cpLess;
443
458
  /** Project + evaluate permissions scope-locally (scope-local-permissions.md). */
444
459
  scopeLocalPermissions;
460
+ /** `projectsVerticals`, or undefined for every scope. */
461
+ projectsVerticals;
445
462
  // Registration-mechanics bookkeeping (validation only — the DO executes).
446
463
  // Code-time, derived from the bundled modules, NOT durable directory state.
447
464
  moduleIds = new Set();
@@ -479,6 +496,8 @@ export class CloudflareScopeHost {
479
496
  predicateNames = new Map(); // name → module
480
497
  /** Executor id → {eventType, handler} (K-22 §4.2). Coordinator-side, not in the DO. */
481
498
  secretBox;
499
+ /** #3464: the canary mode `secretBox` was guarded with, which its preflight reports. */
500
+ secretBoxCanaryMode;
482
501
  fetchImpl;
483
502
  streamIdleMs;
484
503
  connectorCalls;
@@ -573,6 +592,7 @@ export class CloudflareScopeHost {
573
592
  noteDeclaredKeys(this.declaredKeys, m.manifest);
574
593
  }
575
594
  this.secretBox = options.secretBox ?? unconfiguredSecretBox;
595
+ this.secretBoxCanaryMode = options.secretBoxCanary ?? 'off';
576
596
  this.tenantStores = options.tenantStores;
577
597
  this.blobStores = options.blobStores;
578
598
  this.attachmentBuckets = options.attachmentBuckets ?? ambientAttachmentBucket;
@@ -592,6 +612,7 @@ export class CloudflareScopeHost {
592
612
  this.holdSettleMs = switchHoldSettleMs(this.holdSnapshotMs);
593
613
  this.connectorCalls = options.connectorCalls ?? noopConnectorCallRecorder;
594
614
  this.scopeLocalPermissions = options.scopeLocalPermissions ?? false;
615
+ this.projectsVerticals = options.projectsVerticals ? new Set(options.projectsVerticals) : undefined;
595
616
  this.scopeNs = options.scope;
596
617
  this.scopeStoreVertical = options.scopeStores?.vertical;
597
618
  this.scopeStoreDrivers = options.scopeStores?.drivers ?? {};
@@ -602,6 +623,10 @@ export class CloudflareScopeHost {
602
623
  this.cp = options.controlPlane
603
624
  ? options.controlPlane.get(options.controlPlane.idFromName('control-plane'))
604
625
  : nullControlPlane();
626
+ // #3464: guarded after `cp`, which keeps the canary; its records are read at seal time only.
627
+ if (options.secretBox && options.controlPlane) {
628
+ this.secretBox = guardSecretBox(options.secretBox, this.secretBoxCanaryRecords(), this.secretBoxCanaryMode);
629
+ }
605
630
  this.connectorDelegation = options.connectorDelegation;
606
631
  this.eventDrainDelegation = options.eventDrainDelegation;
607
632
  this.systemSwitchDelegation = options.systemSwitchDelegation;
@@ -7071,6 +7096,16 @@ export class CloudflareScopeHost {
7071
7096
  await this.recordAccess(actor, 'openSubjectPayloads', { tenantId, scopeId }, { subjects: new Set(items.map((i) => i.subjectId)).size }, opened.filter((o) => o !== null).length);
7072
7097
  return opened;
7073
7098
  },
7099
+ // #3464: read-only; the guard's `open` is the box's own, so nothing here can seed the canary. A
7100
+ // CP-less host has no directory to read, and its null control plane throws.
7101
+ secretBoxCanaryPreflight: async (actor) => {
7102
+ const report = isSecretBoxConfigured(this.secretBox)
7103
+ ? { mode: this.secretBoxCanaryMode, keyConfigured: true, ...(await secretBoxCanaryPreflight(this.secretBox, this.secretBoxCanaryRecords())) }
7104
+ : { mode: this.secretBoxCanaryMode, keyConfigured: false };
7105
+ const receipt = secretBoxCanaryReceipt(report);
7106
+ await this.recordAccess(actor, 'secretBoxCanaryPreflight', {}, receipt.params, receipt.resultCount);
7107
+ return report;
7108
+ },
7074
7109
  listShreddedSubjects: async (actor, tenantId, scopeId, cursor) => {
7075
7110
  await this.assertScope(tenantId, scopeId);
7076
7111
  const rows = await this.cp.listShreddedSubjects(scopeId, tenantId, cursor ?? null);
@@ -8178,9 +8213,11 @@ export class CloudflareScopeHost {
8178
8213
  * handed over as it fails, and the heal sweep hands over, undelivered, the scopes it finds owed one,
8179
8214
  * the live scopes it finds owed their first delivery after a restore (`owedFirstDelivery`), and the
8180
8215
  * acknowledged holds whose deployment moved (`owedHoldRedelivery`). An acknowledged hold whose
8181
- * deployment did not move is not delivered at all. `retry` is the owner's own run: only a scope owed
8182
- * one of the three, delivered even when the receipt says nothing changed (a failure is owed whatever
8183
- * the receipt), and never handed over again.
8216
+ * deployment did not move is not delivered at all. The #2016 tenant-record asks are the owner's too
8217
+ * (`owedTenantAsk`): the sweep hands over the scopes its rotation lists and asks none, and a delivery
8218
+ * that lands without the record hands its next ask over a re-look on. `retry` is the owner's own run:
8219
+ * only a scope owed one of the four, delivered even when the receipt says nothing changed (a failure
8220
+ * is owed whatever the receipt), and never handed over again.
8184
8221
  */
8185
8222
  async deliverLifecycles(actor, filter) {
8186
8223
  const report = { attempted: 0, delivered: 0, failed: 0 };
@@ -8194,16 +8231,34 @@ export class CloudflareScopeHost {
8194
8231
  // record of the scope's tenant, a copy as much as a primary (no push reconciles a copy), until
8195
8232
  // each answers that it does. A bounded slice per pass, after the drift and the holds.
8196
8233
  const askTenant = new Set();
8234
+ // K-69 (#3540): with an owner the ask is its own. These are the drift's scopes also owed one: one
8235
+ // the drift neither delivers nor hands over (an acknowledged hold) is handed over for its ask.
8236
+ const askOwner = new Set();
8237
+ // K-69 (#3540): deliveries that landed without the tenant's record, each now an ask the owner repeats.
8238
+ const askedNow = [];
8197
8239
  try {
8198
8240
  targets = await this.cp.lifecycleTargets(filter);
8199
8241
  if (filter.drift) {
8200
- const unrecorded = await this.cp.lifecycleTargets({ unrecorded: true, limit: TENANT_UNRECORDED_PER_PASS });
8201
- // Noted before asking, so an ask that fails (or a deployment that never answers) rotates
8202
- // behind the scopes not asked yet, and the next pass reaches them.
8242
+ // With an owner, only the scopes whose last ask is a re-look old: a newer one is the owner's to repeat.
8243
+ const unrecorded = await this.cp.lifecycleTargets({
8244
+ unrecorded: true,
8245
+ limit: TENANT_UNRECORDED_PER_PASS,
8246
+ ...(owner ? { askedBefore: new Date(Date.now() - LIFECYCLE_TENANT_ASK_RELOOK_MS).toISOString() } : {}),
8247
+ });
8248
+ // Noted before asking (or handing the ask over), so an ask that fails (or a deployment that
8249
+ // never answers, or a handoff that is lost) rotates behind the scopes not asked yet, and the
8250
+ // next pass reaches them.
8203
8251
  if (unrecorded.length > 0)
8204
8252
  await this.cp.recordTenantAsks(unrecorded.map((u) => u.scope_id), new Date().toISOString());
8205
8253
  const seen = new Set(targets.map((t) => t.scope_id));
8206
8254
  for (const u of unrecorded) {
8255
+ if (owner) {
8256
+ if (seen.has(u.scope_id))
8257
+ askOwner.add(u.scope_id);
8258
+ else
8259
+ handOver.push({ tenantId: u.tenant_id, scopeId: u.scope_id, dueAt: Date.now() });
8260
+ continue;
8261
+ }
8207
8262
  askTenant.add(u.scope_id);
8208
8263
  if (!seen.has(u.scope_id))
8209
8264
  targets.push(u);
@@ -8217,7 +8272,7 @@ export class CloudflareScopeHost {
8217
8272
  for (const first of targets) {
8218
8273
  const tenantId = first.tenant_id;
8219
8274
  const scopeId = first.scope_id;
8220
- if (filter.retry && first.retry_at === null && !owedFirstDelivery(first) && !owedHoldRedelivery(first))
8275
+ if (filter.retry && first.retry_at === null && !owedFirstDelivery(first) && !owedHoldRedelivery(first) && !owedTenantAsk(first))
8221
8276
  continue;
8222
8277
  // K-69 (#3540): the sweep's check. A scope owed a retry is its owner's, at once: the directory
8223
8278
  // only lists one whose back-off is over, or whose receipt or deployment moved since.
@@ -8243,7 +8298,7 @@ export class CloudflareScopeHost {
8243
8298
  // scope moved since; one acknowledged where it is still served is owed nothing. A hold not
8244
8299
  // acknowledged yet is delivered here, so the sweep never delays a hold that did not land.
8245
8300
  if (filter.drift && owner && !askTenant.has(scopeId) && acknowledgedHold(t)) {
8246
- if (owedHoldRedelivery(t))
8301
+ if (owedHoldRedelivery(t) || askOwner.has(scopeId))
8247
8302
  handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8248
8303
  continue;
8249
8304
  }
@@ -8317,6 +8372,12 @@ export class CloudflareScopeHost {
8317
8372
  // (#3540): with the deployment read before the delivery, so a move during it reads as moved.
8318
8373
  await this.cp.recordLifecycleReceipt(scopeId, lifecycleReceipt(answer.lifecycle), new Date().toISOString(), answer.tenantRecorded === true, t.deployment);
8319
8374
  report.delivered += 1;
8375
+ // K-69 (#3540), #2016: an answer without the tenant's record is the event that makes the next
8376
+ // ask due on the owner, a re-look on. The owner's own run answers when its next ask is instead.
8377
+ if (owner && answer.tenantRecorded !== true) {
8378
+ askedNow.push(scopeId);
8379
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() + LIFECYCLE_TENANT_ASK_RELOOK_MS });
8380
+ }
8320
8381
  }
8321
8382
  catch (err) {
8322
8383
  report.failed += 1;
@@ -8349,6 +8410,12 @@ export class CloudflareScopeHost {
8349
8410
  }
8350
8411
  }
8351
8412
  }
8413
+ if (askedNow.length > 0) {
8414
+ // Noted as asked, as the sweep notes its own, so its rotation does not hand the ask over again within a re-look.
8415
+ await this.cp
8416
+ .recordTenantAsks(askedNow, new Date().toISOString())
8417
+ .catch((err) => console.error('substrat: could not note tenant-record asks (#2016)', err));
8418
+ }
8352
8419
  if (owner && handOver.length > 0) {
8353
8420
  try {
8354
8421
  await owner.handOver(handOver);
@@ -8376,29 +8443,39 @@ export class CloudflareScopeHost {
8376
8443
  * acknowledged state differs from the directory, and again to every scope held now — which is
8377
8444
  * what puts a hold back on a store a carry or a restore landed without it. Bounded per pass
8378
8445
  * (`limit`), drifted scopes first. Run from the shared control plane's cron. With a
8379
- * `lifecycleRetryOwner` (K-69, #3540), the retries, the first deliveries after a restore and the
8380
- * acknowledged holds whose deployment moved are handed to it, undelivered, and an acknowledged hold
8381
- * whose deployment did not move is delivered no more.
8446
+ * `lifecycleRetryOwner` (K-69, #3540), the retries, the first deliveries after a restore, the
8447
+ * acknowledged holds whose deployment moved and the #2016 tenant-record asks are handed to it,
8448
+ * undelivered, and an acknowledged hold whose deployment did not move is delivered no more.
8382
8449
  */
8383
8450
  async healLifecycles(actor, opts) {
8384
8451
  return this.deliverLifecycles(actor, { drift: true, limit: opts?.limit ?? 200 });
8385
8452
  }
8386
8453
  /**
8387
8454
  * K-69 (#3540): one retry of a scope's failed lifecycle delivery, its first delivery after a
8388
- * directory restore, or an acknowledged hold's delivery to the deployment that now serves it, for
8389
- * its `lifecycleRetryOwner`. Re-reads the directory and delivers only when the scope is still owed
8390
- * one of the three (a later transition that landed owes none), with the
8455
+ * directory restore, an acknowledged hold's delivery to the deployment that now serves it, or its
8456
+ * #2016 tenant-record ask, for its `lifecycleRetryOwner`. Re-reads the directory and delivers only
8457
+ * when the scope is still owed one of the four (a later transition that landed owes none), with the
8391
8458
  * delivery's own epoch handling and failure count; a first delivery that fails is a retry from then.
8392
- * Answers when to look again (epoch ms), or null when nothing more is owed. Throws only when the
8459
+ * Answers when to look again (epoch ms): the directory's back-off after a failure, a re-look on
8460
+ * ({@link LIFECYCLE_TENANT_ASK_RELOOK_MS}) after a delivery that landed without the tenant's record,
8461
+ * or null when nothing more is owed. Throws only when the
8393
8462
  * directory cannot be read, so the owner keeps the retry.
8394
8463
  */
8395
8464
  async retryLifecycle(actor, tenantId, scopeId) {
8396
8465
  const [owed] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8397
- if (!owed || (owed.retry_at === null && !owedFirstDelivery(owed) && !owedHoldRedelivery(owed)))
8466
+ if (!owed || (owed.retry_at === null && !owedFirstDelivery(owed) && !owedHoldRedelivery(owed) && !owedTenantAsk(owed)))
8398
8467
  return null;
8468
+ // #2016: noted before asking, as the sweep notes its own, so the sweep's rotation leaves it to this owner.
8469
+ if (owedTenantAsk(owed))
8470
+ await this.cp.recordTenantAsks([scopeId], new Date().toISOString());
8399
8471
  const report = await this.deliverLifecycles(actor, { tenantId, scopeId, retry: true });
8400
- if (report.failed === 0)
8401
- return null;
8472
+ if (report.failed === 0) {
8473
+ if (report.delivered === 0)
8474
+ return null;
8475
+ // Landed. A deployment that answered without the tenant's record is asked again a re-look on.
8476
+ const [after] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8477
+ return after && owedTenantAsk(after) ? Date.now() + LIFECYCLE_TENANT_ASK_RELOOK_MS : null;
8478
+ }
8402
8479
  // A failure the directory did not count (a foreign epoch, a status this code cannot read) is
8403
8480
  // not a retry: the sweep finds that scope again itself, as it did before.
8404
8481
  const [after] = await this.cp.lifecycleTargets({ tenantId, scopeId });
@@ -8468,6 +8545,14 @@ export class CloudflareScopeHost {
8468
8545
  * Record a staff read (K-24). `params` is a bounded summary, capped so one query
8469
8546
  * cannot write an unbounded row.
8470
8547
  */
8548
+ /** #3464: the directory's SecretBox canary, kept by the ControlPlaneDO. Read at seal time, never before. */
8549
+ secretBoxCanaryRecords() {
8550
+ return {
8551
+ read: () => this.cp.readSecretBoxCanary(),
8552
+ insert: (row) => this.cp.insertSecretBoxCanary(row),
8553
+ oldestWrapped: () => this.cp.oldestWrappedSecret(),
8554
+ };
8555
+ }
8471
8556
  async recordAccess(actor, method, target, params, resultCount) {
8472
8557
  // K-73: an actor being summarized adds to its pass's one row instead of writing its own.
8473
8558
  const summary = this.accessSummary.current;
@@ -9100,6 +9185,13 @@ export class CloudflareScopeHost {
9100
9185
  public_key: k.publicKey,
9101
9186
  }));
9102
9187
  }
9188
+ /**
9189
+ * Whether a scope of `vertical` is this host's to project into (`projectsVerticals`). Both
9190
+ * callers pass the vertical from the directory's own row (`listScopes`, `getScopeRecord`).
9191
+ */
9192
+ projectsInto(vertical) {
9193
+ return this.projectsVerticals === undefined || (vertical !== null && this.projectsVerticals.has(vertical));
9194
+ }
9103
9195
  /** Project the tenant's current state into ONE scope + flip it to local. */
9104
9196
  async projectScope(tenantId, scopeId) {
9105
9197
  if (!this.scopeLocalPermissions)
@@ -9111,6 +9203,8 @@ export class CloudflareScopeHost {
9111
9203
  const scope = await this.cp.getScopeRecord(tenantId, scopeId);
9112
9204
  if (!scope)
9113
9205
  throw unknownScopeForTenant(tenantId, scopeId);
9206
+ if (!this.projectsInto(scope.vertical))
9207
+ return;
9114
9208
  const { roles, tuples, entitlements, identities } = await this.tenantProjection(tenantId);
9115
9209
  const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical, scopeId);
9116
9210
  unwrapReply(await this.scopeStub(scopeId).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, connectionKeys));
@@ -9146,10 +9240,10 @@ export class CloudflareScopeHost {
9146
9240
  // at creation, and including it costs one idempotent write while excluding it
9147
9241
  // could race that pull. `suspended` is included because suspension is reversible
9148
9242
  // and a suspended scope must not come back with a stale projection.
9149
- const scopes = await this.cp.listScopes({
9243
+ const scopes = (await this.cp.listScopes({
9150
9244
  tenantId,
9151
9245
  status: ['provisioning', 'active', 'suspended'],
9152
- });
9246
+ })).filter((s) => this.projectsInto(s.vertical));
9153
9247
  // #687: connection keys are per (tenant, vertical), so they are resolved per scope
9154
9248
  // rather than once for the tenant — memoized, because a fan-out over twenty scopes
9155
9249
  // of one vertical must not mint or re-read twenty times.
@@ -9200,6 +9294,9 @@ export class CloudflareScopeHost {
9200
9294
  // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
9201
9295
  // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
9202
9296
  const scopeType = await this.scopeTypeAt(input.scopeId, input.scopeType);
9297
+ // #3962: the platform still supplies one owner role per app. When its role belongs to another
9298
+ // type, carry on with the projections and omit that seat. Existing seats stay in place.
9299
+ const ownerRoleApplies = !this.scopeTypePlan.declared || this.scopeTypePlan.roles.get(scopeType)?.has(input.ownerRoleKey) === true;
9203
9300
  // #2995: then its parent, also before anything migrates. Judged against the store, which holds the
9204
9301
  // link the first provision fixed; whether the parent may hold this child is the directory's call.
9205
9302
  const parentScopeId = input.parentScopeId === undefined
@@ -9213,7 +9310,7 @@ export class CloudflareScopeHost {
9213
9310
  // writes nothing, so a seat a reconcile would have re-asserted is left exactly as it is.
9214
9311
  const reserved = await this.refuseReservedRoleSet(input.roles, input.tenantId, input.scopeId);
9215
9312
  const ownerRole = input.roles.find((r) => r.key === input.ownerRoleKey);
9216
- const ownerRefusal = ownerRole ? reservedRoleRefusal(ownerRole, reserved, 'person') : null;
9313
+ const ownerRefusal = ownerRoleApplies && ownerRole ? reservedRoleRefusal(ownerRole, reserved, 'person') : null;
9217
9314
  if (ownerRefusal)
9218
9315
  throw substratError('forbidden', `the owner's seat: ${ownerRefusal}`);
9219
9316
  const connections = await this.seatableConnectionGrants(input.tenantId, input.scopeId, input.connectionGrants);
@@ -9248,13 +9345,13 @@ export class CloudflareScopeHost {
9248
9345
  // no effective role grant — none whose role the vertical still defines — which is the
9249
9346
  // #332 lockout a reconcile exists to repair.
9250
9347
  [
9251
- {
9252
- subject: `principal:${input.owner}`,
9253
- relation: `role:${input.ownerRoleKey}`,
9254
- object: `scope:${input.scopeId}`,
9255
- expires_at: null,
9256
- lockout_reseat: true,
9257
- },
9348
+ ...(ownerRoleApplies ? [{
9349
+ subject: `principal:${input.owner}`,
9350
+ relation: `role:${input.ownerRoleKey}`,
9351
+ object: `scope:${input.scopeId}`,
9352
+ expires_at: null,
9353
+ lockout_reseat: true,
9354
+ }] : []),
9258
9355
  ...this.declaredSeatsLocal(input.scopeId, connections.seat, scopeType),
9259
9356
  ],
9260
9357
  // #406: identity links, delivered by the platform with provisioning exactly as
@@ -9286,6 +9383,15 @@ export class CloudflareScopeHost {
9286
9383
  const shapes = input.entityGrants
9287
9384
  ? await this.topUpEntityGrantShapesLocal(input.tenantId, input.scopeId, input.entityGrants)
9288
9385
  : null;
9386
+ if (!ownerRoleApplies) {
9387
+ console.warn(JSON.stringify({
9388
+ event: 'scope-provision-owner-role-skipped',
9389
+ tenantId: input.tenantId,
9390
+ scopeId: input.scopeId,
9391
+ scopeType,
9392
+ role: input.ownerRoleKey,
9393
+ }));
9394
+ }
9289
9395
  return {
9290
9396
  ...(input.scopeType !== undefined ? { scopeType } : {}),
9291
9397
  ...(typeof parentScopeId === 'string' ? { parentScopeId } : {}),