@miniaxolotl/grove-server 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -13,7 +13,7 @@ var __export = (target, all) => {
13
13
  var define_GROVE_TELEMETRY_default;
14
14
  var init_define_GROVE_TELEMETRY = __esm({
15
15
  "<define:__GROVE_TELEMETRY__>"() {
16
- define_GROVE_TELEMETRY_default = { enabled: true, revision: "e57cec9680190df3d16d57c722349052fb2a6aba", version: "1.9.0", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
16
+ define_GROVE_TELEMETRY_default = { enabled: true, revision: "cb9b1a44ac8afee6d1c1aafd0f8a34e30c1e8d52", version: "1.10.0", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
17
17
  }
18
18
  });
19
19
 
@@ -2642,6 +2642,97 @@ var publicSharing = {
2642
2642
  }
2643
2643
  };
2644
2644
 
2645
+ // lib/database/src/share-expiration-migration.ts
2646
+ init_define_GROVE_TELEMETRY();
2647
+ var shareExpiration = {
2648
+ name: "20261022_012_share_expiration",
2649
+ async up(db) {
2650
+ await db.raw(`
2651
+ ALTER TABLE public_shares
2652
+ ADD COLUMN duration text CHECK (duration IN ('1h','4h','1d','1w','2w','1mo')),
2653
+ ADD COLUMN expires_at timestamptz,
2654
+ ADD CONSTRAINT public_shares_expiration CHECK ((duration IS NULL) = (expires_at IS NULL));
2655
+
2656
+ CREATE OR REPLACE FUNCTION grove_public_share(
2657
+ secret_digest text, requested_kind text, requested_id uuid,
2658
+ after_id uuid, cursor_share uuid, cursor_version integer, page_size integer
2659
+ ) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$
2660
+ DECLARE link public_shares; owner_id uuid; permitted uuid[]; selected uuid;
2661
+ root_name text; notebook_name text; note memories; result jsonb; page jsonb; children jsonb;
2662
+ BEGIN
2663
+ IF page_size IS NULL OR page_size < 1 OR page_size > 100
2664
+ OR requested_kind IS NULL OR requested_kind NOT IN ('root', 'note', 'notebook') THEN RETURN NULL; END IF;
2665
+ SELECT account_id INTO owner_id FROM public_shares WHERE token_digest = secret_digest AND revoked_at IS NULL;
2666
+ IF owner_id IS NULL THEN RETURN NULL; END IF;
2667
+ -- Keep account-first locking. Wall-clock expiry must be checked AFTER a
2668
+ -- blocked reader acquires its locks, not against transaction-start now().
2669
+ PERFORM 1 FROM accounts WHERE id = owner_id AND status = 'active' FOR SHARE;
2670
+ IF NOT FOUND THEN RETURN NULL; END IF;
2671
+ SELECT * INTO link FROM public_shares WHERE account_id = owner_id
2672
+ AND token_digest = secret_digest AND revoked_at IS NULL FOR SHARE;
2673
+ IF NOT FOUND THEN RETURN NULL; END IF;
2674
+ IF link.expires_at IS NOT NULL AND link.expires_at <= clock_timestamp() THEN RETURN NULL; END IF;
2675
+ IF NOT grove_share_admit(link.id::text) THEN RETURN jsonb_build_object('limited', true); END IF;
2676
+ IF cursor_share IS NOT NULL AND (cursor_share <> link.id OR cursor_version IS DISTINCT FROM link.version)
2677
+ THEN RETURN jsonb_build_object('stale', true); END IF;
2678
+ IF link.project_id IS NOT NULL THEN
2679
+ WITH RECURSIVE scope(id) AS (
2680
+ SELECT id FROM projects WHERE account_id = owner_id AND id = link.project_id
2681
+ UNION
2682
+ SELECT p.id FROM projects p JOIN scope s ON p.parent_id = s.id
2683
+ WHERE p.account_id = owner_id AND link.include_descendants
2684
+ ) SELECT array_agg(id) INTO permitted FROM scope;
2685
+ SELECT name INTO root_name FROM projects WHERE account_id = owner_id AND id = link.project_id;
2686
+ IF root_name IS NULL THEN RETURN NULL; END IF;
2687
+ ELSE
2688
+ SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = link.memory_id
2689
+ AND status = 'active' AND (expires_at IS NULL OR expires_at > now());
2690
+ IF NOT FOUND THEN RETURN NULL; END IF;
2691
+ root_name := left(regexp_replace(split_part(trim(note.content), E'\\n', 1), '^#{1,6}\\s+', ''), 110);
2692
+ END IF;
2693
+ result := jsonb_build_object('shareId', link.id, 'shareVersion', link.version,
2694
+ 'kind', CASE WHEN link.memory_id IS NULL THEN 'notebook' ELSE 'note' END,
2695
+ 'root', jsonb_build_object('id', coalesce(link.project_id, link.memory_id), 'name', root_name),
2696
+ 'notebook', NULL, 'note', NULL, 'notebooks', '[]'::jsonb, 'notes', '[]'::jsonb);
2697
+ IF requested_kind = 'note' OR (requested_kind = 'root' AND link.memory_id IS NOT NULL) THEN
2698
+ selected := CASE WHEN requested_kind = 'root' THEN link.memory_id ELSE requested_id END;
2699
+ SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = selected
2700
+ AND (id = link.memory_id OR project_id = ANY(permitted))
2701
+ AND status = 'active' AND (expires_at IS NULL OR expires_at > now());
2702
+ IF NOT FOUND THEN RETURN NULL; END IF;
2703
+ SELECT coalesce(jsonb_agg(m.id), '[]'::jsonb) INTO page FROM memories m
2704
+ WHERE m.account_id = owner_id AND (m.id = link.memory_id OR m.project_id = ANY(permitted))
2705
+ AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())
2706
+ AND m.id IN (SELECT matches[1]::uuid FROM regexp_matches(note.content,
2707
+ '/app/memories/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})', 'g') AS matches);
2708
+ RETURN result || jsonb_build_object('note', jsonb_build_object('id', note.id,
2709
+ 'title', left(regexp_replace(split_part(trim(note.content), E'\\n', 1), '^#{1,6}\\s+', ''), 110),
2710
+ 'content', note.content, 'updatedAt', note.updated_at, 'linkedNoteIds', page));
2711
+ END IF;
2712
+ selected := CASE WHEN requested_kind = 'root' THEN link.project_id ELSE requested_id END;
2713
+ IF selected IS NULL OR NOT (selected = ANY(permitted)) OR permitted IS NULL THEN RETURN NULL; END IF;
2714
+ SELECT name INTO notebook_name FROM projects WHERE account_id = owner_id AND id = selected;
2715
+ SELECT coalesce(jsonb_agg(jsonb_build_object('id', p.id, 'name', p.name) ORDER BY p.name, p.id), '[]'::jsonb)
2716
+ INTO children FROM projects p WHERE p.account_id = owner_id AND p.parent_id = selected AND p.id = ANY(permitted);
2717
+ SELECT coalesce(jsonb_agg(jsonb_build_object('id', m.id,
2718
+ 'title', left(regexp_replace(split_part(trim(m.content), E'\\n', 1), '^#{1,6}\\s+', ''), 110),
2719
+ 'updatedAt', m.updated_at) ORDER BY m.id), '[]'::jsonb) INTO page FROM (
2720
+ SELECT id, content, updated_at FROM memories WHERE account_id = owner_id AND project_id = selected
2721
+ AND status = 'active' AND (expires_at IS NULL OR expires_at > now())
2722
+ AND (after_id IS NULL OR id > after_id) ORDER BY id LIMIT page_size + 1
2723
+ ) m;
2724
+ RETURN result || jsonb_build_object('notebook', jsonb_build_object('id', selected, 'name', notebook_name),
2725
+ 'notebooks', children, 'notes', page);
2726
+ END $$;
2727
+ REVOKE ALL ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) FROM PUBLIC;
2728
+ GRANT EXECUTE ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) TO grove_runtime;
2729
+ `);
2730
+ },
2731
+ async down() {
2732
+ throw new Error("Use a forward migration");
2733
+ }
2734
+ };
2735
+
2645
2736
  // lib/database/src/migrations.ts
2646
2737
  var migrations = [
2647
2738
  {
@@ -2855,7 +2946,8 @@ var migrations = [
2855
2946
  nestedNotebooks,
2856
2947
  conversations,
2857
2948
  relationships,
2858
- publicSharing
2949
+ publicSharing,
2950
+ shareExpiration
2859
2951
  ];
2860
2952
  var migrationSource = {
2861
2953
  getMigrations: async () => migrations,
@@ -8010,8 +8102,8 @@ function readStack(error3) {
8010
8102
  return {};
8011
8103
  }
8012
8104
  }
8013
- function inertSpan(options, active2) {
8014
- const parent = traceparentHeader(options?.parent) ?? active2;
8105
+ function inertSpan(options, active3) {
8106
+ const parent = traceparentHeader(options?.parent) ?? active3;
8015
8107
  const inbound = "string" == typeof parent || null == parent ? parent : readHandle(parent, "traceparent");
8016
8108
  const traceparent = normalizeTraceparent(inbound);
8017
8109
  if (!traceparent) return NOOP_SPAN;
@@ -8478,9 +8570,9 @@ var PostHogTraces = class {
8478
8570
  return remote;
8479
8571
  }
8480
8572
  if (isOwnSpan(explicit)) return explicit.childContext();
8481
- const active2 = this._contextManager.active();
8482
- if (isOwnSpan(active2)) return active2.childContext();
8483
- if (active2 instanceof PassThroughSpan) return remoteContext(active2.traceparent(), active2.tracestate() ?? void 0);
8573
+ const active3 = this._contextManager.active();
8574
+ if (isOwnSpan(active3)) return active3.childContext();
8575
+ if (active3 instanceof PassThroughSpan) return remoteContext(active3.traceparent(), active3.tracestate() ?? void 0);
8484
8576
  }
8485
8577
  _autoContextAttributes() {
8486
8578
  let context3;
@@ -21242,8 +21334,8 @@ var Conversations = class {
21242
21334
  "Start a new conversation to keep going.",
21243
21335
  409
21244
21336
  );
21245
- const active2 = await trx("conversation_turns").where({ conversationId: id, status: "pending" }).where("leaseUntil", ">", trx.fn.now()).first("id");
21246
- if (active2)
21337
+ const active3 = await trx("conversation_turns").where({ conversationId: id, status: "pending" }).where("leaseUntil", ">", trx.fn.now()).first("id");
21338
+ if (active3)
21247
21339
  throw new GroveError(
21248
21340
  "conversation_busy",
21249
21341
  "Wait for the current reply before sending another message.",
@@ -22007,7 +22099,28 @@ import {
22007
22099
  // lib/shared/src/sharing.ts
22008
22100
  init_define_GROVE_TELEMETRY();
22009
22101
  import { z as z6 } from "zod";
22102
+
22103
+ // lib/shared/src/share-durations.ts
22104
+ init_define_GROVE_TELEMETRY();
22105
+ var shareDurations = {
22106
+ "1h": { label: "1 hour", seconds: 3600 },
22107
+ "4h": { label: "4 hours", seconds: 14400 },
22108
+ "1d": { label: "1 day", seconds: 86400 },
22109
+ "1w": { label: "1 week", seconds: 604800 },
22110
+ "2w": { label: "2 weeks", seconds: 1209600 },
22111
+ "1mo": { label: "1 month", seconds: 2592e3 }
22112
+ };
22113
+
22114
+ // lib/shared/src/sharing.ts
22010
22115
  var shareTokenSchema = z6.string().regex(/^gsh_[A-Za-z0-9_-]{43}$/);
22116
+ var shareDurationSchema = z6.enum([
22117
+ "1h",
22118
+ "4h",
22119
+ "1d",
22120
+ "1w",
22121
+ "2w",
22122
+ "1mo"
22123
+ ]);
22011
22124
  var shareMutationSchema = z6.object({
22012
22125
  operationId: operationSchema,
22013
22126
  expectedVersion: z6.number().int().positive()
@@ -22015,11 +22128,16 @@ var shareMutationSchema = z6.object({
22015
22128
  var shareEnableSchema = shareMutationSchema.extend({
22016
22129
  expectedVersion: z6.number().int().min(0),
22017
22130
  expectedTargetVersion: z6.number().int().positive(),
22018
- includeDescendants: z6.boolean().default(false)
22131
+ includeDescendants: z6.boolean().default(false),
22132
+ duration: shareDurationSchema.nullable().optional()
22019
22133
  });
22020
22134
  var shareScopeSchema = shareMutationSchema.extend({
22021
- includeDescendants: z6.boolean()
22022
- });
22135
+ includeDescendants: z6.boolean().optional(),
22136
+ duration: shareDurationSchema.nullable().optional()
22137
+ }).refine(
22138
+ (value) => value.includeDescendants !== void 0 || value.duration !== void 0,
22139
+ "Choose a sharing setting to change"
22140
+ );
22023
22141
  var publicShareQuerySchema = z6.object({
22024
22142
  cursor: z6.string().max(2048).optional(),
22025
22143
  limit: z6.coerce.number().int().min(1).max(100).default(30)
@@ -22057,6 +22175,12 @@ var conflict2 = () => new GroveError(
22057
22175
  );
22058
22176
  var limited = () => new GroveError("rate_limited", "Too many requests; retry in one minute", 429);
22059
22177
  var targetFor = (row) => row.memoryId ? { kind: "note", id: row.memoryId } : { kind: "notebook", id: row.projectId };
22178
+ var active2 = async (trx, row) => !row.revokedAt && (!row.expiresAt || (await trx.raw("SELECT clock_timestamp() < ?::timestamptz AS active", [
22179
+ row.expiresAt
22180
+ ])).rows[0].active);
22181
+ var expiration = (trx, duration) => duration ? trx.raw("clock_timestamp() + (? * interval '1 second')", [
22182
+ shareDurations[duration].seconds
22183
+ ]) : null;
22060
22184
  var Sharing = class {
22061
22185
  constructor(service, options) {
22062
22186
  this.service = service;
@@ -22132,6 +22256,7 @@ var Sharing = class {
22132
22256
  async state(trx, target) {
22133
22257
  const current = await this.target(trx, target);
22134
22258
  const direct = await this.direct(trx, target);
22259
+ const live = direct ? await active2(trx, direct) : false;
22135
22260
  const notebooks = await trx("projects").select("id", "parentId", "name");
22136
22261
  const ancestors = /* @__PURE__ */ new Set();
22137
22262
  let parent = current.projectId;
@@ -22139,7 +22264,9 @@ var Sharing = class {
22139
22264
  ancestors.add(parent);
22140
22265
  parent = notebooks.find((p) => p.id === parent)?.parentId ?? null;
22141
22266
  }
22142
- const inherited = ancestors.size ? await trx("public_shares").whereIn("projectId", [...ancestors]).whereNull("revokedAt") : [];
22267
+ const inherited = ancestors.size ? await trx("public_shares").whereIn("projectId", [...ancestors]).whereNull("revokedAt").where(
22268
+ (query) => query.whereNull("expiresAt").orWhere("expiresAt", ">", trx.raw("clock_timestamp()"))
22269
+ ) : [];
22143
22270
  return {
22144
22271
  available: !!this.options.key,
22145
22272
  canShare: current.eligible,
@@ -22147,9 +22274,11 @@ var Sharing = class {
22147
22274
  direct: direct ? {
22148
22275
  id: direct.id,
22149
22276
  version: direct.version,
22150
- active: !direct.revokedAt,
22277
+ active: live,
22151
22278
  includeDescendants: direct.includeDescendants,
22152
- url: this.url(direct)
22279
+ duration: direct.duration,
22280
+ expiresAt: direct.expiresAt?.toISOString() ?? null,
22281
+ url: live ? this.url(direct) : null
22153
22282
  } : null,
22154
22283
  inherited: inherited.filter(
22155
22284
  (s) => s.id !== direct?.id && (s.includeDescendants || target.kind === "note" && s.projectId === current.projectId)
@@ -22194,6 +22323,7 @@ var Sharing = class {
22194
22323
  enable(principal, target, input) {
22195
22324
  return this.service.access(principal, "admin", async ({ trx, account }) => {
22196
22325
  this.key();
22326
+ const duration = input.duration ?? null;
22197
22327
  const current = await this.target(trx, target);
22198
22328
  if (!current.eligible)
22199
22329
  throw new GroveError(
@@ -22213,13 +22343,14 @@ var Sharing = class {
22213
22343
  { action: "enable", ...target },
22214
22344
  async () => {
22215
22345
  const existing = await this.direct(trx, target);
22346
+ const live = existing ? await active2(trx, existing) : false;
22216
22347
  if (current.version !== input.expectedTargetVersion) throw conflict2();
22217
- if (existing && !existing.revokedAt && input.expectedVersion === 0 && existing.includeDescendants === input.includeDescendants)
22348
+ if (existing && live && input.expectedVersion === 0 && existing.includeDescendants === input.includeDescendants && existing.duration === duration)
22218
22349
  return existing;
22219
22350
  if ((existing?.version ?? 0) !== input.expectedVersion)
22220
22351
  throw conflict2();
22221
- if (existing && !existing.revokedAt) {
22222
- if (existing.includeDescendants !== input.includeDescendants)
22352
+ if (existing && live) {
22353
+ if (existing.includeDescendants !== input.includeDescendants || existing.duration !== duration)
22223
22354
  throw conflict2();
22224
22355
  return existing;
22225
22356
  }
@@ -22231,6 +22362,8 @@ var Sharing = class {
22231
22362
  ...this.token(identity),
22232
22363
  revokedAt: null,
22233
22364
  includeDescendants: input.includeDescendants,
22365
+ duration,
22366
+ expiresAt: expiration(trx, duration),
22234
22367
  updatedAt: trx.fn.now()
22235
22368
  };
22236
22369
  if (existing)
@@ -22259,7 +22392,7 @@ var Sharing = class {
22259
22392
  if (old.version !== input.expectedVersion) throw conflict2();
22260
22393
  if (action !== "revoke") {
22261
22394
  this.key();
22262
- if (old.revokedAt) throw conflict2();
22395
+ if (!await active2(trx, old)) throw conflict2();
22263
22396
  const current = await this.target(trx, targetFor(old));
22264
22397
  if (!current.eligible)
22265
22398
  throw new GroveError(
@@ -22268,22 +22401,35 @@ var Sharing = class {
22268
22401
  409
22269
22402
  );
22270
22403
  }
22271
- if (action === "scope" && (old.memoryId || input.includeDescendants === void 0))
22404
+ if (action === "scope" && (old.memoryId && input.includeDescendants === true || input.includeDescendants === void 0 && input.duration === void 0))
22272
22405
  throw new GroveError(
22273
22406
  "invalid_request",
22274
- "Choose the notebook sharing scope"
22407
+ "Choose valid sharing settings"
22275
22408
  );
22276
22409
  if (action === "revoke" && old.revokedAt) return old;
22277
22410
  const changes = action === "revoke" ? {
22278
22411
  revokedAt: trx.fn.now(),
22279
22412
  tokenDigest: null,
22280
22413
  tokenCiphertext: null
22281
- } : action === "rotate" ? this.token(old) : { includeDescendants: input.includeDescendants };
22282
- return (await trx("public_shares").where({ id }).update({
22414
+ } : action === "rotate" ? this.token(old) : {
22415
+ ...input.includeDescendants === void 0 ? {} : { includeDescendants: input.includeDescendants },
22416
+ ...input.duration === void 0 || input.duration === old.duration ? {} : {
22417
+ duration: input.duration,
22418
+ expiresAt: expiration(trx, input.duration)
22419
+ }
22420
+ };
22421
+ const update = trx("public_shares").where({ id });
22422
+ if (action !== "revoke")
22423
+ update.where(
22424
+ (query) => query.whereNull("expiresAt").orWhere("expiresAt", ">", trx.raw("clock_timestamp()"))
22425
+ );
22426
+ const [updated] = await update.update({
22283
22427
  ...changes,
22284
22428
  version: old.version + 1,
22285
22429
  updatedAt: trx.fn.now()
22286
- }).returning("*"))[0];
22430
+ }).returning("*");
22431
+ if (!updated) throw conflict2();
22432
+ return updated;
22287
22433
  }
22288
22434
  );
22289
22435
  return this.state(trx, targetFor(row));