@selvajs/selva 4.20.1-beta.1 → 4.20.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -67,6 +67,12 @@ function readRemoteInputs(inputs) {
67
67
  if (!(Array.isArray(inputs) && inputs.every((input) => typeof input === "object" && input !== null && typeof input.id === "string" && typeof input.nickname === "string"))) apiError(400, ApiErrorCode.VALIDATION_FAILED, "A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.");
68
68
  return inputs;
69
69
  }
70
+ function admittedSolveInputs(schema, inputs, values) {
71
+ const solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);
72
+ const serverOnly = postedServerSourcedIds(solveInputs, values);
73
+ if (serverOnly.length > 0) apiError(400, ApiErrorCode.VALIDATION_FAILED, `These inputs are filled on the server and may not be posted in values: ${serverOnly.join(", ")}.`);
74
+ return solveInputs;
75
+ }
70
76
  /**
71
77
  * Run a solve and return the HTTP response.
72
78
  *
@@ -203,6 +209,7 @@ async function runSolve(params) {
203
209
  mark("remoteDef");
204
210
  }
205
211
  const defLoadMs = performance.now() - loadStart;
212
+ let solveInputs = storedSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;
206
213
  if (sharedAccess) {
207
214
  if (await providers.data.shareLinks.tryIncrementSolveCount(solveCtx, sharedAccess.link.id) === null) {
208
215
  recordMetric("share_cap");
@@ -228,9 +235,7 @@ async function runSolve(params) {
228
235
  mark("schemaBackfill");
229
236
  }
230
237
  if (isLocal && !storedSchema) apiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, "This version's inputs could not be read. Retry shortly.");
231
- const solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : readRemoteInputs(inputs);
232
- const serverOnly = postedServerSourcedIds(solveInputs, values);
233
- if (serverOnly.length > 0) apiError(400, ApiErrorCode.VALIDATION_FAILED, `These inputs are filled on the server and may not be posted in values: ${serverOnly.join(", ")}.`);
238
+ solveInputs ??= admittedSolveInputs(storedSchema, inputs, values);
234
239
  const live = bindLiveSolve({
235
240
  ownerKey: liveOwnerKey(access.kind === "user" ? access.ctx.userId : null),
236
241
  streamId,
@@ -1 +1 @@
1
- {"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tconst solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;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UAAU,OAAO;AAC7C;;;;;;AAOA,SAAS,kBACR,QACA,SACA,SACA,WACA,WACO;CACP,MAAM,EAAE,YAAY,QAAQ;CAC5B,OAAO,IAAI,MAAM,qCAAqC;EACrD,WAAW;EACX,QAAQ,KAAK,MAAM,SAAS;EAC5B,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,SAAS,KAAK,MAAM,QAAQ,OAAO;EACnC,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,QAAQ,KAAK,MAAM,QAAQ,MAAM;EACjC,eAAe,KAAK,MAAM,QAAQ,aAAa;EAC/C,iBAAiB,QAAQ;CAC1B,CAAC;CACD,IAAI,QAAQ,oBAAoB,MAC/B,OAAO,IAAI,MAAM,oBAAoB;EACpC,WAAW;EACX,iBAAiB,QAAQ;EACzB,iBAAiB,QAAQ;EACzB,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,gBAAA,CAAiB,QAAQ,CAAC,CAAC;CAC7E,CAAC;MACK;EAGN,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
1
+ {"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.byt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,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
@@ -70,6 +70,21 @@ function inviteDeps() {
70
70
  permissions: getPermissionStore()
71
71
  };
72
72
  }
73
+ async function reopenInvite(inviteId, userId, locals) {
74
+ const store = getInviteStore();
75
+ if (!store.reopen) return false;
76
+ try {
77
+ return await store.reopen(SYSTEM_CONTEXT, inviteId, userId);
78
+ } catch (err) {
79
+ locals.log.error("Could not reopen invite after a failed grant", {
80
+ component: "accept-invite",
81
+ inviteId,
82
+ userId,
83
+ err: renderThrown(err)
84
+ });
85
+ return false;
86
+ }
87
+ }
73
88
  var load = async ({ url, locals }) => {
74
89
  const token = url.searchParams.get("token")?.trim();
75
90
  if (!token) return {
@@ -126,8 +141,10 @@ var actions = { default: async ({ request, cookies, locals }) => {
126
141
  const msg = err instanceof Error ? err.message : "Could not create your account.";
127
142
  return fail(400, { error: msg });
128
143
  }
144
+ let claimed = false;
129
145
  try {
130
- if (!await getInviteStore().markAccepted(SYSTEM_CONTEXT, invite.id, user.id)) {
146
+ claimed = await getInviteStore().markAccepted(SYSTEM_CONTEXT, invite.id, user.id);
147
+ if (!claimed) {
131
148
  locals.log.info("Invite was revoked or used before it could be claimed", {
132
149
  component: "accept-invite",
133
150
  inviteId: invite.id,
@@ -160,6 +177,7 @@ var actions = { default: async ({ request, cookies, locals }) => {
160
177
  component: "accept-invite",
161
178
  err: renderThrown(err)
162
179
  });
180
+ if (claimed && await reopenInvite(invite.id, user.id, locals)) return fail(500, { error: mode === "join" ? "We could not add you to the organization. Please try again." : `Your account was created, but we could not finish joining the organization. Sign in as ${invite.email}, then open this link again to join.` });
163
181
  return fail(500, { error: mode === "join" ? "We could not add you to the organization. Please contact your admin." : "Your account was created, but we could not finish joining the organization. Please contact your admin." });
164
182
  }
165
183
  if (displayName && mode !== "join") try {
@@ -1 +1 @@
1
- {"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../server/src/providers/auth-lookup.ts","../../../../../src/routes/accept-invite/+page.server.ts"],"sourcesContent":["import type { AuthUser, IAuthProvider } from '@selvajs/platform';\n\nconst PAGE_LIMIT = 200;\n// Runaway guard against an adapter returning a non-advancing cursor.\n// 100 pages = 20k users, far past any deployment this product targets.\nconst MAX_PAGES = 100;\n\n/**\n * `IAuthProvider` has no by-email lookup and `listUsers` takes no filter, so\n * this scans. Acceptable because the only caller is invite acceptance — once\n * per invite, never on a hot path.\n *\n * A truncated scan would report an existing user as absent and send the flow\n * down the create-account branch, where the provider rejects the duplicate. So\n * exhausting the cursor matters: `null` must mean \"not found\", not \"gave up\".\n * Returns `null` when the provider has no user store (`listUsers` → null) or\n * when the cap is hit.\n */\nexport async function findAuthUserByEmail(\n\tauth: IAuthProvider,\n\temail: string\n): Promise<AuthUser | null> {\n\tconst needle = email.trim().toLowerCase();\n\tif (!needle) return null;\n\n\tlet cursor: string | undefined;\n\tfor (let page = 0; page < MAX_PAGES; page++) {\n\t\tconst result = await auth.listUsers({ limit: PAGE_LIMIT, cursor });\n\t\tif (!result) return null;\n\t\tconst hit = result.items.find((u) => u.email?.trim().toLowerCase() === needle);\n\t\tif (hit) return hit;\n\t\tcursor = result.nextCursor;\n\t\tif (!cursor) return null;\n\t}\n\treturn null;\n}\n","import { fail, redirect } from '@sveltejs/kit';\nimport type { Actions, PageServerLoad } from './$types';\nimport { SYSTEM_CONTEXT, type Invite } from '@selvajs/platform';\nimport {\n\tgetDataProvider,\n\tgetInviteStore,\n\tgetOrganizationProvider,\n\tgetUserProfileStore\n} from '#lib/server/providers.server.js';\nimport { getAuthProvider, getPermissionStore } from '#lib/server/providers.server.js';\nimport { findAuthUserByEmail } from '@selvajs/server/providers';\nimport { inviterStillVouches } from '@selvajs/server/handlers';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { setSessionCookie } from '#lib/server/admin-auth.server.js';\nimport { findByRawToken } from '#lib/server/invites/token.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\n\n/**\n * Signup mode for an invite whose email has no account yet:\n * - `password` — the provider owns credentials; show password + confirm fields.\n * - `proxy` — identity comes from upstream-proxy headers; the visit itself\n * is the proof of identity and no password is collected.\n */\nfunction signupMode(auth: ReturnType<typeof getAuthProvider>): 'password' | 'proxy' {\n\tif (auth.passwordAuth) return 'password';\n\treturn auth.proxyAuth && auth.createUser ? 'proxy' : 'password';\n}\n\n/**\n * Public page — the invite token is the capability. `SYSTEM_CONTEXT` is\n * passed to the invite store because there is no user session at this point;\n * the store treats an unknown/expired/consumed invite as a miss regardless.\n *\n * The raw URL token is HMAC-hashed before lookup — the store sees only the\n * digest. Mirrors the share-link flow.\n *\n * An invite addressed to an email that already has an account takes the `join`\n * mode instead of signing up: there is nothing to create, only a membership to\n * add. That branch demands a session, because the token proves the invite is\n * genuine — not that the visitor is the person it names. Honouring it\n * anonymously would let anyone holding a forwarded link join an org as someone\n * else.\n */\nfunction inviteDeps() {\n\treturn {\n\t\tauth: getAuthProvider(),\n\t\torgs: getOrganizationProvider(),\n\t\tpermissions: getPermissionStore()\n\t};\n}\n\nexport const load: PageServerLoad = async ({ url, locals }) => {\n\tconst token = url.searchParams.get('token')?.trim();\n\tif (!token) {\n\t\treturn { ok: false as const, reason: 'This invite link is missing a token.' };\n\t}\n\n\tconst invite = await findByRawToken(token, (h) =>\n\t\tgetInviteStore().getByTokenHash(SYSTEM_CONTEXT, h)\n\t);\n\tif (!invite || !(await inviterStillVouches(invite, inviteDeps()))) {\n\t\treturn { ok: false as const, reason: 'This invite link is invalid or has expired.' };\n\t}\n\n\tconst org = await getOrganizationProvider().getOrg(SYSTEM_CONTEXT, invite.orgId);\n\tconst auth = getAuthProvider();\n\tconst existing = await findAuthUserByEmail(auth, invite.email).catch(() => null);\n\tconst mode: 'password' | 'proxy' | 'join' = existing ? 'join' : signupMode(auth);\n\n\treturn {\n\t\tok: true as const,\n\t\temail: invite.email,\n\t\torgName: org?.name ?? 'the organization',\n\t\ttoken,\n\t\tmode,\n\t\t// `join` only: whether the visitor is already signed in as the invitee,\n\t\t// which decides between the confirm button and a sign-in prompt.\n\t\tsignedInAsInvitee: mode === 'join' && !!locals.user && locals.user.id === existing!.id\n\t};\n};\n\nexport const actions = {\n\tdefault: async ({ request, cookies, locals }) => {\n\t\tconst data = await request.formData();\n\t\tconst token = (data.get('token') as string | null)?.trim() ?? '';\n\t\tconst password = data.get('password') as string | null;\n\t\tconst confirm = data.get('confirm') as string | null;\n\t\tconst displayName = (data.get('displayName') as string | null)?.trim() || undefined;\n\n\t\tif (!token) {\n\t\t\treturn fail(400, { error: 'Missing invite token.' });\n\t\t}\n\n\t\tlet invite: Invite | null;\n\t\ttry {\n\t\t\tinvite = await findByRawToken(token, (h) =>\n\t\t\t\tgetInviteStore().getByTokenHash(SYSTEM_CONTEXT, h)\n\t\t\t);\n\t\t} catch {\n\t\t\treturn fail(500, { error: 'Could not validate the invite. Please try again.' });\n\t\t}\n\t\tif (!invite || !(await inviterStillVouches(invite, inviteDeps()))) {\n\t\t\treturn fail(410, { error: 'This invite link is invalid or has expired.' });\n\t\t}\n\n\t\tconst auth = getAuthProvider();\n\t\tconst existing = await findAuthUserByEmail(auth, invite.email).catch(() => null);\n\t\tconst mode: 'password' | 'proxy' | 'join' = existing ? 'join' : signupMode(auth);\n\n\t\tif (mode === 'password') {\n\t\t\tif (!password || password.length < 8) {\n\t\t\t\treturn fail(400, { error: 'Password must be at least 8 characters.' });\n\t\t\t}\n\t\t\tif (password !== confirm) {\n\t\t\t\treturn fail(400, { error: 'Passwords do not match.' });\n\t\t\t}\n\t\t}\n\n\t\t// The token says the invite is real; it does not say who is holding it.\n\t\t// For a brand-new account that gap closes itself — accepting is what\n\t\t// creates the identity. An existing account has to prove it is theirs.\n\t\tif (mode === 'join' && locals.user?.id !== existing!.id) {\n\t\t\treturn fail(401, {\n\t\t\t\terror: `${invite.email} already has an account. Sign in as ${invite.email}, then open this link again to join.`\n\t\t\t});\n\t\t}\n\n\t\tlet user;\n\t\tif (mode === 'join') {\n\t\t\tuser = existing!;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tif (mode === 'password' && auth.passwordAuth) {\n\t\t\t\t\tuser = await auth.passwordAuth.createUserWithPassword(invite.email, password!);\n\t\t\t\t} else if (mode === 'proxy' && auth.createUser) {\n\t\t\t\t\t// Forward-auth allowlist entry — the operator is currently behind the\n\t\t\t\t\t// trusted proxy, so the next request will identify them via headers\n\t\t\t\t\t// and mint a session. No password to collect, no token to set here.\n\t\t\t\t\tuser = await auth.createUser(invite.email);\n\t\t\t\t} else {\n\t\t\t\t\treturn fail(501, { error: 'This provider does not support invite-based signup.' });\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The account is created before the invite is consumed on purpose: a\n\t\t\t\t// failed signup must leave the invite usable. A re-submit is caught by\n\t\t\t\t// the `!invite` guard above, which already returns 410.\n\t\t\t\tconst msg = err instanceof Error ? err.message : 'Could not create your account.';\n\t\t\t\treturn fail(400, { error: msg });\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Claim before granting: an invite revoked while the account was being\n\t\t\t// created fails the claim, and must land no permission or membership.\n\t\t\tconst claimed = await getInviteStore().markAccepted(SYSTEM_CONTEXT, invite.id, user.id);\n\t\t\tif (!claimed) {\n\t\t\t\tlocals.log.info('Invite was revoked or used before it could be claimed', {\n\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\tinviteId: invite.id,\n\t\t\t\t\tuserId: user.id\n\t\t\t\t});\n\t\t\t\treturn fail(410, {\n\t\t\t\t\terror:\n\t\t\t\t\t\tmode === 'join'\n\t\t\t\t\t\t\t? 'This invite was revoked or already used. Ask your admin for a new one.'\n\t\t\t\t\t\t\t: 'Your account was created, but this invite was revoked or already used, so it did not add you to the organization. Ask your admin for a new invite.'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Authority the inviting admin chose at mint time. The mint route already\n\t\t\t// verified they held `instance_admin` — re-checking here is impossible,\n\t\t\t// as the only party present now is the invitee.\n\t\t\tif (invite.platformPermissions?.length) {\n\t\t\t\t// `set` keys on the data-layer row, which is normally seeded by\n\t\t\t\t// `ensureUser` on the first authed request — one the invitee has not\n\t\t\t\t// made yet. Without this the grant returns `not_found` and vanishes.\n\t\t\t\tawait getDataProvider().ensureUser(SYSTEM_CONTEXT, user.id);\n\t\t\t\tconst held = await getPermissionStore().getFor(SYSTEM_CONTEXT, user.id);\n\t\t\t\tconst granted = await setUserPlatformPermissions(SYSTEM_CONTEXT, user.id, [\n\t\t\t\t\t...new Set([...held, ...invite.platformPermissions])\n\t\t\t\t]);\n\t\t\t\tif (granted !== 'ok') {\n\t\t\t\t\tthrow new Error(`Platform permission grant failed: ${granted}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst orgs = getOrganizationProvider();\n\t\t\t// `addOrgMember` upserts, so accepting a second invite to an org the\n\t\t\t// user is already in would overwrite their role — a `member` invite\n\t\t\t// would demote an owner. Consume the invite and leave them as they are.\n\t\t\tconst alreadyMember = await orgs.getOrgMember(SYSTEM_CONTEXT, invite.orgId, user.id);\n\t\t\tif (!alreadyMember) {\n\t\t\t\tconst joinedAt = new Date().toISOString();\n\t\t\t\tawait orgs.addOrgMember(SYSTEM_CONTEXT, {\n\t\t\t\t\torgId: invite.orgId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\trole: invite.orgRole,\n\t\t\t\t\tpermissions: invite.orgPermissions,\n\t\t\t\t\tjoinedAt,\n\t\t\t\t\tupdatedAt: joinedAt,\n\t\t\t\t\tupdatedBy: invite.invitedBy,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Post-signup wiring failed', {\n\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\t// The account is intact either way; surface a softer failure rather\n\t\t\t// than a blank 500. An admin can add the membership by hand.\n\t\t\treturn fail(500, {\n\t\t\t\terror:\n\t\t\t\t\tmode === 'join'\n\t\t\t\t\t\t? 'We could not add you to the organization. Please contact your admin.'\n\t\t\t\t\t\t: 'Your account was created, but we could not finish joining the organization. Please contact your admin.'\n\t\t\t});\n\t\t}\n\n\t\t// Best-effort display name update — never blocks the signup. Skipped when\n\t\t// joining: that profile is the user's own, not this invite's to rename.\n\t\tif (displayName && mode !== 'join') {\n\t\t\ttry {\n\t\t\t\t// `updateProfile` patches an existing row and 404s on a missing one.\n\t\t\t\t// The data-layer row is normally seeded by `ensureUser` on the first\n\t\t\t\t// authed request — one the invitee has not made yet — so without this\n\t\t\t\t// the name the invitee typed was silently dropped.\n\t\t\t\tawait getDataProvider().ensureUser(SYSTEM_CONTEXT, user.id);\n\t\t\t\t// User has just been created and isn't yet logged in — no ctx available.\n\t\t\t\t// SYSTEM_CONTEXT is the right shape for an internal post-signup write.\n\t\t\t\tconst result = await getUserProfileStore().updateProfile(SYSTEM_CONTEXT, user.id, {\n\t\t\t\t\tdisplayName\n\t\t\t\t});\n\t\t\t\t// Returns a status rather than throwing, so an ignored result loses the\n\t\t\t\t// name with no trace.\n\t\t\t\tif (result !== 'ok') {\n\t\t\t\t\tlocals.log.warn('Could not set display name at signup', {\n\t\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\t\tuserId: user.id,\n\t\t\t\t\t\tresult\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// Non-fatal: the account and membership are already in place.\n\t\t\t\tlocals.log.warn('Could not set display name at signup', {\n\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (mode === 'password' && auth.passwordAuth) {\n\t\t\t// Sign in to mint a session token — matches Supabase's shape.\n\t\t\tconst loginResult = await auth.passwordAuth.verifyLogin(invite.email, password!);\n\t\t\tif (loginResult.kind !== 'success') {\n\t\t\t\treturn fail(500, {\n\t\t\t\t\terror: 'Your account was created but login failed. Please sign in manually.'\n\t\t\t\t});\n\t\t\t}\n\t\t\tsetSessionCookie(cookies, loginResult.sessionToken);\n\t\t}\n\t\t// Proxy mode: nothing to mint here. The very next request hits\n\t\t// hooks.server.ts → proxyAuth.identifyFromHeaders → matches the\n\t\t// allowlist row we just created → session attached transparently.\n\t\t//\n\t\t// Join mode: the session already in play is the one that proved identity,\n\t\t// and an existing user lands in the app rather than the admin shell.\n\t\tredirect(303, mode === 'join' ? '/library' : '/admin');\n\t}\n} satisfies Actions;\n"],"mappings":";;;;;;;;;AAEA,IAAM,aAAa;AAGnB,IAAM,YAAY;;;;;;;;;;;;AAalB,eAAsB,oBACrB,MACA,OAC2B;CAC3B,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,QAAQ,OAAO;CAEpB,IAAI;CACJ,KAAK,IAAI,OAAO,GAAG,OAAO,WAAW,QAAQ;EAC5C,MAAM,SAAS,MAAM,KAAK,UAAU;GAAE,OAAO;GAAY;EAAO,CAAC;EACjE,IAAI,CAAC,QAAQ,OAAO;EACpB,MAAM,MAAM,OAAO,MAAM,MAAM,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,YAAY,MAAM,MAAM;EAC7E,IAAI,KAAK,OAAO;EAChB,SAAS,OAAO;EAChB,IAAI,CAAC,QAAQ,OAAO;CACrB;CACA,OAAO;AACR;;;;;;;;ACZA,SAAS,WAAW,MAAgE;CACnF,IAAI,KAAK,cAAc,OAAO;CAC9B,OAAO,KAAK,aAAa,KAAK,aAAa,UAAU;AACtD;;;;;;;;;;;;;;;;AAiBA,SAAS,aAAa;CACrB,OAAO;EACN,MAAM,gBAAgB;EACtB,MAAM,wBAAwB;EAC9B,aAAa,mBAAmB;CACjC;AACD;AAEA,IAAa,OAAuB,OAAO,EAAE,KAAK,aAAa;CAC9D,MAAM,QAAQ,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK;CAClD,IAAI,CAAC,OACJ,OAAO;EAAE,I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a,YAAY,OAAO,OAAO,QAAS;EAC/E,IAAI,YAAY,SAAS,WACxB,OAAO,KAAK,KAAK,EAChB,OAAO,sEACR,CAAC;EAEF,iBAAiB,SAAS,YAAY,YAAY;CACnD;CAOA,SAAS,KAAK,SAAS,SAAS,aAAa,QAAQ;AACtD,EACD"}
1
+ {"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../server/src/providers/auth-lookup.ts","../../../../../src/routes/accept-invite/+page.server.ts"],"sourcesContent":["import type { AuthUser, IAuthProvider } from '@selvajs/platform';\n\nconst PAGE_LIMIT = 200;\n// Runaway guard against an adapter returning a non-advancing cursor.\n// 100 pages = 20k users, far past any deployment this product targets.\nconst MAX_PAGES = 100;\n\n/**\n * `IAuthProvider` has no by-email lookup and `listUsers` takes no filter, so\n * this scans. Acceptable because the only caller is invite acceptance — once\n * per invite, never on a hot path.\n *\n * A truncated scan would report an existing user as absent and send the flow\n * down the create-account branch, where the provider rejects the duplicate. So\n * exhausting the cursor matters: `null` must mean \"not found\", not \"gave up\".\n * Returns `null` when the provider has no user store (`listUsers` → null) or\n * when the cap is hit.\n */\nexport async function findAuthUserByEmail(\n\tauth: IAuthProvider,\n\temail: string\n): Promise<AuthUser | null> {\n\tconst needle = email.trim().toLowerCase();\n\tif (!needle) return null;\n\n\tlet cursor: string | undefined;\n\tfor (let page = 0; page < MAX_PAGES; page++) {\n\t\tconst result = await auth.listUsers({ limit: PAGE_LIMIT, cursor });\n\t\tif (!result) return null;\n\t\tconst hit = result.items.find((u) => u.email?.trim().toLowerCase() === needle);\n\t\tif (hit) return hit;\n\t\tcursor = result.nextCursor;\n\t\tif (!cursor) return null;\n\t}\n\treturn null;\n}\n","import { fail, redirect } from '@sveltejs/kit';\nimport type { Actions, PageServerLoad } from './$types';\nimport { SYSTEM_CONTEXT, type Invite } from '@selvajs/platform';\nimport {\n\tgetDataProvider,\n\tgetInviteStore,\n\tgetOrganizationProvider,\n\tgetUserProfileStore\n} from '#lib/server/providers.server.js';\nimport { getAuthProvider, getPermissionStore } from '#lib/server/providers.server.js';\nimport { findAuthUserByEmail } from '@selvajs/server/providers';\nimport { inviterStillVouches } from '@selvajs/server/handlers';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { setSessionCookie } from '#lib/server/admin-auth.server.js';\nimport { findByRawToken } from '#lib/server/invites/token.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\n\n/**\n * Signup mode for an invite whose email has no account yet:\n * - `password` — the provider owns credentials; show password + confirm fields.\n * - `proxy` — identity comes from upstream-proxy headers; the visit itself\n * is the proof of identity and no password is collected.\n */\nfunction signupMode(auth: ReturnType<typeof getAuthProvider>): 'password' | 'proxy' {\n\tif (auth.passwordAuth) return 'password';\n\treturn auth.proxyAuth && auth.createUser ? 'proxy' : 'password';\n}\n\n/**\n * Public page — the invite token is the capability. `SYSTEM_CONTEXT` is\n * passed to the invite store because there is no user session at this point;\n * the store treats an unknown/expired/consumed invite as a miss regardless.\n *\n * The raw URL token is HMAC-hashed before lookup — the store sees only the\n * digest. Mirrors the share-link flow.\n *\n * An invite addressed to an email that already has an account takes the `join`\n * mode instead of signing up: there is nothing to create, only a membership to\n * add. That branch demands a session, because the token proves the invite is\n * genuine — not that the visitor is the person it names. Honouring it\n * anonymously would let anyone holding a forwarded link join an org as someone\n * else.\n */\nfunction inviteDeps() {\n\treturn {\n\t\tauth: getAuthProvider(),\n\t\torgs: getOrganizationProvider(),\n\t\tpermissions: getPermissionStore()\n\t};\n}\n\n// Every grant step is idempotent, so a claim handed back after a failed grant\n// can be redeemed again instead of leaving the invite spent.\nasync function reopenInvite(\n\tinviteId: string,\n\tuserId: string,\n\tlocals: App.Locals\n): Promise<boolean> {\n\tconst store = getInviteStore();\n\tif (!store.reopen) return false;\n\ttry {\n\t\treturn await store.reopen(SYSTEM_CONTEXT, inviteId, userId);\n\t} catch (err) {\n\t\tlocals.log.error('Could not reopen invite after a failed grant', {\n\t\t\tcomponent: 'accept-invite',\n\t\t\tinviteId,\n\t\t\tuserId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn false;\n\t}\n}\n\nexport const load: PageServerLoad = async ({ url, locals }) => {\n\tconst token = url.searchParams.get('token')?.trim();\n\tif (!token) {\n\t\treturn { ok: false as const, reason: 'This invite link is missing a token.' };\n\t}\n\n\tconst invite = await findByRawToken(token, (h) =>\n\t\tgetInviteStore().getByTokenHash(SYSTEM_CONTEXT, h)\n\t);\n\tif (!invite || !(await inviterStillVouches(invite, inviteDeps()))) {\n\t\treturn { ok: false as const, reason: 'This invite link is invalid or has expired.' };\n\t}\n\n\tconst org = await getOrganizationProvider().getOrg(SYSTEM_CONTEXT, invite.orgId);\n\tconst auth = getAuthProvider();\n\tconst existing = await findAuthUserByEmail(auth, invite.email).catch(() => null);\n\tconst mode: 'password' | 'proxy' | 'join' = existing ? 'join' : signupMode(auth);\n\n\treturn {\n\t\tok: true as const,\n\t\temail: invite.email,\n\t\torgName: org?.name ?? 'the organization',\n\t\ttoken,\n\t\tmode,\n\t\t// `join` only: whether the visitor is already signed in as the invitee,\n\t\t// which decides between the confirm button and a sign-in prompt.\n\t\tsignedInAsInvitee: mode === 'join' && !!locals.user && locals.user.id === existing!.id\n\t};\n};\n\nexport const actions = {\n\tdefault: async ({ request, cookies, locals }) => {\n\t\tconst data = await request.formData();\n\t\tconst token = (data.get('token') as string | null)?.trim() ?? '';\n\t\tconst password = data.get('password') as string | null;\n\t\tconst confirm = data.get('confirm') as string | null;\n\t\tconst displayName = (data.get('displayName') as string | null)?.trim() || undefined;\n\n\t\tif (!token) {\n\t\t\treturn fail(400, { error: 'Missing invite token.' });\n\t\t}\n\n\t\tlet invite: Invite | null;\n\t\ttry {\n\t\t\tinvite = await findByRawToken(token, (h) =>\n\t\t\t\tgetInviteStore().getByTokenHash(SYSTEM_CONTEXT, h)\n\t\t\t);\n\t\t} catch {\n\t\t\treturn fail(500, { error: 'Could not validate the invite. Please try again.' });\n\t\t}\n\t\tif (!invite || !(await inviterStillVouches(invite, inviteDeps()))) {\n\t\t\treturn fail(410, { error: 'This invite link is invalid or has expired.' });\n\t\t}\n\n\t\tconst auth = getAuthProvider();\n\t\tconst existing = await findAuthUserByEmail(auth, invite.email).catch(() => null);\n\t\tconst mode: 'password' | 'proxy' | 'join' = existing ? 'join' : signupMode(auth);\n\n\t\tif (mode === 'password') {\n\t\t\tif (!password || password.length < 8) {\n\t\t\t\treturn fail(400, { error: 'Password must be at least 8 characters.' });\n\t\t\t}\n\t\t\tif (password !== confirm) {\n\t\t\t\treturn fail(400, { error: 'Passwords do not match.' });\n\t\t\t}\n\t\t}\n\n\t\t// The token says the invite is real; it does not say who is holding it.\n\t\t// For a brand-new account that gap closes itself — accepting is what\n\t\t// creates the identity. An existing account has to prove it is theirs.\n\t\tif (mode === 'join' && locals.user?.id !== existing!.id) {\n\t\t\treturn fail(401, {\n\t\t\t\terror: `${invite.email} already has an account. Sign in as ${invite.email}, then open this link again to join.`\n\t\t\t});\n\t\t}\n\n\t\tlet user;\n\t\tif (mode === 'join') {\n\t\t\tuser = existing!;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tif (mode === 'password' && auth.passwordAuth) {\n\t\t\t\t\tuser = await auth.passwordAuth.createUserWithPassword(invite.email, password!);\n\t\t\t\t} else if (mode === 'proxy' && auth.createUser) {\n\t\t\t\t\t// Forward-auth allowlist entry — the operator is currently behind the\n\t\t\t\t\t// trusted proxy, so the next request will identify them via headers\n\t\t\t\t\t// and mint a session. No password to collect, no token to set here.\n\t\t\t\t\tuser = await auth.createUser(invite.email);\n\t\t\t\t} else {\n\t\t\t\t\treturn fail(501, { error: 'This provider does not support invite-based signup.' });\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The account is created before the invite is consumed on purpose: a\n\t\t\t\t// failed signup must leave the invite usable. A re-submit is caught by\n\t\t\t\t// the `!invite` guard above, which already returns 410.\n\t\t\t\tconst msg = err instanceof Error ? err.message : 'Could not create your account.';\n\t\t\t\treturn fail(400, { error: msg });\n\t\t\t}\n\t\t}\n\n\t\tlet claimed = false;\n\t\ttry {\n\t\t\t// Claim before granting: an invite revoked while the account was being\n\t\t\t// created fails the claim, and must land no permission or membership.\n\t\t\tclaimed = await getInviteStore().markAccepted(SYSTEM_CONTEXT, invite.id, user.id);\n\t\t\tif (!claimed) {\n\t\t\t\tlocals.log.info('Invite was revoked or used before it could be claimed', {\n\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\tinviteId: invite.id,\n\t\t\t\t\tuserId: user.id\n\t\t\t\t});\n\t\t\t\treturn fail(410, {\n\t\t\t\t\terror:\n\t\t\t\t\t\tmode === 'join'\n\t\t\t\t\t\t\t? 'This invite was revoked or already used. Ask your admin for a new one.'\n\t\t\t\t\t\t\t: 'Your account was created, but this invite was revoked or already used, so it did not add you to the organization. Ask your admin for a new invite.'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Authority the inviting admin chose at mint time. The mint route already\n\t\t\t// verified they held `instance_admin` — re-checking here is impossible,\n\t\t\t// as the only party present now is the invitee.\n\t\t\tif (invite.platformPermissions?.length) {\n\t\t\t\t// `set` keys on the data-layer row, which is normally seeded by\n\t\t\t\t// `ensureUser` on the first authed request — one the invitee has not\n\t\t\t\t// made yet. Without this the grant returns `not_found` and vanishes.\n\t\t\t\tawait getDataProvider().ensureUser(SYSTEM_CONTEXT, user.id);\n\t\t\t\tconst held = await getPermissionStore().getFor(SYSTEM_CONTEXT, user.id);\n\t\t\t\tconst granted = await setUserPlatformPermissions(SYSTEM_CONTEXT, user.id, [\n\t\t\t\t\t...new Set([...held, ...invite.platformPermissions])\n\t\t\t\t]);\n\t\t\t\tif (granted !== 'ok') {\n\t\t\t\t\tthrow new Error(`Platform permission grant failed: ${granted}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst orgs = getOrganizationProvider();\n\t\t\t// `addOrgMember` upserts, so accepting a second invite to an org the\n\t\t\t// user is already in would overwrite their role — a `member` invite\n\t\t\t// would demote an owner. Consume the invite and leave them as they are.\n\t\t\tconst alreadyMember = await orgs.getOrgMember(SYSTEM_CONTEXT, invite.orgId, user.id);\n\t\t\tif (!alreadyMember) {\n\t\t\t\tconst joinedAt = new Date().toISOString();\n\t\t\t\tawait orgs.addOrgMember(SYSTEM_CONTEXT, {\n\t\t\t\t\torgId: invite.orgId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\trole: invite.orgRole,\n\t\t\t\t\tpermissions: invite.orgPermissions,\n\t\t\t\t\tjoinedAt,\n\t\t\t\t\tupdatedAt: joinedAt,\n\t\t\t\t\tupdatedBy: invite.invitedBy,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Post-signup wiring failed', {\n\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tif (claimed && (await reopenInvite(invite.id, user.id, locals))) {\n\t\t\t\treturn fail(500, {\n\t\t\t\t\terror:\n\t\t\t\t\t\tmode === 'join'\n\t\t\t\t\t\t\t? 'We could not add you to the organization. Please try again.'\n\t\t\t\t\t\t\t: `Your account was created, but we could not finish joining the organization. Sign in as ${invite.email}, then open this link again to join.`\n\t\t\t\t});\n\t\t\t}\n\t\t\t// The account is intact either way; surface a softer failure rather\n\t\t\t// than a blank 500. An admin can add the membership by hand.\n\t\t\treturn fail(500, {\n\t\t\t\terror:\n\t\t\t\t\tmode === 'join'\n\t\t\t\t\t\t? 'We could not add you to the organization. Please contact your admin.'\n\t\t\t\t\t\t: 'Your account was created, but we could not finish joining the organization. Please contact your admin.'\n\t\t\t});\n\t\t}\n\n\t\t// Best-effort display name update — never blocks the signup. Skipped when\n\t\t// joining: that profile is the user's own, not this invite's to rename.\n\t\tif (displayName && mode !== 'join') {\n\t\t\ttry {\n\t\t\t\t// `updateProfile` patches an existing row and 404s on a missing one.\n\t\t\t\t// The data-layer row is normally seeded by `ensureUser` on the first\n\t\t\t\t// authed request — one the invitee has not made yet — so without this\n\t\t\t\t// the name the invitee typed was silently dropped.\n\t\t\t\tawait getDataProvider().ensureUser(SYSTEM_CONTEXT, user.id);\n\t\t\t\t// User has just been created and isn't yet logged in — no ctx available.\n\t\t\t\t// SYSTEM_CONTEXT is the right shape for an internal post-signup write.\n\t\t\t\tconst result = await getUserProfileStore().updateProfile(SYSTEM_CONTEXT, user.id, {\n\t\t\t\t\tdisplayName\n\t\t\t\t});\n\t\t\t\t// Returns a status rather than throwing, so an ignored result loses the\n\t\t\t\t// name with no trace.\n\t\t\t\tif (result !== 'ok') {\n\t\t\t\t\tlocals.log.warn('Could not set display name at signup', {\n\t\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\t\tuserId: user.id,\n\t\t\t\t\t\tresult\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// Non-fatal: the account and membership are already in place.\n\t\t\t\tlocals.log.warn('Could not set display name at signup', {\n\t\t\t\t\tcomponent: 'accept-invite',\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (mode === 'password' && auth.passwordAuth) {\n\t\t\t// Sign in to mint a session token — matches Supabase's shape.\n\t\t\tconst loginResult = await auth.passwordAuth.verifyLogin(invite.email, password!);\n\t\t\tif (loginResult.kind !== 'success') {\n\t\t\t\treturn fail(500, {\n\t\t\t\t\terror: 'Your account was created but login failed. Please sign in manually.'\n\t\t\t\t});\n\t\t\t}\n\t\t\tsetSessionCookie(cookies, loginResult.sessionToken);\n\t\t}\n\t\t// Proxy mode: nothing to mint here. The very next request hits\n\t\t// hooks.server.ts → proxyAuth.identifyFromHeaders → matches the\n\t\t// allowlist row we just created → session attached transparently.\n\t\t//\n\t\t// Join mode: the session already in play is the one that proved identity,\n\t\t// and an existing user lands in the app rather than the admin shell.\n\t\tredirect(303, mode === 'join' ? '/library' : '/admin');\n\t}\n} satisfies Actions;\n"],"mappings":";;;;;;;;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Q,KAAK;GACb,KAAK,aAAa,GAAG;EACtB,CAAC;CACF;CAGD,IAAI,SAAS,cAAc,KAAK,cAAc;EAE7C,MAAM,cAAc,MAAM,KAAK,aAAa,YAAY,OAAO,OAAO,QAAS;EAC/E,IAAI,YAAY,SAAS,WACxB,OAAO,KAAK,KAAK,EAChB,OAAO,sEACR,CAAC;EAEF,iBAAiB,SAAS,YAAY,YAAY;CACnD;CAOA,SAAS,KAAK,SAAS,SAAS,aAAa,QAAQ;AACtD,EACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/selva",
3
- "version": "4.20.1-beta.1",
3
+ "version": "4.20.1-beta.2",
4
4
  "description": "Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.",
5
5
  "license": "MIT",
6
6
  "author": "VektorNode",
@@ -58,18 +58,18 @@
58
58
  "rimraf": "^6.1.3",
59
59
  "tw-animate-css": "^1.4.0",
60
60
  "vitest": "^5.0.5",
61
+ "@selvajs/local-provider": "0.16.1-beta.1",
62
+ "@selvajs/mcp": "0.1.0",
61
63
  "@selvajs/compute": "5.0.1",
62
- "@selvajs/header-auth-provider": "0.11.1",
64
+ "@selvajs/notifications": "0.3.1-beta.1",
63
65
  "@selvajs/config": "0.0.4",
64
- "@selvajs/local-provider": "0.16.1-beta.0",
65
- "@selvajs/mcp": "0.1.0",
66
- "@selvajs/platform": "1.1.0-beta.0",
67
- "@selvajs/schemas": "5.3.1-beta.0",
68
- "@selvajs/notifications": "0.3.1-beta.0",
66
+ "@selvajs/platform": "1.1.0-beta.1",
69
67
  "@selvajs/server": "2.1.0-beta.0",
70
68
  "@selvajs/solve": "2.1.0-beta.1",
69
+ "@selvajs/schemas": "5.3.1-beta.0",
70
+ "@selvajs/header-auth-provider": "0.11.1",
71
+ "@selvajs/supabase-provider": "0.21.0-beta.1",
71
72
  "@selvajs/ui": "7.0.3-beta.1",
72
- "@selvajs/supabase-provider": "0.21.0-beta.0",
73
73
  "@selvajs/visualization": "1.7.1-beta.0"
74
74
  },
75
75
  "imports": {