simetra 0.3.0-next.1 → 0.3.0-next.11

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.
@@ -1,6 +1,6 @@
1
1
  import { t as createChannelGrant } from "../channel-grant-BATD6oQu.js";
2
2
  import { z } from "zod";
3
- import { APPLIED_SNAPSHOT_HASH_FUNCTION_NAME, BATCH_MAX, CENTRIFUGO_CHANNEL_MAX, COMMAND_CORE_ERRORS, COMMAND_ERROR_CODES, COMMAND_SETTING, CURRENT_USER_FUNCTION_NAME, CommandFailure, INTEGER_TEXT, KNOWN_MARKER, LIMIT_REASONS, LOGIN_ROLE_REQUEST_PURPOSES, OBJECT_MODULE_KEYS, OBJECT_OPERATIONS, OPERATION_EVENTS, ORDER_BY_MAX, PINNED_SESSION_SETTINGS, PLATFORM_ROLES, PLATFORM_SCHEMA, PRIVILEGED_LOGIN_REASONS, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, READ_BATCH_MAX, READ_BATCH_STATEMENTS_MAX, READ_COUNT_CAP, RESPONSE_BUDGET_BYTES, RIGHTS_CLIENT_SNAPSHOT_FUNCTION_NAME, ROW_VERSION_EPOCH_FUNCTION_NAME, SESSION_CLAIMS_SETTING, SIGNAL_INVALIDATE_FUNCTION_NAME, SIGNAL_MERGE_MODE, SIGNAL_MERGE_THRESHOLD, SIGNAL_MODE_SETTING, SIGNAL_TOPIC_ALLOWED_FUNCTION_NAME, STORAGE_ERRORS, STORAGE_FUNCTIONS, STORAGE_MAX_BYTES, STORAGE_REASONS, TABULAR_LINES_MAX, UUID_TEXT, WireDecodeError, ZERO_UUID, batchSchema, catalogIndex, changesToWire, dataRequestSchema, decodeRow, encodeAttributes, encodeItemValue, encodePair, encodeRow, errorToWire, fileObjectKey, isFileObjectKey, isFileObjectPrefix, isPlainObject, isTextEncodedType, isWithinType, jsonBytes, jsonbBuildObject, knownFormAllowed, knownSchema, metadataRefSchema, objectColumns, operationFromWire, operationSchema, readPartFromWire, readQuerySchema, readResultToWire, rightsSnapshotSchema, rowWithoutSearch, runtimeCatalogSchema, searchNormalization, searchPrefixNormalization, sessionClaimsSchema, splitKnownMarker, versionEpochSchema, wireCommandErrorSchema, wireReadPartSchema } from "simetra/model";
3
+ import { APPLIED_SNAPSHOT_HASH_FUNCTION_NAME, BATCH_MAX, CENTRIFUGO_CHANNEL_MAX, COMMAND_CORE_ERRORS, COMMAND_ERROR_CODES, COMMAND_SETTING, CURRENT_USER_FUNCTION_NAME, CommandFailure, INTEGER_TEXT, INVITATION_ACCEPT_FUNCTION_NAME, KNOWN_MARKER, LIMIT_REASONS, LOGIN_ROLE_REQUEST_PURPOSES, OBJECT_MODULE_KEYS, OBJECT_OPERATIONS, OPERATION_EVENTS, ORDER_BY_MAX, PINNED_SESSION_SETTINGS, PLATFORM_ROLES, PLATFORM_SCHEMA, PRIVILEGED_LOGIN_REASONS, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, READ_BATCH_MAX, READ_BATCH_STATEMENTS_MAX, READ_COUNT_CAP, RESPONSE_BUDGET_BYTES, RIGHTS_CLIENT_SNAPSHOT_FUNCTION_NAME, RIGHTS_MY_SCOPES_FUNCTION_NAME, ROW_VERSION_EPOCH_FUNCTION_NAME, SESSION_CLAIMS_SETTING, SIGNAL_INVALIDATE_FUNCTION_NAME, SIGNAL_MERGE_MODE, SIGNAL_MERGE_THRESHOLD, SIGNAL_MODE_SETTING, SIGNAL_TOPIC_ALLOWED_FUNCTION_NAME, STORAGE_ERRORS, STORAGE_FUNCTIONS, STORAGE_MAX_BYTES, STORAGE_REASONS, TABULAR_LINES_MAX, UUID_TEXT, WireDecodeError, ZERO_UUID, batchSchema, catalogIndex, changesToWire, dataRequestSchema, decodeRow, encodeAttributes, encodeItemValue, encodePair, encodeRow, errorToWire, fileObjectKey, invitationIssueSchema, isFileObjectKey, isFileObjectPrefix, isInvitationIssue, isPlainObject, isTextEncodedType, isWithinType, jsonBytes, jsonbBuildObject, knownFormAllowed, knownSchema, metadataRefSchema, objectColumns, operationFromWire, operationSchema, readPartFromWire, readQuerySchema, readResultToWire, rightsSnapshotSchema, rowWithoutSearch, runtimeCatalogSchema, searchNormalization, searchPrefixNormalization, sessionClaimsSchema, splitKnownMarker, versionEpochSchema, wireCommandErrorSchema, wireReadPartSchema, wireRunResultFor } from "simetra/model";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  // src/server/file-store.ts
6
6
  /** Object key of the database binding marker (platform spec §8.2). */
