Gate 8375: database-redeem-security expected the old attempt count, and database-redeem-code-kinds-330 assumed a zero starting balance. The migration has not run anywhere yet, so it is edited in place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
490 lines
19 KiB
PL/PgSQL
490 lines
19 KiB
PL/PgSQL
-- #330 (owner 2026-11-22): redeem codes come in kinds.
|
|
-- single = one redemption in total (个人码; a 批量码 is a set of single
|
|
-- codes sharing batch_id / batch_name). Every existing code is
|
|
-- single and keeps behaving exactly as before.
|
|
-- campaign = 活动码: one code, many users, each user at most once, an
|
|
-- optional start time, the existing expiry, and an optional
|
|
-- total cap. The code text may be chosen by the admin; it is
|
|
-- stored as the sha256 of the normalised text (upper case, no
|
|
-- spaces or dashes) and its readable text is kept in code_mask,
|
|
-- because a campaign code is meant to be public.
|
|
-- Every code may carry its own success title / message / style for the
|
|
-- celebration shown after a successful redemption.
|
|
--
|
|
-- Hashing: codes created before this migration (JYOTISH-XXXX-XXXX) were stored
|
|
-- as sha256 of the exact text. Every code created from now on (random
|
|
-- XXXX-XXXX without a prefix, or a custom campaign text) is stored as sha256 of
|
|
-- the normalised text (upper case, no spaces or dashes), so users may type it
|
|
-- with or without the dash. Redemption tries the exact hash first (old codes),
|
|
-- then the normalised hash (new codes).
|
|
--
|
|
-- Add-only: new columns with defaults, one new table, the
|
|
-- credit_transactions.redemption_code_id uniqueness moved from the column to
|
|
-- redemption_code_uses(code_id, user_id), and functions replaced with the same
|
|
-- signatures (redeem_code(text) keeps its return type and becomes a wrapper
|
|
-- around the new redeem_code_v2).
|
|
|
|
begin;
|
|
|
|
alter table public.redemption_codes
|
|
add column if not exists kind text not null default 'single',
|
|
add column if not exists batch_id uuid,
|
|
add column if not exists batch_name text,
|
|
add column if not exists campaign_name text,
|
|
add column if not exists starts_at timestamptz,
|
|
add column if not exists max_redemptions integer,
|
|
add column if not exists redemption_count integer not null default 0,
|
|
add column if not exists success_title text,
|
|
add column if not exists success_message text,
|
|
add column if not exists success_style text not null default 'default';
|
|
|
|
update public.redemption_codes
|
|
set redemption_count = 1
|
|
where redeemed_at is not null and redemption_count = 0;
|
|
|
|
alter table public.redemption_codes
|
|
drop constraint if exists redemption_codes_code_mask_check;
|
|
|
|
alter table public.redemption_codes
|
|
drop constraint if exists redemption_codes_kind_check,
|
|
add constraint redemption_codes_kind_check check (kind in ('single', 'campaign')),
|
|
drop constraint if exists redemption_codes_kind_mask_check,
|
|
add constraint redemption_codes_kind_mask_check check (
|
|
(kind = 'single' and (code_mask like 'JYOTISH-****-%' or code_mask ~ '^[A-Z0-9]{4}-\*{4}$'))
|
|
or (kind = 'campaign' and code_mask ~ '^[A-Z0-9-]{6,40}$')
|
|
),
|
|
drop constraint if exists redemption_codes_kind_fields_check,
|
|
add constraint redemption_codes_kind_fields_check check (
|
|
(kind = 'single' and max_redemptions is null and campaign_name is null
|
|
and redemption_count between 0 and 1)
|
|
or (kind = 'campaign' and redeemed_by is null and redeemed_at is null
|
|
and batch_id is null and batch_name is null)
|
|
),
|
|
drop constraint if exists redemption_codes_counts_check,
|
|
add constraint redemption_codes_counts_check check (
|
|
redemption_count >= 0
|
|
and (max_redemptions is null or max_redemptions > 0)
|
|
),
|
|
drop constraint if exists redemption_codes_window_check,
|
|
add constraint redemption_codes_window_check check (
|
|
starts_at is null or expires_at is null or starts_at < expires_at
|
|
),
|
|
drop constraint if exists redemption_codes_labels_check,
|
|
add constraint redemption_codes_labels_check check (
|
|
(batch_name is null or char_length(batch_name) between 1 and 80)
|
|
and (campaign_name is null or char_length(campaign_name) between 1 and 80)
|
|
and (success_title is null or char_length(success_title) between 1 and 20)
|
|
and (success_message is null or char_length(success_message) between 1 and 120)
|
|
and success_style in ('default', 'stars', 'moon', 'gift')
|
|
);
|
|
|
|
create index if not exists redemption_codes_batch_idx
|
|
on public.redemption_codes (batch_id)
|
|
where batch_id is not null;
|
|
create index if not exists redemption_codes_kind_created_idx
|
|
on public.redemption_codes (kind, created_at desc);
|
|
|
|
-- Who redeemed which code. One row per (code, user): this is what makes every
|
|
-- code at most once per user, for both kinds.
|
|
create table if not exists public.redemption_code_uses (
|
|
id uuid primary key default gen_random_uuid(),
|
|
code_id uuid not null references public.redemption_codes(id) on delete cascade,
|
|
user_id uuid not null references auth.users(id) on delete cascade,
|
|
credit_transaction_id uuid references public.credit_transactions(id) on delete set null,
|
|
redeemed_at timestamptz not null default now(),
|
|
unique (code_id, user_id)
|
|
);
|
|
|
|
create index if not exists redemption_code_uses_user_idx
|
|
on public.redemption_code_uses (user_id, redeemed_at desc);
|
|
|
|
alter table public.redemption_code_uses enable row level security;
|
|
revoke all on table public.redemption_code_uses from public, anon, authenticated, service_role;
|
|
grant select on table public.redemption_code_uses to service_role;
|
|
|
|
insert into public.redemption_code_uses (code_id, user_id, credit_transaction_id, redeemed_at)
|
|
select c.id, c.redeemed_by, t.id, c.redeemed_at
|
|
from public.redemption_codes c
|
|
left join public.credit_transactions t
|
|
on t.redemption_code_id = c.id and t.user_id = c.redeemed_by and t.transaction_type = 'redeem'
|
|
where c.redeemed_by is not null
|
|
and exists (select 1 from auth.users u where u.id = c.redeemed_by)
|
|
on conflict (code_id, user_id) do nothing;
|
|
|
|
-- A campaign code has many ledger rows; per-user uniqueness stays with
|
|
-- redemption_code_uses and the ledger's own (user_id, 'redeem', request_id).
|
|
alter table public.credit_transactions
|
|
drop constraint if exists credit_transactions_redemption_code_id_key;
|
|
create index if not exists credit_transactions_redemption_code_idx
|
|
on public.credit_transactions (redemption_code_id)
|
|
where redemption_code_id is not null;
|
|
|
|
do $$
|
|
begin
|
|
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
|
|
grant select (id, code_mask, credits, expires_at, note, created_at,
|
|
redeemed_by, redeemed_email, redeemed_at, revoked_by, revoked_at,
|
|
kind, batch_id, batch_name, campaign_name, starts_at, max_redemptions,
|
|
redemption_count, success_title, success_message, success_style)
|
|
on table public.redemption_codes to admin_runtime;
|
|
grant select (id, code_id, user_id, redeemed_at)
|
|
on table public.redemption_code_uses to admin_runtime;
|
|
drop policy if exists redemption_code_uses_admin_read on public.redemption_code_uses;
|
|
create policy redemption_code_uses_admin_read on public.redemption_code_uses
|
|
for select to admin_runtime using (true);
|
|
end if;
|
|
end;
|
|
$$;
|
|
|
|
-- Redemption rows are kept on account deletion like the ledger and the codes
|
|
-- themselves (de-identified through the tombstone identity): a deleted user's
|
|
-- campaign redemption still counts toward the cap.
|
|
create or replace function public.account_deletion_kept_tables()
|
|
returns text[]
|
|
language sql
|
|
immutable
|
|
set search_path = pg_catalog
|
|
as $$
|
|
select array[
|
|
'account_deletion_requests',
|
|
'admin_session_revocations',
|
|
'admin_user_roles',
|
|
'admin_users',
|
|
'birth_time_rectification_billing',
|
|
'consultation_requests',
|
|
'credit_request_cancellations',
|
|
'credit_transactions',
|
|
'payment_orders',
|
|
'pricing_experiment_events',
|
|
'redemption_attempts',
|
|
'redemption_code_uses',
|
|
'redemption_codes',
|
|
'usage_ledger',
|
|
'usage_reservations',
|
|
'user_product_redemptions',
|
|
'user_subscriptions',
|
|
-- Complaints and feedback are kept for handling records (2026-09-30,
|
|
-- product decision); the typed-in contact is cleared at purge below.
|
|
'user_feedback'
|
|
]::text[];
|
|
$$;
|
|
|
|
create or replace function public.admin_redemption_code_snapshot(p_code public.redemption_codes)
|
|
returns jsonb
|
|
language sql
|
|
stable
|
|
set search_path = ''
|
|
as $$
|
|
select jsonb_build_object(
|
|
'id', p_code.id,
|
|
'mask', p_code.code_mask,
|
|
'kind', p_code.kind,
|
|
'credits', p_code.credits,
|
|
'startsAt', p_code.starts_at,
|
|
'expiresAt', p_code.expires_at,
|
|
'note', p_code.note,
|
|
'batchId', p_code.batch_id,
|
|
'batchName', p_code.batch_name,
|
|
'campaignName', p_code.campaign_name,
|
|
'maxRedemptions', p_code.max_redemptions,
|
|
'redemptionCount', p_code.redemption_count,
|
|
'successTitle', p_code.success_title,
|
|
'successMessage', p_code.success_message,
|
|
'successStyle', p_code.success_style,
|
|
'status', case
|
|
when p_code.redeemed_at is not null then 'redeemed'
|
|
when p_code.revoked_at is not null then 'revoked'
|
|
when p_code.expires_at is not null and p_code.expires_at <= now() then 'expired'
|
|
when p_code.max_redemptions is not null and p_code.redemption_count >= p_code.max_redemptions then 'exhausted'
|
|
when p_code.starts_at is not null and p_code.starts_at > now() then 'not_started'
|
|
else 'available'
|
|
end,
|
|
'redeemedAt', p_code.redeemed_at,
|
|
'revokedAt', p_code.revoked_at
|
|
)
|
|
$$;
|
|
|
|
revoke all on function public.admin_redemption_code_snapshot(public.redemption_codes)
|
|
from public, anon, authenticated, service_role;
|
|
|
|
-- Same signature and result as before; each item may now carry kind, batch,
|
|
-- campaign, window, cap and success fields.
|
|
create or replace function public.admin_create_redemption_codes(
|
|
p_actor_user_id uuid,
|
|
p_actor_email text,
|
|
p_actor_role text,
|
|
p_request_id text,
|
|
p_codes jsonb
|
|
)
|
|
returns table (
|
|
id uuid,
|
|
code_mask text,
|
|
credits integer,
|
|
expires_at timestamptz,
|
|
note text,
|
|
created_at timestamptz,
|
|
redeemed_by uuid,
|
|
redeemed_email text,
|
|
redeemed_at timestamptz,
|
|
revoked_by uuid,
|
|
revoked_at timestamptz
|
|
)
|
|
language plpgsql
|
|
security definer
|
|
set search_path = ''
|
|
as $$
|
|
declare
|
|
v_item jsonb;
|
|
v_code public.redemption_codes%rowtype;
|
|
v_email text := lower(btrim(p_actor_email));
|
|
v_request_id text := btrim(p_request_id);
|
|
begin
|
|
v_email := public.admin_verified_actor_email(
|
|
p_actor_user_id, p_actor_email, p_actor_role
|
|
);
|
|
if v_request_id is null or char_length(v_request_id) not between 1 and 200 then
|
|
raise exception 'invalid request id' using errcode = '22023';
|
|
end if;
|
|
if p_codes is null or jsonb_typeof(p_codes) is distinct from 'array'
|
|
or jsonb_array_length(p_codes) not between 1 and 100 then
|
|
raise exception 'codes must contain between 1 and 100 items' using errcode = '22023';
|
|
end if;
|
|
|
|
for v_item in select value from jsonb_array_elements(p_codes)
|
|
loop
|
|
insert into public.redemption_codes (
|
|
code_hash, code_mask, credits, expires_at, note, created_by,
|
|
kind, batch_id, batch_name, campaign_name, starts_at, max_redemptions,
|
|
success_title, success_message, success_style
|
|
) values (
|
|
v_item ->> 'codeHash',
|
|
v_item ->> 'codeMask',
|
|
(v_item ->> 'credits')::integer,
|
|
nullif(v_item ->> 'expiresAt', '')::timestamptz,
|
|
nullif(btrim(v_item ->> 'note'), ''),
|
|
p_actor_user_id,
|
|
coalesce(nullif(v_item ->> 'kind', ''), 'single'),
|
|
nullif(v_item ->> 'batchId', '')::uuid,
|
|
nullif(btrim(v_item ->> 'batchName'), ''),
|
|
nullif(btrim(v_item ->> 'campaignName'), ''),
|
|
nullif(v_item ->> 'startsAt', '')::timestamptz,
|
|
nullif(v_item ->> 'maxRedemptions', '')::integer,
|
|
nullif(btrim(v_item ->> 'successTitle'), ''),
|
|
nullif(btrim(v_item ->> 'successMessage'), ''),
|
|
coalesce(nullif(v_item ->> 'successStyle', ''), 'default')
|
|
) returning * into v_code;
|
|
|
|
insert into audit.admin_audit_logs (
|
|
actor_user_id, actor_email, actor_role, action, target_type,
|
|
target_id, before_value, after_value, request_id
|
|
) values (
|
|
p_actor_user_id, v_email, p_actor_role, 'redemption_code.create',
|
|
'redemption_code', v_code.id, null,
|
|
public.admin_redemption_code_snapshot(v_code), v_request_id
|
|
);
|
|
|
|
id := v_code.id;
|
|
code_mask := v_code.code_mask;
|
|
credits := v_code.credits;
|
|
expires_at := v_code.expires_at;
|
|
note := v_code.note;
|
|
created_at := v_code.created_at;
|
|
redeemed_by := v_code.redeemed_by;
|
|
redeemed_email := v_code.redeemed_email;
|
|
redeemed_at := v_code.redeemed_at;
|
|
revoked_by := v_code.revoked_by;
|
|
revoked_at := v_code.revoked_at;
|
|
return next;
|
|
end loop;
|
|
end;
|
|
$$;
|
|
|
|
-- redeem_code_v2: p_code_hash is the hash of the text exactly as typed (how
|
|
-- codes created before #330 are stored); p_normalized_hash is the hash of the
|
|
-- normalised text (how every newer code is stored).
|
|
-- The code row lock serialises every redemption of one code, so a capped
|
|
-- campaign never goes past its cap. Answers that concern a valid code the user
|
|
-- simply cannot use now (not started, used up, already redeemed by this user)
|
|
-- are not counted as guessing failures for the rate limit.
|
|
create or replace function public.redeem_code_v2(p_code_hash text, p_normalized_hash text)
|
|
returns table (
|
|
success boolean,
|
|
credits integer,
|
|
awarded_credits integer,
|
|
error_code text,
|
|
success_title text,
|
|
success_message text,
|
|
success_style text
|
|
)
|
|
language plpgsql
|
|
security definer
|
|
set search_path = public, pg_temp
|
|
as $$
|
|
declare
|
|
v_user_id uuid := auth.uid();
|
|
v_email text := auth.jwt() ->> 'email';
|
|
v_code public.redemption_codes%rowtype;
|
|
v_balance integer;
|
|
v_failed integer;
|
|
v_transaction_id uuid;
|
|
begin
|
|
if v_user_id is null then
|
|
return query select false, null::integer, null::integer, 'unauthorized'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
perform pg_advisory_xact_lock(hashtextextended('redeem:' || v_user_id::text, 0));
|
|
|
|
delete from public.redemption_attempts
|
|
where user_id = v_user_id and created_at < now() - interval '10 minutes';
|
|
|
|
select count(*) into v_failed
|
|
from public.redemption_attempts
|
|
where user_id = v_user_id;
|
|
|
|
if v_failed >= 5 then
|
|
return query select false, null::integer, null::integer, 'rate_limited'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
if p_code_hash is null or p_code_hash !~ '^[0-9a-f]{64}$' then
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'invalid_code'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
select rc.* into v_code
|
|
from public.redemption_codes rc
|
|
where rc.code_hash = p_code_hash
|
|
for update;
|
|
if not found and p_normalized_hash ~ '^[0-9a-f]{64}$'
|
|
and p_normalized_hash is distinct from p_code_hash then
|
|
select rc.* into v_code
|
|
from public.redemption_codes rc
|
|
where rc.code_hash = p_normalized_hash
|
|
for update;
|
|
end if;
|
|
if v_code.id is null then
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'invalid_code'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
if v_code.kind = 'single' and v_code.redeemed_by is not null then
|
|
if v_code.redeemed_by = v_user_id then
|
|
-- A single code reused by its own redeemer still counts as a failed
|
|
-- attempt, as before this migration (database-redeem-security); only
|
|
-- campaign codes skip the count for 「你已经领过」.
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'already_redeemed_by_you'::text,
|
|
null::text, null::text, null::text;
|
|
else
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'already_redeemed'::text,
|
|
null::text, null::text, null::text;
|
|
end if;
|
|
return;
|
|
end if;
|
|
if v_code.revoked_at is not null then
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'revoked_code'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
if v_code.starts_at is not null and v_code.starts_at > now() then
|
|
return query select false, null::integer, null::integer, 'not_started'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
if v_code.expires_at is not null and v_code.expires_at <= now() then
|
|
insert into public.redemption_attempts (user_id) values (v_user_id);
|
|
return query select false, null::integer, null::integer, 'expired_code'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
if exists (
|
|
select 1 from public.redemption_code_uses u
|
|
where u.code_id = v_code.id and u.user_id = v_user_id
|
|
) then
|
|
return query select false, null::integer, null::integer, 'already_redeemed_by_you'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
if v_code.max_redemptions is not null and v_code.redemption_count >= v_code.max_redemptions then
|
|
return query select false, null::integer, null::integer, 'exhausted'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
select p.credits into v_balance
|
|
from public.profiles p
|
|
where p.id = v_user_id
|
|
for update;
|
|
if not found then
|
|
return query select false, null::integer, null::integer, 'profile_missing'::text,
|
|
null::text, null::text, null::text;
|
|
return;
|
|
end if;
|
|
|
|
if v_code.kind = 'single' then
|
|
update public.redemption_codes rc
|
|
set redeemed_by = v_user_id, redeemed_email = v_email, redeemed_at = now(),
|
|
redemption_count = rc.redemption_count + 1
|
|
where rc.id = v_code.id;
|
|
else
|
|
update public.redemption_codes rc
|
|
set redemption_count = rc.redemption_count + 1
|
|
where rc.id = v_code.id;
|
|
end if;
|
|
|
|
update public.profiles p
|
|
set credits = p.credits + v_code.credits, updated_at = now()
|
|
where p.id = v_user_id
|
|
returning p.credits into v_balance;
|
|
|
|
insert into public.credit_transactions (
|
|
user_id, transaction_type, amount, balance_after, request_id, redemption_code_id
|
|
) values (
|
|
v_user_id, 'redeem', v_code.credits, v_balance, v_code.id::text, v_code.id
|
|
) returning id into v_transaction_id;
|
|
|
|
insert into public.redemption_code_uses (code_id, user_id, credit_transaction_id)
|
|
values (v_code.id, v_user_id, v_transaction_id);
|
|
|
|
delete from public.redemption_attempts where user_id = v_user_id;
|
|
|
|
return query select true, v_balance, v_code.credits, null::text,
|
|
v_code.success_title, v_code.success_message, v_code.success_style;
|
|
end;
|
|
$$;
|
|
|
|
revoke all on function public.redeem_code_v2(text, text) from public, anon;
|
|
grant execute on function public.redeem_code_v2(text, text) to authenticated;
|
|
|
|
-- The old entry point keeps its signature and result columns and follows the
|
|
-- same rules (it never bypasses the per-user and cap checks).
|
|
create or replace function public.redeem_code(p_code_hash text)
|
|
returns table (success boolean, credits integer, awarded_credits integer, error_code text)
|
|
language plpgsql
|
|
security definer
|
|
set search_path = public, pg_temp
|
|
as $$
|
|
begin
|
|
-- The old contract reports any reuse of a single code as already_redeemed;
|
|
-- the per-user wording (already_redeemed_by_you) exists only in redeem_code_v2.
|
|
return query
|
|
select r.success, r.credits, r.awarded_credits,
|
|
case when r.error_code = 'already_redeemed_by_you' then 'already_redeemed' else r.error_code end
|
|
from public.redeem_code_v2(p_code_hash, null) r;
|
|
end;
|
|
$$;
|
|
|
|
revoke all on function public.redeem_code(text) from public, anon;
|
|
grant execute on function public.redeem_code(text) to authenticated;
|
|
|
|
commit;
|