simetra 0.3.0-next.7 → 0.3.0-next.9

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`. */
@@ -2342,6 +2429,7 @@ function callOf({ object, target }, op, draft, byFields) {
2342
2429
  text: `SELECT ${fn(target)}($1::uuid, $2::bigint) AS r`,
2343
2430
  params: [op.id, String(op.expectedVersion)]
2344
2431
  };
2432
+ case "issueInvitation": throw new Error("internal: issueInvitation outside its phase");
2345
2433
  }
2346
2434
  }
2347
2435
  const CONTEXT_TEXT = `SELECT pg_catalog.set_config(${literal(COMMAND_SETTING)}, $1, true)`;
@@ -2483,6 +2571,7 @@ async function onWrite(tx, phase, module, row) {
2483
2571
  async function runPhase(tx, op, fullTabularArrays = false) {
2484
2572
  const found = targetOf(tx.state.catalog, op);
2485
2573
  if ("error" in found) tx.abort(found.error);
2574
+ if (op.action === "issueInvitation") return runIssuePhase(tx, found, op);
2486
2575
  const creation = rootCreateOf(tx.state.catalog, found.object, op);
2487
2576
  if (creation !== void 0) return runRootPhase(tx, found, op, creation);
2488
2577
  const { object } = found;
@@ -2568,6 +2657,47 @@ async function runRootPhase(tx, found, op, { membership }) {
2568
2657
  if (member !== void 0) await onWrite(tx, member.phase, member.module, memberRow);
2569
2658
  return rootRow.row;
2570
2659
  }
2660
+ /** Рядок ядра видачі: строк дії запису, як його записала база. */
2661
+ const issueCoreSchema = z.strictObject({ expiresAt: z.string().min(1) });
2662
+ /**
2663
+ * Фаза видачі запрошення (спека запрошень §4, Р-З1-10): без хуків довідника
2664
+ * членства, без декодування рядка каталогу, без запису в набір змін і без
2665
+ * сигналу — рядка вона не змінює. Секрет T3 генерує сам; база отримує лише
2666
+ * його хеш, а секрет іде тільки в рядок результату `{ secret, expiresAt }`.
2667
+ * Сесія з `act` — відмова до ядра: секрет ліг би в контекст агента;
2668
+ * `invitation_put` перевіряє те саме ще раз.
2669
+ */
2670
+ async function runIssuePhase(tx, found, op) {
2671
+ const { object, target } = found;
2672
+ if (tx.actClaim) tx.abort(issueForbidden(op.object));
2673
+ const secret = newInvitationSecret();
2674
+ const call = {
2675
+ text: `SELECT ${fn(target)}($1::uuid, pg_catalog.decode($2, 'hex')) AS r`,
2676
+ params: [op.id, await invitationSecretHash(secret)]
2677
+ };
2678
+ const { rows } = await tx.enqueue([contextOf(found, op), call], writePhase(object, op));
2679
+ const text = rows[0]?.r;
2680
+ let parsed;
2681
+ try {
2682
+ parsed = typeof text === "string" ? issueCoreSchema.safeParse(JSON.parse(text)) : void 0;
2683
+ } catch {
2684
+ parsed = void 0;
2685
+ }
2686
+ if (parsed?.success !== true) coreAnomaly(tx, object);
2687
+ return {
2688
+ secret,
2689
+ expiresAt: parsed.data.expiresAt
2690
+ };
2691
+ }
2692
+ /** Відмова видачі в сесії з claim `act` (спека запрошень §4, крок 2). */
2693
+ const issueForbidden = (object) => ({
2694
+ code: "command.forbidden",
2695
+ object: {
2696
+ kind: object.kind,
2697
+ name: object.name
2698
+ },
2699
+ operation: "issueInvitation"
2700
+ });
2571
2701
  /** Фаза відмови запису: оператори сигналу фази мапляться як її запис. */
2572
2702
  const writePhase = (object, op) => ({
2573
2703
  kind: "write",
@@ -2835,6 +2965,11 @@ var Transaction = class {
2835
2965
  /** The current user of the attempt (step 4 of §6.5). */
2836
2966
  user = "";
2837
2967
  act;
2968
+ /**
2969
+ * Claims сесії несуть ключ `act` за будь-якого значення — правило SQL
2970
+ * (`claims ? 'act'`), а не лише `act` з рядковим `sub`.
2971
+ */
2972
+ actClaim = false;
2838
2973
  /** Фази, які вже почав `ctx.run` у цій спробі (межа `BATCH_MAX`, Ф1). */
2839
2974
  nestedPhases = 0;
2840
2975
  /**
@@ -3022,6 +3157,7 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3022
3157
  }
3023
3158
  const tx = new Transaction(client, state, deadline);
3024
3159
  tx.act = act;
3160
+ tx.actClaim = hasActClaim(claims);
3025
3161
  const rows = [];
3026
3162
  let epoch = "";
3027
3163
  let tag;
@@ -3066,33 +3202,10 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3066
3202
  return (await tx.enqueue([COMMIT])).command;
3067
3203
  });
3068
3204
  } 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
- } };
3205
+ return failedAttempt(tx, client, error);
3095
3206
  }
3207
+ const refused = committed(client, state, tag);
3208
+ if (refused !== void 0) return refused;
3096
3209
  return {
3097
3210
  result: {
3098
3211
  rows,
@@ -3102,6 +3215,37 @@ async function attempt(state, command, claims, act, ops, deadline, fullTabularAr
3102
3215
  afterCommit: tx.afterCommit
3103
3216
  };
3104
3217
  }
3218
+ /** Невдала спроба: відмова черги чи непередбачений виняток — завершення з'єднання. */
3219
+ async function failedAttempt(tx, client, error) {
3220
+ if (tx.terminal === void 0) {
3221
+ if (error instanceof CommandFailure) tx.close({
3222
+ failure: error,
3223
+ retry: false,
3224
+ destroy: false
3225
+ });
3226
+ else try {
3227
+ tx.anomaly(error);
3228
+ } catch {}
3229
+ }
3230
+ await tx.settled();
3231
+ const terminal = tx.terminal;
3232
+ await endFailed(client, terminal.destroy);
3233
+ return { terminal };
3234
+ }
3235
+ /** Звільнення після `COMMIT`; тег, що не `COMMIT`, — відмова, а не успіх. */
3236
+ function committed(client, state, tag) {
3237
+ releaseCommitted(client, state.log);
3238
+ if (tag === "COMMIT") return void 0;
3239
+ state.log({
3240
+ kind: "database",
3241
+ error: /* @__PURE__ */ new Error(`COMMIT answered ${tag}`)
3242
+ });
3243
+ return { terminal: {
3244
+ failure: new CommandFailure(INTERNAL$1),
3245
+ retry: false,
3246
+ destroy: false
3247
+ } };
3248
+ }
3105
3249
  /**
3106
3250
  * Runs `afterCommit` actions in order; a failing action is logged and the
3107
3251
  * next one still runs.
@@ -3173,6 +3317,21 @@ var FileAttachFailure = class extends CommandFailure {
3173
3317
  this.name = "FileAttachFailure";
3174
3318
  }
3175
3319
  };
3320
+ /**
3321
+ * Чи несуть claims ключ `act` — та сама умова, що в SQL видачі й прийняття
3322
+ * (`claims ? 'act'`): за серіалізованим текстом, який отримає база. Функція
3323
+ * тотальна: її кличуть і поза `try` спроби, а `JSON.stringify` нетипізованої
3324
+ * сесії дає `undefined`. Нерозбірні claims — як з `act` (fail-closed): ознака
3325
+ * лише забороняє видачу.
3326
+ */
3327
+ function hasActClaim(claims) {
3328
+ try {
3329
+ const parsed = JSON.parse(claims);
3330
+ return isPlainObject(parsed) && Object.hasOwn(parsed, "act");
3331
+ } catch {
3332
+ return true;
3333
+ }
3334
+ }
3176
3335
  /** A command: validation, attempts with retry, then `afterCommit` (§6.5). */
3177
3336
  async function runCommand(state, session, input, fullTabularArrays = false) {
3178
3337
  rejectNested();
@@ -3189,10 +3348,91 @@ async function runCommand(state, session, input, fullTabularArrays = false) {
3189
3348
  } catch {
3190
3349
  throw new CommandFailure(INTERNAL$1);
3191
3350
  }
3351
+ const issue = ops.find((op) => op.action === "issueInvitation");
3352
+ if (issue !== void 0 && hasActClaim(claims)) throw new CommandFailure(issueForbidden(issue.object));
3192
3353
  const snapshot = structuredClone(ops);
3193
3354
  const act = typeof session.act?.sub === "string" ? { sub: session.act.sub } : void 0;
3194
3355
  return settleOutcome(state, await runAttempts(state, (command, deadline) => attempt(state, command, claims, act, structuredClone(snapshot), deadline, fullTabularArrays)));
3195
3356
  }
3357
+ const ACCEPT_TEXT = `SELECT ${ident(PLATFORM_SCHEMA)}.${ident(INVITATION_ACCEPT_FUNCTION_NAME)}(pg_catalog.decode($1, 'hex'))::text AS r`;
3358
+ /**
3359
+ * Відповідь `invitation_accept` (спека запрошень §5): причини `failed` —
3360
+ * лише ті, що пише функція; інша відповідь — аномалія з відкатом, а не
3361
+ * зафіксована невідома відмова.
3362
+ */
3363
+ const acceptAnswerSchema = z.discriminatedUnion("outcome", [
3364
+ z.strictObject({
3365
+ outcome: z.literal("accepted"),
3366
+ scopeKind: z.guid(),
3367
+ scope: z.guid(),
3368
+ member: z.guid()
3369
+ }),
3370
+ z.strictObject({
3371
+ outcome: z.literal("failed"),
3372
+ reason: z.enum([
3373
+ "actor",
3374
+ "unknown",
3375
+ "expired",
3376
+ "member-gone",
3377
+ "changed",
3378
+ "already-member"
3379
+ ])
3380
+ }),
3381
+ z.strictObject({
3382
+ outcome: z.literal("rate-limited"),
3383
+ reason: z.literal("rate-limited")
3384
+ })
3385
+ ]);
3386
+ /**
3387
+ * Прийняття запрошення у власній транзакції команди (спека запрошень §5):
3388
+ * claims, роль команд і одразу функція — жодного оператора, що взяв би
3389
+ * знімок актора раніше (функція тоді відмовила б `rights-context`). Кожна
3390
+ * відповідь функції фіксується: рядок `failed` журналу й лік спроб мусять
3391
+ * пережити відмову. Повтор — на серіалізації й взаємному блокуванні, як у
3392
+ * `run`; `hash` — hex `sha256` тексту секрету.
3393
+ */
3394
+ async function runAccept(state, session, hash) {
3395
+ rejectNested();
3396
+ let claims;
3397
+ try {
3398
+ claims = JSON.stringify(session);
3399
+ } catch {
3400
+ throw new CommandFailure(INTERNAL$1);
3401
+ }
3402
+ const outcome = await runAttempts(state, (_, deadline) => acceptAttempt(state, claims, hash, deadline));
3403
+ if ("terminal" in outcome) throw outcome.terminal.failure;
3404
+ return outcome.answer;
3405
+ }
3406
+ async function acceptAttempt(state, claims, hash, deadline) {
3407
+ let client;
3408
+ try {
3409
+ client = await state.database.connect();
3410
+ } catch (raw) {
3411
+ return { terminal: terminalOf(raw, state, void 0, false, normalizeError(raw, true)) };
3412
+ }
3413
+ const tx = new Transaction(client, state, deadline);
3414
+ let answer;
3415
+ let tag;
3416
+ try {
3417
+ await tx.enqueue([BEGIN]);
3418
+ await tx.claims(claims);
3419
+ await tx.enqueue([COMMAND_ROLE]);
3420
+ const { rows } = await tx.enqueue([statement(ACCEPT_TEXT, hash)]);
3421
+ const text = rows[0]?.r;
3422
+ let parsed;
3423
+ try {
3424
+ parsed = typeof text === "string" ? acceptAnswerSchema.safeParse(JSON.parse(text)) : void 0;
3425
+ } catch {
3426
+ parsed = void 0;
3427
+ }
3428
+ if (parsed?.success !== true) tx.anomaly(/* @__PURE__ */ new Error("invitation_accept answered no known outcome"));
3429
+ answer = parsed.data;
3430
+ ({command: tag} = await tx.enqueue([COMMIT]));
3431
+ } catch (error) {
3432
+ return failedAttempt(tx, client, error);
3433
+ }
3434
+ return committed(client, state, tag) ?? { answer };
3435
+ }
3196
3436
  /**
3197
3437
  * `attachFile` (спека профілю postgres §8.2 крок 4): одна внутрішня фаза
3198
3438
  * `create` рядка файлу з записом `file_attach` перед нею, у спробах і з
@@ -3537,9 +3777,111 @@ async function createCommandRuntime(options) {
3537
3777
  rejectNested();
3538
3778
  if (await inRecovery(state)) throw new FileStoreError("in-recovery", "the database is in recovery: rebind on the primary");
3539
3779
  await store.rebind(await fileInstance(state));
3540
- }
3780
+ },
3781
+ acceptInvitation: (session, secret, origin) => acceptInvitation(state, session, secret, origin),
3782
+ workspaces: (session, origin) => workspaces(state, session, origin)
3541
3783
  };
3542
3784
  }
3785
+ const ACCEPT_REQUEST = { request: { type: "acceptInvitation" } };
3786
+ const WORKSPACES_REQUEST = { request: { type: "read" } };
3787
+ const ORIGIN_REFUSED = {
3788
+ code: "command.forbidden",
3789
+ reason: LIMIT_REASONS.origin
3790
+ };
3791
+ const FORBIDDEN$1 = { code: "command.forbidden" };
3792
+ /** Без прапорця каталогу запрошень немає ні функції прийняття, ні методів. */
3793
+ function requireInvitations(state) {
3794
+ if (state.catalog.invitations !== true) throw new CommandFailure({ code: "command.invalid" });
3795
+ }
3796
+ /**
3797
+ * Прийняття запрошення (спека запрошень §5): походження — першим, бо чужий
3798
+ * секрет, підсунутий з іншого походження, ввів би жертву до чужого тенанта;
3799
+ * далі все, що відомо без бази, і лише тоді хеш і транзакція команди.
3800
+ */
3801
+ async function acceptInvitation(state, session, secret, origin) {
3802
+ if (originRefused(origin, ACCEPT_REQUEST)) throw new CommandFailure(ORIGIN_REFUSED);
3803
+ rejectNested();
3804
+ requireInvitations(state);
3805
+ let kind;
3806
+ let claims;
3807
+ try {
3808
+ kind = sessionKind(state.catalog.provider, session);
3809
+ claims = claimsOf(session);
3810
+ } catch (error) {
3811
+ if (error instanceof CommandFailure && error.error.code !== "command.unauthenticated") throw error;
3812
+ if (!(error instanceof CommandFailure)) throw new CommandFailure(INTERNAL);
3813
+ throw new CommandFailure(FORBIDDEN$1);
3814
+ }
3815
+ if (kind !== "user" || hasActClaim(claims)) throw new CommandFailure(FORBIDDEN$1);
3816
+ if (!invitationIssueSchema.shape.secret.safeParse(secret).success) throw new CommandFailure({ code: "invitation.invalid" });
3817
+ const answer = await runAccept(state, session, await invitationSecretHash(secret));
3818
+ switch (answer.outcome) {
3819
+ case "accepted": return {
3820
+ scopeKind: answer.scopeKind,
3821
+ scope: answer.scope,
3822
+ member: answer.member
3823
+ };
3824
+ case "rate-limited": throw new CommandFailure({ code: "invitation.rate-limited" });
3825
+ case "failed": switch (answer.reason) {
3826
+ case "actor": throw new CommandFailure(FORBIDDEN$1);
3827
+ case "already-member": throw new CommandFailure({ code: "invitation.already-member" });
3828
+ default: throw new CommandFailure({ code: "invitation.invalid" });
3829
+ }
3830
+ }
3831
+ }
3832
+ const MY_SCOPES = {
3833
+ 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`,
3834
+ params: []
3835
+ };
3836
+ const myScopeSchema = z.strictObject({
3837
+ scope_kind: z.guid(),
3838
+ scope: z.guid(),
3839
+ member: z.guid()
3840
+ });
3841
+ /**
3842
+ * Мої робочі простори (спека запрошень §7): лише про поточного користувача,
3843
+ * і корінь — тим самим серверним читанням під claims сесії, тож невидимий
3844
+ * корінь — `null`, без оракула наявності.
3845
+ */
3846
+ async function workspaces(state, session, origin) {
3847
+ if (originRefused(origin, WORKSPACES_REQUEST)) throw new CommandFailure(ORIGIN_REFUSED);
3848
+ rejectNested();
3849
+ requireInvitations(state);
3850
+ if (checkedKind(state.catalog.provider, session) === "anonymous") return [];
3851
+ const claims = claimsOf(session);
3852
+ const role = readRoleFor(state, session);
3853
+ const { catalog } = state;
3854
+ return inShortTransaction(state, BEGIN_READ, [readSetupStatement(claims, state.readTimeout, state.readBudgetMs + 1e3, role)], async (send) => {
3855
+ const { rows } = await send(MY_SCOPES);
3856
+ const out = [];
3857
+ for (const row of rows) {
3858
+ const mine = myScopeSchema.parse(row);
3859
+ const object = catalog.objects.find((o) => o.scopeKindId === mine.scope_kind && o.rights?.root !== void 0);
3860
+ out.push({
3861
+ scopeKind: mine.scope_kind,
3862
+ scope: mine.scope,
3863
+ member: mine.member,
3864
+ root: object === void 0 ? null : await rootRow(catalog, object, mine.scope, send)
3865
+ });
3866
+ }
3867
+ return out;
3868
+ });
3869
+ }
3870
+ /** Рядок кореня формою картки під роллю запиту; невидимий — `null`. */
3871
+ async function rootRow(catalog, object, scope, send) {
3872
+ const prepared = prepareRead(catalog, {
3873
+ object: {
3874
+ kind: object.kind,
3875
+ name: object.name
3876
+ },
3877
+ id: scope
3878
+ });
3879
+ if ("error" in prepared) throw new Error("root card read was refused");
3880
+ const value = await executeRead(prepared.object, prepared.plan, async (statement) => (await send(statement)).rows, null);
3881
+ if ("error" in value || !("rows" in value)) throw new Error("root card read answered no rows");
3882
+ const [row] = value.rows;
3883
+ return row === void 0 ? null : row;
3884
+ }
3543
3885
  /** Заморожує дані каталогу до дна: каталог — чисті дані JSON, без циклів. */
