@substrat-run/adapter-cloudflare 0.220.0 → 0.221.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.
package/dist/host.js CHANGED
@@ -2,18 +2,20 @@ import { restoreChunksOf } from './directory-restore-chunks.js';
2
2
  import { env as ambientEnv } from 'cloudflare:workers';
3
3
  import { isRewindRefusal, REWIND_REFUSED } from './rewind-refusal.js';
4
4
  import { isSystemDoorMoved, SYSTEM_DOOR_MOVED, SYSTEM_DOOR_REGATES } from './system-door.js';
5
- import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, pushedImport, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, verticalTraceSampling, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, appEnvironment as appEnvironmentSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
5
+ import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, pushedImport, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, verticalTraceSampling, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, appEnvironment as appEnvironmentSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
6
  import { normalizeHostname, toRouteTarget } from './route-resolver.js';
7
7
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
8
8
  import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal } from '@substrat-run/kernel';
9
9
  import { classify as classifyRelease } from '@substrat-run/model-view/bump';
10
10
  import { ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary } from '@substrat-run/kernel';
11
11
  import { CONNECTOR_DISPATCH_REQUESTED_BY, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
12
- import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, provisionedScopeType, 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, 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, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
12
+ import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, provisionedScopeType,
13
+ // #2993 part 3: the modules (and seats) a scope of each declared type has.
14
+ 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, 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, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
13
15
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
14
16
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
15
17
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
16
- import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
18
+ import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, proofCheckedStoreInvoke, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
17
19
  import { PLATFORM_BINDING_PREFIX, PLATFORM_STORE_CODE, parseTraceparent, scopeStoreBindingName, scopeStoreObjectName, STORE_CALL_URL, storeAnswerOf, StoreError, TRACEPARENT_HEADER } from '@substrat-run/contracts';
18
20
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
19
21
  import { isOrangeToOrange, isUpgradeRequest, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, liveInstant, encodeLiveWithin, liveRefusalStatus, liveWithinOf, } from './live-reads.js';
@@ -410,6 +412,11 @@ export class CloudflareScopeHost {
410
412
  declaredKeys = new Set();
411
413
  /** #2430: the declared permission surface `registerModule` holds each module to, when given. */
412
414
  permissions;
415
+ /**
416
+ * #2993 part 3: the modules each declared scope type runs, from `permissions`. Undeclared: one
417
+ * `home` type running every module, and this host neither reads nor asks any scope's type.
418
+ */
419
+ scopeTypePlan;
413
420
  /**
414
421
  * #1705: this deployment's cross-vertical declarations. The DO holds the handlers and makes
415
422
  * every decision. The coordinator keeps its own copy for two reasons: registration refuses
@@ -512,6 +519,7 @@ export class CloudflareScopeHost {
512
519
  constructor(options) {
513
520
  this.servicePrincipals = options.servicePrincipals;
514
521
  this.permissions = options.permissions;
522
+ this.scopeTypePlan = scopeTypePlanOf(options.permissions);
515
523
  // #2430: what the declared surface reserves holds here too, whatever is registered under its ids.
516
524
  for (const m of options.permissions?.modules ?? []) {
517
525
  noteReservedKeys(this.reservedKeys, m.manifest);
@@ -1874,7 +1882,7 @@ export class CloudflareScopeHost {
1874
1882
  this.moduleSchedules.set(manifest.id, manifest.schedules);
1875
1883
  }
1876
1884
  if (manifest.peers && manifest.peers.length > 0) {
1877
- this.peerSources.push({ peers: manifest.peers });
1885
+ this.peerSources.push({ moduleId: manifest.id, peers: manifest.peers });
1878
1886
  }
1879
1887
  if (manifest.freshness && manifest.freshness.length > 0) {
1880
1888
  this.moduleFreshness.set(manifest.id, manifest.freshness);
@@ -1923,15 +1931,38 @@ export class CloudflareScopeHost {
1923
1931
  }
1924
1932
  /** `provisionScope`, answering whether this call created the directory row (#2555: an import's teardown). */
1925
1933
  async provisionScopeCreating(actor, input) {
1934
+ // #2995: this host does not keep parent links yet (the pure host does). A child provisioned here
1935
+ // would be a scope with no link, reachable as a sibling and outliving its parent, so it is refused.
1936
+ if (input.parentScopeId !== undefined) {
1937
+ throw substratError('unavailable', 'a child scope cannot be provisioned on this host yet: the parent link is kept by the pure host only (#2995)');
1938
+ }
1926
1939
  // Shared with the pure adapter so the defaults cannot drift between them.
1927
1940
  const record = resolveScopeRecord(input);
1928
- // #2993: this host runs no declared scope types yet, so it takes 'home' and refuses any
1929
- // other type, by the kernel's rule, before anything is written. A typed scope provisioned
1930
- // here as 'home' would carry the wrong modules for its life.
1931
- provisionedScopeType({ declared: false }, input.scopeType, undefined, input.scopeId);
1941
+ // #2993: the type this provision gives the scope, by the kernel's rule, before anything is
1942
+ // written: an undeclared type, or one other than the type the directory records, is refused.
1943
+ // A host with no declared types reads nothing for it and takes 'home'. Part 4: a module-less
1944
+ // coordinator asked for another type of a vertical's scope judges it by the types the
1945
+ // vertical's deployed version declares (`verticalScopeTypePlan`); asked for none, or for
1946
+ // 'home', it reads nothing, as before.
1947
+ const own = this.scopeTypePlan;
1948
+ const plan = !own.declared && input.scopeType !== undefined && input.scopeType !== HOME_SCOPE_TYPE && record.vertical
1949
+ ? await this.verticalScopeTypePlan(record.vertical)
1950
+ : own;
1951
+ const typed = plan.declared;
1952
+ const recorded = typed ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
1953
+ const scopeType = provisionedScopeType(plan, input.scopeType, recorded === undefined ? undefined : (recorded.scope_type ?? null), input.scopeId);
1932
1954
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1933
1955
  // or audit, so a rejected provision creates nothing and writes no audit row.
1934
- const created = await this.directory('provisionScope', input.tenantId, input.scopeId, record, new Date().toISOString());
1956
+ const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
1957
+ // #2993: the directory row records the type ('home' as NULL), and refuses a different one in
1958
+ // its own unit. An untyped host sends none and writes the row it always did.
1959
+ typed ? { ...record, scopeType: scopeType === HOME_SCOPE_TYPE ? null : scopeType } : record, new Date().toISOString());
1960
+ // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1961
+ // first pass lays down only its type's tables. A host with no declared types asks nothing. A
1962
+ // coordinator judging by a vertical's types (part 4) does not either: the vertical's own
1963
+ // object is fixed by its `/internal/provision`, which the platform sends the type.
1964
+ if (own.declared)
1965
+ unwrapReply(await this.scopeStub(input.scopeId).fixScopeTypeReply(scopeType, input.scopeId));
1935
1966
  // Instantiate the scope DO and trigger its lazy migration.
1936
1967
  await this.migrateAndRecord(input.scopeId);
1937
1968
  // Scope-local permissions: a freshly-provisioned scope evaluates from its own
@@ -1949,6 +1980,9 @@ export class CloudflareScopeHost {
1949
1980
  // (`grantToSystem` still clears a tuple's tombstone, but it does not move the switch.)
1950
1981
  const seats = [];
1951
1982
  for (const [moduleId, schedules] of this.moduleSchedules) {
1983
+ // #2993 part 3: only the modules this scope's type runs seat their schedules' grants.
1984
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, moduleId))
1985
+ continue;
1952
1986
  const perms = new Set();
1953
1987
  for (const s of schedules)
1954
1988
  for (const p of s.permissions)
@@ -1961,7 +1995,7 @@ export class CloudflareScopeHost {
1961
1995
  // call (`peerSeats`) that makes "declared and installed" mean "live". Same seat as the
1962
1996
  // schedule grants above, so a grant a switch tombstoned stays tombstoned and a
1963
1997
  // switched-off peer gets nothing seated.
1964
- for (const seat of peerSeats(collectPeers(this.peerSources), input.scopeId)) {
1998
+ for (const seat of peerSeats(collectPeers(this.peerSourcesOf(scopeType)), input.scopeId)) {
1965
1999
  seats.push({ subject: seat.subject, relation: seat.relation, object: seat.object, expires_at: null });
1966
2000
  }
1967
2001
  // #1674: re-assert the recorded OFF positions after the seat (`system-switch-record.ts`).
@@ -1980,10 +2014,43 @@ export class CloudflareScopeHost {
1980
2014
  }
1981
2015
  // Audit a real provision only; an idempotent re-provision changed nothing.
1982
2016
  if (created) {
1983
- await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null, record);
2017
+ await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2018
+ // #2993: a typed scope's audit row names its type, as on the pure host; a home scope's reads as it always did.
2019
+ scopeType === HOME_SCOPE_TYPE ? record : { ...record, scopeType });
1984
2020
  }
1985
2021
  return created;
1986
2022
  }
2023
+ /**
2024
+ * #2993 part 4: a vertical's scope types, as the version a new scope of it would run declares
2025
+ * them: the version its serving script serves, else the one its `prod` channel names. Read from
2026
+ * the stored manifest, unaudited, for the reason {@link versionImports} is. A vertical with no
2027
+ * such version, or one that declares no types, has the one `home` type.
2028
+ */
2029
+ async verticalScopeTypePlan(slug) {
2030
+ const vertical = await this.cp.readVertical(slug);
2031
+ const versionId = vertical?.serving_version_id ?? (await this.cp.readChannel(slug, 'prod'))?.version_id;
2032
+ const version = versionId ? await this.cp.readVersion(versionId) : undefined;
2033
+ return scopeTypePlanOfManifest(version?.manifest_json);
2034
+ }
2035
+ /** #2993 part 3: the peer declarations of the modules a scope of `scopeType` runs. */
2036
+ peerSourcesOf(scopeType) {
2037
+ return this.scopeTypePlan.declared
2038
+ ? this.peerSources.filter((p) => scopeTypeRuns(this.scopeTypePlan, scopeType, p.moduleId))
2039
+ : this.peerSources;
2040
+ }
2041
+ /**
2042
+ * #2993 part 3: the scope's type as its own object holds it, fixing it when `requested` names one.
2043
+ * Asked only when it can matter: this host declares types, or the caller named one (the object
2044
+ * judges that by its class's own declaration). Otherwise 'home', with no call, as before types.
2045
+ */
2046
+ async scopeTypeAt(scopeId, requested) {
2047
+ if (!this.scopeTypePlan.declared && requested === undefined)
2048
+ return HOME_SCOPE_TYPE;
2049
+ const stub = this.scopeStub(scopeId);
2050
+ return requested === undefined && this.scopeTypePlan.declared
2051
+ ? stub.scopeTypeHere()
2052
+ : unwrapReply(await stub.fixScopeTypeReply(requested, scopeId));
2053
+ }
1987
2054
  // Per-tenant relational stores (#301, PR-2 — the live D1 path). The coordinator holds
1988
2055
  // the platform's D1 credential (the same split secretBox uses: the DO records, it never
1989
2056
  // holds a key), the ControlPlaneDO serializes the ledger write, and the D1 REST client
@@ -2393,8 +2460,15 @@ export class CloudflareScopeHost {
2393
2460
  // replaces its provisioned schema with the dump wholesale (drop-then-replay), so
2394
2461
  // the end state is the dump, at the source's frontier. Provenance is stamped from
2395
2462
  // the dump unless the caller set it (§3: a fork always records its origin).
2463
+ // #2993 part 3: a copy is a scope of its source's type — the type names the tables the dump
2464
+ // carries. The caller's type when it names one, else the source's, when the directory holds it.
2465
+ const source = input.scopeType === undefined && this.scopeTypePlan.declared
2466
+ ? await this.cp.getScopeRecord(input.tenantId, dump.scopeId)
2467
+ : undefined;
2468
+ const copiedType = input.scopeType ?? (source ? (source.scope_type ?? HOME_SCOPE_TYPE) : undefined);
2396
2469
  const created = await this.provisionScopeCreating(actor, {
2397
2470
  ...input,
2471
+ ...(copiedType === undefined ? {} : { scopeType: copiedType }),
2398
2472
  forkedFrom: input.forkedFrom ?? dump.scopeId,
2399
2473
  forkedAt: input.forkedAt ?? dump.capturedAt,
2400
2474
  });
@@ -2619,22 +2693,30 @@ export class CloudflareScopeHost {
2619
2693
  }
2620
2694
  return this.buildStub(tenantId, scopeId, principal, undefined, undefined, options, undefined, undefined, undefined, options?.verifiedEmail ?? null, parsedDelegation);
2621
2695
  }
2622
- async getScopeStore(_principal, tenantId, scopeId, binding, options) {
2696
+ async getScopeStore(principal, tenantId, scopeId, binding, options) {
2697
+ // #2996 (K-64): every path spends the proof on the scope's own queue before it sends the call,
2698
+ // whatever the transport. The scope object is in this worker's own namespace on each of them.
2699
+ const redeem = async (secret, operation) => {
2700
+ unwrapReply(await this.scopeStub(scopeId).storeProofRedeemReply(secret, binding, operation, principal));
2701
+ };
2623
2702
  if (this.scopeStoreTransport === 'platform') {
2624
2703
  return {
2625
2704
  tenantId,
2626
2705
  scopeId,
2627
2706
  subjectKind: 'principal',
2628
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore({
2707
+ invoke: proofCheckedStoreInvoke({
2708
+ binding,
2709
+ redeem,
2629
2710
  // The egress hop answers with the platform's own codes too (#2815).
2630
- through: 'platform',
2631
- send: async (request) => {
2711
+ throughPlatform: true,
2712
+ send: async (request, proof) => {
2632
2713
  // #3368: the request's trace, so the call joins it through egress and the router.
2633
2714
  const trace = currentTraceparent();
2634
2715
  const response = await this.fetchImpl(STORE_CALL_URL, {
2635
2716
  method: 'POST',
2636
2717
  headers: { 'content-type': 'application/json', ...(parseTraceparent(trace) ? { [TRACEPARENT_HEADER]: trace } : {}) },
2637
- body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input }),
2718
+ // The spent proof rides along, so the router can refuse a call that did not pass this door.
2719
+ body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input, proof }),
2638
2720
  });
2639
2721
  try {
2640
2722
  return await response.json();
@@ -2643,7 +2725,8 @@ export class CloudflareScopeHost {
2643
2725
  throw new StoreError({ code: PLATFORM_STORE_CODE.badEnvelope, status: 502 });
2644
2726
  }
2645
2727
  },
2646
- }, operation, input, ...extra), options?.onStoreCall),
2728
+ onStoreCall: options?.onStoreCall,
2729
+ }),
2647
2730
  };
2648
2731
  }
