@simplelayer/graniteer-core 0.3.23 → 0.3.26
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/bookingEffects.js +9 -6
- package/dist/checkoutSessionParams.js +1 -0
- package/dist/connectBookingCharge.d.ts +8 -0
- package/dist/connectBookingCharge.js +11 -2
- package/dist/functions/admin-issue-day-pass.js +1 -0
- package/dist/functions/admin-mint-portal-link.js +5 -4
- package/dist/functions/booking-access-grant.d.ts +32 -0
- package/dist/functions/booking-access-grant.js +195 -0
- package/dist/functions/booking-access-revoke-backstop.d.ts +7 -0
- package/dist/functions/booking-access-revoke-backstop.js +11 -0
- package/dist/functions/booking-status.js +20 -11
- package/dist/functions/create-agreement.d.ts +6 -0
- package/dist/functions/create-agreement.js +15 -7
- package/dist/functions/create-portal-session.js +4 -2
- package/dist/functions/manage-booking.d.ts +1 -0
- package/dist/functions/manage-booking.js +26 -19
- package/dist/functions/request-portal-link.js +7 -8
- package/dist/functions/reschedule-booking.js +4 -3
- package/dist/functions/stripe-webhook.js +19 -4
- package/dist/manageToken.d.ts +7 -0
- package/dist/manageToken.js +30 -0
- package/dist/migrationCheckout.js +6 -2
- package/dist/portalSession.js +4 -0
- package/dist/rateLimit.d.ts +7 -0
- package/dist/rateLimit.js +12 -0
- package/package.json +9 -1
package/dist/bookingEffects.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// That whole door/calendar-signing group is deferred to a later phase gated on
|
|
13
13
|
// a dedicated security review, so createCalendarEvent stays in gc-connect,
|
|
14
14
|
// untouched, and imports isDepositOnly/parseTstzRange/formatDollars from here.
|
|
15
|
-
import { buildManageUrl } from './manageToken.js';
|
|
15
|
+
import { buildManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE } from './manageToken.js';
|
|
16
16
|
import { deriveReservationWifiCode, isReservationWifiRoom } from './reservationWifiCode.js';
|
|
17
17
|
const LA_TZ = 'America/Los_Angeles';
|
|
18
18
|
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
@@ -163,15 +163,18 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
|
|
|
163
163
|
const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
|
|
164
164
|
const gcalLocation = booking.rooms?.address || operator.name;
|
|
165
165
|
const gcalUrl = googleCalendarUrl(startISO, endISO, gcalTitle, gcalDetails, gcalLocation);
|
|
166
|
-
const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET')
|
|
166
|
+
const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
167
167
|
let manageUrl = '';
|
|
168
|
-
if (manageSecret) {
|
|
168
|
+
if (!isManageTokenSecretUsable(manageSecret)) {
|
|
169
|
+
console.error('[bookingEffects]', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
169
172
|
try {
|
|
170
173
|
const exp = Math.floor(new Date(endISO).getTime() / 1000) + 30 * 24 * 60 * 60;
|
|
171
174
|
manageUrl = await buildManageUrl(config.manageUrlBase, { bid: booking.id, eml: (booking.contact_email || '').toLowerCase(), exp }, manageSecret);
|
|
172
175
|
}
|
|
173
|
-
catch
|
|
174
|
-
console.
|
|
176
|
+
catch {
|
|
177
|
+
console.error('[bookingEffects]', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
175
178
|
}
|
|
176
179
|
}
|
|
177
180
|
const headers = ghlHeaders(apiKey);
|
|
@@ -265,7 +268,7 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
|
|
|
265
268
|
const address = booking.rooms.address || operator.name;
|
|
266
269
|
const manageParagraph = manageUrl
|
|
267
270
|
? `<p>Need to change plans? <a href='${manageUrl}' style='color:#C98A5E'>Manage your booking</a> — free cancellation with credit up to 48 hours before your start time.</p>`
|
|
268
|
-
:
|
|
271
|
+
: `<p>Need to change plans? Reply to this email to manage your booking — a manage link is not available for this confirmation.</p>`;
|
|
269
272
|
let doorSection = '';
|
|
270
273
|
if (doorAccess?.pin) {
|
|
271
274
|
const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
|
|
@@ -130,6 +130,7 @@ export function buildDayPassSessionParams(input) {
|
|
|
130
130
|
: { receipt_email: input.receiptEmail };
|
|
131
131
|
return {
|
|
132
132
|
mode: 'payment',
|
|
133
|
+
payment_method_types: ['card'],
|
|
133
134
|
customer: input.customerId,
|
|
134
135
|
line_items: [{ price: input.priceId, quantity: 1 }],
|
|
135
136
|
...(input.stripeCouponId
|
|
@@ -44,6 +44,14 @@ type SessionCreator = {
|
|
|
44
44
|
};
|
|
45
45
|
};
|
|
46
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* Single choke point for booking Checkout sessions. Both branches force
|
|
49
|
+
* payment_method_types ['card']: delayed-notification methods (e.g. ACH debit)
|
|
50
|
+
* are excluded so a completed session always means money moved, which the
|
|
51
|
+
* stripe-webhook paid guard (payment_status 'paid' / 'no_payment_required')
|
|
52
|
+
* relies on. Connect sessions additionally go to the connected account with
|
|
53
|
+
* the application fee.
|
|
54
|
+
*/
|
|
47
55
|
export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
|
|
48
56
|
export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
|
|
49
57
|
export {};
|
|
@@ -57,12 +57,21 @@ export function applyConnectToSessionParams(params, plan) {
|
|
|
57
57
|
export function stripeAccountRequestOptions(accountId) {
|
|
58
58
|
return accountId ? { stripeAccount: accountId } : undefined;
|
|
59
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Single choke point for booking Checkout sessions. Both branches force
|
|
62
|
+
* payment_method_types ['card']: delayed-notification methods (e.g. ACH debit)
|
|
63
|
+
* are excluded so a completed session always means money moved, which the
|
|
64
|
+
* stripe-webhook paid guard (payment_status 'paid' / 'no_payment_required')
|
|
65
|
+
* relies on. Connect sessions additionally go to the connected account with
|
|
66
|
+
* the application fee.
|
|
67
|
+
*/
|
|
60
68
|
export function createBookingCheckoutSession(stripe, params, plan) {
|
|
61
69
|
if ('error' in plan) {
|
|
62
70
|
return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
|
|
63
71
|
}
|
|
64
|
-
if (!plan.connected)
|
|
65
|
-
return stripe.checkout.sessions.create(params);
|
|
72
|
+
if (!plan.connected) {
|
|
73
|
+
return stripe.checkout.sessions.create({ ...params, payment_method_types: ['card'] });
|
|
74
|
+
}
|
|
66
75
|
return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, { stripeAccount: plan.accountId });
|
|
67
76
|
}
|
|
68
77
|
export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
|
|
@@ -136,6 +136,7 @@ operator, deps) {
|
|
|
136
136
|
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
137
137
|
const session = await stripe.checkout.sessions.create({
|
|
138
138
|
mode: 'payment',
|
|
139
|
+
payment_method_types: ['card'],
|
|
139
140
|
customer: customerId,
|
|
140
141
|
line_items: [{ price: plan.stripe_price_id, quantity: 1 }],
|
|
141
142
|
allow_promotion_codes: true,
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// signature_documents row. Read-only against the DB; reuses MANAGE_TOKEN_SECRET
|
|
3
3
|
// and the same buildAgreementPortalUrl helper as create-agreement.
|
|
4
4
|
import { createClient } from '@supabase/supabase-js';
|
|
5
|
-
import { buildAgreementPortalUrl } from '../manageToken.js';
|
|
5
|
+
import { buildAgreementPortalUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
|
|
6
6
|
const corsHeaders = {
|
|
7
7
|
'Access-Control-Allow-Origin': '*',
|
|
8
8
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
@@ -32,6 +32,10 @@ export async function handle(req, operator) {
|
|
|
32
32
|
return json(400, { ok: false, error: 'invalid_signature_document_id' });
|
|
33
33
|
if (!email)
|
|
34
34
|
return json(400, { ok: false, error: 'invalid_signer_email' });
|
|
35
|
+
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
36
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
37
|
+
return json(503, { ok: false, error: MANAGE_TOKEN_UNAVAILABLE_CODE });
|
|
38
|
+
}
|
|
35
39
|
const admin = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'), { auth: { persistSession: false, autoRefreshToken: false } });
|
|
36
40
|
const { data: row, error } = await admin
|
|
37
41
|
.from('signature_documents')
|
|
@@ -46,9 +50,6 @@ export async function handle(req, operator) {
|
|
|
46
50
|
if (!rowEmail || rowEmail !== email.toLowerCase()) {
|
|
47
51
|
return json(404, { ok: false, error: 'not_found' });
|
|
48
52
|
}
|
|
49
|
-
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
50
|
-
if (!secret)
|
|
51
|
-
return json(500, { ok: false, error: 'not_configured' });
|
|
52
53
|
const url = await buildAgreementPortalUrl(`https://${operator.domain}`, String(row.id), rowEmail, secret);
|
|
53
54
|
return json(200, { ok: true, url });
|
|
54
55
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
export type SupabaseLike = SupabaseClient<any, any, any>;
|
|
3
|
+
export declare const ORGANIZER_GRANT_TIMEOUT_MS = 95000;
|
|
4
|
+
export interface RequestOrganizerGrantOptions {
|
|
5
|
+
bookingId: string;
|
|
6
|
+
/** gc-io doors.id (uuid), NOT the UniFi id; resolved from the doors table. */
|
|
7
|
+
doorId: string;
|
|
8
|
+
organizer: {
|
|
9
|
+
name?: string | null;
|
|
10
|
+
email?: string | null;
|
|
11
|
+
phone?: string | null;
|
|
12
|
+
};
|
|
13
|
+
startUtc: string;
|
|
14
|
+
endUtc: string;
|
|
15
|
+
/** Caller supplied, e.g. commons:<bookingId>:<doorId>. */
|
|
16
|
+
idempotencyKey: string;
|
|
17
|
+
actingUserId: string;
|
|
18
|
+
busBase?: string;
|
|
19
|
+
fetchImpl?: typeof fetch;
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
}
|
|
22
|
+
export type RequestOrganizerGrantError = 'invalid_input' | 'door_lookup_failed' | 'door_not_found' | 'door_not_provisioned' | 'door_not_live' | 'lockdown_not_verified' | 'secret_missing' | 'middleware_unreachable' | 'middleware_rejected' | 'middleware_error' | 'bad_response' | 'unexpected';
|
|
23
|
+
export type RequestOrganizerGrantResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
grant_id: string;
|
|
26
|
+
idempotent: boolean;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
error: RequestOrganizerGrantError;
|
|
30
|
+
status?: number;
|
|
31
|
+
};
|
|
32
|
+
export declare function requestOrganizerGrant(admin: SupabaseLike, opts: RequestOrganizerGrantOptions): Promise<RequestOrganizerGrantResult>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Request an organizer door-access grant for a booking via the tenant
|
|
2
|
+
// middleware's signed /admin/event-access/grant path (same e1 HMAC contract and
|
|
3
|
+
// outbound body as the staff "grant" branch in event-access-admin.ts).
|
|
4
|
+
//
|
|
5
|
+
// Unattended path that can open physical doors: every step fails closed, the
|
|
6
|
+
// function never throws, and nothing sensitive (PINs, organizer PII, secret,
|
|
7
|
+
// signature, raw response) is returned or logged.
|
|
8
|
+
import { logOps } from '../ops.js';
|
|
9
|
+
import { sha256Hex, signBusMessage } from '../busSignature.js';
|
|
10
|
+
import { getEventAccessBusBase } from '../tenant-config.js';
|
|
11
|
+
// Grant-only headroom, same as event-access-admin's GRANT_TIMEOUT_MS: the
|
|
12
|
+
// middleware mints PINs with a retry loop (worst case ~85s) and the Cloudflare
|
|
13
|
+
// Tunnel edge cuts proxied HTTP at ~100s, so 95s clears the former and there
|
|
14
|
+
// is no point going higher.
|
|
15
|
+
export const ORGANIZER_GRANT_TIMEOUT_MS = 95_000;
|
|
16
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
+
const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
|
|
18
|
+
// Explicit zone required: a zone-less string would be parsed as server-local time.
|
|
19
|
+
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i;
|
|
20
|
+
const MAX_IDEMPOTENCY_KEY_LENGTH = 200;
|
|
21
|
+
function errorName(e) {
|
|
22
|
+
if (e instanceof Error && e.name)
|
|
23
|
+
return e.name;
|
|
24
|
+
return 'Error';
|
|
25
|
+
}
|
|
26
|
+
async function safeLog(admin, kind, detail, bookingId) {
|
|
27
|
+
try {
|
|
28
|
+
await logOps(admin, kind, detail, { severity: 'error', ...(bookingId ? { bookingId } : {}) });
|
|
29
|
+
}
|
|
30
|
+
catch { /* logging must never throw or change the result */ }
|
|
31
|
+
}
|
|
32
|
+
function optionalText(v) {
|
|
33
|
+
if (v === undefined || v === null)
|
|
34
|
+
return null;
|
|
35
|
+
if (typeof v !== 'string')
|
|
36
|
+
return undefined;
|
|
37
|
+
const t = v.trim();
|
|
38
|
+
return t === '' ? null : t;
|
|
39
|
+
}
|
|
40
|
+
function requiredText(v) {
|
|
41
|
+
if (typeof v !== 'string')
|
|
42
|
+
return null;
|
|
43
|
+
const t = v.trim();
|
|
44
|
+
return t === '' ? null : t;
|
|
45
|
+
}
|
|
46
|
+
function instant(v) {
|
|
47
|
+
if (typeof v !== 'string')
|
|
48
|
+
return null;
|
|
49
|
+
const t = v.trim();
|
|
50
|
+
if (!ISO_INSTANT.test(t))
|
|
51
|
+
return null;
|
|
52
|
+
const ms = Date.parse(t);
|
|
53
|
+
if (!Number.isFinite(ms))
|
|
54
|
+
return null;
|
|
55
|
+
return new Date(ms).toISOString();
|
|
56
|
+
}
|
|
57
|
+
function validate(opts) {
|
|
58
|
+
if (!opts || typeof opts !== 'object')
|
|
59
|
+
return null;
|
|
60
|
+
const bookingId = requiredText(opts.bookingId);
|
|
61
|
+
const doorId = requiredText(opts.doorId);
|
|
62
|
+
if (!bookingId || !UUID.test(bookingId) || !doorId || !UUID.test(doorId))
|
|
63
|
+
return null;
|
|
64
|
+
const start = instant(opts.startUtc);
|
|
65
|
+
const end = instant(opts.endUtc);
|
|
66
|
+
if (!start || !end)
|
|
67
|
+
return null;
|
|
68
|
+
if (!(Date.parse(end) > Date.parse(start)))
|
|
69
|
+
return null;
|
|
70
|
+
const idempotencyKey = requiredText(opts.idempotencyKey);
|
|
71
|
+
const actingUserId = requiredText(opts.actingUserId);
|
|
72
|
+
if (!idempotencyKey || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH || !actingUserId)
|
|
73
|
+
return null;
|
|
74
|
+
const org = opts.organizer;
|
|
75
|
+
if (!org || typeof org !== 'object')
|
|
76
|
+
return null;
|
|
77
|
+
const name = optionalText(org.name);
|
|
78
|
+
const email = optionalText(org.email);
|
|
79
|
+
const phone = optionalText(org.phone);
|
|
80
|
+
if (name === undefined || email === undefined || phone === undefined)
|
|
81
|
+
return null;
|
|
82
|
+
return { bookingId, doorId, person: { name, email, phone }, start, end, idempotencyKey, actingUserId };
|
|
83
|
+
}
|
|
84
|
+
export async function requestOrganizerGrant(admin, opts) {
|
|
85
|
+
let logBookingId;
|
|
86
|
+
try {
|
|
87
|
+
const input = validate(opts);
|
|
88
|
+
if (!input)
|
|
89
|
+
return { ok: false, error: 'invalid_input' };
|
|
90
|
+
logBookingId = input.bookingId;
|
|
91
|
+
// Door resolution: doors.id -> UniFi door id. Stricter than the staff path
|
|
92
|
+
// (this is the unattended path): must be live and lockdown-verified.
|
|
93
|
+
const { data: doorData, error: doorErr } = await admin
|
|
94
|
+
.from('doors').select('id,unifi_door_id,status,lockdown_verified').eq('id', input.doorId).maybeSingle();
|
|
95
|
+
if (doorErr) {
|
|
96
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_lookup_failed' }, logBookingId);
|
|
97
|
+
return { ok: false, error: 'door_lookup_failed' };
|
|
98
|
+
}
|
|
99
|
+
if (!doorData) {
|
|
100
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_found' }, logBookingId);
|
|
101
|
+
return { ok: false, error: 'door_not_found' };
|
|
102
|
+
}
|
|
103
|
+
const door = doorData;
|
|
104
|
+
const unifi = typeof door.unifi_door_id === 'string' ? door.unifi_door_id.trim() : '';
|
|
105
|
+
if (!unifi || unifi === 'PENDING') {
|
|
106
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_provisioned' }, logBookingId);
|
|
107
|
+
return { ok: false, error: 'door_not_provisioned' };
|
|
108
|
+
}
|
|
109
|
+
if (door.status !== 'live') {
|
|
110
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_live' }, logBookingId);
|
|
111
|
+
return { ok: false, error: 'door_not_live' };
|
|
112
|
+
}
|
|
113
|
+
if (door.lockdown_verified !== true) {
|
|
114
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'lockdown_not_verified' }, logBookingId);
|
|
115
|
+
return { ok: false, error: 'lockdown_not_verified' };
|
|
116
|
+
}
|
|
117
|
+
const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
|
|
118
|
+
const secret = typeof secretRaw === 'string' ? secretRaw : null;
|
|
119
|
+
if (secretErr || !secret) {
|
|
120
|
+
await safeLog(admin, 'commons_organizer_grant_secret_missing', {}, logBookingId);
|
|
121
|
+
return { ok: false, error: 'secret_missing' };
|
|
122
|
+
}
|
|
123
|
+
// Mirrors event-access-admin.ts's grant branch (key order is part of the signed bytes).
|
|
124
|
+
const outbound = {
|
|
125
|
+
acting_user_id: input.actingUserId,
|
|
126
|
+
person: {
|
|
127
|
+
name: input.person.name,
|
|
128
|
+
email: input.person.email,
|
|
129
|
+
phone: input.person.phone,
|
|
130
|
+
},
|
|
131
|
+
room: { booking_id: input.bookingId },
|
|
132
|
+
door_id: unifi,
|
|
133
|
+
start: input.start,
|
|
134
|
+
end: input.end,
|
|
135
|
+
idempotency_key: input.idempotencyKey,
|
|
136
|
+
};
|
|
137
|
+
const rawBody = JSON.stringify(outbound);
|
|
138
|
+
const bodyHash = await sha256Hex(rawBody);
|
|
139
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
140
|
+
const signature = await signBusMessage(['e1', 'grant', ts, bodyHash].join('\n'), secret);
|
|
141
|
+
const busBase = opts.busBase ?? getEventAccessBusBase();
|
|
142
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
143
|
+
const timeoutMs = typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
|
|
144
|
+
? opts.timeoutMs
|
|
145
|
+
: ORGANIZER_GRANT_TIMEOUT_MS;
|
|
146
|
+
let res;
|
|
147
|
+
try {
|
|
148
|
+
res = await doFetch(`${busBase}/admin/event-access/grant`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: {
|
|
151
|
+
'Content-Type': 'application/json',
|
|
152
|
+
'X-Event-Access-Signature': signature,
|
|
153
|
+
'X-Event-Access-Timestamp': ts,
|
|
154
|
+
},
|
|
155
|
+
body: rawBody,
|
|
156
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
|
|
161
|
+
return { ok: false, error: 'middleware_unreachable' };
|
|
162
|
+
}
|
|
163
|
+
let parsed = null;
|
|
164
|
+
try {
|
|
165
|
+
const text = await res.text();
|
|
166
|
+
parsed = text ? JSON.parse(text) : null;
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
parsed = null;
|
|
170
|
+
}
|
|
171
|
+
const parsedObj = parsed && typeof parsed === 'object' ? parsed : null;
|
|
172
|
+
if (!res.ok) {
|
|
173
|
+
const detail = { status: res.status };
|
|
174
|
+
const code = parsedObj?.error;
|
|
175
|
+
if (typeof code === 'string' && SAFE_ERROR_CODE.test(code))
|
|
176
|
+
detail.error_code = code;
|
|
177
|
+
await safeLog(admin, 'commons_organizer_grant_call_failed', detail, logBookingId);
|
|
178
|
+
return {
|
|
179
|
+
ok: false,
|
|
180
|
+
error: res.status === 401 || res.status === 403 ? 'middleware_rejected' : 'middleware_error',
|
|
181
|
+
status: res.status,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const grantId = parsedObj?.grant_id;
|
|
185
|
+
if (!parsedObj || parsedObj.ok !== true || typeof grantId !== 'string' || grantId.trim() === '') {
|
|
186
|
+
await safeLog(admin, 'commons_organizer_grant_bad_response', { status: res.status }, logBookingId);
|
|
187
|
+
return { ok: false, error: 'bad_response', status: res.status };
|
|
188
|
+
}
|
|
189
|
+
return { ok: true, grant_id: grantId, idempotent: parsedObj.idempotent === true };
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
|
|
193
|
+
return { ok: false, error: 'unexpected' };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -9,3 +9,10 @@ export declare function bookingRowRequiresBackstopRevoke(booking: {
|
|
|
9
9
|
access_revoke_required_at?: string | null;
|
|
10
10
|
}): boolean;
|
|
11
11
|
export declare function handle(req: Request): Promise<Response>;
|
|
12
|
+
export interface BookingAccessRevokeBackstopConfig {
|
|
13
|
+
/** Hand-maintained deploy-verification marker returned by the GET branch. */
|
|
14
|
+
buildMarker: string;
|
|
15
|
+
}
|
|
16
|
+
/** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
|
|
17
|
+
* every other method is delegated to `handle` unchanged. */
|
|
18
|
+
export declare function createBookingAccessRevokeBackstopHandler(config: BookingAccessRevokeBackstopConfig): (req: Request) => Promise<Response>;
|
|
@@ -119,3 +119,14 @@ export async function handle(req) {
|
|
|
119
119
|
headers: { 'Content-Type': 'application/json' },
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
|
+
/** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
|
|
123
|
+
* every other method is delegated to `handle` unchanged. */
|
|
124
|
+
export function createBookingAccessRevokeBackstopHandler(config) {
|
|
125
|
+
const buildMarker = config.buildMarker;
|
|
126
|
+
return (req) => {
|
|
127
|
+
if (req.method === 'GET') {
|
|
128
|
+
return Promise.resolve(new Response(JSON.stringify({ ok: true, function: 'booking-access-revoke-backstop', build: buildMarker }), { status: 200, headers: { 'Content-Type': 'application/json' } }));
|
|
129
|
+
}
|
|
130
|
+
return handle(req);
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { corsHeaders } from '@supabase/supabase-js/cors';
|
|
2
2
|
import { createClient } from '@supabase/supabase-js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { buildManageUrl, verifyManageToken } from '../manageToken.js';
|
|
4
|
+
import { buildManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken, } from '../manageToken.js';
|
|
5
5
|
// Auth model: this endpoint is unauthenticated but MUST NOT return PII for a
|
|
6
6
|
// bare booking UUID (that was an IDOR). Callers must supply either:
|
|
7
7
|
// - session_id: the Stripe Checkout Session id (unguessable, only known to
|
|
@@ -51,11 +51,12 @@ export async function handle(req, operator) {
|
|
|
51
51
|
// Resolve to a booking id via the caller's chosen credential.
|
|
52
52
|
let bookingId = null;
|
|
53
53
|
let tokenBoundEmail = null;
|
|
54
|
-
const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET')
|
|
54
|
+
const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
55
55
|
if (parsed.data.token) {
|
|
56
|
-
if (!manageSecret) {
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
if (!isManageTokenSecretUsable(manageSecret)) {
|
|
57
|
+
console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
58
|
+
return new Response(JSON.stringify({ error: MANAGE_TOKEN_UNAVAILABLE_CODE }), {
|
|
59
|
+
status: 503, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
59
60
|
});
|
|
60
61
|
}
|
|
61
62
|
const claims = await verifyManageToken(parsed.data.token, manageSecret);
|
|
@@ -111,9 +112,17 @@ export async function handle(req, operator) {
|
|
|
111
112
|
const room = data.rooms;
|
|
112
113
|
// Build a manage-booking magic link the confirmation page can surface.
|
|
113
114
|
let manageUrl = null;
|
|
114
|
-
if (manageSecret && range?.end && data.contact_email) {
|
|
115
|
-
|
|
116
|
-
|
|
115
|
+
if (isManageTokenSecretUsable(manageSecret) && range?.end && data.contact_email) {
|
|
116
|
+
try {
|
|
117
|
+
const exp = Math.floor(new Date(range.end).getTime() / 1000) + 30 * 24 * 60 * 60;
|
|
118
|
+
manageUrl = await buildManageUrl(`https://${operator.domain}`, { bid: data.id, eml: data.contact_email.toLowerCase(), exp }, manageSecret);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else if (!isManageTokenSecretUsable(manageSecret)) {
|
|
125
|
+
console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
117
126
|
}
|
|
118
127
|
return new Response(JSON.stringify({
|
|
119
128
|
room_name: room?.name ?? null,
|
|
@@ -130,9 +139,9 @@ export async function handle(req, operator) {
|
|
|
130
139
|
manage_url: manageUrl,
|
|
131
140
|
}), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
|
|
132
141
|
}
|
|
133
|
-
catch
|
|
134
|
-
console.error('booking-status
|
|
135
|
-
return new Response(JSON.stringify({ error:
|
|
142
|
+
catch {
|
|
143
|
+
console.error('booking-status', 'internal_error');
|
|
144
|
+
return new Response(JSON.stringify({ error: 'internal_error' }), {
|
|
136
145
|
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
137
146
|
});
|
|
138
147
|
}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mint an agreement-portal URL, or return null when MANAGE_TOKEN_SECRET is
|
|
3
|
+
* missing/under 32 UTF-8 bytes. Fail closed: never produces a weak URL, never
|
|
4
|
+
* logs the secret or its length.
|
|
5
|
+
*/
|
|
6
|
+
export declare function issueAgreementPortalUrl(base: string, signatureDocumentId: string, signerEmail: string, secret: string | undefined | null): Promise<string | null>;
|
|
1
7
|
export declare function handle(req: Request, operator: {
|
|
2
8
|
operatorName: string;
|
|
3
9
|
operatorShortName: string;
|
|
@@ -4,7 +4,7 @@ import JSZip from 'jszip';
|
|
|
4
4
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
5
5
|
import { centsFrom } from '../agreementCheckout.js';
|
|
6
6
|
import { parseRetainerConfig } from '../money.js';
|
|
7
|
-
import { buildAgreementPortalUrl } from '../manageToken.js';
|
|
7
|
+
import { buildAgreementPortalUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
|
|
8
8
|
import { sendAgreementPortalEmail } from '../agreementPortalEmail.js';
|
|
9
9
|
import { logOps } from '../ops.js';
|
|
10
10
|
const corsHeaders = {
|
|
@@ -182,6 +182,18 @@ function validateAgreementBillability(v) {
|
|
|
182
182
|
return retainer.code === 'service_retainer_absent' ? 'service_retainer_must_be_positive' : retainer.code;
|
|
183
183
|
return null;
|
|
184
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* Mint an agreement-portal URL, or return null when MANAGE_TOKEN_SECRET is
|
|
187
|
+
* missing/under 32 UTF-8 bytes. Fail closed: never produces a weak URL, never
|
|
188
|
+
* logs the secret or its length.
|
|
189
|
+
*/
|
|
190
|
+
export async function issueAgreementPortalUrl(base, signatureDocumentId, signerEmail, secret) {
|
|
191
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
192
|
+
console.error('[create-agreement]', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
return buildAgreementPortalUrl(base, signatureDocumentId, signerEmail, secret);
|
|
196
|
+
}
|
|
185
197
|
export async function handle(req, operator) {
|
|
186
198
|
if (req.method === 'OPTIONS')
|
|
187
199
|
return new Response('ok', { headers: corsHeaders });
|
|
@@ -461,9 +473,8 @@ export async function handle(req, operator) {
|
|
|
461
473
|
// own native signing email is unaffected and still goes out either way.
|
|
462
474
|
if (tpl.fires_stripe) {
|
|
463
475
|
try {
|
|
464
|
-
const
|
|
465
|
-
if (
|
|
466
|
-
const portalUrl = await buildAgreementPortalUrl(`https://${operator.domain}`, docId, row.signer_email, tokenSecret);
|
|
476
|
+
const portalUrl = await issueAgreementPortalUrl(`https://${operator.domain}`, docId, row.signer_email, Deno.env.get('MANAGE_TOKEN_SECRET'));
|
|
477
|
+
if (portalUrl) {
|
|
467
478
|
const emailResult = await sendAgreementPortalEmail(admin, {
|
|
468
479
|
email: row.signer_email, name: row.signer_name, portalUrl, officeNumber: String(v.office_number ?? '') || undefined,
|
|
469
480
|
}, {
|
|
@@ -476,9 +487,6 @@ export async function handle(req, operator) {
|
|
|
476
487
|
if (emailResult !== 'sent')
|
|
477
488
|
console.warn('[create-agreement] portal email not sent:', emailResult);
|
|
478
489
|
}
|
|
479
|
-
else {
|
|
480
|
-
console.error('[create-agreement] MANAGE_TOKEN_SECRET not configured -- portal email not sent');
|
|
481
|
-
}
|
|
482
490
|
}
|
|
483
491
|
catch (e) {
|
|
484
492
|
console.error('[create-agreement] portal email dispatch failed (non-fatal)', e);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createClient } from '@supabase/supabase-js';
|
|
2
2
|
import Stripe from 'stripe';
|
|
3
3
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
4
|
-
import { verifyMemberToken } from '../manageToken.js';
|
|
4
|
+
import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyMemberToken, } from '../manageToken.js';
|
|
5
5
|
import { resolvePortalSession } from '../portalSession.js';
|
|
6
6
|
import { logOps } from '../ops.js';
|
|
7
7
|
import { getOrCreateCoworkingPortalConfig } from '../stripeCoworkingPortal.js';
|
|
@@ -25,7 +25,9 @@ export async function handle(req, operator) {
|
|
|
25
25
|
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
|
26
26
|
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
27
27
|
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
28
|
-
if (!secret
|
|
28
|
+
if (!isManageTokenSecretUsable(secret))
|
|
29
|
+
return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
|
|
30
|
+
if (!stripeKey)
|
|
29
31
|
return json(500, { error: 'not_configured' });
|
|
30
32
|
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
31
33
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createClient } from '@supabase/supabase-js';
|
|
2
2
|
import { JWT } from 'google-auth-library';
|
|
3
3
|
import { writebackBookingCancelled } from '../gcalBookingEvents.js';
|
|
4
|
-
import {
|
|
5
|
-
import { verifyManageToken } from '../manageToken.js';
|
|
4
|
+
import { manageBookingClientIp, checkRateLimit } from '../rateLimit.js';
|
|
5
|
+
import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken } from '../manageToken.js';
|
|
6
6
|
import { resolvePortalSessionEmail } from '../portalSession.js';
|
|
7
7
|
import { logOps } from '../ops.js';
|
|
8
8
|
import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
|
|
@@ -91,6 +91,14 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, bus
|
|
|
91
91
|
return await fail('exception', { message: String(e) });
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
|
+
/** Grant is usable only while access_start <= now < access_end. Missing/unparseable bounds fail closed. */
|
|
95
|
+
function grantWindowContainsNow(grant, nowMs = Date.now()) {
|
|
96
|
+
const startMs = grant.access_start ? new Date(grant.access_start).getTime() : NaN;
|
|
97
|
+
const endMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
|
|
98
|
+
if (!Number.isFinite(startMs) || !Number.isFinite(endMs))
|
|
99
|
+
return false;
|
|
100
|
+
return startMs <= nowMs && nowMs < endMs;
|
|
101
|
+
}
|
|
94
102
|
function parseTstzRange(range) {
|
|
95
103
|
const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
|
|
96
104
|
if (!m)
|
|
@@ -207,17 +215,17 @@ export async function handle(req, operator, deps) {
|
|
|
207
215
|
const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
|
|
208
216
|
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
|
209
217
|
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
210
|
-
if (!secret)
|
|
211
|
-
return json(
|
|
218
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
219
|
+
return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
|
|
220
|
+
}
|
|
212
221
|
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
213
222
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
214
223
|
});
|
|
215
224
|
const busBase = deps.busBase ?? getEventAccessBusBase();
|
|
216
|
-
// Rate-limit BEFORE any DB work.
|
|
217
|
-
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
]);
|
|
225
|
+
// Rate-limit BEFORE any DB work. failClosed: a limiter outage must not
|
|
226
|
+
// become an unthrottled PIN/token oracle.
|
|
227
|
+
const ip = manageBookingClientIp(req);
|
|
228
|
+
const ipOk = await checkRateLimit(admin, 'manage-booking-ip', ip, 30, 300, { failClosed: true });
|
|
221
229
|
if (!ipOk)
|
|
222
230
|
return json(429, { error: 'rate_limited' });
|
|
223
231
|
// Extract token + action.
|
|
@@ -263,12 +271,12 @@ export async function handle(req, operator, deps) {
|
|
|
263
271
|
authedEmail = sessionEmail;
|
|
264
272
|
}
|
|
265
273
|
// Rate-limit per booking id to cap abuse of a single link/session.
|
|
266
|
-
const bidOk = await checkRateLimit(admin, 'manage-booking-bid', bookingId, 30, 300);
|
|
274
|
+
const bidOk = await checkRateLimit(admin, 'manage-booking-bid', bookingId, 30, 300, { failClosed: true });
|
|
267
275
|
if (!bidOk)
|
|
268
276
|
return json(429, { error: 'rate_limited' });
|
|
269
277
|
const { data: booking, error: bErr } = await admin
|
|
270
278
|
.from('bookings')
|
|
271
|
-
.select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
|
|
279
|
+
.select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,access_revoke_required_at,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
|
|
272
280
|
.eq('id', bookingId)
|
|
273
281
|
.maybeSingle();
|
|
274
282
|
if (bErr)
|
|
@@ -340,7 +348,7 @@ export async function handle(req, operator, deps) {
|
|
|
340
348
|
if (action === 'two_pin_credential') {
|
|
341
349
|
const parsedRange = parseTstzRange(b.during);
|
|
342
350
|
const endMs = parsedRange ? new Date(parsedRange.endISO).getTime() : 0;
|
|
343
|
-
if (b.status !== 'paid' || endMs <= Date.now()) {
|
|
351
|
+
if (b.status !== 'paid' || endMs <= Date.now() || b.access_revoke_required_at) {
|
|
344
352
|
return json(404, { error: 'no_credential' });
|
|
345
353
|
}
|
|
346
354
|
try {
|
|
@@ -354,14 +362,13 @@ export async function handle(req, operator, deps) {
|
|
|
354
362
|
const grant = data;
|
|
355
363
|
if (!grant.unlock_pin && !grant.relock_pin)
|
|
356
364
|
return json(404, { error: 'no_credential' });
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
//
|
|
360
|
-
//
|
|
365
|
+
if (!grantWindowContainsNow(grant))
|
|
366
|
+
return json(404, { error: 'no_credential' });
|
|
367
|
+
// Organizer early-manual-lock/unlock link (D35 follow-up): only reached
|
|
368
|
+
// while the grant is inside its active window. Never blocks or alters
|
|
369
|
+
// the PIN response: a failed mint is just a null url.
|
|
361
370
|
let organizerLinkUrl = null;
|
|
362
|
-
|
|
363
|
-
const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
|
|
364
|
-
if (grant.id && grantWithinWindow) {
|
|
371
|
+
if (grant.id) {
|
|
365
372
|
organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
|
|
366
373
|
}
|
|
367
374
|
return json(200, {
|
|
@@ -2,7 +2,7 @@ import { createClient } from '@supabase/supabase-js';
|
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
4
4
|
import { logOps } from '../ops.js';
|
|
5
|
-
import { buildMemberManageUrl } from '../manageToken.js';
|
|
5
|
+
import { buildMemberManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
|
|
6
6
|
const corsHeaders = {
|
|
7
7
|
'Access-Control-Allow-Origin': '*',
|
|
8
8
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
@@ -115,14 +115,13 @@ export async function handle(req, operator) {
|
|
|
115
115
|
return new Response('ok', { headers: corsHeaders });
|
|
116
116
|
if (req.method !== 'POST')
|
|
117
117
|
return json(405, { error: 'method_not_allowed' });
|
|
118
|
-
const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
|
|
119
|
-
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
|
120
118
|
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
console.warn('[request-portal-link] MANAGE_TOKEN_SECRET not configured');
|
|
119
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
120
|
+
console.warn('[request-portal-link]', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
121
|
+
return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
|
|
125
122
|
}
|
|
123
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
|
|
124
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
|
126
125
|
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
127
126
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
128
127
|
});
|
|
@@ -163,7 +162,7 @@ export async function handle(req, operator) {
|
|
|
163
162
|
return json(200, GENERIC_OK);
|
|
164
163
|
}
|
|
165
164
|
const membership = (membershipRows ?? [])[0];
|
|
166
|
-
if (!membership
|
|
165
|
+
if (!membership) {
|
|
167
166
|
// Same shape/timing as the found path (no existence leak).
|
|
168
167
|
return json(200, GENERIC_OK);
|
|
169
168
|
}
|
|
@@ -2,7 +2,7 @@ import { createClient } from '@supabase/supabase-js';
|
|
|
2
2
|
import Stripe from 'stripe';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
5
|
-
import { verifyManageToken } from '../manageToken.js';
|
|
5
|
+
import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken, } from '../manageToken.js';
|
|
6
6
|
import { resolvePortalSessionEmail } from '../portalSession.js';
|
|
7
7
|
import { logOps } from '../ops.js';
|
|
8
8
|
import { reclaimStaleHoldsExceptCompletedTier3 } from '../bookingHoldReclaim.js';
|
|
@@ -60,8 +60,9 @@ export async function handle(req, operator, deps) {
|
|
|
60
60
|
const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
|
|
61
61
|
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
|
62
62
|
const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
|
|
63
|
-
if (!secret)
|
|
64
|
-
return json(
|
|
63
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
64
|
+
return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
|
|
65
|
+
}
|
|
65
66
|
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
66
67
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
67
68
|
});
|
|
@@ -1546,6 +1546,18 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
1546
1546
|
const session = event.data.object;
|
|
1547
1547
|
// Day Pass one-time checkout — record the purchase, no booking / no membership.
|
|
1548
1548
|
if (session.metadata?.checkout_type === 'day_pass') {
|
|
1549
|
+
// Fail-closed payment guard: a completed session that has not moved
|
|
1550
|
+
// money (e.g. 'unpaid' from a delayed-notification method such as ACH
|
|
1551
|
+
// debit) must never grant door access, email, or create anything.
|
|
1552
|
+
if (session.payment_status !== 'paid' && session.payment_status !== 'no_payment_required') {
|
|
1553
|
+
await logOps(supabase, 'day_pass_session_completed_unpaid', {
|
|
1554
|
+
session_id: session.id,
|
|
1555
|
+
payment_status: session.payment_status ?? null,
|
|
1556
|
+
amount_total: session.amount_total ?? null,
|
|
1557
|
+
day_pass_id: session.metadata?.day_pass_id ?? session.metadata?.booking_id ?? null,
|
|
1558
|
+
}, { severity: 'error', dedupeKey: `day_pass_session_completed_unpaid:${session.id}` });
|
|
1559
|
+
break;
|
|
1560
|
+
}
|
|
1549
1561
|
const email = session.customer_details?.email ?? session.customer_email ?? null;
|
|
1550
1562
|
const customerId = typeof session.customer === 'string'
|
|
1551
1563
|
? session.customer
|
|
@@ -1807,9 +1819,12 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
1807
1819
|
// else-if branch further down -- which handles the actual
|
|
1808
1820
|
// cancelled_* case -- can reuse it without recomputing.
|
|
1809
1821
|
const bkIsCancelled = bkStatus.startsWith('cancelled_');
|
|
1810
|
-
//
|
|
1811
|
-
|
|
1812
|
-
|
|
1822
|
+
// Universal paid guard: a completed session whose payment_status is
|
|
1823
|
+
// not 'paid' / 'no_payment_required' (e.g. 'unpaid' from a
|
|
1824
|
+
// delayed-notification method such as ACH debit) has not moved any
|
|
1825
|
+
// money, so it must never flip a booking to paid or provision access,
|
|
1826
|
+
// for Connect and non-Connect operators alike.
|
|
1827
|
+
const sessionIsPaid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
|
1813
1828
|
if (booking &&
|
|
1814
1829
|
!sessionIsPaid &&
|
|
1815
1830
|
bkStatus !== 'paid' &&
|
|
@@ -1824,7 +1839,7 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
1824
1839
|
booking_status: bkStatus,
|
|
1825
1840
|
amount_total: session.amount_total ?? null,
|
|
1826
1841
|
}, {
|
|
1827
|
-
severity: '
|
|
1842
|
+
severity: 'error',
|
|
1828
1843
|
bookingId: booking.id,
|
|
1829
1844
|
dedupeKey: `booking_session_completed_unpaid:${booking.id}:${session.id}`,
|
|
1830
1845
|
});
|
package/dist/manageToken.d.ts
CHANGED
|
@@ -3,6 +3,13 @@ export interface ManageTokenPayload {
|
|
|
3
3
|
eml: string;
|
|
4
4
|
exp: number;
|
|
5
5
|
}
|
|
6
|
+
/** Allowlisted handler/error code when the HMAC key is missing or too short. */
|
|
7
|
+
export declare const MANAGE_TOKEN_UNAVAILABLE_CODE = "manage_token_unavailable";
|
|
8
|
+
/**
|
|
9
|
+
* M2(a): MANAGE_TOKEN_SECRET must be present and at least 32 UTF-8 bytes.
|
|
10
|
+
* Never log, throw, or return the secret value or its length.
|
|
11
|
+
*/
|
|
12
|
+
export declare function isManageTokenSecretUsable(secret: string | undefined | null): secret is string;
|
|
6
13
|
export declare function signManageToken(payload: ManageTokenPayload, secret: string): Promise<string>;
|
|
7
14
|
export declare function verifyManageToken(token: string, secret: string): Promise<ManageTokenPayload | null>;
|
|
8
15
|
/**
|
package/dist/manageToken.js
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
// HMAC-SHA256 signed token for self-serve booking management. Payload is a
|
|
2
2
|
// small JSON object identifying the booking and the customer email, plus an
|
|
3
3
|
// expiry. Never accept a bare booking UUID for PII — the token is the only key.
|
|
4
|
+
/** Allowlisted handler/error code when the HMAC key is missing or too short. */
|
|
5
|
+
export const MANAGE_TOKEN_UNAVAILABLE_CODE = 'manage_token_unavailable';
|
|
6
|
+
const MANAGE_TOKEN_UNAVAILABLE_MESSAGE = 'manage token unavailable';
|
|
7
|
+
const MIN_MANAGE_TOKEN_SECRET_BYTES = 32;
|
|
8
|
+
/**
|
|
9
|
+
* M2(a): MANAGE_TOKEN_SECRET must be present and at least 32 UTF-8 bytes.
|
|
10
|
+
* Never log, throw, or return the secret value or its length.
|
|
11
|
+
*/
|
|
12
|
+
export function isManageTokenSecretUsable(secret) {
|
|
13
|
+
if (typeof secret !== 'string')
|
|
14
|
+
return false;
|
|
15
|
+
return new TextEncoder().encode(secret).byteLength >= MIN_MANAGE_TOKEN_SECRET_BYTES;
|
|
16
|
+
}
|
|
17
|
+
function requireManageTokenSecret(secret) {
|
|
18
|
+
if (!isManageTokenSecretUsable(secret)) {
|
|
19
|
+
throw new Error(MANAGE_TOKEN_UNAVAILABLE_MESSAGE);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
4
22
|
function b64urlEncode(bytes) {
|
|
5
23
|
const s = btoa(String.fromCharCode(...bytes));
|
|
6
24
|
return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
@@ -25,12 +43,15 @@ function timingSafeEqual(a, b) {
|
|
|
25
43
|
return diff === 0;
|
|
26
44
|
}
|
|
27
45
|
export async function signManageToken(payload, secret) {
|
|
46
|
+
requireManageTokenSecret(secret);
|
|
28
47
|
const key = await getKey(secret);
|
|
29
48
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
30
49
|
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
|
|
31
50
|
return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
|
|
32
51
|
}
|
|
33
52
|
export async function verifyManageToken(token, secret) {
|
|
53
|
+
if (!isManageTokenSecretUsable(secret))
|
|
54
|
+
return null;
|
|
34
55
|
const parts = token.split('.');
|
|
35
56
|
if (parts.length !== 2)
|
|
36
57
|
return null;
|
|
@@ -74,12 +95,15 @@ export async function buildManageUrl(base, payload, secret) {
|
|
|
74
95
|
return `${base.replace(/\/+$/, '')}/manage-booking?token=${encodeURIComponent(token)}`;
|
|
75
96
|
}
|
|
76
97
|
export async function signMemberToken(payload, secret) {
|
|
98
|
+
requireManageTokenSecret(secret);
|
|
77
99
|
const key = await getKey(secret);
|
|
78
100
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
79
101
|
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
|
|
80
102
|
return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
|
|
81
103
|
}
|
|
82
104
|
export async function verifyMemberToken(token, secret) {
|
|
105
|
+
if (!isManageTokenSecretUsable(secret))
|
|
106
|
+
return null;
|
|
83
107
|
const parts = token.split('.');
|
|
84
108
|
if (parts.length !== 2)
|
|
85
109
|
return null;
|
|
@@ -117,6 +141,7 @@ export async function buildMemberManageUrl(base, payload, secret) {
|
|
|
117
141
|
return `${base.replace(/\/+$/, '')}/membership/manage?token=${encodeURIComponent(token)}`;
|
|
118
142
|
}
|
|
119
143
|
export async function signAgreementPortalToken(payload, secret) {
|
|
144
|
+
requireManageTokenSecret(secret);
|
|
120
145
|
const key = await getKey(secret);
|
|
121
146
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
122
147
|
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
|
|
@@ -128,6 +153,8 @@ export async function signAgreementPortalToken(payload, secret) {
|
|
|
128
153
|
* verifies again without any separate un-revoke step.
|
|
129
154
|
*/
|
|
130
155
|
export async function verifyAgreementPortalToken(token, secret, revokedAtIso) {
|
|
156
|
+
if (!isManageTokenSecretUsable(secret))
|
|
157
|
+
return null;
|
|
131
158
|
const parts = token.split('.');
|
|
132
159
|
if (parts.length !== 2)
|
|
133
160
|
return null;
|
|
@@ -190,6 +217,7 @@ export async function buildAgreementPortalUrl(base, signatureDocumentId, signerE
|
|
|
190
217
|
*/
|
|
191
218
|
export const MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS = 60 * 24 * 3600;
|
|
192
219
|
export async function signMigrationCheckoutToken(payload, secret) {
|
|
220
|
+
requireManageTokenSecret(secret);
|
|
193
221
|
const key = await getKey(secret);
|
|
194
222
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
|
195
223
|
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
|
|
@@ -197,6 +225,8 @@ export async function signMigrationCheckoutToken(payload, secret) {
|
|
|
197
225
|
}
|
|
198
226
|
/** Phase 1: decode + HMAC + shape + expiry. Pure — no DB, no revocation check. */
|
|
199
227
|
export async function verifyMigrationCheckoutToken(token, secret) {
|
|
228
|
+
if (!isManageTokenSecretUsable(secret))
|
|
229
|
+
return null;
|
|
200
230
|
const parts = token.split('.');
|
|
201
231
|
if (parts.length !== 2)
|
|
202
232
|
return null;
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
// remains exclusively stripe-webhook's job, unmodified.
|
|
20
20
|
import { createClient } from '@supabase/supabase-js';
|
|
21
21
|
import Stripe from 'stripe';
|
|
22
|
-
import { verifyMigrationCheckoutToken, migrationCheckoutTokenIsRevoked, } from './manageToken.js';
|
|
22
|
+
import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyMigrationCheckoutToken, migrationCheckoutTokenIsRevoked, } from './manageToken.js';
|
|
23
23
|
export const MIGRATION_CONFIRM_PATH = '/functions/v1/migration-checkout-confirm';
|
|
24
24
|
export const MIGRATION_REDIRECT_PATH = '/functions/v1/migration-checkout-redirect';
|
|
25
25
|
export function resolveDeps(req, defaultBaseUrl) {
|
|
@@ -70,8 +70,12 @@ export const EXISTING_MEMBERSHIP_STATUSES = [
|
|
|
70
70
|
*/
|
|
71
71
|
export async function loadTokenStateAndPlan(deps, token) {
|
|
72
72
|
// --- step 1 ---
|
|
73
|
-
if (!token
|
|
73
|
+
if (!token)
|
|
74
74
|
return { kind: 'token_error' };
|
|
75
|
+
if (!isManageTokenSecretUsable(deps.tokenSecret)) {
|
|
76
|
+
console.error('[migrationCheckout]', MANAGE_TOKEN_UNAVAILABLE_CODE);
|
|
77
|
+
return { kind: 'token_error' };
|
|
78
|
+
}
|
|
75
79
|
const payload = await verifyMigrationCheckoutToken(token, deps.tokenSecret);
|
|
76
80
|
if (!payload)
|
|
77
81
|
return { kind: 'token_error' };
|
package/dist/portalSession.js
CHANGED
|
@@ -16,6 +16,10 @@ export async function resolvePortalSession(req, admin) {
|
|
|
16
16
|
const { data, error } = await admin.auth.getUser(jwt);
|
|
17
17
|
if (error || !data?.user?.email)
|
|
18
18
|
return null;
|
|
19
|
+
// A session JWT is not enough: the address must be confirmed so an
|
|
20
|
+
// unconfirmed signup cannot present as that email on manage-booking.
|
|
21
|
+
if (!data.user.email_confirmed_at)
|
|
22
|
+
return null;
|
|
19
23
|
return { id: data.user.id, email: data.user.email.toLowerCase() };
|
|
20
24
|
}
|
|
21
25
|
catch (e) {
|
package/dist/rateLimit.d.ts
CHANGED
|
@@ -14,6 +14,13 @@ export declare const RETELL_ALLOWLISTED_IP = "100.20.5.228";
|
|
|
14
14
|
*/
|
|
15
15
|
export declare const RETELL_EXEMPT_BUCKETS: Set<string>;
|
|
16
16
|
export declare function clientIp(req: Request): string;
|
|
17
|
+
/**
|
|
18
|
+
* Manage-booking IP buckets only. Uses Cloudflare's cf-connecting-ip and
|
|
19
|
+
* ignores client-supplied X-Forwarded-For. Missing CF header shares the
|
|
20
|
+
* same `'unknown'` sentinel clientIp() uses, rather than a fresh bucket
|
|
21
|
+
* per spoofed hop.
|
|
22
|
+
*/
|
|
23
|
+
export declare function manageBookingClientIp(req: Request): string;
|
|
17
24
|
export declare function checkRateLimit(supabase: SupabaseLike, bucket: string, identifier: string, max: number, windowSeconds: number, opts?: {
|
|
18
25
|
failClosed?: boolean;
|
|
19
26
|
}): Promise<boolean>;
|
package/dist/rateLimit.js
CHANGED
|
@@ -30,6 +30,18 @@ export function clientIp(req) {
|
|
|
30
30
|
return cf.trim();
|
|
31
31
|
return 'unknown';
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Manage-booking IP buckets only. Uses Cloudflare's cf-connecting-ip and
|
|
35
|
+
* ignores client-supplied X-Forwarded-For. Missing CF header shares the
|
|
36
|
+
* same `'unknown'` sentinel clientIp() uses, rather than a fresh bucket
|
|
37
|
+
* per spoofed hop.
|
|
38
|
+
*/
|
|
39
|
+
export function manageBookingClientIp(req) {
|
|
40
|
+
const cf = req.headers.get('cf-connecting-ip')?.trim();
|
|
41
|
+
if (cf)
|
|
42
|
+
return cf;
|
|
43
|
+
return 'unknown';
|
|
44
|
+
}
|
|
33
45
|
export async function checkRateLimit(supabase, bucket, identifier, max, windowSeconds,
|
|
34
46
|
// Should-fix S2 (adversarial review, round 1): the shared default here is
|
|
35
47
|
// fail-OPEN on an RPC error/throw -- deliberately, since most callers of
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplelayer/graniteer-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.26",
|
|
4
4
|
"description": "Shared platform core for Graniteer",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -417,6 +417,14 @@
|
|
|
417
417
|
"types": "./dist/functions/boldsign-sender-identity.d.ts",
|
|
418
418
|
"default": "./dist/functions/boldsign-sender-identity.js"
|
|
419
419
|
},
|
|
420
|
+
"./functions/booking-access-grant": {
|
|
421
|
+
"types": "./dist/functions/booking-access-grant.d.ts",
|
|
422
|
+
"default": "./dist/functions/booking-access-grant.js"
|
|
423
|
+
},
|
|
424
|
+
"./functions/booking-access-revoke": {
|
|
425
|
+
"types": "./dist/functions/booking-access-revoke.d.ts",
|
|
426
|
+
"default": "./dist/functions/booking-access-revoke.js"
|
|
427
|
+
},
|
|
420
428
|
"./functions/booking-access-revoke-backstop": {
|
|
421
429
|
"types": "./dist/functions/booking-access-revoke-backstop.d.ts",
|
|
422
430
|
"default": "./dist/functions/booking-access-revoke-backstop.js"
|