@fayz-ai/plugin-blog 0.12.5 → 0.12.7
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/index.js +798 -448
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +2 -2
- package/dist/migrations/index.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export declare const MIGRATION_001_BLOG = "-- ============================================================================\n-- plugin-blog 001: blog content model + public (anon) read surface\n--\n-- Backs the blog backoffice (managed from the marketing plugin's \"Blog\" tab) and\n-- the public website surface (/blog, /blog/:slug). Prefix: plg_blog_.\n-- \u00A71 plg_blog_categories \u2014 first-class category (name/slug/description)\n-- \u00A72 plg_blog_posts \u2014 articles; category_id FK, author byline, status\n-- \u00A73 RLS: authenticated tenant CRUD on both tables (the backoffice)\n-- \u00A74 v_public_blog_posts \u2014 anon-readable view of PUBLISHED posts (the site)\n--\n-- Anon-access design mirrors plugin-agenda's public booking surface: the public\n-- website runs with the publishable key and no session, so canonical tenant RLS\n-- yields nothing. Anon read is granted ONLY through the column-whitelisted,\n-- published-only view (\u00A74); the front provider filters it by tenant_id.\n-- Idempotent + safe to re-run.\n-- ============================================================================\n\n-- \u00A71 \u2014 categories\nCREATE TABLE IF NOT EXISTS public.plg_blog_categories (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n slug text NOT NULL,\n description text,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_blog_categories ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_blog_categories_tenant ON public.plg_blog_categories(tenant_id);\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_blog_categories_tenant_slug ON public.plg_blog_categories(tenant_id, slug);\n\n-- \u00A72 \u2014 posts\nCREATE TABLE IF NOT EXISTS public.plg_blog_posts (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n category_id uuid REFERENCES public.plg_blog_categories(id) ON DELETE SET NULL,\n slug text NOT NULL,\n title text NOT NULL,\n excerpt text NOT NULL DEFAULT '',\n body text NOT NULL DEFAULT '',\n cover_image text,\n author_name text,\n author_role text,\n author_avatar_url text,\n author_bio text,\n status text NOT NULL DEFAULT 'draft'\n CHECK (status IN ('draft', 'published')),\n read_time text,\n published_at timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_blog_posts ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_blog_posts_tenant ON public.plg_blog_posts(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_blog_posts_category ON public.plg_blog_posts(category_id);\nCREATE INDEX IF NOT EXISTS idx_plg_blog_posts_status ON public.plg_blog_posts(tenant_id, status, published_at DESC);\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_blog_posts_tenant_slug ON public.plg_blog_posts(tenant_id, slug);\n\n-- \u00A73 \u2014 RLS: authenticated tenant CRUD (the backoffice writes here)\nDROP POLICY IF EXISTS plg_blog_categories_select ON public.plg_blog_categories;\nDROP POLICY IF EXISTS plg_blog_categories_insert ON public.plg_blog_categories;\nDROP POLICY IF EXISTS plg_blog_categories_update ON public.plg_blog_categories;\nDROP POLICY IF EXISTS plg_blog_categories_delete ON public.plg_blog_categories;\nCREATE POLICY plg_blog_categories_select ON public.plg_blog_categories FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_categories_insert ON public.plg_blog_categories FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_categories_update ON public.plg_blog_categories FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_categories_delete ON public.plg_blog_categories FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_blog_categories TO authenticated;\n\nDROP POLICY IF EXISTS plg_blog_posts_select ON public.plg_blog_posts;\nDROP POLICY IF EXISTS plg_blog_posts_insert ON public.plg_blog_posts;\nDROP POLICY IF EXISTS plg_blog_posts_update ON public.plg_blog_posts;\nDROP POLICY IF EXISTS plg_blog_posts_delete ON public.plg_blog_posts;\nCREATE POLICY plg_blog_posts_select ON public.plg_blog_posts FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_posts_insert ON public.plg_blog_posts FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_posts_update ON public.plg_blog_posts FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nCREATE POLICY plg_blog_posts_delete ON public.plg_blog_posts FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_blog_posts TO authenticated;\n\n-- \u00A74 \u2014 anon-readable public catalog (owner-rights view = deliberate, whitelisted,\n-- PUBLISHED only). The front provider filters by tenant_id. Category name is\n-- surfaced as `tag` so the website's BlogPost shape stays unchanged.\n-- Dropped, not replaced: a later file widens this view and CREATE OR REPLACE\n-- cannot narrow a live one back down (\"cannot drop columns from view\"), which is\n-- what a re-run of this file is asking for. 143 carries any dependent across.\n--\n-- This is one of the three anon-facing views 043 deliberately left alone, so it\n-- comes back WITHOUT security_invoker: flipping it would make it resolve as\n-- `anon` and the public blog would go dark.\nSELECT app.detach_view_dependents('public.v_public_blog_posts');\nDROP VIEW IF EXISTS public.v_public_blog_posts;\nCREATE OR REPLACE VIEW public.v_public_blog_posts AS\nSELECT\n p.id,\n p.tenant_id,\n p.slug,\n p.title,\n p.excerpt,\n p.body,\n COALESCE(c.name, '') AS tag,\n p.cover_image,\n p.author_name,\n p.author_role,\n p.author_avatar_url,\n p.author_bio,\n p.read_time,\n p.published_at\nFROM public.plg_blog_posts p\nLEFT JOIN public.plg_blog_categories c ON c.id = p.category_id\nWHERE p.status = 'published';\n\nGRANT SELECT ON public.v_public_blog_posts TO anon, authenticated, service_role;\n\nSELECT app.reattach_view_dependents();\n";
|
|
2
|
-
export declare const MIGRATION_002_EXTERNAL_POSTS = "-- ============================================================================\n-- plugin-blog 002: the ingest seam \u2014 per-post SEO, external identity, and the\n-- single function an outside publisher passes through.\n--\n-- 001 gave the blog a content model written by one hand: the backoffice, behind\n-- a session, through RLS. RankLayer publishes INTO the tenant instead, so the\n-- write arrives from a machine we do not run, carrying HTML we did not author\n-- and an identity that lives in someone else's database. Three things follow,\n-- and each is a section here.\n--\n-- \u00A71 columns per-post SEO + the external identity (external_ref, source\u2026)\n-- \u00A72 identity partial unique index on (tenant_id, external_ref)\n-- \u00A73 sanitiser plg_blog_sanitize_html \u2014 a tag allowlist, in SQL\n-- \u00A74 ingest blog_upsert_external_post(p_payload jsonb)\n-- \u00A75 agent agent_blog_draft_post \u2014 the assistant's write, guarded\n-- \u00A76 facts blog.post.{created,updated,published,deleted}\n-- \u00A77 view v_public_blog_posts extended with the SEO the site renders\n--\n-- Additive and idempotent: no table is created, no policy is rewritten, the\n-- existing tenant RLS from 001 already covers every column added here.\n-- ============================================================================\n\n-- \u00A71 \u2500\u2500 columns \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- Per-post SEO. The blog already had site-level SEO (lib/seo.ts builds the\n-- descriptors), but an organic-SEO product's whole output is per-ARTICLE: the\n-- title it wants in the SERP is not the title on the page, and a syndicated\n-- post has a canonical that points somewhere else entirely.\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS meta_title text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS meta_description text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS canonical_url text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS og_image text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS noindex boolean NOT NULL DEFAULT false;\n\n-- The external identity. `external_ref` is the publisher's id for the article \u2014\n-- ours is a uuid it has never seen, so re-delivery can only be recognised by\n-- theirs. `source` is the anti-loop field: it names who WROTE the post, and a\n-- connector reads it to avoid echoing an article back to the system it came\n-- from. Defaulting to 'admin' is not a placeholder \u2014 every row that exists\n-- today was written by a person in the backoffice, and saying so is what makes\n-- the field usable from the first event.\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS external_ref text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS source text NOT NULL DEFAULT 'admin';\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS language text;\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS tags text[];\nALTER TABLE public.plg_blog_posts ADD COLUMN IF NOT EXISTS author_member_id uuid\n REFERENCES public.tenant_members(id) ON DELETE SET NULL;\n\n-- \u00A72 \u2500\u2500 identity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- This index is the whole of idempotency. Without it the same article delivered\n-- twice \u2014 a retry, a redeployed connector, a replayed queue \u2014 lands as two\n-- posts with two slugs, and the tenant's blog grows duplicates nobody ordered.\n-- Partial because the backoffice's own posts have no external ref and must not\n-- collide with each other on NULL.\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_blog_posts_tenant_external_ref\n ON public.plg_blog_posts (tenant_id, external_ref)\n WHERE external_ref IS NOT NULL;\n\n-- \"What did this source publish here?\" is the connector's own reconciliation\n-- query, and the ledger's.\nCREATE INDEX IF NOT EXISTS idx_plg_blog_posts_source\n ON public.plg_blog_posts (tenant_id, source, updated_at DESC);\n\n-- \u00A73 \u2500\u2500 sanitiser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- The sanitising happens HERE, in the function, and not in the client that\n-- renders the post. The RPC below is the only door an external publisher passes\n-- through; a browser-side sanitiser protects the one reader whose browser runs\n-- it and nothing else \u2014 the row is already poisoned, the RSS feed, the sitemap\n-- and every server-rendered page still carry the script. A control has to sit\n-- where the data enters, not where it is displayed.\n\n-- Extract one attribute from a tag, tolerating the three ways HTML quotes a\n-- value. `p_name` is always a literal this file controls, never caller input.\nCREATE OR REPLACE FUNCTION public.plg_blog_html_attr(p_tag text, p_name text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $fn$\n SELECT coalesce(\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*\"([^\"]*)\"'),\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*''([^'']*)'''),\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*([^\\s\">]+)')\n );\n$fn$;\n\nCREATE OR REPLACE FUNCTION public.plg_blog_html_escape(p_text text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $fn$\n SELECT replace(replace(replace(coalesce(p_text, ''), '<', '<'), '>', '>'), '\"', '"');\n$fn$;\n\n-- A URL we are willing to put back into the document.\nCREATE OR REPLACE FUNCTION public.plg_blog_safe_url(p_url text)\nRETURNS text\nLANGUAGE plpgsql\nIMMUTABLE\nAS $fn$\nDECLARE\n v text;\nBEGIN\n IF p_url IS NULL THEN RETURN NULL; END IF;\n -- Whitespace and control characters go BEFORE the scheme test: `java\\tscript:`\n -- is a working URL in every browser and would pass a naive prefix check.\n v := regexp_replace(btrim(p_url), '[[:space:][:cntrl:]]', '', 'g');\n IF v = '' THEN RETURN NULL; END IF;\n -- Allowlist of schemes. `data:` is absent on purpose: a data URL is a way to\n -- ship a whole document \u2014 including an SVG that scripts \u2014 inside an href.\n IF v ~* '^(https?://|mailto:|/|#)' THEN\n RETURN public.plg_blog_html_escape(v);\n END IF;\n RETURN NULL;\nEND;\n$fn$;\n\nCREATE OR REPLACE FUNCTION public.plg_blog_sanitize_html(p_html text)\nRETURNS text\nLANGUAGE plpgsql\nIMMUTABLE\nSET search_path = public\nAS $fn$\nDECLARE\n -- The allowlist is what an ARTICLE is made of. Layout tags (div, span,\n -- section, main) are deliberately out: they carry nothing a blog post needs\n -- and every one of them is a place to hang an attribute. Anything not listed\n -- loses its tag and keeps its text, so a stripped wrapper degrades to prose\n -- rather than to a hole in the article.\n c_allowed constant text[] := ARRAY[\n 'p','br','hr','h1','h2','h3','h4','h5','h6',\n 'strong','b','em','i','u','s','sup','sub','code','pre','blockquote','q','cite',\n 'ul','ol','li','dl','dt','dd',\n 'a','img','figure','figcaption',\n 'table','thead','tbody','tfoot','tr','th','td','caption'\n ];\n c_void constant text[] := ARRAY['br','hr','img'];\n -- Elements whose CONTENT is code rather than text.\n c_active constant text :=\n 'script|style|iframe|object|embed|applet|form|noscript|svg|math|template|frameset|frame';\n v text;\n v_rest text;\n v_out text := '';\n v_lt int;\n v_gt int;\n v_tag text;\n v_name text;\n v_val text;\n v_attrs text;\nBEGIN\n IF p_html IS NULL OR btrim(p_html) = '' THEN RETURN ''; END IF;\n v := p_html;\n\n -- Comments first: a conditional comment is executable markup in older\n -- engines, and `<!-- <script>\u2026 -->` would otherwise reach the pass below\n -- already commented out and survive it.\n v := regexp_replace(v, '<!--.*?-->', '', 'g');\n v := regexp_replace(v, '<!\\[CDATA\\[.*?\\]\\]>', '', 'g');\n v := regexp_replace(v, '<\\?.*?\\?>', '', 'g');\n\n -- Active elements go whole. Dropping only the tag would leave the script body\n -- standing as visible page text \u2014 the article would read as vandalised even\n -- though nothing executed.\n -- Two Postgres regex traps, both of which fail OPEN and were caught by\n -- running this against a container rather than by reading it:\n -- `\\y`, not `\\b` \u2014 in a Postgres RE `\\b` is the BACKSPACE character, so\n -- `<script\\b` matches nothing and the script body survives as page text.\n -- Every quantifier non-greedy \u2014 a Postgres RE takes its greediness from its\n -- FIRST quantifier, so one greedy `\\s*` at the front makes the trailing\n -- `.*?` greedy too, and the first <script> swallows the article down to the\n -- last closing tag in the document.\n v := regexp_replace(v, '<\\s*?(' || c_active || ')\\y[^>]*?>.*?<\\s*?/\\s*?\\1\\s*?>', '', 'gi');\n -- \u2026and the unbalanced halves of the same set, plus the document-level tags\n -- that have no business inside an article body.\n v := regexp_replace(\n v,\n '<\\s*/?\\s*(' || c_active || '|link|meta|base|title|head|body|html)\\y[^>]*>',\n '', 'gi');\n\n -- Walk the remaining tags. A rewrite rather than a filter: every tag that\n -- comes out the other side was BUILT here from a name and an allowlisted\n -- attribute, so nothing an attacker wrote is copied through by accident.\n v_rest := v;\n LOOP\n v_lt := position('<' in v_rest);\n IF v_lt = 0 THEN\n v_out := v_out || v_rest;\n EXIT;\n END IF;\n v_out := v_out || substr(v_rest, 1, v_lt - 1);\n v_rest := substr(v_rest, v_lt);\n\n v_gt := position('>' in v_rest);\n IF v_gt = 0 THEN\n -- An unterminated '<' is text. It is escaped so it cannot open a tag when\n -- something is concatenated after this body.\n v_out := v_out || replace(v_rest, '<', '<');\n EXIT;\n END IF;\n v_tag := substr(v_rest, 1, v_gt);\n v_rest := substr(v_rest, v_gt + 1);\n\n v_name := lower(coalesce(substring(v_tag from '^<\\s*/?\\s*([a-zA-Z][a-zA-Z0-9]*)'), ''));\n IF v_name = '' OR NOT (v_name = ANY (c_allowed)) THEN\n CONTINUE; -- tag dropped, its text kept\n END IF;\n\n IF v_tag ~ '^<\\s*/' THEN\n IF NOT (v_name = ANY (c_void)) THEN v_out := v_out || '</' || v_name || '>'; END IF;\n CONTINUE;\n END IF;\n\n -- Attributes are an allowlist too, and a per-tag one: `href` on <a>,\n -- `src`/`alt` on <img>. Everything else \u2014 style, on*, srcset, class,\n -- data-* \u2014 is dropped rather than inspected, because inspecting means\n -- maintaining a list of what is dangerous, and that list is never finished.\n v_attrs := '';\n IF v_name = 'a' THEN\n v_val := public.plg_blog_safe_url(public.plg_blog_html_attr(v_tag, 'href'));\n IF v_val IS NOT NULL THEN\n -- An external publisher's outbound links are not the tenant's\n -- endorsement, and an unmarked link farm is precisely the SEO damage\n -- this seam could otherwise cause on the tenant's own domain.\n v_attrs := ' href=\"' || v_val || '\" rel=\"nofollow noopener\"';\n END IF;\n ELSIF v_name = 'img' THEN\n v_val := public.plg_blog_safe_url(public.plg_blog_html_attr(v_tag, 'src'));\n IF v_val IS NULL THEN CONTINUE; END IF; -- an <img> with no safe src is nothing\n v_attrs := ' src=\"' || v_val || '\" alt=\"'\n || public.plg_blog_html_escape(public.plg_blog_html_attr(v_tag, 'alt')) || '\"';\n END IF;\n\n v_out := v_out || '<' || v_name || v_attrs\n || CASE WHEN v_name = ANY (c_void) THEN ' />' ELSE '>' END;\n END LOOP;\n\n RETURN v_out;\nEND;\n$fn$;\n\n-- Accents are transliterated rather than stripped: 'sa\u00FAde-bucal' beats\n-- 'sa-de-bucal', and a slug is a URL somebody will read out loud.\nCREATE OR REPLACE FUNCTION public.plg_blog_slugify(p_text text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $fn$\n SELECT btrim(\n regexp_replace(\n translate(lower(coalesce(p_text, '')),\n '\u00E1\u00E0\u00E2\u00E3\u00E4\u00E5\u00E9\u00E8\u00EA\u00EB\u00ED\u00EC\u00EE\u00EF\u00F3\u00F2\u00F4\u00F5\u00F6\u00F8\u00FA\u00F9\u00FB\u00FC\u00E7\u00F1\u00FD\u00FF',\n 'aaaaaaeeeeiiiioooooouuuucnyy'),\n '[^a-z0-9]+', '-', 'g'),\n '-');\n$fn$;\n\nREVOKE ALL ON FUNCTION public.plg_blog_html_attr(text, text) FROM public, anon;\nREVOKE ALL ON FUNCTION public.plg_blog_html_escape(text) FROM public, anon;\nREVOKE ALL ON FUNCTION public.plg_blog_safe_url(text) FROM public, anon;\nREVOKE ALL ON FUNCTION public.plg_blog_sanitize_html(text) FROM public, anon;\nREVOKE ALL ON FUNCTION public.plg_blog_slugify(text) FROM public, anon;\nGRANT EXECUTE ON FUNCTION public.plg_blog_html_attr(text, text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.plg_blog_html_escape(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.plg_blog_safe_url(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.plg_blog_sanitize_html(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.plg_blog_slugify(text) TO authenticated, service_role;\n\n-- \u00A74 \u2500\u2500 ingest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- The one door. Takes a single jsonb so the caller never has to know a column\n-- list, and returns what it did so a connector can reconcile without a second\n-- read.\n--\n-- Payload: external_ref, title, slug, excerpt, body_html, status, source,\n-- language, tags[], author_member_id, published_at, cover_image, meta_title,\n-- meta_description, canonical_url, og_image, noindex.\nCREATE OR REPLACE FUNCTION public.blog_upsert_external_post(p_payload jsonb)\nRETURNS jsonb\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public\nAS $fn$\nDECLARE\n v_tenants uuid[];\n v_tenant uuid;\n v_claimed uuid;\n v_ref text;\n v_title text;\n v_base text;\n v_slug text;\n v_status text;\n v_source text;\n v_lang text;\n v_body text;\n v_excerpt text;\n v_tags text[];\n v_author uuid;\n v_pub timestamptz;\n v_cover text;\n v_existing_id uuid;\n v_existing_pub timestamptz;\n v_existing_slug text;\n v_n int := 1;\n v_id uuid;\n v_created boolean := false;\nBEGIN\n -- \u2500\u2500 tenant: from the credential, never from the payload \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n -- A tenant id the caller supplies is how one tenant writes into another's\n -- blog, and the caller is a machine outside our trust boundary. The only\n -- statement about identity we can believe is the one the credential makes.\n SELECT array_agg(t) INTO v_tenants FROM public.user_tenant_ids() AS t;\n IF v_tenants IS NULL OR array_length(v_tenants, 1) <> 1 THEN\n RAISE EXCEPTION\n 'blog_upsert_external_post: the caller must present a credential scoped to exactly one tenant'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n v_tenant := v_tenants[1];\n\n -- Refusing beats ignoring: a publisher that believes it is writing into\n -- another tenant must be told so, not silently redirected into this one.\n IF nullif(btrim(p_payload->>'tenant_id'), '') IS NOT NULL THEN\n BEGIN\n v_claimed := (p_payload->>'tenant_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_claimed := NULL;\n END;\n IF v_claimed IS DISTINCT FROM v_tenant THEN\n RAISE EXCEPTION 'blog_upsert_external_post: payload names another tenant; the tenant comes from the credential'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n END IF;\n\n -- \u2500\u2500 the article \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n v_ref := nullif(btrim(p_payload->>'external_ref'), '');\n v_title := nullif(btrim(p_payload->>'title'), '');\n IF v_title IS NULL THEN\n RAISE EXCEPTION 'blog_upsert_external_post: title is required'\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n v_status := lower(coalesce(nullif(btrim(p_payload->>'status'), ''), 'draft'));\n IF v_status NOT IN ('draft', 'published') THEN\n RAISE EXCEPTION 'blog_upsert_external_post: unknown status %; expected draft or published', v_status\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n -- Never taken as 'admin' by default: a post that arrived through this door is\n -- external by definition, and mislabelling it is what makes a connector echo\n -- it back to the system that sent it.\n v_source := lower(coalesce(nullif(btrim(p_payload->>'source'), ''), 'external'));\n v_lang := nullif(btrim(p_payload->>'language'), '');\n v_body := public.plg_blog_sanitize_html(p_payload->>'body_html');\n v_excerpt := left(btrim(regexp_replace(coalesce(p_payload->>'excerpt', ''), '<[^>]*>', '', 'g')), 500);\n\n IF jsonb_typeof(p_payload->'tags') = 'array' THEN\n SELECT array_agg(btrim(x)) INTO v_tags\n FROM jsonb_array_elements_text(p_payload->'tags') AS x\n WHERE btrim(x) <> '';\n END IF;\n\n -- An author id is a claim about a person in THIS tenant. Unverified, it would\n -- let an external publisher put a real employee's name on anything it writes.\n IF nullif(btrim(p_payload->>'author_member_id'), '') IS NOT NULL THEN\n BEGIN\n SELECT tm.id INTO v_author\n FROM public.tenant_members tm\n WHERE tm.tenant_id = v_tenant AND tm.id = (p_payload->>'author_member_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_author := NULL;\n END;\n END IF;\n\n v_cover := public.plg_blog_safe_url(\n coalesce(nullif(btrim(p_payload->>'cover_image'), ''), nullif(btrim(p_payload->>'og_image'), '')));\n\n -- \u2500\u2500 identity + slug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_ref IS NOT NULL THEN\n SELECT p.id, p.published_at, p.slug INTO v_existing_id, v_existing_pub, v_existing_slug\n FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.external_ref = v_ref;\n END IF;\n\n -- On re-delivery the existing slug WINS over one re-derived from the title.\n -- A published post's slug is its URL: silently re-slugging it because the\n -- publisher fixed a typo in the headline breaks every inbound link \u2014 on an\n -- SEO product's own articles, of all things. Changing it stays possible, but\n -- only by saying so explicitly in `slug`.\n v_base := coalesce(\n nullif(public.plg_blog_slugify(p_payload->>'slug'), ''),\n nullif(v_existing_slug, ''),\n nullif(public.plg_blog_slugify(v_title), ''),\n 'post-' || left(md5(coalesce(v_ref, gen_random_uuid()::text)), 8));\n v_base := left(v_base, 120);\n\n -- Slug is unique per tenant (001). Two different articles that slugify the\n -- same must not make the second delivery fail \u2014 a suffixed slug is a smaller\n -- surprise than a rejected publish.\n v_slug := v_base;\n WHILE EXISTS (\n SELECT 1 FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.slug = v_slug\n AND (v_existing_id IS NULL OR p.id <> v_existing_id)\n ) LOOP\n v_n := v_n + 1;\n IF v_n > 50 THEN\n RAISE EXCEPTION 'blog_upsert_external_post: cannot derive a free slug from %', v_base\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n v_slug := left(v_base, 112) || '-' || v_n;\n END LOOP;\n\n BEGIN\n v_pub := nullif(btrim(p_payload->>'published_at'), '')::timestamptz;\n EXCEPTION WHEN OTHERS THEN\n v_pub := NULL;\n END;\n -- A post that goes back to draft keeps the date it first went out; the public\n -- view filters on status, so nothing leaks, and the history stays true.\n v_pub := coalesce(v_pub, v_existing_pub, CASE WHEN v_status = 'published' THEN now() END);\n\n -- \u2500\u2500 write \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_existing_id IS NOT NULL THEN\n UPDATE public.plg_blog_posts SET\n slug = v_slug,\n title = v_title,\n excerpt = v_excerpt,\n body = v_body,\n status = v_status,\n published_at = v_pub,\n source = v_source,\n language = v_lang,\n tags = v_tags,\n author_member_id = coalesce(v_author, author_member_id),\n cover_image = coalesce(v_cover, cover_image),\n meta_title = nullif(btrim(p_payload->>'meta_title'), ''),\n meta_description = nullif(btrim(p_payload->>'meta_description'), ''),\n canonical_url = public.plg_blog_safe_url(p_payload->>'canonical_url'),\n og_image = public.plg_blog_safe_url(p_payload->>'og_image'),\n noindex = coalesce((p_payload->>'noindex')::boolean, false),\n updated_at = now()\n WHERE id = v_existing_id;\n v_id := v_existing_id;\n ELSE\n -- ON CONFLICT on the partial index, not just the SELECT above: two\n -- deliveries of the same article racing each other would both find nothing\n -- and both insert. The index is what makes the second one an update.\n INSERT INTO public.plg_blog_posts (\n tenant_id, slug, title, excerpt, body, status, published_at,\n external_ref, source, language, tags, author_member_id, cover_image,\n meta_title, meta_description, canonical_url, og_image, noindex, updated_at)\n VALUES (\n v_tenant, v_slug, v_title, v_excerpt, v_body, v_status, v_pub,\n v_ref, v_source, v_lang, v_tags, v_author, v_cover,\n nullif(btrim(p_payload->>'meta_title'), ''),\n nullif(btrim(p_payload->>'meta_description'), ''),\n public.plg_blog_safe_url(p_payload->>'canonical_url'),\n public.plg_blog_safe_url(p_payload->>'og_image'),\n coalesce((p_payload->>'noindex')::boolean, false),\n now())\n ON CONFLICT (tenant_id, external_ref) WHERE external_ref IS NOT NULL\n DO UPDATE SET\n title = excluded.title,\n excerpt = excluded.excerpt,\n body = excluded.body,\n status = excluded.status,\n published_at = coalesce(excluded.published_at, plg_blog_posts.published_at),\n source = excluded.source,\n language = excluded.language,\n tags = excluded.tags,\n cover_image = coalesce(excluded.cover_image, plg_blog_posts.cover_image),\n meta_title = excluded.meta_title,\n meta_description = excluded.meta_description,\n canonical_url = excluded.canonical_url,\n og_image = excluded.og_image,\n noindex = excluded.noindex,\n updated_at = now()\n RETURNING id, (xmax = 0) INTO v_id, v_created;\n END IF;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'slug', v_slug,\n 'status', v_status,\n 'source', v_source,\n 'external_ref', v_ref,\n 'created', coalesce(v_created, false));\nEND;\n$fn$;\n\nREVOKE ALL ON FUNCTION public.blog_upsert_external_post(jsonb) FROM public, anon;\nGRANT EXECUTE ON FUNCTION public.blog_upsert_external_post(jsonb) TO authenticated, service_role;\n\n-- \u00A75 \u2500\u2500 agent \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- The assistant's write, in the shape the broker calls (p_tenant_id,\n-- p_actor_user_id, p_payload) \u2014 a different signature from \u00A74 on purpose: the\n-- broker injects a verified actor and agent_guard runs role \u2192 plan \u2192 the\n-- blog_posts cap before anything is written. A draft, never a publish: an agent\n-- that can put a page on the public site without anyone reading it first is a\n-- worse product than one that cannot.\nCREATE OR REPLACE FUNCTION public.agent_blog_draft_post(\n p_tenant_id uuid,\n p_actor_user_id uuid,\n p_payload jsonb\n) RETURNS jsonb\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public\nAS $fn$\nDECLARE\n v_denial jsonb;\n v_used int;\n v_title text;\n v_base text;\n v_slug text;\n v_n int := 1;\n v_id uuid;\nBEGIN\n v_title := nullif(btrim(p_payload->>'title'), '');\n IF v_title IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error', 'title is required to draft a post');\n END IF;\n\n SELECT count(*) INTO v_used FROM public.plg_blog_posts p WHERE p.tenant_id = p_tenant_id;\n v_denial := public.agent_guard(p_tenant_id, p_actor_user_id, 'blog', 'create', 'blog_posts', v_used, 1);\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n v_base := coalesce(nullif(public.plg_blog_slugify(v_title), ''), 'post-' || left(md5(v_title), 8));\n v_slug := left(v_base, 120);\n WHILE EXISTS (SELECT 1 FROM public.plg_blog_posts p\n WHERE p.tenant_id = p_tenant_id AND p.slug = v_slug) LOOP\n v_n := v_n + 1;\n IF v_n > 50 THEN\n RETURN jsonb_build_object('ok', false, 'error', format('cannot derive a free slug from %L', v_base));\n END IF;\n v_slug := left(v_base, 112) || '-' || v_n;\n END LOOP;\n\n INSERT INTO public.plg_blog_posts (\n tenant_id, slug, title, excerpt, body, status, source, language, tags, updated_at)\n VALUES (\n p_tenant_id, v_slug, v_title,\n left(btrim(regexp_replace(coalesce(p_payload->>'excerpt', ''), '<[^>]*>', '', 'g')), 500),\n -- Same sanitiser as the external door: the model's output is not more\n -- trustworthy than a partner's, it is just closer to home.\n public.plg_blog_sanitize_html(p_payload->>'body_html'),\n 'draft', 'agent',\n nullif(btrim(p_payload->>'language'), ''),\n CASE WHEN jsonb_typeof(p_payload->'tags') = 'array'\n THEN ARRAY(SELECT btrim(x) FROM jsonb_array_elements_text(p_payload->'tags') AS x WHERE btrim(x) <> '')\n END,\n now())\n RETURNING id INTO v_id;\n\n INSERT INTO public.audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.draftBlogPost', 'blog_post', v_id::text,\n jsonb_build_object('title', v_title, 'slug', v_slug));\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'plg_blog_posts', 'entityKey', 'blog:posts'),\n 'name', v_title,\n 'slug', v_slug,\n 'status', 'draft'));\nEND;\n$fn$;\n\nREVOKE ALL ON FUNCTION public.agent_blog_draft_post(uuid, uuid, jsonb) FROM public, anon;\nGRANT EXECUTE ON FUNCTION public.agent_blog_draft_post(uuid, uuid, jsonb) TO authenticated, service_role;\n\n-- \u00A76 \u2500\u2500 facts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- One trigger on the table rather than an emit call inside each writer. The\n-- backoffice, this file's two RPCs and a hand-run SQL fix all end up in the\n-- same place, so a connector hears the same four facts no matter who wrote \u2014\n-- which is the entire reason the row-level emitter exists (packages/db/\n-- migrations/027_domain_events.sql).\n--\n-- `published` is not a row action, which is why the generic\n-- plg_attach_event_source trigger cannot produce it: it is a TRANSITION, and\n-- only something holding OLD and NEW can see it happen.\nCREATE OR REPLACE FUNCTION public.plg_blog_emit_post_event()\nRETURNS trigger\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public\nAS $fn$\nDECLARE\n v_row jsonb;\n v_tenant uuid;\n v_id text;\n v_payload jsonb;\nBEGIN\n -- A save that changed nothing is not a fact; without this any bulk re-save\n -- buries the real updates.\n IF TG_OP = 'UPDATE' AND OLD IS NOT DISTINCT FROM NEW THEN\n RETURN NULL;\n END IF;\n\n IF TG_OP = 'DELETE' THEN\n v_row := to_jsonb(OLD);\n ELSE\n v_row := to_jsonb(NEW);\n END IF;\n v_tenant := nullif(v_row->>'tenant_id', '')::uuid;\n v_id := v_row->>'id';\n -- The contract every consumer reads. Not the row: a whole-row payload puts\n -- the article body inside every webhook by default, and whoever needs it\n -- fetches by id.\n v_payload := jsonb_build_object(\n 'post_id', v_id,\n 'slug', v_row->>'slug',\n 'title', v_row->>'title',\n 'status', v_row->>'status',\n 'source', coalesce(v_row->>'source', 'admin'),\n 'external_ref', v_row->>'external_ref',\n 'language', v_row->>'language');\n\n BEGIN\n IF TG_OP = 'INSERT' THEN\n PERFORM public.plg_emit_event('blog.post.created', v_payload, 'blog_post', v_id, v_tenant, NULL);\n IF NEW.status = 'published' THEN\n PERFORM public.plg_emit_event('blog.post.published', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n ELSIF TG_OP = 'UPDATE' THEN\n PERFORM public.plg_emit_event('blog.post.updated', v_payload, 'blog_post', v_id, v_tenant, NULL);\n IF NEW.status = 'published' AND OLD.status IS DISTINCT FROM 'published' THEN\n PERFORM public.plg_emit_event('blog.post.published', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n ELSE\n PERFORM public.plg_emit_event('blog.post.deleted', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n EXCEPTION WHEN OTHERS THEN\n -- Observability must never be able to reject the write that caused it.\n RAISE WARNING '[plg_blog_emit_post_event] % on %: %', TG_OP, TG_TABLE_NAME, SQLERRM;\n END;\n\n RETURN NULL;\nEND;\n$fn$;\n\nREVOKE ALL ON FUNCTION public.plg_blog_emit_post_event() FROM public, anon;\n\nDROP TRIGGER IF EXISTS plg_blog_posts_emit_facts ON public.plg_blog_posts;\nCREATE TRIGGER plg_blog_posts_emit_facts\n AFTER INSERT OR UPDATE OR DELETE ON public.plg_blog_posts\n FOR EACH ROW EXECUTE FUNCTION public.plg_blog_emit_post_event();\n\n-- \u00A77 \u2500\u2500 view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- The public site runs anon and reads only this view, so per-post SEO that the\n-- view does not carry cannot be rendered \u2014 the columns would exist and no page\n-- would ever show them.\n--\n-- `source` and `external_ref` stay out: they are operational facts about who\n-- writes this tenant's blog, and the anon surface is the open internet.\n-- New columns are appended, never reordered \u2014 CREATE OR REPLACE VIEW only\n-- tolerates additions at the end.\nCREATE OR REPLACE VIEW public.v_public_blog_posts AS\nSELECT\n p.id,\n p.tenant_id,\n p.slug,\n p.title,\n p.excerpt,\n p.body,\n COALESCE(c.name, '') AS tag,\n p.cover_image,\n p.author_name,\n p.author_role,\n p.author_avatar_url,\n p.author_bio,\n p.read_time,\n p.published_at,\n p.meta_title,\n p.meta_description,\n p.canonical_url,\n p.og_image,\n p.noindex,\n p.language,\n p.tags\nFROM public.plg_blog_posts p\nLEFT JOIN public.plg_blog_categories c ON c.id = p.category_id\nWHERE p.status = 'published';\n\nGRANT SELECT ON public.v_public_blog_posts TO anon, authenticated, service_role;\n";
|
|
1
|
+
export declare const MIGRATION_000_BASELINE = "-- ============================================================================\n-- plugins/plugin-blog/src/migrations/000_baseline.sql \u2014 what installing this provisions, as one file.\n--\n-- GENERATED by scripts/emit-unit-baselines.mjs (#338). Do not edit by hand:\n-- change the schema, regenerate, and let scripts/check-chain-equivalence.mjs\n-- prove the result still matches.\n--\n-- This replaced 2 migration files. They are kept, unapplied, in\n-- migrations.archive/ \u2014 a year of decisions is worth reading even when it is no\n-- longer worth replaying.\n--\n-- Object order is fixed rather than dependency-sorted: schemas, types,\n-- sequences, tables, defaults, functions, constraints, views, indexes, foreign\n-- keys, triggers, row security, policies, grants. Dependencies BETWEEN units\n-- are carried by the order packages/db/chain.json declares.\n-- ============================================================================\n\n-- A LANGUAGE sql function binds its body at CREATE time, and 570 functions\n-- sorted by name are not sorted by who calls whom. This is what lets them load\n-- in any order; every body is still compiled on first call, so a genuinely\n-- broken reference surfaces then rather than never. Session-scoped.\nSET check_function_bodies = false;\n\n\n\n-- \u2500\u2500 default privileges: reset \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- Cleared BEFORE anything is created, so every object below gets the ACL the\n-- dump describes rather than the image's defaults on top of it. Restored at\n-- the end of this file.\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;\nEND $dp$;\n\n\n-- \u2500\u2500 table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE TABLE public.plg_blog_categories (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n name text NOT NULL,\n slug text NOT NULL,\n description text,\n created_at timestamp with time zone DEFAULT now() NOT NULL,\n updated_at timestamp with time zone DEFAULT now() NOT NULL\n);\n\nCREATE TABLE public.plg_blog_posts (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n category_id uuid,\n slug text NOT NULL,\n title text NOT NULL,\n excerpt text DEFAULT ''::text NOT NULL,\n body text DEFAULT ''::text NOT NULL,\n cover_image text,\n author_name text,\n author_role text,\n author_avatar_url text,\n author_bio text,\n status text DEFAULT 'draft'::text NOT NULL,\n read_time text,\n published_at timestamp with time zone,\n created_at timestamp with time zone DEFAULT now() NOT NULL,\n updated_at timestamp with time zone DEFAULT now() NOT NULL,\n meta_title text,\n meta_description text,\n canonical_url text,\n og_image text,\n noindex boolean DEFAULT false NOT NULL,\n external_ref text,\n source text DEFAULT 'admin'::text NOT NULL,\n language text,\n tags text[],\n author_member_id uuid,\n CONSTRAINT plg_blog_posts_status_check CHECK ((status = ANY (ARRAY['draft'::text, 'published'::text])))\n);\n\n\n-- \u2500\u2500 function \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE FUNCTION public.agent_blog_draft_post(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb) RETURNS jsonb\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO 'public'\n AS $$\nDECLARE\n v_denial jsonb;\n v_used int;\n v_title text;\n v_base text;\n v_slug text;\n v_n int := 1;\n v_id uuid;\nBEGIN\n v_title := nullif(btrim(p_payload->>'title'), '');\n IF v_title IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error', 'title is required to draft a post');\n END IF;\n\n SELECT count(*) INTO v_used FROM public.plg_blog_posts p WHERE p.tenant_id = p_tenant_id;\n v_denial := public.agent_guard(p_tenant_id, p_actor_user_id, 'blog', 'create', 'blog_posts', v_used, 1);\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n v_base := coalesce(nullif(public.plg_blog_slugify(v_title), ''), 'post-' || left(md5(v_title), 8));\n v_slug := left(v_base, 120);\n WHILE EXISTS (SELECT 1 FROM public.plg_blog_posts p\n WHERE p.tenant_id = p_tenant_id AND p.slug = v_slug) LOOP\n v_n := v_n + 1;\n IF v_n > 50 THEN\n RETURN jsonb_build_object('ok', false, 'error', format('cannot derive a free slug from %L', v_base));\n END IF;\n v_slug := left(v_base, 112) || '-' || v_n;\n END LOOP;\n\n INSERT INTO public.plg_blog_posts (\n tenant_id, slug, title, excerpt, body, status, source, language, tags, updated_at)\n VALUES (\n p_tenant_id, v_slug, v_title,\n left(btrim(regexp_replace(coalesce(p_payload->>'excerpt', ''), '<[^>]*>', '', 'g')), 500),\n -- Same sanitiser as the external door: the model's output is not more\n -- trustworthy than a partner's, it is just closer to home.\n public.plg_blog_sanitize_html(p_payload->>'body_html'),\n 'draft', 'agent',\n nullif(btrim(p_payload->>'language'), ''),\n CASE WHEN jsonb_typeof(p_payload->'tags') = 'array'\n THEN ARRAY(SELECT btrim(x) FROM jsonb_array_elements_text(p_payload->'tags') AS x WHERE btrim(x) <> '')\n END,\n now())\n RETURNING id INTO v_id;\n\n INSERT INTO public.audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.draftBlogPost', 'blog_post', v_id::text,\n jsonb_build_object('title', v_title, 'slug', v_slug));\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'plg_blog_posts', 'entityKey', 'blog:posts'),\n 'name', v_title,\n 'slug', v_slug,\n 'status', 'draft'));\nEND;\n$$;\n\nCREATE FUNCTION public.blog_upsert_external_post(p_payload jsonb) RETURNS jsonb\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO 'public'\n AS $$\nDECLARE\n v_tenants uuid[];\n v_tenant uuid;\n v_claimed uuid;\n v_ref text;\n v_title text;\n v_base text;\n v_slug text;\n v_status text;\n v_source text;\n v_lang text;\n v_body text;\n v_excerpt text;\n v_tags text[];\n v_author uuid;\n v_pub timestamptz;\n v_cover text;\n v_existing_id uuid;\n v_existing_pub timestamptz;\n v_existing_slug text;\n v_n int := 1;\n v_id uuid;\n v_created boolean := false;\nBEGIN\n -- \u2500\u2500 tenant: from the credential, never from the payload \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n -- A tenant id the caller supplies is how one tenant writes into another's\n -- blog, and the caller is a machine outside our trust boundary. The only\n -- statement about identity we can believe is the one the credential makes.\n SELECT array_agg(t) INTO v_tenants FROM public.user_tenant_ids() AS t;\n IF v_tenants IS NULL OR array_length(v_tenants, 1) <> 1 THEN\n RAISE EXCEPTION\n 'blog_upsert_external_post: the caller must present a credential scoped to exactly one tenant'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n v_tenant := v_tenants[1];\n\n -- Refusing beats ignoring: a publisher that believes it is writing into\n -- another tenant must be told so, not silently redirected into this one.\n IF nullif(btrim(p_payload->>'tenant_id'), '') IS NOT NULL THEN\n BEGIN\n v_claimed := (p_payload->>'tenant_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_claimed := NULL;\n END;\n IF v_claimed IS DISTINCT FROM v_tenant THEN\n RAISE EXCEPTION 'blog_upsert_external_post: payload names another tenant; the tenant comes from the credential'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n END IF;\n\n -- \u2500\u2500 the article \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n v_ref := nullif(btrim(p_payload->>'external_ref'), '');\n v_title := nullif(btrim(p_payload->>'title'), '');\n IF v_title IS NULL THEN\n RAISE EXCEPTION 'blog_upsert_external_post: title is required'\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n v_status := lower(coalesce(nullif(btrim(p_payload->>'status'), ''), 'draft'));\n IF v_status NOT IN ('draft', 'published') THEN\n RAISE EXCEPTION 'blog_upsert_external_post: unknown status %; expected draft or published', v_status\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n -- Never taken as 'admin' by default: a post that arrived through this door is\n -- external by definition, and mislabelling it is what makes a connector echo\n -- it back to the system that sent it.\n v_source := lower(coalesce(nullif(btrim(p_payload->>'source'), ''), 'external'));\n v_lang := nullif(btrim(p_payload->>'language'), '');\n v_body := public.plg_blog_sanitize_html(p_payload->>'body_html');\n v_excerpt := left(btrim(regexp_replace(coalesce(p_payload->>'excerpt', ''), '<[^>]*>', '', 'g')), 500);\n\n IF jsonb_typeof(p_payload->'tags') = 'array' THEN\n SELECT array_agg(btrim(x)) INTO v_tags\n FROM jsonb_array_elements_text(p_payload->'tags') AS x\n WHERE btrim(x) <> '';\n END IF;\n\n -- An author id is a claim about a person in THIS tenant. Unverified, it would\n -- let an external publisher put a real employee's name on anything it writes.\n IF nullif(btrim(p_payload->>'author_member_id'), '') IS NOT NULL THEN\n BEGIN\n SELECT tm.id INTO v_author\n FROM public.tenant_members tm\n WHERE tm.tenant_id = v_tenant AND tm.id = (p_payload->>'author_member_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_author := NULL;\n END;\n END IF;\n\n v_cover := public.plg_blog_safe_url(\n coalesce(nullif(btrim(p_payload->>'cover_image'), ''), nullif(btrim(p_payload->>'og_image'), '')));\n\n -- \u2500\u2500 identity + slug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_ref IS NOT NULL THEN\n SELECT p.id, p.published_at, p.slug INTO v_existing_id, v_existing_pub, v_existing_slug\n FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.external_ref = v_ref;\n END IF;\n\n -- On re-delivery the existing slug WINS over one re-derived from the title.\n -- A published post's slug is its URL: silently re-slugging it because the\n -- publisher fixed a typo in the headline breaks every inbound link \u2014 on an\n -- SEO product's own articles, of all things. Changing it stays possible, but\n -- only by saying so explicitly in `slug`.\n v_base := coalesce(\n nullif(public.plg_blog_slugify(p_payload->>'slug'), ''),\n nullif(v_existing_slug, ''),\n nullif(public.plg_blog_slugify(v_title), ''),\n 'post-' || left(md5(coalesce(v_ref, gen_random_uuid()::text)), 8));\n v_base := left(v_base, 120);\n\n -- Slug is unique per tenant (001). Two different articles that slugify the\n -- same must not make the second delivery fail \u2014 a suffixed slug is a smaller\n -- surprise than a rejected publish.\n v_slug := v_base;\n WHILE EXISTS (\n SELECT 1 FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.slug = v_slug\n AND (v_existing_id IS NULL OR p.id <> v_existing_id)\n ) LOOP\n v_n := v_n + 1;\n IF v_n > 50 THEN\n RAISE EXCEPTION 'blog_upsert_external_post: cannot derive a free slug from %', v_base\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n v_slug := left(v_base, 112) || '-' || v_n;\n END LOOP;\n\n BEGIN\n v_pub := nullif(btrim(p_payload->>'published_at'), '')::timestamptz;\n EXCEPTION WHEN OTHERS THEN\n v_pub := NULL;\n END;\n -- A post that goes back to draft keeps the date it first went out; the public\n -- view filters on status, so nothing leaks, and the history stays true.\n v_pub := coalesce(v_pub, v_existing_pub, CASE WHEN v_status = 'published' THEN now() END);\n\n -- \u2500\u2500 write \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_existing_id IS NOT NULL THEN\n UPDATE public.plg_blog_posts SET\n slug = v_slug,\n title = v_title,\n excerpt = v_excerpt,\n body = v_body,\n status = v_status,\n published_at = v_pub,\n source = v_source,\n language = v_lang,\n tags = v_tags,\n author_member_id = coalesce(v_author, author_member_id),\n cover_image = coalesce(v_cover, cover_image),\n meta_title = nullif(btrim(p_payload->>'meta_title'), ''),\n meta_description = nullif(btrim(p_payload->>'meta_description'), ''),\n canonical_url = public.plg_blog_safe_url(p_payload->>'canonical_url'),\n og_image = public.plg_blog_safe_url(p_payload->>'og_image'),\n noindex = coalesce((p_payload->>'noindex')::boolean, false),\n updated_at = now()\n WHERE id = v_existing_id;\n v_id := v_existing_id;\n ELSE\n -- ON CONFLICT on the partial index, not just the SELECT above: two\n -- deliveries of the same article racing each other would both find nothing\n -- and both insert. The index is what makes the second one an update.\n INSERT INTO public.plg_blog_posts (\n tenant_id, slug, title, excerpt, body, status, published_at,\n external_ref, source, language, tags, author_member_id, cover_image,\n meta_title, meta_description, canonical_url, og_image, noindex, updated_at)\n VALUES (\n v_tenant, v_slug, v_title, v_excerpt, v_body, v_status, v_pub,\n v_ref, v_source, v_lang, v_tags, v_author, v_cover,\n nullif(btrim(p_payload->>'meta_title'), ''),\n nullif(btrim(p_payload->>'meta_description'), ''),\n public.plg_blog_safe_url(p_payload->>'canonical_url'),\n public.plg_blog_safe_url(p_payload->>'og_image'),\n coalesce((p_payload->>'noindex')::boolean, false),\n now())\n ON CONFLICT (tenant_id, external_ref) WHERE external_ref IS NOT NULL\n DO UPDATE SET\n title = excluded.title,\n excerpt = excluded.excerpt,\n body = excluded.body,\n status = excluded.status,\n published_at = coalesce(excluded.published_at, plg_blog_posts.published_at),\n source = excluded.source,\n language = excluded.language,\n tags = excluded.tags,\n cover_image = coalesce(excluded.cover_image, plg_blog_posts.cover_image),\n meta_title = excluded.meta_title,\n meta_description = excluded.meta_description,\n canonical_url = excluded.canonical_url,\n og_image = excluded.og_image,\n noindex = excluded.noindex,\n updated_at = now()\n RETURNING id, (xmax = 0) INTO v_id, v_created;\n END IF;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'slug', v_slug,\n 'status', v_status,\n 'source', v_source,\n 'external_ref', v_ref,\n 'created', coalesce(v_created, false));\nEND;\n$$;\n\nCREATE FUNCTION public.plg_blog_emit_post_event() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO 'public'\n AS $$\nDECLARE\n v_row jsonb;\n v_tenant uuid;\n v_id text;\n v_payload jsonb;\nBEGIN\n -- A save that changed nothing is not a fact; without this any bulk re-save\n -- buries the real updates.\n IF TG_OP = 'UPDATE' AND OLD IS NOT DISTINCT FROM NEW THEN\n RETURN NULL;\n END IF;\n\n IF TG_OP = 'DELETE' THEN\n v_row := to_jsonb(OLD);\n ELSE\n v_row := to_jsonb(NEW);\n END IF;\n v_tenant := nullif(v_row->>'tenant_id', '')::uuid;\n v_id := v_row->>'id';\n -- The contract every consumer reads. Not the row: a whole-row payload puts\n -- the article body inside every webhook by default, and whoever needs it\n -- fetches by id.\n v_payload := jsonb_build_object(\n 'post_id', v_id,\n 'slug', v_row->>'slug',\n 'title', v_row->>'title',\n 'status', v_row->>'status',\n 'source', coalesce(v_row->>'source', 'admin'),\n 'external_ref', v_row->>'external_ref',\n 'language', v_row->>'language');\n\n BEGIN\n IF TG_OP = 'INSERT' THEN\n PERFORM public.plg_emit_event('blog.post.created', v_payload, 'blog_post', v_id, v_tenant, NULL);\n IF NEW.status = 'published' THEN\n PERFORM public.plg_emit_event('blog.post.published', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n ELSIF TG_OP = 'UPDATE' THEN\n PERFORM public.plg_emit_event('blog.post.updated', v_payload, 'blog_post', v_id, v_tenant, NULL);\n IF NEW.status = 'published' AND OLD.status IS DISTINCT FROM 'published' THEN\n PERFORM public.plg_emit_event('blog.post.published', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n ELSE\n PERFORM public.plg_emit_event('blog.post.deleted', v_payload, 'blog_post', v_id, v_tenant, NULL);\n END IF;\n EXCEPTION WHEN OTHERS THEN\n -- Observability must never be able to reject the write that caused it.\n RAISE WARNING '[plg_blog_emit_post_event] % on %: %', TG_OP, TG_TABLE_NAME, SQLERRM;\n END;\n\n RETURN NULL;\nEND;\n$$;\n\nCREATE FUNCTION public.plg_blog_html_attr(p_tag text, p_name text) RETURNS text\n LANGUAGE sql IMMUTABLE\n AS $$\n SELECT coalesce(\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*\"([^\"]*)\"'),\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*''([^'']*)'''),\n substring(p_tag from '(?i)\\s' || p_name || '\\s*=\\s*([^\\s\">]+)')\n );\n$$;\n\nCREATE FUNCTION public.plg_blog_html_escape(p_text text) RETURNS text\n LANGUAGE sql IMMUTABLE\n AS $$\n SELECT replace(replace(replace(coalesce(p_text, ''), '<', '<'), '>', '>'), '\"', '"');\n$$;\n\nCREATE FUNCTION public.plg_blog_safe_url(p_url text) RETURNS text\n LANGUAGE plpgsql IMMUTABLE\n AS $$\nDECLARE\n v text;\nBEGIN\n IF p_url IS NULL THEN RETURN NULL; END IF;\n -- Whitespace and control characters go BEFORE the scheme test: `java\\tscript:`\n -- is a working URL in every browser and would pass a naive prefix check.\n v := regexp_replace(btrim(p_url), '[[:space:][:cntrl:]]', '', 'g');\n IF v = '' THEN RETURN NULL; END IF;\n -- Allowlist of schemes. `data:` is absent on purpose: a data URL is a way to\n -- ship a whole document \u2014 including an SVG that scripts \u2014 inside an href.\n IF v ~* '^(https?://|mailto:|/|#)' THEN\n RETURN public.plg_blog_html_escape(v);\n END IF;\n RETURN NULL;\nEND;\n$$;\n\nCREATE FUNCTION public.plg_blog_sanitize_html(p_html text) RETURNS text\n LANGUAGE plpgsql IMMUTABLE\n SET search_path TO 'public'\n AS $$\nDECLARE\n -- The allowlist is what an ARTICLE is made of. Layout tags (div, span,\n -- section, main) are deliberately out: they carry nothing a blog post needs\n -- and every one of them is a place to hang an attribute. Anything not listed\n -- loses its tag and keeps its text, so a stripped wrapper degrades to prose\n -- rather than to a hole in the article.\n c_allowed constant text[] := ARRAY[\n 'p','br','hr','h1','h2','h3','h4','h5','h6',\n 'strong','b','em','i','u','s','sup','sub','code','pre','blockquote','q','cite',\n 'ul','ol','li','dl','dt','dd',\n 'a','img','figure','figcaption',\n 'table','thead','tbody','tfoot','tr','th','td','caption'\n ];\n c_void constant text[] := ARRAY['br','hr','img'];\n -- Elements whose CONTENT is code rather than text.\n c_active constant text :=\n 'script|style|iframe|object|embed|applet|form|noscript|svg|math|template|frameset|frame';\n v text;\n v_rest text;\n v_out text := '';\n v_lt int;\n v_gt int;\n v_tag text;\n v_name text;\n v_val text;\n v_attrs text;\nBEGIN\n IF p_html IS NULL OR btrim(p_html) = '' THEN RETURN ''; END IF;\n v := p_html;\n\n -- Comments first: a conditional comment is executable markup in older\n -- engines, and `<!-- <script>\u2026 -->` would otherwise reach the pass below\n -- already commented out and survive it.\n v := regexp_replace(v, '<!--.*?-->', '', 'g');\n v := regexp_replace(v, '<!\\[CDATA\\[.*?\\]\\]>', '', 'g');\n v := regexp_replace(v, '<\\?.*?\\?>', '', 'g');\n\n -- Active elements go whole. Dropping only the tag would leave the script body\n -- standing as visible page text \u2014 the article would read as vandalised even\n -- though nothing executed.\n -- Two Postgres regex traps, both of which fail OPEN and were caught by\n -- running this against a container rather than by reading it:\n -- `\\y`, not `\\b` \u2014 in a Postgres RE `\\b` is the BACKSPACE character, so\n -- `<script\\b` matches nothing and the script body survives as page text.\n -- Every quantifier non-greedy \u2014 a Postgres RE takes its greediness from its\n -- FIRST quantifier, so one greedy `\\s*` at the front makes the trailing\n -- `.*?` greedy too, and the first <script> swallows the article down to the\n -- last closing tag in the document.\n v := regexp_replace(v, '<\\s*?(' || c_active || ')\\y[^>]*?>.*?<\\s*?/\\s*?\\1\\s*?>', '', 'gi');\n -- \u2026and the unbalanced halves of the same set, plus the document-level tags\n -- that have no business inside an article body.\n v := regexp_replace(\n v,\n '<\\s*/?\\s*(' || c_active || '|link|meta|base|title|head|body|html)\\y[^>]*>',\n '', 'gi');\n\n -- Walk the remaining tags. A rewrite rather than a filter: every tag that\n -- comes out the other side was BUILT here from a name and an allowlisted\n -- attribute, so nothing an attacker wrote is copied through by accident.\n v_rest := v;\n LOOP\n v_lt := position('<' in v_rest);\n IF v_lt = 0 THEN\n v_out := v_out || v_rest;\n EXIT;\n END IF;\n v_out := v_out || substr(v_rest, 1, v_lt - 1);\n v_rest := substr(v_rest, v_lt);\n\n v_gt := position('>' in v_rest);\n IF v_gt = 0 THEN\n -- An unterminated '<' is text. It is escaped so it cannot open a tag when\n -- something is concatenated after this body.\n v_out := v_out || replace(v_rest, '<', '<');\n EXIT;\n END IF;\n v_tag := substr(v_rest, 1, v_gt);\n v_rest := substr(v_rest, v_gt + 1);\n\n v_name := lower(coalesce(substring(v_tag from '^<\\s*/?\\s*([a-zA-Z][a-zA-Z0-9]*)'), ''));\n IF v_name = '' OR NOT (v_name = ANY (c_allowed)) THEN\n CONTINUE; -- tag dropped, its text kept\n END IF;\n\n IF v_tag ~ '^<\\s*/' THEN\n IF NOT (v_name = ANY (c_void)) THEN v_out := v_out || '</' || v_name || '>'; END IF;\n CONTINUE;\n END IF;\n\n -- Attributes are an allowlist too, and a per-tag one: `href` on <a>,\n -- `src`/`alt` on <img>. Everything else \u2014 style, on*, srcset, class,\n -- data-* \u2014 is dropped rather than inspected, because inspecting means\n -- maintaining a list of what is dangerous, and that list is never finished.\n v_attrs := '';\n IF v_name = 'a' THEN\n v_val := public.plg_blog_safe_url(public.plg_blog_html_attr(v_tag, 'href'));\n IF v_val IS NOT NULL THEN\n -- An external publisher's outbound links are not the tenant's\n -- endorsement, and an unmarked link farm is precisely the SEO damage\n -- this seam could otherwise cause on the tenant's own domain.\n v_attrs := ' href=\"' || v_val || '\" rel=\"nofollow noopener\"';\n END IF;\n ELSIF v_name = 'img' THEN\n v_val := public.plg_blog_safe_url(public.plg_blog_html_attr(v_tag, 'src'));\n IF v_val IS NULL THEN CONTINUE; END IF; -- an <img> with no safe src is nothing\n v_attrs := ' src=\"' || v_val || '\" alt=\"'\n || public.plg_blog_html_escape(public.plg_blog_html_attr(v_tag, 'alt')) || '\"';\n END IF;\n\n v_out := v_out || '<' || v_name || v_attrs\n || CASE WHEN v_name = ANY (c_void) THEN ' />' ELSE '>' END;\n END LOOP;\n\n RETURN v_out;\nEND;\n$$;\n\nCREATE FUNCTION public.plg_blog_slugify(p_text text) RETURNS text\n LANGUAGE sql IMMUTABLE\n AS $$\n SELECT btrim(\n regexp_replace(\n translate(lower(coalesce(p_text, '')),\n '\u00E1\u00E0\u00E2\u00E3\u00E4\u00E5\u00E9\u00E8\u00EA\u00EB\u00ED\u00EC\u00EE\u00EF\u00F3\u00F2\u00F4\u00F5\u00F6\u00F8\u00FA\u00F9\u00FB\u00FC\u00E7\u00F1\u00FD\u00FF',\n 'aaaaaaeeeeiiiioooooouuuucnyy'),\n '[^a-z0-9]+', '-', 'g'),\n '-');\n$$;\n\n\n-- \u2500\u2500 constraint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE ONLY public.plg_blog_categories\n ADD CONSTRAINT plg_blog_categories_pkey PRIMARY KEY (id);\n\nALTER TABLE ONLY public.plg_blog_posts\n ADD CONSTRAINT plg_blog_posts_pkey PRIMARY KEY (id);\n\n\n-- \u2500\u2500 view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE VIEW public.v_public_blog_posts AS\n SELECT p.id,\n p.tenant_id,\n p.slug,\n p.title,\n p.excerpt,\n p.body,\n COALESCE(c.name, ''::text) AS tag,\n p.cover_image,\n p.author_name,\n p.author_role,\n p.author_avatar_url,\n p.author_bio,\n p.read_time,\n p.published_at,\n p.meta_title,\n p.meta_description,\n p.canonical_url,\n p.og_image,\n p.noindex,\n p.language,\n p.tags\n FROM (public.plg_blog_posts p\n LEFT JOIN public.plg_blog_categories c ON ((c.id = p.category_id)))\n WHERE (p.status = 'published'::text);\n\n\n-- \u2500\u2500 index \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE INDEX idx_plg_blog_categories_tenant ON public.plg_blog_categories USING btree (tenant_id);\n\nCREATE INDEX idx_plg_blog_posts_category ON public.plg_blog_posts USING btree (category_id);\n\nCREATE INDEX idx_plg_blog_posts_source ON public.plg_blog_posts USING btree (tenant_id, source, updated_at DESC);\n\nCREATE INDEX idx_plg_blog_posts_status ON public.plg_blog_posts USING btree (tenant_id, status, published_at DESC);\n\nCREATE INDEX idx_plg_blog_posts_tenant ON public.plg_blog_posts USING btree (tenant_id);\n\nCREATE UNIQUE INDEX uq_plg_blog_categories_tenant_slug ON public.plg_blog_categories USING btree (tenant_id, slug);\n\nCREATE UNIQUE INDEX uq_plg_blog_posts_tenant_external_ref ON public.plg_blog_posts USING btree (tenant_id, external_ref) WHERE (external_ref IS NOT NULL);\n\nCREATE UNIQUE INDEX uq_plg_blog_posts_tenant_slug ON public.plg_blog_posts USING btree (tenant_id, slug);\n\n\n-- \u2500\u2500 fk constraint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE ONLY public.plg_blog_categories\n ADD CONSTRAINT plg_blog_categories_tenant_id_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;\n\nALTER TABLE ONLY public.plg_blog_posts\n ADD CONSTRAINT plg_blog_posts_author_member_id_fkey FOREIGN KEY (author_member_id) REFERENCES public.tenant_members(id) ON DELETE SET NULL;\n\nALTER TABLE ONLY public.plg_blog_posts\n ADD CONSTRAINT plg_blog_posts_category_id_fkey FOREIGN KEY (category_id) REFERENCES public.plg_blog_categories(id) ON DELETE SET NULL;\n\nALTER TABLE ONLY public.plg_blog_posts\n ADD CONSTRAINT plg_blog_posts_tenant_id_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;\n\n\n-- \u2500\u2500 trigger \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE TRIGGER plg_blog_posts_emit_facts AFTER INSERT OR DELETE OR UPDATE ON public.plg_blog_posts FOR EACH ROW EXECUTE FUNCTION public.plg_blog_emit_post_event();\n\n\n-- \u2500\u2500 row security \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE public.plg_blog_categories ENABLE ROW LEVEL SECURITY;\n\nALTER TABLE public.plg_blog_posts ENABLE ROW LEVEL SECURITY;\n\n\n-- \u2500\u2500 policy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE POLICY plg_blog_categories_delete ON public.plg_blog_categories FOR DELETE TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_categories_insert ON public.plg_blog_categories FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_categories_select ON public.plg_blog_categories FOR SELECT TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_categories_update ON public.plg_blog_categories FOR UPDATE TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_posts_delete ON public.plg_blog_posts FOR DELETE TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_posts_insert ON public.plg_blog_posts FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_posts_select ON public.plg_blog_posts FOR SELECT TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\nCREATE POLICY plg_blog_posts_update ON public.plg_blog_posts FOR UPDATE TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));\n\n\n-- \u2500\u2500 acl \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nREVOKE ALL ON FUNCTION public.agent_blog_draft_post(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.agent_blog_draft_post(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb) TO authenticated;\nGRANT ALL ON FUNCTION public.agent_blog_draft_post(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb) TO service_role;\n\nREVOKE ALL ON FUNCTION public.blog_upsert_external_post(p_payload jsonb) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.blog_upsert_external_post(p_payload jsonb) TO authenticated;\nGRANT ALL ON FUNCTION public.blog_upsert_external_post(p_payload jsonb) TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_emit_post_event() FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_emit_post_event() TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_emit_post_event() TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_html_attr(p_tag text, p_name text) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_html_attr(p_tag text, p_name text) TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_html_attr(p_tag text, p_name text) TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_html_escape(p_text text) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_html_escape(p_text text) TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_html_escape(p_text text) TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_safe_url(p_url text) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_safe_url(p_url text) TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_safe_url(p_url text) TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_sanitize_html(p_html text) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_sanitize_html(p_html text) TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_sanitize_html(p_html text) TO service_role;\n\nREVOKE ALL ON FUNCTION public.plg_blog_slugify(p_text text) FROM PUBLIC;\nGRANT ALL ON FUNCTION public.plg_blog_slugify(p_text text) TO authenticated;\nGRANT ALL ON FUNCTION public.plg_blog_slugify(p_text text) TO service_role;\n\nGRANT MAINTAIN ON TABLE public.plg_blog_categories TO anon;\nGRANT ALL ON TABLE public.plg_blog_categories TO authenticated;\nGRANT ALL ON TABLE public.plg_blog_categories TO service_role;\n\nGRANT MAINTAIN ON TABLE public.plg_blog_posts TO anon;\nGRANT ALL ON TABLE public.plg_blog_posts TO authenticated;\nGRANT ALL ON TABLE public.plg_blog_posts TO service_role;\n\nGRANT SELECT,MAINTAIN ON TABLE public.v_public_blog_posts TO anon;\nGRANT ALL ON TABLE public.v_public_blog_posts TO authenticated;\nGRANT ALL ON TABLE public.v_public_blog_posts TO service_role;\n\n\n-- \u2500\u2500 default privileges: restore \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- Put back, so the NEXT thing installed inherits what the chain had.\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT MAINTAIN ON TABLES TO anon$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT MAINTAIN ON TABLES TO anon$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;\nEND $dp$;\n\nDO $dp$ BEGIN\n EXECUTE $stmt$--\n-- PostgreSQL database dump complete\n--$stmt$;\nEXCEPTION WHEN insufficient_privilege OR undefined_object THEN\n RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$--\n-- PostgreSQL database dump complete\n--$stmt$;\nEND $dp$;\n";
|
|
2
|
+
export declare const MIGRATION_001_THE_AUTHOR_IS_A_MEMBERSHIP = "-- ============================================================================\n-- 001_the_author_is_a_membership \u2014 the FK and the lookup leave the projection\n-- (#214 / #352).\n--\n-- plg_blog_posts.author_member_id pointed at public.tenant_members(id), which\n-- is a COMPAT PROJECTION of app.memberships maintained by triggers \u2014 so a real\n-- foreign key was resting on a derived table. That is the reason the projection\n-- could not be dropped, and it is a stronger reason than \"a screen reads it\":\n-- Postgres refuses to drop a table another table references.\n--\n-- The move is safe precisely because the projection's own comment says the ids\n-- are the same (\"COMPAT PROJECTION of app.memberships (#134): same ids\"), so\n-- every existing author_member_id already names an app.memberships row.\n-- ============================================================================\n\nALTER TABLE public.plg_blog_posts DROP CONSTRAINT IF EXISTS plg_blog_posts_author_member_id_fkey;\nALTER TABLE public.plg_blog_posts\n ADD CONSTRAINT plg_blog_posts_author_member_id_fkey\n FOREIGN KEY (author_member_id) REFERENCES app.memberships(id) ON DELETE SET NULL;\n\nCREATE OR REPLACE FUNCTION public.blog_upsert_external_post(p_payload jsonb) RETURNS jsonb\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO 'public'\n AS $$\nDECLARE\n v_tenants uuid[];\n v_tenant uuid;\n v_claimed uuid;\n v_ref text;\n v_title text;\n v_base text;\n v_slug text;\n v_status text;\n v_source text;\n v_lang text;\n v_body text;\n v_excerpt text;\n v_tags text[];\n v_author uuid;\n v_pub timestamptz;\n v_cover text;\n v_existing_id uuid;\n v_existing_pub timestamptz;\n v_existing_slug text;\n v_n int := 1;\n v_id uuid;\n v_created boolean := false;\nBEGIN\n -- \u2500\u2500 tenant: from the credential, never from the payload \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n -- A tenant id the caller supplies is how one tenant writes into another's\n -- blog, and the caller is a machine outside our trust boundary. The only\n -- statement about identity we can believe is the one the credential makes.\n SELECT array_agg(t) INTO v_tenants FROM public.user_tenant_ids() AS t;\n IF v_tenants IS NULL OR array_length(v_tenants, 1) <> 1 THEN\n RAISE EXCEPTION\n 'blog_upsert_external_post: the caller must present a credential scoped to exactly one tenant'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n v_tenant := v_tenants[1];\n\n -- Refusing beats ignoring: a publisher that believes it is writing into\n -- another tenant must be told so, not silently redirected into this one.\n IF nullif(btrim(p_payload->>'tenant_id'), '') IS NOT NULL THEN\n BEGIN\n v_claimed := (p_payload->>'tenant_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_claimed := NULL;\n END;\n IF v_claimed IS DISTINCT FROM v_tenant THEN\n RAISE EXCEPTION 'blog_upsert_external_post: payload names another tenant; the tenant comes from the credential'\n USING ERRCODE = 'insufficient_privilege';\n END IF;\n END IF;\n\n -- \u2500\u2500 the article \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n v_ref := nullif(btrim(p_payload->>'external_ref'), '');\n v_title := nullif(btrim(p_payload->>'title'), '');\n IF v_title IS NULL THEN\n RAISE EXCEPTION 'blog_upsert_external_post: title is required'\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n v_status := lower(coalesce(nullif(btrim(p_payload->>'status'), ''), 'draft'));\n IF v_status NOT IN ('draft', 'published') THEN\n RAISE EXCEPTION 'blog_upsert_external_post: unknown status %; expected draft or published', v_status\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n\n -- Never taken as 'admin' by default: a post that arrived through this door is\n -- external by definition, and mislabelling it is what makes a connector echo\n -- it back to the system that sent it.\n v_source := lower(coalesce(nullif(btrim(p_payload->>'source'), ''), 'external'));\n v_lang := nullif(btrim(p_payload->>'language'), '');\n v_body := public.plg_blog_sanitize_html(p_payload->>'body_html');\n v_excerpt := left(btrim(regexp_replace(coalesce(p_payload->>'excerpt', ''), '<[^>]*>', '', 'g')), 500);\n\n IF jsonb_typeof(p_payload->'tags') = 'array' THEN\n SELECT array_agg(btrim(x)) INTO v_tags\n FROM jsonb_array_elements_text(p_payload->'tags') AS x\n WHERE btrim(x) <> '';\n END IF;\n\n -- An author id is a claim about a person in THIS tenant. Unverified, it would\n -- let an external publisher put a real employee's name on anything it writes.\n IF nullif(btrim(p_payload->>'author_member_id'), '') IS NOT NULL THEN\n BEGIN\n SELECT tm.id INTO v_author\n FROM app.memberships tm\n WHERE tm.tenant_id = v_tenant AND tm.id = (p_payload->>'author_member_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n v_author := NULL;\n END;\n END IF;\n\n v_cover := public.plg_blog_safe_url(\n coalesce(nullif(btrim(p_payload->>'cover_image'), ''), nullif(btrim(p_payload->>'og_image'), '')));\n\n -- \u2500\u2500 identity + slug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_ref IS NOT NULL THEN\n SELECT p.id, p.published_at, p.slug INTO v_existing_id, v_existing_pub, v_existing_slug\n FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.external_ref = v_ref;\n END IF;\n\n -- On re-delivery the existing slug WINS over one re-derived from the title.\n -- A published post's slug is its URL: silently re-slugging it because the\n -- publisher fixed a typo in the headline breaks every inbound link \u2014 on an\n -- SEO product's own articles, of all things. Changing it stays possible, but\n -- only by saying so explicitly in `slug`.\n v_base := coalesce(\n nullif(public.plg_blog_slugify(p_payload->>'slug'), ''),\n nullif(v_existing_slug, ''),\n nullif(public.plg_blog_slugify(v_title), ''),\n 'post-' || left(md5(coalesce(v_ref, gen_random_uuid()::text)), 8));\n v_base := left(v_base, 120);\n\n -- Slug is unique per tenant (001). Two different articles that slugify the\n -- same must not make the second delivery fail \u2014 a suffixed slug is a smaller\n -- surprise than a rejected publish.\n v_slug := v_base;\n WHILE EXISTS (\n SELECT 1 FROM public.plg_blog_posts p\n WHERE p.tenant_id = v_tenant AND p.slug = v_slug\n AND (v_existing_id IS NULL OR p.id <> v_existing_id)\n ) LOOP\n v_n := v_n + 1;\n IF v_n > 50 THEN\n RAISE EXCEPTION 'blog_upsert_external_post: cannot derive a free slug from %', v_base\n USING ERRCODE = 'invalid_parameter_value';\n END IF;\n v_slug := left(v_base, 112) || '-' || v_n;\n END LOOP;\n\n BEGIN\n v_pub := nullif(btrim(p_payload->>'published_at'), '')::timestamptz;\n EXCEPTION WHEN OTHERS THEN\n v_pub := NULL;\n END;\n -- A post that goes back to draft keeps the date it first went out; the public\n -- view filters on status, so nothing leaks, and the history stays true.\n v_pub := coalesce(v_pub, v_existing_pub, CASE WHEN v_status = 'published' THEN now() END);\n\n -- \u2500\u2500 write \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_existing_id IS NOT NULL THEN\n UPDATE public.plg_blog_posts SET\n slug = v_slug,\n title = v_title,\n excerpt = v_excerpt,\n body = v_body,\n status = v_status,\n published_at = v_pub,\n source = v_source,\n language = v_lang,\n tags = v_tags,\n author_member_id = coalesce(v_author, author_member_id),\n cover_image = coalesce(v_cover, cover_image),\n meta_title = nullif(btrim(p_payload->>'meta_title'), ''),\n meta_description = nullif(btrim(p_payload->>'meta_description'), ''),\n canonical_url = public.plg_blog_safe_url(p_payload->>'canonical_url'),\n og_image = public.plg_blog_safe_url(p_payload->>'og_image'),\n noindex = coalesce((p_payload->>'noindex')::boolean, false),\n updated_at = now()\n WHERE id = v_existing_id;\n v_id := v_existing_id;\n ELSE\n -- ON CONFLICT on the partial index, not just the SELECT above: two\n -- deliveries of the same article racing each other would both find nothing\n -- and both insert. The index is what makes the second one an update.\n INSERT INTO public.plg_blog_posts (\n tenant_id, slug, title, excerpt, body, status, published_at,\n external_ref, source, language, tags, author_member_id, cover_image,\n meta_title, meta_description, canonical_url, og_image, noindex, updated_at)\n VALUES (\n v_tenant, v_slug, v_title, v_excerpt, v_body, v_status, v_pub,\n v_ref, v_source, v_lang, v_tags, v_author, v_cover,\n nullif(btrim(p_payload->>'meta_title'), ''),\n nullif(btrim(p_payload->>'meta_description'), ''),\n public.plg_blog_safe_url(p_payload->>'canonical_url'),\n public.plg_blog_safe_url(p_payload->>'og_image'),\n coalesce((p_payload->>'noindex')::boolean, false),\n now())\n ON CONFLICT (tenant_id, external_ref) WHERE external_ref IS NOT NULL\n DO UPDATE SET\n title = excluded.title,\n excerpt = excluded.excerpt,\n body = excluded.body,\n status = excluded.status,\n published_at = coalesce(excluded.published_at, plg_blog_posts.published_at),\n source = excluded.source,\n language = excluded.language,\n tags = excluded.tags,\n cover_image = coalesce(excluded.cover_image, plg_blog_posts.cover_image),\n meta_title = excluded.meta_title,\n meta_description = excluded.meta_description,\n canonical_url = excluded.canonical_url,\n og_image = excluded.og_image,\n noindex = excluded.noindex,\n updated_at = now()\n RETURNING id, (xmax = 0) INTO v_id, v_created;\n END IF;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'slug', v_slug,\n 'status', v_status,\n 'source', v_source,\n 'external_ref', v_ref,\n 'created', coalesce(v_created, false));\nEND;\n$$;";
|
|
3
3
|
export declare const MIGRATIONS: Array<{
|
|
4
4
|
id: string;
|
|
5
5
|
sql: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,io+CAu5BlC,CAAA;AAED,eAAO,MAAM,wCAAwC,omWAsOjD,CAAA;AAEJ,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAGzD,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fayz-ai/plugin-blog",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.7",
|
|
4
4
|
"description": "[experimental] Fayz SDK — blog / articles plugin (website surface)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"lucide-react": ">=0.400.0 <1.0.0"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@fayz-ai/core": "^0.
|
|
30
|
+
"@fayz-ai/core": "^0.19.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^20.0.0",
|