2649
2732
  // A missing binding is answered before any directory read. A CP-less host's
@@ -2661,7 +2744,12 @@ export class CloudflareScopeHost {
2661
2744
  tenantId,
2662
2745
  scopeId,
2663
2746
  subjectKind: 'principal',
2664
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore((request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request), operation, input, ...extra), options?.onStoreCall),
2747
+ invoke: proofCheckedStoreInvoke({
2748
+ binding,
2749
+ redeem,
2750
+ send: (request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request),
2751
+ onStoreCall: options?.onStoreCall,
2752
+ }),
2665
2753
  };
2666
2754
  }
2667
2755
  const namespace = bound;
@@ -2671,7 +2759,7 @@ export class CloudflareScopeHost {
2671
2759
  tenantId,
2672
2760
  scopeId,
2673
2761
  subjectKind: 'principal',
2674
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore(storeObjectSend(object), operation, input, ...extra), options?.onStoreCall),
2762
+ invoke: proofCheckedStoreInvoke({ binding, redeem, send: storeObjectSend(object), onStoreCall: options?.onStoreCall }),
2675
2763
  };
2676
2764
  }
2677
2765
  /**
@@ -3563,7 +3651,11 @@ export class CloudflareScopeHost {
3563
3651
  }
3564
3652
  const stub = this.scopeStub(scopeId);
3565
3653
  const windows = new Map();
3566
- for (const specs of this.moduleFreshness.values()) {
3654
+ // #2993 part 3: only the modules this scope's type runs are judged on it.
3655
+ const scopeType = await this.scopeTypeAt(scopeId);
3656
+ for (const [freshnessModule, specs] of this.moduleFreshness) {
3657
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, freshnessModule))
3658
+ continue;
3567
3659
  for (const f of specs) {
3568
3660
  const prev = windows.get(f.eventType);
3569
3661
  if (prev === undefined || f.within.hours < prev)
@@ -3655,15 +3747,38 @@ export class CloudflareScopeHost {
3655
3747
  let purgeRequests = 0;
3656
3748
  // #3540: what this call is — the scope's own alarm, which runs only the purges it found due, or a
3657
3749
  // pass, which tells the scope whether its sweeper can take that alarm's call (`purgeMode`).
3658
- const purgeMode = tick?.purgeAlarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3750
+ // `dueAlarm` is the same alarm, through `runScopeDue`, which also asks for its due schedules.
3751
+ const alarm = tick?.purgeAlarm === true || tick?.dueAlarm === true;
3752
+ const purgeMode = alarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3659
3753
  for (const schedule of schedules) {
3660
3754
  if (tick?.purgeAlarm && !schedule.purge)
3661
3755
  continue;
3662
- const last = await stub.scheduleLastRun(schedule.operation);
3756
+ // #3540: a `due: 'event'` schedule is the scope's to place — its alarm runs it once it has run
3757
+ // under that form — wherever the caller can take that alarm's call; its cadence decides otherwise.
3758
+ const byEvent = !schedule.purge && schedule.due === 'event';
3759
+ if (tick?.dueAlarm && !schedule.purge && !byEvent)
3760
+ continue;
3761
+ let byDate;
3762
+ let last;
3763
+ if (byEvent && (tick?.dueAlarm || tick?.alarmRunsDue)) {
3764
+ const gate = await stub.dueScheduleGate(schedule.operation, tenantId, scopeId, tick.dueAlarm ? 'alarm' : 'deferrable');
3765
+ if (gate.byAlarm || (tick.dueAlarm && (gate.dueAt === null || now < gate.dueAt))) {
3766
+ // Its alarm runs it, or it is not due by its date: nothing ran, no line, no cadence row.
3767
+ report.skipped += 1;
3768
+ report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3769
+ continue;
3770
+ }
3771
+ if (tick.dueAlarm)
3772
+ byDate = gate.dueAt;
3773
+ last = gate.lastRunAt;
3774
+ }
3775
+ else {
3776
+ last = await stub.scheduleLastRun(schedule.operation);
3777
+ }
3663
3778
  const lastRun = last ? Date.parse(last) : null;
3664
- const dueAt = lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
3779
+ const dueAt = byDate ?? (lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000);
3665
3780
  // #3540: the scope's alarm found the purge due by its rows, so the cadence does not gate it.
3666
- if (now < dueAt && !tick?.purgeAlarm) {
3781
+ if (now < dueAt && !(alarm && schedule.purge)) {
3667
3782
  report.skipped += 1;
3668
3783
  report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3669
3784
  continue;
@@ -3756,8 +3871,8 @@ export class CloudflareScopeHost {
3756
3871
  startedAt,
3757
3872
  outcome: status,
3758
3873
  ...failure,
3759
- dueAt: lastRun === null ? null : new Date(dueAt).toISOString(),
3760
- latenessMs: lastRun === null ? null : now - dueAt,
3874
+ dueAt: byDate === undefined && lastRun === null ? null : new Date(dueAt).toISOString(),
3875
+ latenessMs: byDate === undefined && lastRun === null ? null : now - dueAt,
3761
3876
  ...(emitted ? { emitted } : {}),
3762
3877
  });
3763
3878
  report.runs.push({ operation: schedule.operation, outcome: status === 'ok' ? 'ok' : 'failed' });
@@ -4127,6 +4242,8 @@ export class CloudflareScopeHost {
4127
4242
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
4128
4243
  archivedAt: r.archived_at ?? null,
4129
4244
  archivedFromStatus: (r.archived_from_status ?? null),
4245
+ // #2993: a typed scope names its type; a home scope's record (NULL) is unchanged.
4246
+ ...(r.scope_type ? { scopeType: r.scope_type } : {}),
4130
4247
  createdAt: r.created_at,
4131
4248
  });
4132
4249
  // The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
@@ -5246,6 +5363,17 @@ export class CloudflareScopeHost {
5246
5363
  const vertical = verticalSlug.parse(input.vertical);
5247
5364
  return this.directory('removeEnvironmentAndAudit', { ...input, vertical }, this.adminEntry(actor, 'removeEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5248
5365
  },
5366
+ claimEnvironmentServe: async (_actor, input, claim, leaseMs) => this.directory('claimEnvironmentServe', { ...input, vertical: verticalSlug.parse(input.vertical) }, claim, leaseMs),
5367
+ releaseEnvironmentServe: async (_actor, input, claim) => {
5368
+ await this.cp.releaseEnvironmentServe({ ...input, vertical: verticalSlug.parse(input.vertical) }, claim);
5369
+ },
5370
+ setEnvironmentServing: async (actor, input, next, expected, claim) => {
5371
+ const vertical = verticalSlug.parse(input.vertical);
5372
+ const moved = await this.directory('setEnvironmentServingAndAudit', { ...input, vertical }, next, expected, this.adminEntry(actor, 'setEnvironmentServing', { tenantId: input.tenantId, vertical }, null, null), claim);
5373
+ if (!moved) {
5374
+ throw substratError('precondition_failed', `the environment '${input.name}' of '${vertical}' serves another record than the one this serve was diffed from: read it again`);
5375
+ }
5376
+ },
5249
5377
  resolveHostname: async (raw) =>
5250
5378
  // The router's per-request read. No actor, not logged — the same machine-path
5251
5379
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5470,6 +5598,9 @@ export class CloudflareScopeHost {
5470
5598
  : null;
5471
5599
  if (breakingWithinMajor && owning?.listed)
5472
5600
  throw breakingWithinMajorRefusal(breakingWithinMajor);
5601
+ // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
5602
+ // of the acknowledgements, because none of them passes it.
5603
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5473
5604
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5474
5605
  const reviewed = async (v) => ({
5475
5606
  id: v.id,
@@ -5732,6 +5863,8 @@ export class CloudflareScopeHost {
5732
5863
  if (r.serving_version_id && !supersede) {
5733
5864
  const incoming = await this.cp.readVersion(parsed.versionId);
5734
5865
  if (incoming) {
5866
+ // #2993 part 4: and it declares every type their scopes hold.
5867
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5735
5868
  await this.assertNoStrandFrom([r.serving_version_id], incoming.id, incoming, r.serving_ref ? await this.cp.provisionedVersionsOf(verticalSlug, { ref: r.serving_ref, versionId: r.serving_version_id }, null) : []);
5736
5869
  }
5737
5870
  }
@@ -8550,6 +8683,9 @@ export class CloudflareScopeHost {
8550
8683
  */
