@miniaxolotl/grove-server 1.11.3 → 1.11.4

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/migrate.js CHANGED
@@ -59,6 +59,234 @@ var billing = {
59
59
  }
60
60
  };
61
61
 
62
+ // lib/database/src/system-admin-migration.ts
63
+ var systemAdministration = {
64
+ name: "20261025_025_system_administration",
65
+ async up(db2) {
66
+ await db2.raw(`
67
+ CREATE TABLE account_administration (
68
+ account_id uuid PRIMARY KEY REFERENCES public.accounts(id),
69
+ role text NOT NULL DEFAULT 'user' CHECK (role IN ('user','system_admin')),
70
+ access text NOT NULL DEFAULT 'default' CHECK (access IN ('default','pro','unlimited')),
71
+ version integer NOT NULL DEFAULT 0 CHECK (version >= 0)
72
+ );
73
+ ALTER TABLE account_administration ENABLE ROW LEVEL SECURITY;
74
+ CREATE POLICY tenant ON account_administration FOR SELECT
75
+ USING (account_id = NULLIF(current_setting('grove.account_id',true),'')::uuid);
76
+ CREATE TABLE system_admin_audit (
77
+ id uuid PRIMARY KEY, actor_id uuid REFERENCES public.accounts(id),
78
+ account_id uuid NOT NULL REFERENCES public.accounts(id),
79
+ kind text NOT NULL CHECK (kind IN ('change','bootstrap')),
80
+ reason text NOT NULL CHECK (length(reason) BETWEEN 3 AND 300),
81
+ before jsonb NOT NULL, after jsonb NOT NULL,
82
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
83
+ );
84
+ CREATE INDEX system_admin_audit_recent ON system_admin_audit(created_at DESC, id);
85
+ ALTER TABLE system_admin_audit ENABLE ROW LEVEL SECURITY;
86
+ REVOKE ALL ON account_administration,system_admin_audit FROM PUBLIC,grove_runtime,grove_worker;
87
+ GRANT SELECT ON account_administration TO grove_runtime,grove_worker;
88
+
89
+ CREATE FUNCTION grove_admin_state(target uuid) RETURNS jsonb
90
+ LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
91
+ SELECT jsonb_build_object('accountId',a.id,'subject',a.clerk_subject,
92
+ 'status',a.status,'createdAt',a.created_at,
93
+ 'role',COALESCE(s.role,'user'),'access',COALESCE(s.access,'default'),
94
+ 'version',COALESCE(s.version,0))
95
+ FROM public.accounts a LEFT JOIN public.account_administration s ON s.account_id=a.id
96
+ WHERE a.id=target
97
+ $$;
98
+ CREATE FUNCTION grove_admin_guard() RETURNS uuid
99
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
100
+ DECLARE actor uuid := NULLIF(current_setting('grove.account_id',true),'')::uuid;
101
+ BEGIN
102
+ -- A fresh role snapshot after the lock wait fences concurrent revocation.
103
+ PERFORM pg_advisory_xact_lock(68142025);
104
+ IF NOT EXISTS(SELECT 1 FROM public.account_administration s
105
+ JOIN public.accounts a ON a.id=s.account_id
106
+ WHERE s.account_id=actor AND s.role='system_admin' AND a.status='active') THEN
107
+ RAISE EXCEPTION 'system_admin_required' USING ERRCODE='GA001';
108
+ END IF;
109
+ RETURN actor;
110
+ END $$;
111
+ CREATE FUNCTION grove_admin_accounts(wanted text[] DEFAULT NULL) RETURNS jsonb
112
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
113
+ DECLARE result jsonb;
114
+ BEGIN
115
+ PERFORM public.grove_admin_guard();
116
+ SELECT COALESCE(jsonb_agg(public.grove_admin_state(a.id) ORDER BY a.created_at DESC,a.id),'[]'::jsonb)
117
+ INTO result FROM (SELECT id,created_at FROM public.accounts
118
+ WHERE status IN ('active','disabled') AND (wanted IS NULL OR clerk_subject=ANY(wanted))
119
+ ORDER BY created_at DESC,id LIMIT 30) a;
120
+ RETURN result;
121
+ END $$;
122
+ CREATE FUNCTION grove_admin_change(target uuid, operation uuid, expected integer,
123
+ wanted_role text, wanted_access text, explanation text) RETURNS jsonb
124
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
125
+ DECLARE actor uuid; previous public.system_admin_audit; old jsonb; result jsonb;
126
+ BEGIN
127
+ actor := public.grove_admin_guard();
128
+ IF wanted_role NOT IN ('user','system_admin') OR wanted_role IS NULL
129
+ OR wanted_access NOT IN ('default','pro','unlimited') OR wanted_access IS NULL
130
+ OR explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300
131
+ OR expected IS NULL OR expected < 0 OR operation IS NULL THEN
132
+ RAISE EXCEPTION 'invalid_request' USING ERRCODE='GA002';
133
+ END IF;
134
+ SELECT * INTO previous FROM public.system_admin_audit WHERE id=operation;
135
+ IF FOUND THEN
136
+ IF previous.actor_id IS DISTINCT FROM actor OR previous.account_id IS DISTINCT FROM target
137
+ OR previous.reason IS DISTINCT FROM explanation
138
+ OR previous.after->>'role' IS DISTINCT FROM wanted_role
139
+ OR previous.after->>'access' IS DISTINCT FROM wanted_access
140
+ OR (previous.before->>'version')::integer IS DISTINCT FROM expected THEN
141
+ RAISE EXCEPTION 'operation_conflict' USING ERRCODE='GA003';
142
+ END IF;
143
+ RETURN previous.after;
144
+ END IF;
145
+ old := public.grove_admin_state(target);
146
+ IF old IS NULL OR old->>'status' <> 'active' THEN
147
+ RAISE EXCEPTION 'account_unavailable' USING ERRCODE='GA004';
148
+ END IF;
149
+ IF (old->>'version')::integer <> expected THEN
150
+ RAISE EXCEPTION 'admin_version_conflict' USING ERRCODE='GA005';
151
+ END IF;
152
+ IF old->>'role'='system_admin' AND wanted_role='user' AND NOT EXISTS(
153
+ SELECT 1 FROM public.account_administration s JOIN public.accounts a ON a.id=s.account_id
154
+ WHERE s.role='system_admin' AND a.status='active' AND s.account_id<>target) THEN
155
+ RAISE EXCEPTION 'last_system_admin' USING ERRCODE='GA006';
156
+ END IF;
157
+ INSERT INTO public.account_administration(account_id,role,access,version)
158
+ VALUES(target,wanted_role,wanted_access,expected+1)
159
+ ON CONFLICT(account_id) DO UPDATE SET role=EXCLUDED.role,access=EXCLUDED.access,version=EXCLUDED.version;
160
+ result := public.grove_admin_state(target);
161
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
162
+ VALUES(operation,actor,target,'change',explanation,old,result);
163
+ RETURN result;
164
+ END $$;
165
+ CREATE FUNCTION grove_admin_audit() RETURNS jsonb
166
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
167
+ DECLARE result jsonb;
168
+ BEGIN
169
+ PERFORM public.grove_admin_guard();
170
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id',id,'actorId',actor_id,
171
+ 'accountId',account_id,'kind',kind,'reason',reason,'before',before,'after',after,
172
+ 'createdAt',created_at) ORDER BY created_at DESC,id),'[]'::jsonb)
173
+ INTO result FROM (SELECT * FROM public.system_admin_audit ORDER BY created_at DESC,id LIMIT 50) recent;
174
+ RETURN result;
175
+ END $$;
176
+ CREATE FUNCTION grove_bootstrap_system_admin(subject text, explanation text) RETURNS uuid
177
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
178
+ DECLARE target uuid; old jsonb;
179
+ BEGIN
180
+ PERFORM pg_advisory_xact_lock(68142025);
181
+ SELECT id INTO target FROM public.accounts WHERE clerk_subject=subject AND status='active';
182
+ IF target IS NULL THEN RAISE EXCEPTION 'account_unavailable'; END IF;
183
+ IF explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300 THEN
184
+ RAISE EXCEPTION 'invalid_request';
185
+ END IF;
186
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE account_id=target AND role='system_admin') THEN RETURN target; END IF;
187
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE role='system_admin') THEN
188
+ RAISE EXCEPTION 'already_bootstrapped';
189
+ END IF;
190
+ old := public.grove_admin_state(target);
191
+ INSERT INTO public.account_administration(account_id,role,version) VALUES(target,'system_admin',1)
192
+ ON CONFLICT(account_id) DO UPDATE SET role='system_admin',version=public.account_administration.version+1;
193
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
194
+ VALUES(gen_random_uuid(),NULL,target,'bootstrap',explanation,old,public.grove_admin_state(target));
195
+ RETURN target;
196
+ END $$;
197
+ REVOKE ALL ON FUNCTION grove_admin_state(uuid),grove_admin_guard(),grove_admin_accounts(text[]),
198
+ grove_admin_change(uuid,uuid,integer,text,text,text),grove_admin_audit(),
199
+ grove_bootstrap_system_admin(text,text) FROM PUBLIC,grove_runtime,grove_worker;
200
+ GRANT EXECUTE ON FUNCTION grove_admin_accounts(text[]),grove_admin_change(uuid,uuid,integer,text,text,text),
201
+ grove_admin_audit() TO grove_runtime;
202
+ `);
203
+ },
204
+ async down() {
205
+ throw new Error("Use a forward migration");
206
+ }
207
+ };
208
+
209
+ // lib/database/src/speech-cache-migration.ts
210
+ var speechCache = {
211
+ name: "20261024_024_speech_cache",
212
+ async up(db2) {
213
+ await db2.raw(`
214
+ -- Cache metadata belongs to the tracked object, not its short-lived request.
215
+ -- Existing speech/ objects retain their original deadlines and lifecycle.
216
+ ALTER TABLE export_objects
217
+ ADD COLUMN speech_memory_id uuid,
218
+ ADD COLUMN speech_text_hash text,
219
+ ADD COLUMN speech_cache_key text,
220
+ ADD COLUMN speech_sha256 text,
221
+ ADD CONSTRAINT export_objects_speech_memory FOREIGN KEY(account_id,speech_memory_id)
222
+ REFERENCES memories(account_id,id),
223
+ ADD CONSTRAINT export_objects_speech_metadata CHECK (
224
+ (speech_memory_id IS NULL AND speech_text_hash IS NULL AND speech_cache_key IS NULL AND speech_sha256 IS NULL)
225
+ OR (speech_memory_id IS NOT NULL AND speech_text_hash IS NOT NULL AND speech_cache_key IS NOT NULL AND speech_sha256 IS NOT NULL
226
+ AND speech_text_hash ~ '^[a-f0-9]{64}$' AND speech_cache_key ~ '^[a-f0-9]{64}$'
227
+ AND speech_sha256 ~ '^[a-f0-9]{64}$' AND object_key LIKE 'narration/%'));
228
+ CREATE INDEX export_objects_speech_cache ON export_objects(account_id,speech_cache_key)
229
+ WHERE speech_cache_key IS NOT NULL;
230
+ CREATE INDEX export_objects_speech_memory ON export_objects(account_id,speech_memory_id)
231
+ WHERE speech_memory_id IS NOT NULL;
232
+
233
+ -- Every write path (including Undo, imports and API edits) gets the same
234
+ -- retention transition. Expired objects can already be claimed for removal:
235
+ -- never revive one, even if its bytes have not been physically deleted yet.
236
+ CREATE FUNCTION grove_speech_cache_text() RETURNS trigger LANGUAGE plpgsql
237
+ SET search_path=pg_catalog,public,pg_temp AS $$
238
+ BEGIN
239
+ UPDATE export_objects SET expires_at=CASE
240
+ WHEN NEW.status='active' AND NEW.deleted_at IS NULL
241
+ AND (NEW.expires_at IS NULL OR NEW.expires_at>now())
242
+ AND speech_text_hash=encode(sha256(convert_to(NEW.content,'UTF8')),'hex')
243
+ THEN coalesce(NEW.expires_at+interval '7 days','infinity'::timestamptz)
244
+ ELSE least(expires_at,now()+interval '7 days') END
245
+ WHERE account_id=NEW.account_id AND speech_memory_id=NEW.id AND expires_at>now();
246
+ RETURN NULL;
247
+ END $$;
248
+ REVOKE ALL ON FUNCTION grove_speech_cache_text() FROM PUBLIC;
249
+ CREATE TRIGGER speech_cache_text AFTER UPDATE OF content,status,deleted_at,expires_at ON memories
250
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_cache_text();
251
+ `);
252
+ },
253
+ async down() {
254
+ throw new Error("Use a forward migration");
255
+ }
256
+ };
257
+
258
+ // lib/database/src/speech-duration-migration.ts
259
+ var speechDuration = {
260
+ name: "20261025_026_speech_duration",
261
+ async up(db2) {
262
+ await db2.raw(`
263
+ ALTER TABLE speech_usage ADD COLUMN duration_ms bigint NOT NULL DEFAULT 0 CHECK(duration_ms>=0);
264
+ -- Retain character counters. Unknown historical audio/failed attempts get
265
+ -- a conservative bound: 3 MiB of MP3 at minimum 8 kbps plus one 72 ms frame.
266
+ -- Do not reset current-month usage or claim an exact conversion from text.
267
+ UPDATE speech_usage SET duration_ms=requests::bigint*3145800 WHERE kind='speech_synthesize';
268
+ CREATE FUNCTION grove_speech_legacy_duration() RETURNS trigger LANGUAGE plpgsql
269
+ SET search_path=pg_catalog,public,pg_temp AS $$
270
+ BEGIN
271
+ IF NEW.kind='speech_synthesize' THEN
272
+ IF TG_OP='INSERT' AND NEW.requests>0 AND NEW.duration_ms=0 THEN
273
+ NEW.duration_ms:=NEW.requests::bigint*3145800;
274
+ ELSIF TG_OP='UPDATE' AND NEW.requests>OLD.requests AND NEW.duration_ms=OLD.duration_ms THEN
275
+ NEW.duration_ms:=OLD.duration_ms+(NEW.requests-OLD.requests)::bigint*3145800;
276
+ END IF;
277
+ END IF;
278
+ RETURN NEW;
279
+ END $$;
280
+ REVOKE ALL ON FUNCTION grove_speech_legacy_duration() FROM PUBLIC;
281
+ CREATE TRIGGER speech_legacy_duration BEFORE INSERT OR UPDATE ON speech_usage
282
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_legacy_duration();
283
+ `);
284
+ },
285
+ async down() {
286
+ throw new Error("Use a forward migration");
287
+ }
288
+ };
289
+
62
290
  // lib/database/src/speech-voices-migration.ts
63
291
  var speechVoices = {
64
292
  name: "20261024_022_speech_voices",
@@ -2386,7 +2614,10 @@ var migrations = [
2386
2614
  researchTools,
2387
2615
  speechDefaults,
2388
2616
  speechVoices,
2389
- billing
2617
+ billing,
2618
+ speechCache,
2619
+ systemAdministration,
2620
+ speechDuration
2390
2621
  ];
2391
2622
  var migrationSource = {
2392
2623
  getMigrations: async () => migrations,