@@ -500,6 +500,11 @@ function mapDatabaseError(error, catalog, phase, deletes = []) {
500
500
  reason: `storage.${reason}`
501
501
  };
502
502
  }
503
+ if (code === E.invitationNotPending.errcode && message === E.invitationNotPending.message) return phase?.kind === "write" ? {
504
+ code: "invitation.not-pending",
505
+ object: refOf$1(phase.object),
506
+ operation: phase.operation
507
+ } : { code: "invitation.not-pending" };
503
508
  switch (code) {
504
509
  case E.forbidden.errcode:
505
510
  if (message === E.forbidden.message) return detail !== void 0 && FORBIDDEN_REASONS.includes(detail) ? {
@@ -606,6 +611,88 @@ function rlsOf(catalog, phase, tableName) {
606
611
  ...phase?.kind === "write" ? { operation: phase.operation } : {}
607
612
  };
608
613
  }
614
+ // src/server/invitation-secret.ts
615
+ /**
616
+ * Секрет запрошення (спека запрошень §4, крок 1): 32 байти криптостійкого
617
+ * генератора, текст — їхній base64url без доповнення (43 символи); у базу йде
618
+ * лише `sha256` тексту. Web Crypto, а не `node:crypto`: зона чистоти T3
619
+ * пускає з Node лише `node:async_hooks` (спека П4 Рт17).
620
+ */
621
+ const SECRET_BYTES = 32;
622
+ /** base64url без доповнення. */
623
+ function base64url(bytes) {
624
+ let binary = "";
625
+ for (const byte of bytes) binary += String.fromCharCode(byte);
626
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
627
+ }
628
+ /** Новий секрет запрошення. */
629
+ function newInvitationSecret() {
630
+ return base64url(crypto.getRandomValues(new Uint8Array(SECRET_BYTES)));
631
+ }
632
+ /**
633
+ * `sha256` UTF-8 тексту секрету в hex — параметр `decode($n, 'hex')`: порт
634
+ * передає лише текстові параметри.
635
+ */
636
+ async function invitationSecretHash(secret) {
637
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
638
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
639
+ }
640
+ // src/server/origin.ts
641
+ const REFUSED = {
642
+ code: "command.forbidden",
643
+ reason: LIMIT_REASONS.origin
644
+ };
645
+ /**
646
+ * In-process calls may only read: `run` needs the facts of an HTTP request.
647
+ * The parts of a `read` are not looked at — every part only reads.
648
+ */
649
+ const IN_PROCESS_TYPES = /* @__PURE__ */ new Set(["read"]);
650
+ /**
651
+ * Step 0 of the data handler: refuses a request that could be forged by
652
+ * another site. Runs before the envelope is parsed, so it touches nothing but
653
+ * the origin facts (and, for `inProcess`, the raw request type).
654
+ *
655
+ * @returns the refusal, or `undefined` when the request may proceed.
656
+ */
657
+ function checkRequestOrigin(origin, rawRequest) {
658
+ if (isInProcess(origin)) return inProcessAllowed(rawRequest) ? void 0 : REFUSED;
659
+ return httpAllowed(origin) ? void 0 : REFUSED;
660
+ }
661
+ /**
662
+ * {@link checkRequestOrigin} that refuses on any exception too: an untyped
663
+ * call without `origin`, or a hostile object, must not let a request pass.
664
+ */
665
+ function originRefused(origin, rawRequest) {
666
+ try {
667
+ return checkRequestOrigin(origin, rawRequest) !== void 0;
668
+ } catch {
669
+ return true;
670
+ }
671
+ }
672
+ function isInProcess(origin) {
673
+ return origin.inProcess === true;
674
+ }
675
+ function httpAllowed(origin) {
676
+ if (!isCanonicalOrigin(origin.expectedOrigin)) return false;
677
+ if (origin.secFetchSite !== void 0 && origin.secFetchSite !== "same-origin") return false;
678
+ if (origin.origin !== void 0) return origin.origin === origin.expectedOrigin;
679
+ return origin.secFetchSite === "same-origin";
680
+ }
681
+ function isCanonicalOrigin(value) {
682
+ try {
683
+ return new URL(value).origin === value;
684
+ } catch {
685
+ return false;
686
+ }
687
+ }
688
+ function inProcessAllowed(rawRequest) {
689
+ try {
690
+ const type = rawRequest.request.type;
691
+ return typeof type === "string" && IN_PROCESS_TYPES.has(type);
692
+ } catch {
693
+ return false;
694
+ }
695
+ }
609
696
  // src/server/decode.ts
610
697
  const internal = () => new CommandFailure({ code: "command.internal" });
611
698
  /** Parses the JSON text of a result column; broken text is `command.internal`. */
@@ -1937,6 +2024,7 @@ const ANONYMOUS_SNAPSHOT = Object.freeze({
1937
2024
  scopeSets: [],
1938
2025
  rights: [],
1939
2026
  members: [],
2027
+ heldContainers: [],
1940
2028
  dimensionValues: []
1941
2029
  });
1942
2030
  const tupleKey = (...fields) => JSON.stringify(fields);
@@ -1981,6 +2069,11 @@ function canonicalSnapshot(snapshot) {
1981
2069
  scope: m.scope,
1982
2070
  member: m.member
1983
2071
  })),
