@simplelayer/graniteer-core 0.1.2 → 0.2.1
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/index.js +2 -2
- package/package.json +73 -2
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -308
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -0
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -0
- package/src/functions/get-provider-sign-link.ts +155 -0
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -0
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -0
- package/src/functions/voice-day-pass.ts +346 -0
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/pacificDate.ts +54 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -1,150 +1,150 @@
|
|
|
1
|
-
// Remove a sponsored "team member" (Company member) seat.
|
|
2
|
-
//
|
|
3
|
-
// Scope: seats with NO Stripe subscription of their own. Anyone holding a real
|
|
4
|
-
// subscription must go through admin-cancel-membership instead.
|
|
5
|
-
//
|
|
6
|
-
// Auth/audit scaffold copied from admin-cancel-membership (minus its Stripe
|
|
7
|
-
// pre-flight, which does not apply here).
|
|
8
|
-
|
|
9
|
-
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
-
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
11
|
-
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
12
|
-
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
13
|
-
|
|
14
|
-
const corsHeaders = {
|
|
15
|
-
'Access-Control-Allow-Origin': '*',
|
|
16
|
-
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
17
|
-
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
interface CallerClaims {
|
|
21
|
-
sub: string;
|
|
22
|
-
email?: string;
|
|
23
|
-
aal?: string;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
27
|
-
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
28
|
-
function getJwks(supabaseUrl: string) {
|
|
29
|
-
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
30
|
-
return jwksCache;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
34
|
-
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
35
|
-
const token = authHeader.slice(7).trim();
|
|
36
|
-
try {
|
|
37
|
-
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
38
|
-
const claims = payload as unknown as CallerClaims;
|
|
39
|
-
if (!claims.sub) return null;
|
|
40
|
-
return claims;
|
|
41
|
-
} catch {
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function json(status: number, body: unknown) {
|
|
47
|
-
return new Response(JSON.stringify(body), {
|
|
48
|
-
status,
|
|
49
|
-
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const SEAT_COLUMNS = 'id,email,customer_name,status,stripe_subscription_id,sponsor_membership_id,membership_ended_at';
|
|
54
|
-
|
|
55
|
-
export async function handle(req: Request): Promise<Response> {
|
|
56
|
-
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
57
|
-
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
58
|
-
|
|
59
|
-
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
60
|
-
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
61
|
-
|
|
62
|
-
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
63
|
-
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
64
|
-
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
65
|
-
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
66
|
-
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
67
|
-
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
68
|
-
|
|
69
|
-
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
70
|
-
auth: { persistSession: false, autoRefreshToken: false },
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
const [ipOk, emailOk] = await Promise.all([
|
|
74
|
-
checkRateLimit(admin, 'admin-remove-team-member-ip', clientIp(req), 30, 300),
|
|
75
|
-
checkRateLimit(admin, 'admin-remove-team-member-email', callerEmail, 20, 300),
|
|
76
|
-
]);
|
|
77
|
-
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
78
|
-
|
|
79
|
-
const { data: allow, error: allowErr } = await admin
|
|
80
|
-
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
81
|
-
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
82
|
-
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
83
|
-
|
|
84
|
-
let body: { membership_id?: string; idempotency_key?: string; reason?: string };
|
|
85
|
-
try {
|
|
86
|
-
body = await req.json();
|
|
87
|
-
} catch {
|
|
88
|
-
return json(400, { ok: false, error: 'invalid_json' });
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const membershipId = (body.membership_id ?? '').trim();
|
|
92
|
-
if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
|
|
93
|
-
return json(400, { ok: false, error: 'invalid_membership_id' });
|
|
94
|
-
}
|
|
95
|
-
const idempotencyKey = (body.idempotency_key ?? '').trim();
|
|
96
|
-
if (!idempotencyKey || idempotencyKey.length > 100) {
|
|
97
|
-
return json(400, { ok: false, error: 'invalid_idempotency_key' });
|
|
98
|
-
}
|
|
99
|
-
const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
|
|
100
|
-
|
|
101
|
-
const { data: seat, error: sErr } = await admin
|
|
102
|
-
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
103
|
-
if (sErr) return json(500, { ok: false, error: 'lookup_failed', detail: sErr.message });
|
|
104
|
-
if (!seat) return json(404, { ok: false, error: 'membership_not_found' });
|
|
105
|
-
if (seat.stripe_subscription_id) {
|
|
106
|
-
return json(400, { ok: false, error: 'has_stripe_subscription' });
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Audit first, with the idempotency key. A duplicate means this removal
|
|
110
|
-
// already ran — report the row's actual current state, not a bare flag.
|
|
111
|
-
const { error: insErr } = await admin.from('membership_admin_actions').insert({
|
|
112
|
-
membership_id: membershipId,
|
|
113
|
-
action: 'sponsor_removed',
|
|
114
|
-
actor_email: callerEmail,
|
|
115
|
-
idempotency_key: idempotencyKey,
|
|
116
|
-
reason: reasonInput,
|
|
117
|
-
effective_at: new Date().toISOString(),
|
|
118
|
-
} as never);
|
|
119
|
-
if (insErr) {
|
|
120
|
-
if ((insErr as { code?: string }).code === '23505') {
|
|
121
|
-
const { data: current } = await admin
|
|
122
|
-
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
123
|
-
return json(200, { ok: true, duplicate: true, membership: current ?? null });
|
|
124
|
-
}
|
|
125
|
-
return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Explicit column allowlist. door_managed is deliberately left as-is: door
|
|
129
|
-
// revocation is handled downstream, not by flipping this flag here.
|
|
130
|
-
const { error: updErr } = await admin
|
|
131
|
-
.from('memberships')
|
|
132
|
-
.update({
|
|
133
|
-
status: 'canceled',
|
|
134
|
-
membership_ended_at: new Date().toISOString(),
|
|
135
|
-
sponsor_membership_id: null,
|
|
136
|
-
} as never)
|
|
137
|
-
.eq('id', membershipId);
|
|
138
|
-
if (updErr) {
|
|
139
|
-
await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
|
|
140
|
-
await logOps(admin, 'team_member_remove_failed', {
|
|
141
|
-
membership_id: membershipId, actor: callerEmail, message: updErr.message,
|
|
142
|
-
}, { severity: 'error' }).catch(() => {});
|
|
143
|
-
return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
const { data: finalRow } = await admin
|
|
147
|
-
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
148
|
-
|
|
149
|
-
return json(200, { ok: true, membership: finalRow ?? null });
|
|
150
|
-
}
|
|
1
|
+
// Remove a sponsored "team member" (Company member) seat.
|
|
2
|
+
//
|
|
3
|
+
// Scope: seats with NO Stripe subscription of their own. Anyone holding a real
|
|
4
|
+
// subscription must go through admin-cancel-membership instead.
|
|
5
|
+
//
|
|
6
|
+
// Auth/audit scaffold copied from admin-cancel-membership (minus its Stripe
|
|
7
|
+
// pre-flight, which does not apply here).
|
|
8
|
+
|
|
9
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
11
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
12
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
13
|
+
|
|
14
|
+
const corsHeaders = {
|
|
15
|
+
'Access-Control-Allow-Origin': '*',
|
|
16
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
17
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
interface CallerClaims {
|
|
21
|
+
sub: string;
|
|
22
|
+
email?: string;
|
|
23
|
+
aal?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
27
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
28
|
+
function getJwks(supabaseUrl: string) {
|
|
29
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
30
|
+
return jwksCache;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
34
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
35
|
+
const token = authHeader.slice(7).trim();
|
|
36
|
+
try {
|
|
37
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
38
|
+
const claims = payload as unknown as CallerClaims;
|
|
39
|
+
if (!claims.sub) return null;
|
|
40
|
+
return claims;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function json(status: number, body: unknown) {
|
|
47
|
+
return new Response(JSON.stringify(body), {
|
|
48
|
+
status,
|
|
49
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const SEAT_COLUMNS = 'id,email,customer_name,status,stripe_subscription_id,sponsor_membership_id,membership_ended_at';
|
|
54
|
+
|
|
55
|
+
export async function handle(req: Request): Promise<Response> {
|
|
56
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
57
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
58
|
+
|
|
59
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
60
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
61
|
+
|
|
62
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
63
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
64
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
65
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
66
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
67
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
68
|
+
|
|
69
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
70
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
74
|
+
checkRateLimit(admin, 'admin-remove-team-member-ip', clientIp(req), 30, 300),
|
|
75
|
+
checkRateLimit(admin, 'admin-remove-team-member-email', callerEmail, 20, 300),
|
|
76
|
+
]);
|
|
77
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
78
|
+
|
|
79
|
+
const { data: allow, error: allowErr } = await admin
|
|
80
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
81
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
82
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
83
|
+
|
|
84
|
+
let body: { membership_id?: string; idempotency_key?: string; reason?: string };
|
|
85
|
+
try {
|
|
86
|
+
body = await req.json();
|
|
87
|
+
} catch {
|
|
88
|
+
return json(400, { ok: false, error: 'invalid_json' });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const membershipId = (body.membership_id ?? '').trim();
|
|
92
|
+
if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
|
|
93
|
+
return json(400, { ok: false, error: 'invalid_membership_id' });
|
|
94
|
+
}
|
|
95
|
+
const idempotencyKey = (body.idempotency_key ?? '').trim();
|
|
96
|
+
if (!idempotencyKey || idempotencyKey.length > 100) {
|
|
97
|
+
return json(400, { ok: false, error: 'invalid_idempotency_key' });
|
|
98
|
+
}
|
|
99
|
+
const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
|
|
100
|
+
|
|
101
|
+
const { data: seat, error: sErr } = await admin
|
|
102
|
+
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
103
|
+
if (sErr) return json(500, { ok: false, error: 'lookup_failed', detail: sErr.message });
|
|
104
|
+
if (!seat) return json(404, { ok: false, error: 'membership_not_found' });
|
|
105
|
+
if (seat.stripe_subscription_id) {
|
|
106
|
+
return json(400, { ok: false, error: 'has_stripe_subscription' });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Audit first, with the idempotency key. A duplicate means this removal
|
|
110
|
+
// already ran — report the row's actual current state, not a bare flag.
|
|
111
|
+
const { error: insErr } = await admin.from('membership_admin_actions').insert({
|
|
112
|
+
membership_id: membershipId,
|
|
113
|
+
action: 'sponsor_removed',
|
|
114
|
+
actor_email: callerEmail,
|
|
115
|
+
idempotency_key: idempotencyKey,
|
|
116
|
+
reason: reasonInput,
|
|
117
|
+
effective_at: new Date().toISOString(),
|
|
118
|
+
} as never);
|
|
119
|
+
if (insErr) {
|
|
120
|
+
if ((insErr as { code?: string }).code === '23505') {
|
|
121
|
+
const { data: current } = await admin
|
|
122
|
+
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
123
|
+
return json(200, { ok: true, duplicate: true, membership: current ?? null });
|
|
124
|
+
}
|
|
125
|
+
return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Explicit column allowlist. door_managed is deliberately left as-is: door
|
|
129
|
+
// revocation is handled downstream, not by flipping this flag here.
|
|
130
|
+
const { error: updErr } = await admin
|
|
131
|
+
.from('memberships')
|
|
132
|
+
.update({
|
|
133
|
+
status: 'canceled',
|
|
134
|
+
membership_ended_at: new Date().toISOString(),
|
|
135
|
+
sponsor_membership_id: null,
|
|
136
|
+
} as never)
|
|
137
|
+
.eq('id', membershipId);
|
|
138
|
+
if (updErr) {
|
|
139
|
+
await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
|
|
140
|
+
await logOps(admin, 'team_member_remove_failed', {
|
|
141
|
+
membership_id: membershipId, actor: callerEmail, message: updErr.message,
|
|
142
|
+
}, { severity: 'error' }).catch(() => {});
|
|
143
|
+
return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const { data: finalRow } = await admin
|
|
147
|
+
.from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
|
|
148
|
+
|
|
149
|
+
return json(200, { ok: true, membership: finalRow ?? null });
|
|
150
|
+
}
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { z } from 'npm:zod@3.23.8';
|
|
3
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
4
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
5
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
6
|
+
|
|
7
|
+
const corsHeaders = {
|
|
8
|
+
'Access-Control-Allow-Origin': '*',
|
|
9
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
10
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const LA_TZ = 'America/Los_Angeles';
|
|
14
|
+
const TRIAL_DAYS = 7;
|
|
15
|
+
const TIMEOUT_MS = 20_000;
|
|
16
|
+
|
|
17
|
+
export interface AdminRequestTrialConfig {
|
|
18
|
+
busBase: string;
|
|
19
|
+
defaultDailyWindowLabel: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
23
|
+
|
|
24
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
25
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
26
|
+
function getJwks(supabaseUrl: string) {
|
|
27
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
28
|
+
return jwksCache;
|
|
29
|
+
}
|
|
30
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
31
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
32
|
+
const token = authHeader.slice(7).trim();
|
|
33
|
+
try {
|
|
34
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
35
|
+
const claims = payload as unknown as CallerClaims;
|
|
36
|
+
if (!claims.sub) return null;
|
|
37
|
+
return claims;
|
|
38
|
+
} catch { return null; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function json(status: number, body: unknown) {
|
|
42
|
+
return new Response(JSON.stringify(body), {
|
|
43
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function sha256Hex(text: string): Promise<string> {
|
|
48
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
49
|
+
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Same construction as event-access-admin's b64urlNoPad (kept byte-identical
|
|
53
|
+
// in behavior): standard base64, then URL-safe substitution, then strip padding.
|
|
54
|
+
function b64urlNoPad(bytes: Uint8Array): string {
|
|
55
|
+
let s = '';
|
|
56
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
57
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// t1 canonical message per ftw-middleware's trial_hmac.py — a body-hash
|
|
61
|
+
// form, NOT event-access-admin's e1 field-list form:
|
|
62
|
+
// t1\n{verb}\n{ts}\n{body_sha256_hex}
|
|
63
|
+
// verb is the literal "provision"/"cancel" URL path segment; ts is stamped
|
|
64
|
+
// immediately before the fetch call (300s replay window, 30s skew tolerance
|
|
65
|
+
// on the server, so a stale ts here fails closed).
|
|
66
|
+
async function signT1(secret: string, verb: string, ts: string, bodyHashHex: string): Promise<string> {
|
|
67
|
+
const key = await crypto.subtle.importKey(
|
|
68
|
+
'raw', new TextEncoder().encode(secret),
|
|
69
|
+
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
|
|
70
|
+
);
|
|
71
|
+
const msg = ['t1', verb, ts, bodyHashHex].join('\n');
|
|
72
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg));
|
|
73
|
+
return b64urlNoPad(new Uint8Array(sig));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// LA-calendar-day math, mirroring the todayLA()-style Intl.DateTimeFormat
|
|
77
|
+
// pattern in admin-issue-day-pass/index.ts, extended to add N days and land
|
|
78
|
+
// on that day's midnight boundary rather than just adding N*24h — a plain
|
|
79
|
+
// hour offset would land trial_end_at an hour off across a DST transition.
|
|
80
|
+
function laOffsetHours(atUtc: Date): number {
|
|
81
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
82
|
+
timeZone: LA_TZ,
|
|
83
|
+
timeZoneName: 'longOffset',
|
|
84
|
+
}).formatToParts(atUtc);
|
|
85
|
+
const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
|
|
86
|
+
const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
|
|
87
|
+
if (!m) return -8;
|
|
88
|
+
const sign = m[1] === '+' ? 1 : -1;
|
|
89
|
+
return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function laDateParts(d: Date): { y: number; mo: number; day: number } {
|
|
93
|
+
const fmt = new Intl.DateTimeFormat('en-CA', {
|
|
94
|
+
timeZone: LA_TZ, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
95
|
+
}).formatToParts(d);
|
|
96
|
+
const get = (t: string) => fmt.find((p) => p.type === t)?.value ?? '';
|
|
97
|
+
return { y: parseInt(get('year'), 10), mo: parseInt(get('month'), 10), day: parseInt(get('day'), 10) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function laWallToUtc(y: number, mo: number, day: number, hh: number, mm: number): Date {
|
|
101
|
+
const guess = new Date(Date.UTC(y, mo - 1, day, 12));
|
|
102
|
+
const off = laOffsetHours(guess);
|
|
103
|
+
return new Date(Date.UTC(y, mo - 1, day, hh - Math.trunc(off), mm));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** LA midnight at the end of the 7th calendar day from `start`'s LA-local
|
|
107
|
+
* date — i.e. add TRIAL_DAYS calendar days to that date, then take 00:00
|
|
108
|
+
* LA of the result. */
|
|
109
|
+
function trialEndAtLA(start: Date): Date {
|
|
110
|
+
const { y, mo, day } = laDateParts(start);
|
|
111
|
+
// Date.UTC normalizes an overflowing day-of-month (e.g. day 31 + 7 in a
|
|
112
|
+
// 30-day month), so this correctly rolls into the next month/year.
|
|
113
|
+
const target = new Date(Date.UTC(y, mo - 1, day + TRIAL_DAYS, 12));
|
|
114
|
+
const t = laDateParts(target);
|
|
115
|
+
return laWallToUtc(t.y, t.mo, t.day, 0, 0);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const Body = z.object({
|
|
119
|
+
first_name: z.string().trim().min(1).max(200),
|
|
120
|
+
last_name: z.string().trim().min(1).max(200),
|
|
121
|
+
email: z.string().trim().email().max(255),
|
|
122
|
+
phone: z.string().trim().max(32).optional(),
|
|
123
|
+
trial_start_at: z.string().datetime().optional(),
|
|
124
|
+
daily_window_label: z.string().trim().min(1).max(200).optional(),
|
|
125
|
+
override_prior_grant_id: z.string().uuid().optional(),
|
|
126
|
+
override_reason: z.string().trim().min(1).max(500).optional(),
|
|
127
|
+
}).refine((data) => !data.override_prior_grant_id || !!data.override_reason, {
|
|
128
|
+
message: 'override_reason is required when override_prior_grant_id is set',
|
|
129
|
+
path: ['override_reason'],
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
export async function handle(req: Request, config: AdminRequestTrialConfig): Promise<Response> {
|
|
133
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
134
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
135
|
+
|
|
136
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
137
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
138
|
+
|
|
139
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
140
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
141
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
142
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
143
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
144
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
145
|
+
|
|
146
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
147
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
151
|
+
checkRateLimit(admin, 'admin-request-trial-ip', clientIp(req), 30, 300),
|
|
152
|
+
checkRateLimit(admin, 'admin-request-trial-email', callerEmail, 20, 300),
|
|
153
|
+
]);
|
|
154
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
155
|
+
|
|
156
|
+
const { data: allow, error: allowErr } = await admin
|
|
157
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
158
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
159
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
160
|
+
|
|
161
|
+
let raw: unknown;
|
|
162
|
+
try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
163
|
+
const parsed = Body.safeParse(raw);
|
|
164
|
+
if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
|
|
165
|
+
const {
|
|
166
|
+
first_name, last_name, email, phone,
|
|
167
|
+
trial_start_at, daily_window_label,
|
|
168
|
+
override_prior_grant_id, override_reason,
|
|
169
|
+
} = parsed.data;
|
|
170
|
+
|
|
171
|
+
const emailNormalized = email.trim().toLowerCase();
|
|
172
|
+
const isOverride = !!override_prior_grant_id && !!override_reason;
|
|
173
|
+
const eligibilityKeyHash = await sha256Hex(emailNormalized);
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
const { data: existingLedger, error: ledgerErr } = await admin
|
|
177
|
+
.from('trial_eligibility_ledger')
|
|
178
|
+
.select('id')
|
|
179
|
+
.eq('key_type', 'email')
|
|
180
|
+
.eq('key_hash', eligibilityKeyHash)
|
|
181
|
+
.maybeSingle();
|
|
182
|
+
if (ledgerErr) return json(500, { ok: false, error: 'eligibility_lookup_failed', detail: ledgerErr.message });
|
|
183
|
+
if (existingLedger && !isOverride) {
|
|
184
|
+
return json(409, { ok: false, error: 'already_used_trial' });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const trialStart = trial_start_at ? new Date(trial_start_at) : new Date();
|
|
188
|
+
if (isNaN(trialStart.getTime())) return json(400, { ok: false, error: 'invalid_trial_start_at' });
|
|
189
|
+
const trialEnd = trialEndAtLA(trialStart);
|
|
190
|
+
const windowLabel = daily_window_label ?? config.defaultDailyWindowLabel;
|
|
191
|
+
|
|
192
|
+
const { data: grant, error: grantErr } = await admin
|
|
193
|
+
.from('trial_grants')
|
|
194
|
+
.insert({
|
|
195
|
+
status: 'requested',
|
|
196
|
+
email_normalized: emailNormalized,
|
|
197
|
+
phone_e164: phone ?? null,
|
|
198
|
+
first_name,
|
|
199
|
+
last_name,
|
|
200
|
+
eligibility_key_hash: eligibilityKeyHash,
|
|
201
|
+
source: 'staff_console',
|
|
202
|
+
created_by: callerEmail,
|
|
203
|
+
trial_start_at: trialStart.toISOString(),
|
|
204
|
+
trial_end_at: trialEnd.toISOString(),
|
|
205
|
+
daily_window_label: windowLabel,
|
|
206
|
+
override_prior_grant_id: override_prior_grant_id ?? null,
|
|
207
|
+
override_reason: override_reason ?? null,
|
|
208
|
+
})
|
|
209
|
+
.select('id, trial_start_at, trial_end_at, status, provisioning_attempts')
|
|
210
|
+
.single();
|
|
211
|
+
if (grantErr) return json(500, { ok: false, error: 'insert_failed', detail: grantErr.message });
|
|
212
|
+
|
|
213
|
+
// Provision door access right away. Every path below (missing secret,
|
|
214
|
+
// network/timeout, non-200) is caught and logged, never thrown — the
|
|
215
|
+
// trial_grants row already committed above must never be blocked by a
|
|
216
|
+
// downstream provisioning failure.
|
|
217
|
+
let finalStatus: string = grant.status;
|
|
218
|
+
let credential: { pin: string } | undefined;
|
|
219
|
+
let provisioningErrorForResponse: string | undefined;
|
|
220
|
+
let provisionOk = false;
|
|
221
|
+
let provisionUnifiUserId: string | undefined;
|
|
222
|
+
let provisionPin: string | undefined;
|
|
223
|
+
let provisionErrorCode: string | undefined;
|
|
224
|
+
|
|
225
|
+
const trialHmacSecret = Deno.env.get('TRIAL_HMAC_SECRET');
|
|
226
|
+
if (!trialHmacSecret) {
|
|
227
|
+
await logOps(admin, 'admin_request_trial_provision_secret_missing',
|
|
228
|
+
{ grant_id: grant.id }, { severity: 'error' });
|
|
229
|
+
provisionErrorCode = 'provisioning_unconfigured';
|
|
230
|
+
} else {
|
|
231
|
+
const outboundProvision = {
|
|
232
|
+
grant_id: grant.id,
|
|
233
|
+
first_name,
|
|
234
|
+
last_name,
|
|
235
|
+
email: emailNormalized,
|
|
236
|
+
phone: phone ?? undefined,
|
|
237
|
+
trial_start_at: grant.trial_start_at,
|
|
238
|
+
trial_end_at: grant.trial_end_at,
|
|
239
|
+
daily_window_label: windowLabel,
|
|
240
|
+
};
|
|
241
|
+
// Exact bytes posted are the exact bytes digested.
|
|
242
|
+
const rawProvisionBody = JSON.stringify(outboundProvision);
|
|
243
|
+
const provisionBodyHash = await sha256Hex(rawProvisionBody);
|
|
244
|
+
// Stamp ts last, immediately before the fetch — 300s replay window.
|
|
245
|
+
const provisionTs = String(Math.floor(Date.now() / 1000));
|
|
246
|
+
const provisionSignature = await signT1(trialHmacSecret, 'provision', provisionTs, provisionBodyHash);
|
|
247
|
+
|
|
248
|
+
let provisionRes: Response | null = null;
|
|
249
|
+
try {
|
|
250
|
+
provisionRes = await fetch(`${config.busBase}/trial/provision`, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: {
|
|
253
|
+
'Content-Type': 'application/json',
|
|
254
|
+
'X-Trial-Signature': provisionSignature,
|
|
255
|
+
'X-Trial-Timestamp': provisionTs,
|
|
256
|
+
},
|
|
257
|
+
body: rawProvisionBody,
|
|
258
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
259
|
+
});
|
|
260
|
+
} catch (e) {
|
|
261
|
+
const isTimeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError');
|
|
262
|
+
await logOps(admin, 'admin_request_trial_provision_call_error',
|
|
263
|
+
{ grant_id: grant.id, message: String(e) }, { severity: 'error' });
|
|
264
|
+
provisionErrorCode = isTimeout ? 'middleware_timeout' : 'middleware_unreachable';
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (provisionRes) {
|
|
268
|
+
const provisionText = await provisionRes.text();
|
|
269
|
+
let provisionParsed: Record<string, unknown> | null = null;
|
|
270
|
+
try { provisionParsed = provisionText ? JSON.parse(provisionText) : null; } catch { provisionParsed = null; }
|
|
271
|
+
|
|
272
|
+
if (!provisionRes.ok) {
|
|
273
|
+
// Never log the raw response body/text — a 200 body can carry
|
|
274
|
+
// credential.pin, and non-200 bodies aren't guaranteed pin-free either.
|
|
275
|
+
provisionErrorCode = typeof provisionParsed?.error === 'string'
|
|
276
|
+
? provisionParsed.error : `http_${provisionRes.status}`;
|
|
277
|
+
await logOps(admin, 'admin_request_trial_provision_failed',
|
|
278
|
+
{ grant_id: grant.id, status: provisionRes.status, error: provisionErrorCode }, { severity: 'error' });
|
|
279
|
+
} else {
|
|
280
|
+
provisionOk = true;
|
|
281
|
+
provisionUnifiUserId = typeof provisionParsed?.unifi_user_id === 'string'
|
|
282
|
+
? provisionParsed.unifi_user_id : undefined;
|
|
283
|
+
const cred = provisionParsed?.credential as Record<string, unknown> | undefined;
|
|
284
|
+
provisionPin = cred && typeof cred.pin === 'string' ? cred.pin : undefined;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (provisionOk) {
|
|
290
|
+
const updatePayload: Record<string, unknown> = {
|
|
291
|
+
status: 'active',
|
|
292
|
+
unifi_user_id: provisionUnifiUserId ?? null,
|
|
293
|
+
credential_type: 'pin',
|
|
294
|
+
activated_at: new Date().toISOString(),
|
|
295
|
+
};
|
|
296
|
+
if (provisionPin) {
|
|
297
|
+
updatePayload.pin_issued_at = new Date().toISOString();
|
|
298
|
+
} else {
|
|
299
|
+
updatePayload.notes = 'Provisioned without a PIN — mint/set failed on ftw-middleware.';
|
|
300
|
+
}
|
|
301
|
+
const { error: statusUpdateErr } = await admin.from('trial_grants').update(updatePayload).eq('id', grant.id);
|
|
302
|
+
if (statusUpdateErr) {
|
|
303
|
+
await logOps(admin, 'admin_request_trial_status_update_failed',
|
|
304
|
+
{ grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
|
|
305
|
+
}
|
|
306
|
+
finalStatus = 'active';
|
|
307
|
+
if (provisionPin) credential = { pin: provisionPin };
|
|
308
|
+
} else {
|
|
309
|
+
const errorCode = provisionErrorCode ?? 'middleware_unreachable';
|
|
310
|
+
const { error: statusUpdateErr } = await admin.from('trial_grants').update({
|
|
311
|
+
status: 'failed',
|
|
312
|
+
provisioning_attempts: (grant.provisioning_attempts ?? 0) + 1,
|
|
313
|
+
last_provisioning_error: errorCode,
|
|
314
|
+
}).eq('id', grant.id);
|
|
315
|
+
if (statusUpdateErr) {
|
|
316
|
+
await logOps(admin, 'admin_request_trial_status_update_failed',
|
|
317
|
+
{ grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
|
|
318
|
+
}
|
|
319
|
+
finalStatus = 'failed';
|
|
320
|
+
provisioningErrorForResponse = errorCode;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const { error: ledgerInsertErr } = await admin
|
|
324
|
+
.from('trial_eligibility_ledger')
|
|
325
|
+
.insert({
|
|
326
|
+
key_type: 'email',
|
|
327
|
+
key_hash: eligibilityKeyHash,
|
|
328
|
+
grant_id: grant.id,
|
|
329
|
+
outcome: 'granted',
|
|
330
|
+
});
|
|
331
|
+
// Append-only, best-effort: a duplicate-key retry on the unique
|
|
332
|
+
// (key_type, key_hash) index is harmless — the grant row above is
|
|
333
|
+
// already the source of truth for this request.
|
|
334
|
+
if (ledgerInsertErr && (ledgerInsertErr as { code?: string }).code !== '23505') {
|
|
335
|
+
await logOps(admin, 'admin_request_trial_ledger_insert_failed',
|
|
336
|
+
{ message: ledgerInsertErr.message, grant_id: grant.id, actor: callerEmail },
|
|
337
|
+
{ severity: 'warning' });
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
await admin.from('trial_grant_events').insert({
|
|
341
|
+
grant_id: grant.id,
|
|
342
|
+
actor_user_id: callerEmail,
|
|
343
|
+
action: 'grant_requested',
|
|
344
|
+
request_payload: parsed.data,
|
|
345
|
+
ok: true,
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
return json(200, {
|
|
349
|
+
ok: true,
|
|
350
|
+
grant_id: grant.id,
|
|
351
|
+
trial_start_at: grant.trial_start_at,
|
|
352
|
+
trial_end_at: grant.trial_end_at,
|
|
353
|
+
status: finalStatus,
|
|
354
|
+
...(credential ? { credential } : {}),
|
|
355
|
+
...(provisioningErrorForResponse ? { provisioning_error: provisioningErrorForResponse } : {}),
|
|
356
|
+
});
|
|
357
|
+
} catch (e) {
|
|
358
|
+
console.error('admin-request-trial error', e);
|
|
359
|
+
try {
|
|
360
|
+
await logOps(admin, 'admin_request_trial_error',
|
|
361
|
+
{ message: e instanceof Error ? e.message : String(e), actor: callerEmail },
|
|
362
|
+
{ severity: 'error' });
|
|
363
|
+
} catch { /* ignore */ }
|
|
364
|
+
return json(500, { ok: false, error: 'unexpected_error' });
|
|
365
|
+
}
|
|
366
|
+
}
|