@simplelayer/graniteer-core 0.3.21-referral.1 → 0.3.21-referral.2

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.
@@ -49,7 +49,7 @@ export function minNoticeErrorMessage(nowMs, cfg) {
49
49
  const earliest = new Intl.DateTimeFormat('en-US', {
50
50
  timeZone: 'America/Los_Angeles',
51
51
  weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
52
- }).format(new Date(earliestBookingStartMs(nowMs, cfg)));
52
+ }).format(new Date(earliestBookingStartMs(nowMs, cfg))).replace(/[  ]/g, ' ');
53
53
  return `Bookings need at least ${cfg.minNoticeBusinessHours} business hours notice ` +
54
54
  `(Monday–Friday, excluding holidays). The earliest available start is ${earliest} Pacific time.`;
55
55
  }
@@ -11,7 +11,7 @@ import { buildSubscriptionSessionParams } from '../checkoutSessionParams.js';
11
11
  // migration-checkout functions can reuse the exact same clamp/validation
12
12
  // arithmetic instead of duplicating it. Pure refactor: no behavior change.
13
13
  import { MAX_START_DATE_DAYS, pacificDateStr, addDaysStr } from '../pacificDate.js';
14
- import { escapeLikePattern } from '../referralCodeLookup.js';
14
+ import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
15
15
  const Body = z.object({
16
16
  plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
17
17
  email: z.string().email().max(255),
@@ -206,7 +206,9 @@ export async function handle(req, operator) {
206
206
  // code, malicious input) is NOT an error -- it just means no referral
207
207
  // metadata gets attached, same as if the field had been omitted.
208
208
  let referralCode;
209
- if (referral_code) {
209
+ // Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a '*'
210
+ // wildcard) is treated exactly like an omitted/unknown code -- no lookup.
211
+ if (referral_code && isValidReferralCode(referral_code)) {
210
212
  try {
211
213
  const { data: referrer, error: refErr } = await supabase
212
214
  .from('memberships')
@@ -424,6 +424,8 @@ export async function handle(req, operator, deps) {
424
424
  outcome: fresh.status,
425
425
  });
426
426
  }
427
+ // Re-read failed: fail closed, never fall through to the credit grant.
428
+ return json(409, { error: 'already_changed' });
427
429
  }
428
430
  // Credit ledger row(s): split cash-funded (1yr) vs credit-funded (capped at
429
431
  // the ORIGINAL credit's own expiry) so a cancellation can never launder a
@@ -7,7 +7,7 @@ import { extractDoorAccess } from '../busClient.js';
7
7
  import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js';
8
8
  import { sendDunningEmail } from '../dunningEmails.js';
9
9
  import { recordReferralFailure } from '../referralGrant.js';
10
- import { escapeLikePattern } from '../referralCodeLookup.js';
10
+ import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
11
11
  import { findBaseItem } from '../membershipSubscriptionItems.js';
12
12
  import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
13
13
  import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
@@ -101,7 +101,9 @@ function buildStripeWebhookHandler(config, connect) {
101
101
  .from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
102
102
  return data;
103
103
  }
104
+ let bookingLookupErrored = false;
104
105
  async function findBookingIdByPaymentIntent(paymentIntentId) {
106
+ bookingLookupErrored = false;
105
107
  const { data: rows, error } = await supabase
106
108
  .from('bookings')
107
109
  .select('id')
@@ -113,6 +115,7 @@ function buildStripeWebhookHandler(config, connect) {
113
115
  payment_intent_id: paymentIntentId,
114
116
  ...(typeof code === 'string' ? { error_code: code } : {}),
115
117
  }, { severity: 'error', bookingId: null });
118
+ bookingLookupErrored = true;
116
119
  return null;
117
120
  }
118
121
  const list = (rows ?? []);
@@ -150,8 +153,11 @@ function buildStripeWebhookHandler(config, connect) {
150
153
  let markerFailed = false;
151
154
  try {
152
155
  bookingId = await findBookingIdByPaymentIntent(piId);
153
- if (!bookingId)
154
- return 'skipped';
156
+ if (!bookingId) {
157
+ // Connect: the marker is the only thing blocking self-service credit,
158
+ // so a lookup DB error must be retried by Stripe, not silently acked.
159
+ return connect && bookingLookupErrored ? 'marker_failed' : 'skipped';
160
+ }
155
161
  if (connect) {
156
162
  // Connect (direct-charge) bookings are refunded outside the app, so
157
163
  // nothing cancels the booking: status stays 'paid', the slot stays
@@ -585,6 +591,10 @@ function buildStripeWebhookHandler(config, connect) {
585
591
  const refCode = sub.metadata?.referral_code;
586
592
  if (!refCode)
587
593
  return; // no referral on this signup -- normal case
594
+ // Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a
595
+ // '*' wildcard) is treated exactly like no referral code at all.
596
+ if (!isValidReferralCode(refCode))
597
+ return;
588
598
  const { data: referrer, error: referrerErr } = await supabase
589
599
  .from('memberships')
590
600
  .select('id')
@@ -2117,10 +2127,17 @@ function buildStripeWebhookHandler(config, connect) {
2117
2127
  }
2118
2128
  }
2119
2129
  catch (e) {
2130
+ const permanentStripeError = e?.type === 'StripeInvalidRequestError' && !isRetryableStripeError(e);
2120
2131
  await logOps(supabase, 'booking_access_revoke_step_failed', {
2121
2132
  reason: 'charge_dispute_created',
2122
2133
  error_name: errorNameFromUnknown(e),
2134
+ permanent_stripe_error: permanentStripeError,
2123
2135
  }, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
2136
+ if (connect && !permanentStripeError) {
2137
+ // Marker is the only thing blocking self-service credit on Connect; let Stripe retry.
2138
+ await releaseStripeEventLedgerForRetry(event.id);
2139
+ return webhookResponseMarkerFailedForRetry();
2140
+ }
2124
2141
  }
2125
2142
  break;
2126
2143
  }
@@ -1 +1,13 @@
1
1
  export declare function escapeLikePattern(input: string): string;
2
+ /**
3
+ * Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
4
+ * the 1..32 range matches the zod bound on the checkout input and tolerates
5
+ * lowercase typos, which ilike matches case-insensitively).
6
+ *
7
+ * Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
8
+ * ilike value as a wildcard alias for '%', and escapeLikePattern does not
9
+ * escape it, so '*' would match the first membership's code. Anything outside
10
+ * [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
11
+ * lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
12
+ */
13
+ export declare function isValidReferralCode(input: unknown): input is string;
@@ -1,3 +1,17 @@
1
1
  export function escapeLikePattern(input) {
2
2
  return input.replace(/[\\%_]/g, (ch) => '\\' + ch);
3
3
  }
4
+ /**
5
+ * Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
6
+ * the 1..32 range matches the zod bound on the checkout input and tolerates
7
+ * lowercase typos, which ilike matches case-insensitively).
8
+ *
9
+ * Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
10
+ * ilike value as a wildcard alias for '%', and escapeLikePattern does not
11
+ * escape it, so '*' would match the first membership's code. Anything outside
12
+ * [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
13
+ * lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
14
+ */
15
+ export function isValidReferralCode(input) {
16
+ return typeof input === 'string' && /^[A-Za-z0-9]{1,32}$/.test(input);
17
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.21-referral.1",
3
+ "version": "0.3.21-referral.2",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",