3544
3886
  function deepFreeze(value) {
3545
3887
  if (value !== null && typeof value === "object") {
@@ -4180,51 +4522,6 @@ function checkRead(index, wire) {
4180
4522
  if (![...query.where === void 0 ? [] : filterColumns(query.where, []), ...(query.orderBy ?? []).map((item) => item.attribute)].every((column) => target.has(column))) return stale(object);
4181
4523
  if (!(query.include ?? []).every((column) => header.has(column))) return stale(object);
4182
4524
  }
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
4525
  // src/server/response-budget.ts
4229
4526
  /**
4230
4527
  * Бюджет відповіді (спека П4-B §4.1, крок 6 §4.5, Рд26). Міряється вся
@@ -4493,7 +4790,9 @@ const SECTIONS$1 = "tabularSections";
4493
4790
  * Fits a `run` result into the response budget (P4-B spec §4.5 step 6):
4494
4791
  * rows lose their lazy columns and tabular sections; if the whole
4495
4792
  * `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]`
4793
+ * and the client rereads by key. A batch with `issueInvitation` keeps its
4794
+ * rows instead: the issue row whole (its secret cannot be read again), every
4795
+ * catalog row cut to its key and version (invitations spec §4). `changes` and `epoch` always go. Row `i` belongs to `operations[i]`
4497
4796
  * (`CommandResult.rows` — one row per input operation, in input order).
4498
4797
  *
4499
4798
  * `changes` never exceed the budget: there are at most `BATCH_MAX` batch
@@ -4516,7 +4815,9 @@ function fitRunResult(index, operations, result, serverHash) {
4516
4815
  lazy.set(object, columns);
4517
4816
  return columns;
4518
4817
  };
4818
+ const issues = operations.map((op) => op.action === "issueInvitation");
4519
4819
  const rows = result.rows.map((row, i) => {
4820
+ if (issues[i]) return row;
4520
4821
  const skip = lazyOf(operations[i].object);
4521
4822
  return Object.fromEntries(Object.entries(row).filter(([key]) => key !== SECTIONS$1 && !skip.has(key)));
4522
4823
  });
@@ -4526,7 +4827,17 @@ function fitRunResult(index, operations, result, serverHash) {
4526
4827
  changes,
4527
4828
  epoch
4528
4829
  };
4529
- return responseBytes(value, serverHash) <= RESPONSE_BUDGET_BYTES ? value : {
4830
+ if (responseBytes(value, serverHash) <= RESPONSE_BUDGET_BYTES) return value;
4831
+ if (!issues.includes(true)) return {
4832
+ changes,
4833
+ epoch
4834
+ };
4835
+ return {
4836
+ rows: rows.map((row, i) => {
4837
+ if (issues[i]) return row;
4838
+ const entry = index.byId.get(operations[i].object);
4839
+ return Object.fromEntries(Object.entries(row).filter(([key]) => key === entry.key || key === entry.versionColumn));
4840
+ }),
4530
4841
  changes,
4531
4842
  epoch
4532
4843
  };
@@ -4550,13 +4861,6 @@ const FORBIDDEN = {
4550
4861
  };
4551
4862
  const guid = z.guid();
4552
4863
  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
4864
  /**
4561
4865
  * Запит старого розгортання: тип, якого сервер не знає (окремий `version`,
4562
4866
  * якого більше немає), чи `read` без `items` (одиночний `query`). Стара вкладка має
@@ -4801,18 +5105,24 @@ function createDataHandler(runtime, options = {}) {
4801
5105
  }
4802
5106
  const result = await runtime.run(claims, request.batch === void 0 ? logical[0] : logical, { fullTabularArrays: true });
4803
5107
  const rows = result.rows.map((row, i) => {
5108
+ if (operations[i]?.action === "issueInvitation") {
5109
+ if (!isInvitationIssue(row)) throw new Defect("issueInvitation row of a wrong shape");
5110
+ return row;
5111
+ }
4804
5112
  const entry = entryOf(index, operations[i]?.object);
4805
5113
  return encodeRow(entry, runHeader(entry, row));
4806
5114
  });
4807
5115
  const changes = mappedOrRefused(changesToWire(index, result.changes));
4808
5116
  if ("refused" in changes) throw new Defect(changes.refused);
5117
+ const value = fitRunResult(index, operations, {
5118
+ rows,
5119
+ changes: changes.value,
5120
+ epoch: result.epoch
5121
+ }, serverHash);
5122
+ if (operations.some((op) => op.action === "issueInvitation") && !wireRunResultFor(operations).safeParse(value).success) throw new Defect("run result does not match its issueInvitation rows");
4809
5123
  return {
4810
5124
  ok: true,
4811
- value: fitRunResult(index, operations, {
4812
- rows,
4813
- changes: changes.value,
4814
- epoch: result.epoch
4815
- }, serverHash),
5125
+ value,
4816
5126
  serverHash
4817
5127
  };
4818
5128
  }
@@ -4871,7 +5181,8 @@ const OPERATION_VERBS = {
4871
5181
  markDeletion: "remove",
4872
5182
  delete: "remove",
4873
5183
  publish: "write",
4874
- unpublish: "write"
5184
+ unpublish: "write",
5185
+ issueInvitation: "write"
4875
5186
  };
4876
5187
  /** Операції рантайму, які об'єкт каталогу має, у порядку `OBJECT_OPERATIONS`. */
4877
5188
  const operationsOf = (object) => OBJECT_OPERATIONS.filter((op) => object.operations?.[op] !== void 0);
@@ -4952,13 +5263,15 @@ var AgentWriteRefused = class extends Error {
4952
5263
  * The rights-write guard: a pure function over the runtime catalog and a batch,
4953
5264
  * so an adapter can call it before opening a pool. It refuses when any
4954
5265
  * 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.
5266
+ * (its operations have the `administerRights` context), creates a scope root
5267
+ * with a creator or issues an invitation. An object outside the catalog is
5268
+ * skipped: the runtime schema rejects it. Without `rightsWrite` the refusal
5269
+ * comes before the database.
4958
5270
  */
4959
5271
  function agentWriteRefusal(catalog, batch, permissions) {
4960
5272
  if (permissions.rightsWrite) return void 0;
4961
5273
  for (const op of batch) {
5274
+ if (op.action === "issueInvitation") return { object: op.object };
4962
5275
  const object = catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name);
4963
5276
  if (object === void 0) continue;
4964
5277
  if (Object.values(object.operations ?? {}).some((target) => target.context === "administerRights")) return { object: op.object };
@@ -5028,6 +5341,10 @@ const AGENT_OUTCOMES = {
5028
5341
  "command.busy": "retry",
5029
5342
  "command.stale-client": "retry",
5030
5343
  "command.internal": "ask_user",
5344
+ "invitation.invalid": "ask_user",
5345
+ "invitation.already-member": "ask_user",
5346
+ "invitation.rate-limited": "retry",
5347
+ "invitation.not-pending": "ask_user",
5031
5348
  "catalog.invalid-input": "fix_input",
5032
5349
  "catalog.unknown-tool": "fix_input",
5033
5350
  "catalog.unknown-object": "fix_input",
@@ -5053,6 +5370,10 @@ const HINTS = {
5053
5370
  "command.busy": "The service is busy. Retry in a moment.",
5054
5371
  "command.stale-client": "The catalog is out of date. Call describe again, then retry.",
5055
5372
  "command.internal": "An internal error occurred. Ask the user to check the server log.",
5373
+ "invitation.invalid": "The invitation is not valid. Ask the user to request a new one.",
5374
+ "invitation.already-member": "The user is already a member. Ask the user to continue in the application.",
5375
+ "invitation.rate-limited": "Too many failed attempts. Retry later.",
5376
+ "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
5377
  "catalog.invalid-input": "The input does not match the tool schema. Fix the field named in path and resend.",
5057
5378
  "catalog.unknown-tool": "There is no such tool. Use one of the listed tools.",
5058
5379
  "catalog.unknown-object": "There is no such object. Call describe without arguments to list the objects.",