8551
8684
  async provisionScopeLocal(input) {
8552
8685
  const carry = recordedOffFromWire(input);
8686
+ // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
8687
+ // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
8688
+ const scopeType = await this.scopeTypeAt(input.scopeId, input.scopeType);
8553
8689
  // #2430: refused before anything is written, rather than at the top-up after the projection.
8554
8690
  if (input.entityGrants)
8555
8691
  await this.refuseReservedShapes(input.entityGrants, input.scopeId);
@@ -8600,7 +8736,7 @@ export class CloudflareScopeHost {
8600
8736
  expires_at: null,
8601
8737
  lockout_reseat: true,
8602
8738
  },
8603
- ...this.declaredSeatsLocal(input.scopeId, connections.seat),
8739
+ ...this.declaredSeatsLocal(input.scopeId, connections.seat, scopeType),
8604
8740
  ],
8605
8741
  // #406: identity links, delivered by the platform with provisioning exactly as
8606
8742
  // entitlements are (#310). Preserve-on-undefined, so an absent field never wipes
@@ -8632,6 +8768,7 @@ export class CloudflareScopeHost {
8632
8768
  ? await this.topUpEntityGrantShapesLocal(input.tenantId, input.scopeId, input.entityGrants)
8633
8769
  : null;
8634
8770
  return {
8771
+ ...(input.scopeType !== undefined ? { scopeType } : {}),
8635
8772
  ...(carry ? { switchedOff } : {}),
8636
8773
  ...(shapes ? { retirementsLeftOpen: shapes.retirementsLeftOpen ?? 0 } : {}),
8637
8774
  ...(shapes?.boundEver ? { boundShapeTypes: shapes.boundEver } : {}),
@@ -8888,16 +9025,18 @@ export class CloudflareScopeHost {
8888
9025
  * function that decides them), and the tenant's connection grants the platform delivered (#592,
8889
9026
  * the provision-time mirror of `connectorGrantLocal`).
8890
9027
  */
8891
- declaredSeatsLocal(scopeId, connectionGrants) {
9028
+ declaredSeatsLocal(scopeId, connectionGrants,
9029
+ /** #2993 part 3: only the modules this type runs seat their schedule and peer grants. */
9030
+ scopeType) {
8892
9031
  return [
8893
- ...[...this.moduleSchedules].flatMap(([modId, schedules]) => {
9032
+ ...[...this.moduleSchedules].filter(([modId]) => scopeTypeRuns(this.scopeTypePlan, scopeType, modId)).flatMap(([modId, schedules]) => {
8894
9033
  const perms = new Set();
8895
9034
  for (const s of schedules)
8896
9035
  for (const p of s.permissions)
8897
9036
  perms.add(p);
8898
9037
  return [...perms].map((perm) => ({ subject: `system:${modId}`, relation: `granted:${perm}`, object: `scope:${scopeId}`, expires_at: null }));
8899
9038
  }),
8900
- ...peerSeats(collectPeers(this.peerSources), scopeId).map((seat) => ({ ...seat, expires_at: null })),
9039
+ ...peerSeats(collectPeers(this.peerSourcesOf(scopeType)), scopeId).map((seat) => ({ ...seat, expires_at: null })),
8901
9040
  ...(connectionGrants ?? []).map((g) => ({
8902
9041
  subject: `connection:${g.connectionId}`,
8903
9042
  relation: `granted:${g.permission}`,
@@ -8930,7 +9069,9 @@ export class CloudflareScopeHost {
8930
9069
  const carry = recordedOffFromWire(input);
8931
9070
  const connections = await this.seatableConnectionGrants(input.tenantId, input.scopeId, input.connectionGrants); // #2430
8932
9071
  await this.migrateAndRecord(input.scopeId);
8933
- const seated = await stub.seatTuplesFor(input.tenantId, this.declaredSeatsLocal(input.scopeId, connections.seat), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
9072
+ const seated = await stub.seatTuplesFor(input.tenantId,
9073
+ // #2993 part 3: the type the scope holds; this seat never names one.
9074
+ this.declaredSeatsLocal(input.scopeId, connections.seat, await this.scopeTypeAt(input.scopeId)), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
8934
9075
  // Reaped or recorded for another tenant since the check: K-3's refusal, naming no other tenant.
8935
9076
  if ('refused' in seated)
8936
9077
  throw unknownScopeForTenant(input.tenantId, input.scopeId);