2072
+ heldContainers: byKey(snapshot.heldContainers, (h) => tupleKey(h.object, h.container, h.scope)).map((h) => ({
2073
+ object: h.object,
2074
+ container: h.container,
2075
+ scope: h.scope
2076
+ })),
1984
2077
  dimensionValues: byKey(snapshot.dimensionValues, (d) => tupleKey(d.dimension)).map(canonicalDimension)
1985
2078
  };
1986
2079
  }
@@ -2342,6 +2435,7 @@ function callOf({ object, target }, op, draft, byFields) {
2342
2435
  text: `SELECT ${fn(target)}($1::uuid, $2::bigint) AS r`,
2343
2436
  params: [op.id, String(op.expectedVersion)]
2344
2437
  };
2438
+ case "issueInvitation": throw new Error("internal: issueInvitation outside its phase");
2345
2439
  }
2346
2440
  }
2347
2441
  const CONTEXT_TEXT = `SELECT pg_catalog.set_config(${literal(COMMAND_SETTING)}, $1, true)`;
@@ -2483,6 +2577,7 @@ async function onWrite(tx, phase, module, row) {
2483
2577
  async function runPhase(tx, op, fullTabularArrays = false) {
2484
2578
  const found = targetOf(tx.state.catalog, op);
2485
2579
  if ("error" in found) tx.abort(found.error);
2580
+ if (op.action === "issueInvitation") return runIssuePhase(tx, found, op);
2486
2581
  const creation = rootCreateOf(tx.state.catalog, found.object, op);
2487
2582
  if (creation !== void 0) return runRootPhase(tx, found, op, creation);
2488
2583
  const { object } = found;
@@ -2568,6 +2663,47 @@ async function runRootPhase(tx, found, op, { membership }) {
2568
2663
  if (member !== void 0) await onWrite(tx, member.phase, member.module, memberRow);
2569
2664
  return rootRow.row;
2570
2665
  }
2666
+ /** Рядок ядра видачі: строк дії запису, як його записала база. */
2667
+ const issueCoreSchema = z.strictObject({ expiresAt: z.string().min(1) });
2668
+ /**
2669
+ * Фаза видачі запрошення (спека запрошень §4, Р-З1-10): без хуків довідника
2670
+ * членства, без декодування рядка каталогу, без запису в набір змін і без
2671
+ * сигналу — рядка вона не змінює. Секрет T3 генерує сам; база отримує лише
2672
+ * його хеш, а секрет іде тільки в рядок результату `{ secret, expiresAt }`.
2673
+ * Сесія з `act` — відмова до ядра: секрет ліг би в контекст агента;
2674
+ * `invitation_put` перевіряє те саме ще раз.
2675
+ */
2676
+ async function runIssuePhase(tx, found, op) {
2677
+ const { object, target } = found;
2678
+ if (tx.actClaim) tx.abort(issueForbidden(op.object));
2679
+ const secret = newInvitationSecret();
2680
+ const call = {
2681
+ text: `SELECT ${fn(target)}($1::uuid, pg_catalog.decode($2, 'hex')) AS r`,
2682
+ params: [op.id, await invitationSecretHash(secret)]
2683
+ };
2684
+ const { rows } = await tx.enqueue([contextOf(found, op), call], writePhase(object, op));
2685
+ const text = rows[0]?.r;
2686
+ let parsed;
2687
+ try {
2688
+ parsed = typeof text === "string" ? issueCoreSchema.safeParse(JSON.parse(text)) : void 0;
2689
+ } catch {
2690
+ parsed = void 0;
2691
+ }
2692
+ if (parsed?.success !== true) coreAnomaly(tx, object);
2693
+ return {
2694
+ secret,
2695
+ expiresAt: parsed.data.expiresAt
2696
+ };
2697
+ }
2698
+ /** Відмова видачі в сесії з claim `act` (спека запрошень §4, крок 2). */
2699
+ const issueForbidden = (object) => ({
2700
+ code: "command.forbidden",
2701
+ object: {
2702
+ kind: object.kind,
2703
+ name: object.name
2704
+ },
2705
+ operation: "issueInvitation"
2706
+ });
2571
2707
  /** Фаза відмови запису: оператори сигналу фази мапляться як її запис. */
2572
2708
  const writePhase = (object, op) => ({
2573
2709
  kind: "write",
@@ -2835,6 +2971,11 @@ var Transaction = class {
2835
2971
  /** The current user of the attempt (step 4 of §6.5). */
2836
2972
  user = "";
2837
2973
  act;
2974
+ /**
2975
+ * Claims сесії несуть ключ `act` за будь-якого значення — правило SQL
2976
+ * (`claims ? 'act'`), а не лише `act` з рядковим `sub`.
2977
+ */
2978
+ actClaim = false;
2838
2979
  /** Фази, які вже почав `ctx.run` у цій спробі (межа `BATCH_MAX`, Ф1). */
2839
2980
  nestedPhases = 0;
2840
2981
  /**
@@ -3022,6 +3163,7 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3022
3163
  }
3023
3164
  const tx = new Transaction(client, state, deadline);
3024
3165
  tx.act = act;
3166
+ tx.actClaim = hasActClaim(claims);
3025
3167
  const rows = [];
3026
3168
  let epoch = "";
3027
3169
  let tag;
@@ -3066,33 +3208,10 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3066
3208
  return (await tx.enqueue([COMMIT])).command;
3067
3209
  });
3068
3210
  } catch (error) {
3069
- if (tx.terminal === void 0) {
3070
- if (error instanceof CommandFailure) tx.close({
3071
- failure: error,
3072
- retry: false,
3073
- destroy: false
3074
- });
3075
- else try {
3076
- tx.anomaly(error);
3077
- } catch {}
3078
- }
3079
- await tx.settled();
3080
- const terminal = tx.terminal;
3081
- await endFailed(client, terminal.destroy);
3082
- return { terminal };
3083
- }
3084
- releaseCommitted(client, state.log);
3085
- if (tag !== "COMMIT") {
3086
- state.log({
3087
- kind: "database",
3088
- error: /* @__PURE__ */ new Error(`COMMIT answered ${tag}`)
3089
- });
3090
- return { terminal: {
3091
- failure: new CommandFailure(INTERNAL$1),
3092
- retry: false,
3093
- destroy: false
3094
- } };
3211
+ return failedAttempt(tx, client, error);
3095
3212
  }
3213
+ const refused = committed(client, state, tag);
3214
+ if (refused !== void 0) return refused;
3096
3215
  return {
3097
3216
  result: {
3098
3217
  rows,
@@ -3102,6 +3221,37 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3102
3221
  afterCommit: tx.afterCommit
3103
3222
  };
3104
3223
  }
3224
+ /** Невдала спроба: відмова черги чи непередбачений виняток — завершення з'єднання. */
3225
+ async function failedAttempt(tx, client, error) {
3226
+ if (tx.terminal === void 0) {
3227
+ if (error instanceof CommandFailure) tx.close({
3228
+ failure: error,
3229
+ retry: false,
3230
+ destroy: false
3231
+ });
3232
+ else try {
3233
+ tx.anomaly(error);
3234
+ } catch {}
3235
+ }
3236
+ await tx.settled();
3237
+ const terminal = tx.terminal;
3238
+ await endFailed(client, terminal.destroy);
3239
+ return { terminal };
3240
+ }
3241
+ /** Звільнення після `COMMIT`; тег, що не `COMMIT`, — відмова, а не успіх. */
3242
+ function committed(client, state, tag) {
3243
+ releaseCommitted(client, state.log);
3244
+ if (tag === "COMMIT") return void 0;
3245
+ state.log({
3246
+ kind: "database",
3247
+ error: /* @__PURE__ */ new Error(`COMMIT answered ${tag}`)
3248
+ });
3249
+ return { terminal: {
3250
+ failure: new CommandFailure(INTERNAL$1),
3251
+ retry: false,
3252
+ destroy: false
3253
+ } };
3254
+ }
3105
3255
  /**
3106
3256
  * Runs `afterCommit` actions in order; a failing action is logged and the
3107
3257
  * next one still runs.
@@ -3173,6 +3323,21 @@ var FileAttachFailure = class extends CommandFailure {
3173
3323
  this.name = "FileAttachFailure";
3174
3324
  }
3175
3325
  };
3326
+ /**
3327
+ * Чи несуть claims ключ `act` — та сама умова, що в SQL видачі й прийняття
3328
+ * (`claims ? 'act'`): за серіалізованим текстом, який отримає база. Функція
3329
+ * тотальна: її кличуть і поза `try` спроби, а `JSON.stringify` нетипізованої
3330
+ * сесії дає `undefined`. Нерозбірні claims — як з `act` (fail-closed): ознака
3331
+ * лише забороняє видачу.
3332
+ */
3333
+ function hasActClaim(claims) {
3334
+ try {
3335
+ const parsed = JSON.parse(claims);
3336
+ return isPlainObject(parsed) && Object.hasOwn(parsed, "act");
3337
+ } catch {
3338
+ return true;
3339
+ }
3340
+ }
3176
3341
  /** A command: validation, attempts with retry, then `afterCommit` (§6.5). */
3177
3342
  async function runCommand(state, session, input, fullTabularArrays = false) {
3178
3343
  rejectNested();
@@ -3189,10 +3354,91 @@ async function runCommand(state, session, input, fullTabularArrays = false) {
3189
3354
  } catch {
3190
3355
  throw new CommandFailure(INTERNAL$1);
3191
3356
  }
3357
+ const issue = ops.find((op) => op.action === "issueInvitation");
3358
+ if (issue !== void 0 && hasActClaim(claims)) throw new CommandFailure(issueForbidden(issue.object));
3192
3359
  const snapshot = structuredClone(ops);
3193
3360
  const act = typeof session.act?.sub === "string" ? { sub: session.act.sub } : void 0;
3194
3361
  return settleOutcome(state, await runAttempts(state, (command, deadline) => attempt(state, command, claims, act, structuredClone(snapshot), deadline, fullTabularArrays)));
3195
3362
  }
3363
+ const ACCEPT_TEXT = `SELECT ${ident(PLATFORM_SCHEMA)}.${ident(INVITATION_ACCEPT_FUNCTION_NAME)}(pg_catalog.decode($1, 'hex'))::text AS r`;
3364
+ /**
3365
+ * Відповідь `invitation_accept` (спека запрошень §5): причини `failed` —
3366
+ * лише ті, що пише функція; інша відповідь — аномалія з відкатом, а не
3367
+ * зафіксована невідома відмова.
3368
+ */
3369
+ const acceptAnswerSchema = z.discriminatedUnion("outcome", [
3370
+ z.strictObject({
3371
+ outcome: z.literal("accepted"),
3372
+ scopeKind: z.guid(),
3373
+ scope: z.guid(),
3374
+ member: z.guid()
3375
+ }),
3376
+ z.strictObject({
3377
+ outcome: z.literal("failed"),
3378
+ reason: z.enum([
3379
+ "actor",
3380
+ "unknown",
3381
+ "expired",
3382
+ "member-gone",
3383
+ "changed",
3384
+ "already-member"
3385
+ ])
3386
+ }),
3387
+ z.strictObject({
3388
+ outcome: z.literal("rate-limited"),
3389
+ reason: z.literal("rate-limited")
3390
+ })
3391
+ ]);
3392
+ /**
3393
+ * Прийняття запрошення у власній транзакції команди (спека запрошень §5):
3394
+ * claims, роль команд і одразу функція — жодного оператора, що взяв би
3395
+ * знімок актора раніше (функція тоді відмовила б `rights-context`). Кожна
3396
+ * відповідь функції фіксується: рядок `failed` журналу й лік спроб мусять
3397
+ * пережити відмову. Повтор — на серіалізації й взаємному блокуванні, як у
3398
+ * `run`; `hash` — hex `sha256` тексту секрету.
3399
+ */
3400
+ async function runAccept(state, session, hash) {
3401
+ rejectNested();
3402
+ let claims;
3403
+ try {
3404
+ claims = JSON.stringify(session);
3405
+ } catch {
3406
+ throw new CommandFailure(INTERNAL$1);
3407
+ }
3408
+ const outcome = await runAttempts(state, (_, deadline) => acceptAttempt(state, claims, hash, deadline));
3409
+ if ("terminal" in outcome) throw outcome.terminal.failure;
3410
+ return outcome.answer;
3411
+ }
3412
+ async function acceptAttempt(state, claims, hash, deadline) {
3413
+ let client;
3414
+ try {
3415
+ client = await state.database.connect();
3416
+ } catch (raw) {
3417
+ return { terminal: terminalOf(raw, state, void 0, false, normalizeError(raw, true)) };
3418
+ }
3419
+ const tx = new Transaction(client, state, deadline);
3420
+ let answer;
3421
+ let tag;
3422
+ try {
3423
+ await tx.enqueue([BEGIN]);
3424
+ await tx.claims(claims);
3425
+ await tx.enqueue([COMMAND_ROLE]);
3426
+ const { rows } = await tx.enqueue([statement(ACCEPT_TEXT, hash)]);
3427
+ const text = rows[0]?.r;
3428
+ let parsed;
3429
+ try {
3430
+ parsed = typeof text === "string" ? acceptAnswerSchema.safeParse(JSON.parse(text)) : void 0;
3431
+ } catch {
3432
+ parsed = void 0;
3433
+ }
3434
+ if (parsed?.success !== true) tx.anomaly(/* @__PURE__ */ new Error("invitation_accept answered no known outcome"));
3435
+ answer = parsed.data;
3436
+ ({command: tag} = await tx.enqueue([COMMIT]));
3437
+ } catch (error) {
3438
+ return failedAttempt(tx, client, error);
3439
+ }
3440
+ return committed(client, state, tag) ?? { answer };
3441
+ }
3196
3442
  /**
3197
3443
  * `attachFile` (спека профілю postgres §8.2 крок 4): одна внутрішня фаза
3198
3444
  * `create` рядка файлу з записом `file_attach` перед нею, у спробах і з
@@ -3537,9 +3783,111 @@ async function createCommandRuntime(options) {
3537
3783
  rejectNested();
3538
3784
  if (await inRecovery(state)) throw new FileStoreError("in-recovery", "the database is in recovery: rebind on the primary");
3539
3785
  await store.rebind(await fileInstance(state));
3540
- }
3786
+ },
3787
+ acceptInvitation: (session, secret, origin) => acceptInvitation(state, session, secret, origin),
3788
+ workspaces: (session, origin) => workspaces(state, session, origin)
3541
3789
  };
3542
3790
  }
3791
+ const ACCEPT_REQUEST = { request: { type: "acceptInvitation" } };
3792
+ const WORKSPACES_REQUEST = { request: { type: "read" } };
3793
+ const ORIGIN_REFUSED = {
3794
+ code: "command.forbidden",
3795
+ reason: LIMIT_REASONS.origin
3796
+ };
3797
+ const FORBIDDEN$1 = { code: "command.forbidden" };
3798
+ /** Без прапорця каталогу запрошень немає ні функції прийняття, ні методів. */
3799
+ function requireInvitations(state) {
3800
+ if (state.catalog.invitations !== true) throw new CommandFailure({ code: "command.invalid" });
3801
+ }
3802
+ /**
3803
+ * Прийняття запрошення (спека запрошень §5): походження — першим, бо чужий
3804
+ * секрет, підсунутий з іншого походження, ввів би жертву до чужого тенанта;
3805
+ * далі все, що відомо без бази, і лише тоді хеш і транзакція команди.
3806
+ */
3807
+ async function acceptInvitation(state, session, secret, origin) {
3808
+ if (originRefused(origin, ACCEPT_REQUEST)) throw new CommandFailure(ORIGIN_REFUSED);
3809
+ rejectNested();
3810
+ requireInvitations(state);
3811
+ let kind;
3812
+ let claims;
3813
+ try {
3814
+ kind = sessionKind(state.catalog.provider, session);
3815
+ claims = claimsOf(session);
3816
+ } catch (error) {
3817
+ if (error instanceof CommandFailure && error.error.code !== "command.unauthenticated") throw error;
3818
+ if (!(error instanceof CommandFailure)) throw new CommandFailure(INTERNAL);
3819
+ throw new CommandFailure(FORBIDDEN$1);
3820
+ }
3821
+ if (kind !== "user" || hasActClaim(claims)) throw new CommandFailure(FORBIDDEN$1);
3822
+ if (!invitationIssueSchema.shape.secret.safeParse(secret).success) throw new CommandFailure({ code: "invitation.invalid" });
3823
+ const answer = await runAccept(state, session, await invitationSecretHash(secret));
3824
+ switch (answer.outcome) {
3825
+ case "accepted": return {
3826
+ scopeKind: answer.scopeKind,
3827
+ scope: answer.scope,
3828
+ member: answer.member
3829
+ };
3830
+ case "rate-limited": throw new CommandFailure({ code: "invitation.rate-limited" });
3831
+ case "failed": switch (answer.reason) {
3832
+ case "actor": throw new CommandFailure(FORBIDDEN$1);
3833
+ case "already-member": throw new CommandFailure({ code: "invitation.already-member" });
3834
+ default: throw new CommandFailure({ code: "invitation.invalid" });
3835
+ }
3836
+ }
3837
+ }
3838
+ const MY_SCOPES = {
3839
+ text: `SELECT s.scope_kind_id::text AS scope_kind, s.scope::text AS scope, s.member::text AS member FROM ${ident(PLATFORM_SCHEMA)}.${ident(RIGHTS_MY_SCOPES_FUNCTION_NAME)}() s ORDER BY 1, 2, 3`,
3840
+ params: []
3841
+ };
3842
+ const myScopeSchema = z.strictObject({
3843
+ scope_kind: z.guid(),
3844
+ scope: z.guid(),
3845
+ member: z.guid()
3846
+ });
3847
+ /**
3848
+ * Мої робочі простори (спека запрошень §7): лише про поточного користувача,
3849
+ * і корінь — тим самим серверним читанням під claims сесії, тож невидимий
3850
+ * корінь — `null`, без оракула наявності.
3851
+ */
3852
+ async function workspaces(state, session, origin) {
3853
+ if (originRefused(origin, WORKSPACES_REQUEST)) throw new CommandFailure(ORIGIN_REFUSED);
3854
+ rejectNested();
3855
+ requireInvitations(state);
3856
+ if (checkedKind(state.catalog.provider, session) === "anonymous") return [];
3857
+ const claims = claimsOf(session);
3858
+ const role = readRoleFor(state, session);
3859
+ const { catalog } = state;
3860
+ return inShortTransaction(state, BEGIN_READ, [readSetupStatement(claims, state.readTimeout, state.readBudgetMs + 1e3, role)], async (send) => {
3861
+ const { rows } = await send(MY_SCOPES);
3862
+ const out = [];
3863
+ for (const row of rows) {
3864
+ const mine = myScopeSchema.parse(row);
3865
+ const object = catalog.objects.find((o) => o.scopeKindId === mine.scope_kind && o.rights?.root !== void 0);
3866
+ out.push({
3867
+ scopeKind: mine.scope_kind,
3868
+ scope: mine.scope,
3869
+ member: mine.member,
3870
+ root: object === void 0 ? null : await rootRow(catalog, object, mine.scope, send)
3871
+ });
3872
+ }
3873
+ return out;
3874
+ });
3875
+ }
3876
+ /** Рядок кореня формою картки під роллю запиту; невидимий — `null`. */
3877
+ async function rootRow(catalog, object, scope, send) {
3878
+ const prepared = prepareRead(catalog, {
3879
+ object: {
3880
+ kind: object.kind,
3881
+ name: object.name
3882
+ },
3883
+ id: scope
3884
+ });
3885
+ if ("error" in prepared) throw new Error("root card read was refused");
3886
+ const value = await executeRead(prepared.object, prepared.plan, async (statement) => (await send(statement)).rows, null);
3887
+ if ("error" in value || !("rows" in value)) throw new Error("root card read answered no rows");
3888
+ const [row] = value.rows;
3889
+ return row === void 0 ? null : row;
3890
+ }
3543
3891
  /** Заморожує дані каталогу до дна: каталог — чисті дані JSON, без циклів. */
3544
3892
  function deepFreeze(value) {
3545
3893
  if (value !== null && typeof value === "object") {
@@ -4180,51 +4528,6 @@ function checkRead(index, wire) {
4180
4528
  if (![...query.where === void 0 ? [] : filterColumns(query.where, []), ...(query.orderBy ?? []).map((item) => item.attribute)].every((column) => target.has(column))) return stale(object);
4181
4529
  if (!(query.include ?? []).every((column) => header.has(column))) return stale(object);
4182
4530
  }
4183
- // src/server/origin.ts
4184
- const REFUSED = {
4185
- code: "command.forbidden",
4186
- reason: LIMIT_REASONS.origin
4187
- };
4188
- /**
4189
- * In-process calls may only read: `run` needs the facts of an HTTP request.
4190
- * The parts of a `read` are not looked at — every part only reads.
4191
- */
4192
- const IN_PROCESS_TYPES = /* @__PURE__ */ new Set(["read"]);
4193
- /**
4194
- * Step 0 of the data handler: refuses a request that could be forged by
4195
- * another site. Runs before the envelope is parsed, so it touches nothing but
4196
- * the origin facts (and, for `inProcess`, the raw request type).
4197
- *
4198
- * @returns the refusal, or `undefined` when the request may proceed.
4199
- */
4200
- function checkRequestOrigin(origin, rawRequest) {
4201
- if (isInProcess(origin)) return inProcessAllowed(rawRequest) ? void 0 : REFUSED;
4202
- return httpAllowed(origin) ? void 0 : REFUSED;
4203
- }
4204
- function isInProcess(origin) {
4205
- return origin.inProcess === true;
4206
- }
4207
- function httpAllowed(origin) {
4208
- if (!isCanonicalOrigin(origin.expectedOrigin)) return false;
4209
- if (origin.secFetchSite !== void 0 && origin.secFetchSite !== "same-origin") return false;
4210
- if (origin.origin !== void 0) return origin.origin === origin.expectedOrigin;
4211
- return origin.secFetchSite === "same-origin";
4212
- }
4213
- function isCanonicalOrigin(value) {
4214
- try {
4215
- return new URL(value).origin === value;
4216
- } catch {
4217
- return false;
4218
- }
4219
- }
4220
- function inProcessAllowed(rawRequest) {
4221
- try {
4222
- const type = rawRequest.request.type;
4223
- return typeof type === "string" && IN_PROCESS_TYPES.has(type);
4224
- } catch {
4225
- return false;
4226
- }
4227
- }
4228
4531
  // src/server/response-budget.ts
4229
4532
  /**
4230
4533
  * Бюджет відповіді (спека П4-B §4.1, крок 6 §4.5, Рд26). Міряється вся
@@ -4493,7 +4796,9 @@ const SECTIONS$1 = "tabularSections";
4493
4796
  * Fits a `run` result into the response budget (P4-B spec §4.5 step 6):
4494
4797
  * rows lose their lazy columns and tabular sections; if the whole
4495
4798
  * `DataResponse` still exceeds the budget, the result goes without `rows`
4496
- * and the client rereads by key. `changes` and `epoch` always go. Row `i` belongs to `operations[i]`
4799
+ * and the client rereads by key. A batch with `issueInvitation` keeps its
4800
+ * rows instead: the issue row whole (its secret cannot be read again), every
4801
+ * catalog row cut to its key and version (invitations spec §4). `changes` and `epoch` always go. Row `i` belongs to `operations[i]`
4497
4802
  * (`CommandResult.rows` — one row per input operation, in input order).
4498
4803
  *
4499
4804
  * `changes` never exceed the budget: there are at most `BATCH_MAX` batch
@@ -4516,7 +4821,9 @@ function fitRunResult(index, operations, result, serverHash) {
4516
4821
  lazy.set(object, columns);
4517
4822
  return columns;
4518
4823
  };
4824
+ const issues = operations.map((op) => op.action === "issueInvitation");
4519
4825
  const rows = result.rows.map((row, i) => {
4826
+ if (issues[i]) return row;
4520
4827
  const skip = lazyOf(operations[i].object);
4521
4828
  return Object.fromEntries(Object.entries(row).filter(([key]) => key !== SECTIONS$1 && !skip.has(key)));
4522
4829
  });
@@ -4526,7 +4833,17 @@ function fitRunResult(index, operations, result, serverHash) {
4526
4833
  changes,
4527
4834
  epoch
4528
4835
  };
4529
- return responseBytes(value, serverHash) <= RESPONSE_BUDGET_BYTES ? value : {
4836
+ if (responseBytes(value, serverHash) <= RESPONSE_BUDGET_BYTES) return value;
4837
+ if (!issues.includes(true)) return {
4838
+ changes,
4839
+ epoch
4840
+ };
4841
+ return {
4842
+ rows: rows.map((row, i) => {
4843
+ if (issues[i]) return row;
4844
+ const entry = index.byId.get(operations[i].object);
4845
+ return Object.fromEntries(Object.entries(row).filter(([key]) => key === entry.key || key === entry.versionColumn));
4846
+ }),
4530
4847
  changes,
4531
4848
  epoch
4532
4849
  };
@@ -4550,13 +4867,6 @@ const FORBIDDEN = {
4550
4867
  };
4551
4868
  const guid = z.guid();
4552
4869
  const SECTIONS = "tabularSections";
4553
- function originRefused(origin, request) {
4554
- try {
4555
- return checkRequestOrigin(origin, request) !== void 0;
4556
- } catch {
4557
- return true;
4558
- }
4559
- }
4560
4870
  /**
4561
4871
  * Запит старого розгортання: тип, якого сервер не знає (окремий `version`,
4562
4872
  * якого більше немає), чи `read` без `items` (одиночний `query`). Стара вкладка має
@@ -4801,18 +5111,24 @@ function createDataHandler(runtime, options = {}) {
4801
5111
  }
4802
5112
  const result = await runtime.run(claims, request.batch === void 0 ? logical[0] : logical, { fullTabularArrays: true });
4803
5113
  const rows = result.rows.map((row, i) => {
5114
+ if (operations[i]?.action === "issueInvitation") {
5115
+ if (!isInvitationIssue(row)) throw new Defect("issueInvitation row of a wrong shape");
5116
+ return row;
5117
+ }
4804
5118
  const entry = entryOf(index, operations[i]?.object);
4805
5119
  return encodeRow(entry, runHeader(entry, row));
4806
5120
  });
4807
5121
  const changes = mappedOrRefused(changesToWire(index, result.changes));
4808
5122
  if ("refused" in changes) throw new Defect(changes.refused);
5123
+ const value = fitRunResult(index, operations, {
5124
+ rows,
5125
+ changes: changes.value,
5126
+ epoch: result.epoch
5127
+ }, serverHash);
5128
+ if (operations.some((op) => op.action === "issueInvitation") && !wireRunResultFor(operations).safeParse(value).success) throw new Defect("run result does not match its issueInvitation rows");
4809
5129
  return {
4810
5130
  ok: true,
4811
- value: fitRunResult(index, operations, {
4812
- rows,
4813
- changes: changes.value,
4814
- epoch: result.epoch
4815
- }, serverHash),
5131
+ value,
4816
5132
  serverHash
4817
5133
  };
4818
5134
  }
@@ -4871,7 +5187,8 @@ const OPERATION_VERBS = {
4871
5187
  markDeletion: "remove",
4872
5188
  delete: "remove",
4873
5189
  publish: "write",
4874
- unpublish: "write"
5190
+ unpublish: "write",
5191
+ issueInvitation: "write"
4875
5192
  };
4876
5193
  /** Операції рантайму, які об'єкт каталогу має, у порядку `OBJECT_OPERATIONS`. */
4877
5194
  const operationsOf = (object) => OBJECT_OPERATIONS.filter((op) => object.operations?.[op] !== void 0);
@@ -4952,13 +5269,15 @@ var AgentWriteRefused = class extends Error {
4952
5269
  * The rights-write guard: a pure function over the runtime catalog and a batch,
4953
5270
  * so an adapter can call it before opening a pool. It refuses when any
4954
5271
  * operation of the batch (not only the first) touches a rights system catalog
4955
- * (its operations have the `administerRights` context) or creates a scope root
4956
- * with a creator. An object outside the catalog is skipped: the runtime schema
4957
- * rejects it. Without `rightsWrite` the refusal comes before the database.
5272
+ * (its operations have the `administerRights` context), creates a scope root
5273
+ * with a creator or issues an invitation. An object outside the catalog is
5274
+ * skipped: the runtime schema rejects it. Without `rightsWrite` the refusal
5275
+ * comes before the database.
4958
5276
  */
4959
5277
  function agentWriteRefusal(catalog, batch, permissions) {
4960
5278
  if (permissions.rightsWrite) return void 0;
4961
5279
  for (const op of batch) {
5280
+ if (op.action === "issueInvitation") return { object: op.object };
4962
5281
  const object = catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name);
4963
5282
  if (object === void 0) continue;
4964
5283
  if (Object.values(object.operations ?? {}).some((target) => target.context === "administerRights")) return { object: op.object };
@@ -5028,6 +5347,10 @@ const AGENT_OUTCOMES = {
5028
5347
  "command.busy": "retry",
5029
5348
  "command.stale-client": "retry",
5030
5349
  "command.internal": "ask_user",
5350
+ "invitation.invalid": "ask_user",
5351
+ "invitation.already-member": "ask_user",
5352
+ "invitation.rate-limited": "retry",
5353
+ "invitation.not-pending": "ask_user",
5031
5354
  "catalog.invalid-input": "fix_input",
5032
5355
  "catalog.unknown-tool": "fix_input",
5033
5356
  "catalog.unknown-object": "fix_input",
@@ -5053,6 +5376,10 @@ const HINTS = {
5053
5376
  "command.busy": "The service is busy. Retry in a moment.",
5054
5377
  "command.stale-client": "The catalog is out of date. Call describe again, then retry.",
5055
5378
  "command.internal": "An internal error occurred. Ask the user to check the server log.",
5379
+ "invitation.invalid": "The invitation is not valid. Ask the user to request a new one.",
5380
+ "invitation.already-member": "The user is already a member. Ask the user to continue in the application.",
5381
+ "invitation.rate-limited": "Too many failed attempts. Retry later.",
5382
+ "invitation.not-pending": "The member already has a user or is marked for deletion, so no invitation can be issued. Ask the user to choose another member.",
5056
5383
  "catalog.invalid-input": "The input does not match the tool schema. Fix the field named in path and resend.",
5057
5384
  "catalog.unknown-tool": "There is no such tool. Use one of the listed tools.",
5058
5385
  "catalog.unknown-object": "There is no such object. Call describe without arguments to list the objects.",