@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
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// Graniteer Access v1 — the tenant-app side of the four member-initiated access actions.
|
|
2
|
+
// Implements the "tenant-app Supabase edge function member-door-action (NEW)" box in
|
|
3
|
+
// graniteer-access-v8-plan.md §4, for the four ftw-middleware member routes:
|
|
4
|
+
//
|
|
5
|
+
// unlock -> POST /member/unlock
|
|
6
|
+
// pin_regenerate -> POST /member/pin/regenerate
|
|
7
|
+
// activity -> GET /member/activity
|
|
8
|
+
// wifi_voucher -> POST /member/wifi-voucher
|
|
9
|
+
//
|
|
10
|
+
// The tenant app is the SOLE gateway between Graniteer and ftw-middleware/UniFi (plan §4,
|
|
11
|
+
// "not fixed by design"). This function performs NO UniFi work itself and holds no
|
|
12
|
+
// UniFi credential; it authenticates the member, decides the tenant app's half of the dual
|
|
13
|
+
// authorization check, mints the identity assertion, and forwards.
|
|
14
|
+
//
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// IDENTITY — the whole point of this function (plan, Identity section)
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// The member subject is taken ONLY from the Supabase session Supabase itself
|
|
19
|
+
// validated (resolvePortalSession -> admin.auth.getUser(jwt)). A request body
|
|
20
|
+
// `sub` / `user_id` / `unifi_user_id` / `actor_id` is NEVER read, compared, or
|
|
21
|
+
// preferred — see IGNORED_BODY_FIELDS below, which exists so that a future editor
|
|
22
|
+
// adding a field has to notice.
|
|
23
|
+
//
|
|
24
|
+
// The assertion is minted SERVER-SIDE here and never round-tripped through the
|
|
25
|
+
// client (plan R2-5): the browser never sees or holds it. Claims are
|
|
26
|
+
// {sub, aud, iss, act, door_id, iat, nbf, exp, jti} with exp <= 120s out, signed
|
|
27
|
+
// Ed25519 ("EdDSA"). ftw-middleware MUST pin the algorithm server-side and never
|
|
28
|
+
// read `alg` from the header (closes the alg:none acceptance class).
|
|
29
|
+
//
|
|
30
|
+
// `door_id` travels in the assertion, not the outbound body — the outbound bodies
|
|
31
|
+
// are literally `{}` — so there is no body field for the middleware to be tempted
|
|
32
|
+
// to prefer.
|
|
33
|
+
//
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// FOURTH SIBLING HMAC SCHEME — "d1"
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
// This repo has no single "shared admin token" to ftw-middleware; it has four
|
|
38
|
+
// byte-distinct per-route HMAC constructions (busClient "v1" / BUS_HMAC_SECRET,
|
|
39
|
+
// membershipBusClient "m1" / BUS_HMAC_SECRET_MEMBERSHIP, portal-resend-invite
|
|
40
|
+
// "r1" / BUS_HMAC_SECRET_RESEND, event-access-admin "e1" / the
|
|
41
|
+
// get_event_access_hmac_secret RPC). This is the fifth prefix and the fourth
|
|
42
|
+
// env-held secret: "d1" under MEMBER_ACTIONS_HMAC_SECRET. It proves only "this
|
|
43
|
+
// call came from the tenant app", NEVER "this call is about member X" — that is the
|
|
44
|
+
// assertion's job, and the two must not be conflated.
|
|
45
|
+
//
|
|
46
|
+
// Canonical message — 5 lines joined with "\n", no trailing newline:
|
|
47
|
+
// d1
|
|
48
|
+
// {action} one of MEMBER_ACTIONS, verbatim
|
|
49
|
+
// {ts} unix seconds, decimal, as sent in the timestamp header
|
|
50
|
+
// {assertion_sha256} sha256 hex of the exact assertion JWT string sent
|
|
51
|
+
// {payload_sha256} sha256 hex of the exact POST body bytes, or of the
|
|
52
|
+
// canonical query string for the GET (see PAYLOAD below)
|
|
53
|
+
//
|
|
54
|
+
// Binding the assertion hash into the HMAC means a leaked assertion cannot be
|
|
55
|
+
// replayed at the middleware by anyone who does not also hold the d1 secret, and
|
|
56
|
+
// binding {action} means an assertion minted for `activity` cannot be presented
|
|
57
|
+
// at /member/unlock.
|
|
58
|
+
//
|
|
59
|
+
// PAYLOAD: every POST body is `{}` (all parameters are either in the assertion or
|
|
60
|
+
// fixed server-side on the middleware per plan §6.2's "non-member-configurable"
|
|
61
|
+
// rule). The GET carries `?limit=N`, and its canonical query string `limit=N` is
|
|
62
|
+
// what gets hashed.
|
|
63
|
+
//
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// FAIL DIRECTIONS (deliberately not uniform — plan, Rate limiting section)
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// * Auth / identity / entitlement / signing: FAIL CLOSED. Anything unknown denies.
|
|
68
|
+
// * Rate limiter backend: FAILS OPEN (allow + warn) — that is checkRateLimit's
|
|
69
|
+
// existing documented behaviour and is the correct direction for availability
|
|
70
|
+
// protection, deliberately opposite to the middleware's jti replay cache.
|
|
71
|
+
// * Ambiguous unlock outcome (timeout, 5xx, missing/!= 'unlocked' outcome): report
|
|
72
|
+
// "couldn't confirm — use your card", NEVER "unlocked", never "denied", and
|
|
73
|
+
// never auto-retry (plan finding #12: a retry risks a double-pulse or a late
|
|
74
|
+
// unlock with nobody present).
|
|
75
|
+
//
|
|
76
|
+
// Every authorization refusal returns ONE uniform opaque body (`not_permitted`)
|
|
77
|
+
// regardless of which check failed, so the response cannot be used to enumerate
|
|
78
|
+
// door inventory or another member's tier (plan entitlement step 7). The specific
|
|
79
|
+
// reason goes to ops_events only.
|
|
80
|
+
|
|
81
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
82
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
83
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
84
|
+
import { computeEntitlement } from 'npm:@simplelayer/graniteer-core/membership';
|
|
85
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
86
|
+
|
|
87
|
+
const corsHeaders = {
|
|
88
|
+
'Access-Control-Allow-Origin': '*',
|
|
89
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
90
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// REQUIRED SUPABASE SECRETS for Graniteer Access v1 (this feature, both
|
|
95
|
+
// functions). This repo has no central secret manifest — the convention is the
|
|
96
|
+
// per-function `*_ENV` constant block, so this list is the manifest. Everything
|
|
97
|
+
// here defaults to absent, and absent means the feature is inert, never open.
|
|
98
|
+
//
|
|
99
|
+
// FTW_MIDDLEWARE_BASE_URL https:// base of the ftw-middleware deploy
|
|
100
|
+
// MEMBER_ACTIONS_HMAC_SECRET the "d1" outbound HMAC secret
|
|
101
|
+
// MEMBER_ASSERTION_SIGNING_KEY Ed25519 PKCS#8 (PEM or bare base64)
|
|
102
|
+
// MEMBER_ASSERTION_ISS assertion `iss`
|
|
103
|
+
// MEMBER_ASSERTION_AUD assertion `aud` (per-deployment/tenant)
|
|
104
|
+
// MEMBER_ASSERTION_TTL_SECONDS optional; clamped to [10, 120], default 60
|
|
105
|
+
// MEMBER_ACTIONS_ENABLED master gate, default false
|
|
106
|
+
// MEMBER_ACTIONS_ALLOWLIST Supabase `sub` list; EMPTY DENIES EVERYONE
|
|
107
|
+
// MEMBER_ACTIONS_MAPPING_SECRET inbound bearer for member-unifi-mapping
|
|
108
|
+
// (see that function; must differ from every
|
|
109
|
+
// secret above and from the service-role key —
|
|
110
|
+
// keyIsolationViolations() enforces it)
|
|
111
|
+
//
|
|
112
|
+
// No hardcoded live host. Every other tenant-app -> middleware caller in this repo
|
|
113
|
+
// hardcodes `https://ftw.granitecity.io`; this one does not, so the function is
|
|
114
|
+
// inert (503 not_configured) until an operator sets the base URL as a secret.
|
|
115
|
+
// That also keeps a mis-deployed member-facing door route from ever reaching the
|
|
116
|
+
// real middleware by default.
|
|
117
|
+
// ---------------------------------------------------------------------------
|
|
118
|
+
const BASE_URL_ENV = 'FTW_MIDDLEWARE_BASE_URL';
|
|
119
|
+
const HMAC_SECRET_ENV = 'MEMBER_ACTIONS_HMAC_SECRET';
|
|
120
|
+
const SIGNING_KEY_ENV = 'MEMBER_ASSERTION_SIGNING_KEY';
|
|
121
|
+
const ASSERTION_ISS_ENV = 'MEMBER_ASSERTION_ISS';
|
|
122
|
+
const ASSERTION_AUD_ENV = 'MEMBER_ASSERTION_AUD';
|
|
123
|
+
const ASSERTION_TTL_ENV = 'MEMBER_ASSERTION_TTL_SECONDS';
|
|
124
|
+
|
|
125
|
+
export const ASSERTION_HEADER = 'X-Member-Action-Assertion';
|
|
126
|
+
export const SIGNATURE_HEADER = 'X-Member-Action-Signature';
|
|
127
|
+
export const TIMESTAMP_HEADER = 'X-Member-Action-Timestamp';
|
|
128
|
+
export const SCHEME_HEADER = 'X-Member-Action-Scheme';
|
|
129
|
+
export const HMAC_SCHEME = 'd1';
|
|
130
|
+
|
|
131
|
+
/** Plan pins exp at <= 120s out throughout; the jti retention floor derives from it. */
|
|
132
|
+
export const ASSERTION_MAX_TTL_SECONDS = 120;
|
|
133
|
+
const ASSERTION_MIN_TTL_SECONDS = 10;
|
|
134
|
+
const ASSERTION_DEFAULT_TTL_SECONDS = 60;
|
|
135
|
+
|
|
136
|
+
const MAX_BODY_BYTES = 4096;
|
|
137
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
138
|
+
|
|
139
|
+
export const MEMBER_ACTIONS = ['unlock', 'pin_regenerate', 'activity', 'wifi_voucher'] as const;
|
|
140
|
+
export type MemberAction = typeof MEMBER_ACTIONS[number];
|
|
141
|
+
|
|
142
|
+
interface RouteSpec {
|
|
143
|
+
method: 'GET' | 'POST';
|
|
144
|
+
path: string;
|
|
145
|
+
timeoutMs: number;
|
|
146
|
+
/** Buckets are (name, max, windowSeconds), keyed on the verified Supabase sub. */
|
|
147
|
+
limits: readonly (readonly [string, number, number])[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const ROUTES: Record<MemberAction, RouteSpec> = {
|
|
151
|
+
unlock: {
|
|
152
|
+
method: 'POST',
|
|
153
|
+
path: '/member/unlock',
|
|
154
|
+
// Shorter than the other writes on purpose: the middleware's own chain deadline
|
|
155
|
+
// sits inside its 5s lock-acquire budget, so a call still open at 15s is already
|
|
156
|
+
// an outcome we must report as unconfirmed rather than keep waiting on.
|
|
157
|
+
timeoutMs: 15_000,
|
|
158
|
+
limits: [
|
|
159
|
+
['member-door-unlock-burst', 1, 5],
|
|
160
|
+
['member-door-unlock', 10, 300],
|
|
161
|
+
],
|
|
162
|
+
},
|
|
163
|
+
pin_regenerate: {
|
|
164
|
+
method: 'POST',
|
|
165
|
+
path: '/member/pin/regenerate',
|
|
166
|
+
timeoutMs: 15_000,
|
|
167
|
+
limits: [['member-door-pin-regenerate', 3, 3600]],
|
|
168
|
+
},
|
|
169
|
+
activity: {
|
|
170
|
+
method: 'GET',
|
|
171
|
+
path: '/member/activity',
|
|
172
|
+
timeoutMs: 10_000,
|
|
173
|
+
limits: [['member-door-activity', 60, 300]],
|
|
174
|
+
},
|
|
175
|
+
wifi_voucher: {
|
|
176
|
+
method: 'POST',
|
|
177
|
+
path: '/member/wifi-voucher',
|
|
178
|
+
timeoutMs: 15_000,
|
|
179
|
+
// Plan §6.2's placeholder cap of 3/member/day, pending Kyle's product call.
|
|
180
|
+
limits: [['member-door-wifi-voucher', 3, 86_400]],
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Fields a caller might send hoping they get read. They never are. Listed so this
|
|
186
|
+
* is a deliberate, greppable refusal rather than an omission, and so a future
|
|
187
|
+
* editor adding body handling has to walk past it.
|
|
188
|
+
*/
|
|
189
|
+
export const IGNORED_BODY_FIELDS = [
|
|
190
|
+
'sub', 'user_id', 'auth_user_id', 'member_id', 'membership_id', 'email',
|
|
191
|
+
'unifi_user_id', 'unifi_access_user_id', 'actor_id', 'actor_name',
|
|
192
|
+
] as const;
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Explicit SCALAR allowlists for what may be handed back to the browser. Same
|
|
196
|
+
* discipline as membership-door-sync's two-field allowlist: never spread a
|
|
197
|
+
* middleware object, never pass a `_source` through raw (plan finding #5).
|
|
198
|
+
*/
|
|
199
|
+
const RESPONSE_FIELDS: Record<MemberAction, readonly string[]> = {
|
|
200
|
+
unlock: ['outcome', 'door_name', 'confirmed_at'],
|
|
201
|
+
// `pin` is shown once and never persisted anywhere (plan finding #11's resolved
|
|
202
|
+
// recommendation: status-only + regenerate-to-reveal). It is deliberately absent
|
|
203
|
+
// from every audit payload built below.
|
|
204
|
+
//
|
|
205
|
+
// `group_check` is the middleware's before/after `GET /user_groups/{id}/users`
|
|
206
|
+
// reverse-index verdict around the PIN write (plan, PIN regeneration section).
|
|
207
|
+
// It is allowlisted specifically so a 'mismatch' — a PIN write that also
|
|
208
|
+
// silently cost the member a door-group membership, the §4.2b incident class
|
|
209
|
+
// this check exists to catch — SURVIVES projection and reaches the tenant app's own
|
|
210
|
+
// ops_events. Dropping it here would have left the audit row reading
|
|
211
|
+
// `outcome: 'ok'` while the middleware was shouting.
|
|
212
|
+
pin_regenerate: ['pin', 'pin_length', 'issued_at', 'group_check'],
|
|
213
|
+
activity: [],
|
|
214
|
+
wifi_voucher: ['code', 'expires_at', 'time_limit_minutes', 'authorized_guest_limit'],
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const ACTIVITY_HIT_FIELDS = ['at', 'door_id', 'door_name', 'result', 'method'] as const;
|
|
218
|
+
const ACTIVITY_DEFAULT_LIMIT = 25;
|
|
219
|
+
const ACTIVITY_MAX_LIMIT = 50;
|
|
220
|
+
|
|
221
|
+
function json(status: number, body: unknown) {
|
|
222
|
+
return new Response(JSON.stringify(body), {
|
|
223
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The ONE uniform opaque refusal. Used for every authorization outcome —
|
|
229
|
+
* unknown member, no UniFi mapping, ambiguous mapping, not entitled, not
|
|
230
|
+
* allowlisted, unknown/unprovisioned door, and the middleware's own denial —
|
|
231
|
+
* so differential responses cannot enumerate doors or tiers.
|
|
232
|
+
*/
|
|
233
|
+
function denied() {
|
|
234
|
+
return json(403, { ok: false, error: 'not_permitted' });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function b64urlNoPad(bytes: Uint8Array): string {
|
|
238
|
+
let s = '';
|
|
239
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
240
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function b64urlText(text: string): string {
|
|
244
|
+
return b64urlNoPad(new TextEncoder().encode(text));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function toHex(bytes: Uint8Array): string {
|
|
248
|
+
let out = '';
|
|
249
|
+
for (const b of bytes) out += b.toString(16).padStart(2, '0');
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function sha256Hex(text: string): Promise<string> {
|
|
254
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
255
|
+
return toHex(new Uint8Array(digest));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Canonical "d1" message. Must match member_actions.py on ftw-middleware exactly. */
|
|
259
|
+
export function canonicalMemberActionMessage(
|
|
260
|
+
action: string,
|
|
261
|
+
ts: string,
|
|
262
|
+
assertionHashHex: string,
|
|
263
|
+
payloadHashHex: string,
|
|
264
|
+
): string {
|
|
265
|
+
return [HMAC_SCHEME, action, ts, assertionHashHex, payloadHashHex].join('\n');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function signD1(secret: string, msg: string): Promise<string> {
|
|
269
|
+
const key = await crypto.subtle.importKey(
|
|
270
|
+
'raw', new TextEncoder().encode(secret),
|
|
271
|
+
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
|
|
272
|
+
);
|
|
273
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg));
|
|
274
|
+
return b64urlNoPad(new Uint8Array(sig));
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// --------------------------------------------------------------------------
|
|
278
|
+
// Ed25519 assertion minting
|
|
279
|
+
// --------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
export interface AssertionClaims {
|
|
282
|
+
sub: string;
|
|
283
|
+
aud: string;
|
|
284
|
+
iss: string;
|
|
285
|
+
act: MemberAction;
|
|
286
|
+
door_id: string | null;
|
|
287
|
+
iat: number;
|
|
288
|
+
nbf: number;
|
|
289
|
+
exp: number;
|
|
290
|
+
jti: string;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Accepts a PKCS#8 key as PEM or as bare base64 DER. */
|
|
294
|
+
function decodePkcs8(raw: string): Uint8Array | null {
|
|
295
|
+
const b64 = raw
|
|
296
|
+
.replace(/-----BEGIN [A-Z0-9 ]+-----/g, '')
|
|
297
|
+
.replace(/-----END [A-Z0-9 ]+-----/g, '')
|
|
298
|
+
.replace(/\s+/g, '');
|
|
299
|
+
if (!b64) return null;
|
|
300
|
+
try {
|
|
301
|
+
const bin = atob(b64);
|
|
302
|
+
const out = new Uint8Array(bin.length);
|
|
303
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
304
|
+
return out;
|
|
305
|
+
} catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
let signingKeyCache: { raw: string; key: CryptoKey } | null = null;
|
|
311
|
+
|
|
312
|
+
async function getSigningKey(raw: string): Promise<CryptoKey | null> {
|
|
313
|
+
if (signingKeyCache?.raw === raw) return signingKeyCache.key;
|
|
314
|
+
const der = decodePkcs8(raw);
|
|
315
|
+
if (!der) return null;
|
|
316
|
+
try {
|
|
317
|
+
const key = await crypto.subtle.importKey(
|
|
318
|
+
'pkcs8', der as unknown as ArrayBuffer, { name: 'Ed25519' }, false, ['sign'],
|
|
319
|
+
);
|
|
320
|
+
signingKeyCache = { raw, key };
|
|
321
|
+
return key;
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function assertionTtlSeconds(raw: string | undefined): number {
|
|
328
|
+
const t = (raw ?? '').trim();
|
|
329
|
+
// Blank must fall to the default, not through Number('') === 0 into the floor.
|
|
330
|
+
if (t === '') return ASSERTION_DEFAULT_TTL_SECONDS;
|
|
331
|
+
const n = Number(t);
|
|
332
|
+
if (!Number.isFinite(n)) return ASSERTION_DEFAULT_TTL_SECONDS;
|
|
333
|
+
return Math.min(ASSERTION_MAX_TTL_SECONDS, Math.max(ASSERTION_MIN_TTL_SECONDS, Math.floor(n)));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Mints the Ed25519 assertion. `alg` is written, never read: the verifier pins
|
|
338
|
+
* Ed25519 server-side, so this header is documentation for humans and must not
|
|
339
|
+
* be treated as an algorithm selector by ftw-middleware.
|
|
340
|
+
*/
|
|
341
|
+
export async function mintAssertion(keyRaw: string, claims: AssertionClaims): Promise<string | null> {
|
|
342
|
+
const key = await getSigningKey(keyRaw);
|
|
343
|
+
if (!key) return null;
|
|
344
|
+
const signingInput =
|
|
345
|
+
`${b64urlText(JSON.stringify({ alg: 'EdDSA', crv: 'Ed25519', typ: 'JWT' }))}.` +
|
|
346
|
+
`${b64urlText(JSON.stringify(claims))}`;
|
|
347
|
+
const sig = await crypto.subtle.sign(
|
|
348
|
+
{ name: 'Ed25519' }, key, new TextEncoder().encode(signingInput),
|
|
349
|
+
);
|
|
350
|
+
return `${signingInput}.${b64urlNoPad(new Uint8Array(sig))}`;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Plan R2-2: "refuse to start if the assertion-signing key equals the
|
|
355
|
+
* membership-sync admin token value." An edge function has no boot phase, so the
|
|
356
|
+
* closest equivalent is: evaluate at module load, and refuse EVERY request while
|
|
357
|
+
* a violation stands. Checked against every tenant-app -> middleware secret this repo
|
|
358
|
+
* holds in env, plus the service-role key, plus d1's own secret.
|
|
359
|
+
*/
|
|
360
|
+
export function keyIsolationViolations(env: Record<string, string | undefined>): string[] {
|
|
361
|
+
const signing = (env[SIGNING_KEY_ENV] ?? '').trim();
|
|
362
|
+
const d1 = (env[HMAC_SECRET_ENV] ?? '').trim();
|
|
363
|
+
const others: [string, string][] = [
|
|
364
|
+
['BUS_HMAC_SECRET', (env.BUS_HMAC_SECRET ?? '').trim()],
|
|
365
|
+
['BUS_HMAC_SECRET_MEMBERSHIP', (env.BUS_HMAC_SECRET_MEMBERSHIP ?? '').trim()],
|
|
366
|
+
['BUS_HMAC_SECRET_RESEND', (env.BUS_HMAC_SECRET_RESEND ?? '').trim()],
|
|
367
|
+
['SUPABASE_SERVICE_ROLE_KEY', (env.SUPABASE_SERVICE_ROLE_KEY ?? '').trim()],
|
|
368
|
+
// member-unifi-mapping's inbound bearer. It gates ftw-middleware's INDEPENDENT
|
|
369
|
+
// sub -> UniFi-user-id resolution, so if it were the same value as anything
|
|
370
|
+
// the tenant app signs with, the dual check would collapse back into a single one.
|
|
371
|
+
['MEMBER_ACTIONS_MAPPING_SECRET', (env.MEMBER_ACTIONS_MAPPING_SECRET ?? '').trim()],
|
|
372
|
+
];
|
|
373
|
+
const out: string[] = [];
|
|
374
|
+
for (const [name, value] of others) {
|
|
375
|
+
if (value && signing && value === signing) out.push(`${SIGNING_KEY_ENV}==${name}`);
|
|
376
|
+
if (value && d1 && value === d1) out.push(`${HMAC_SECRET_ENV}==${name}`);
|
|
377
|
+
}
|
|
378
|
+
if (signing && d1 && signing === d1) out.push(`${SIGNING_KEY_ENV}==${HMAC_SECRET_ENV}`);
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// --------------------------------------------------------------------------
|
|
383
|
+
// Gating (plan, Gating section — ships WITH identity, not later)
|
|
384
|
+
// --------------------------------------------------------------------------
|
|
385
|
+
|
|
386
|
+
const TRUTHY = new Set(['1', 'true', 't', 'yes', 'y', 'on']);
|
|
387
|
+
const FALSY = new Set(['', '0', 'false', 'f', 'no', 'n', 'off']);
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Parsed as a STRING with an explicit truthy check, never a coerced bool:
|
|
391
|
+
* anything unrecognized becomes `false` plus a warning. A malformed bool on this
|
|
392
|
+
* system's existing flags is a documented whole-container crash on the
|
|
393
|
+
* middleware, and a new feature flag must not be able to cause that.
|
|
394
|
+
*/
|
|
395
|
+
export function parseEnabled(raw: string | undefined): { enabled: boolean; malformed: boolean } {
|
|
396
|
+
const v = (raw ?? '').trim().toLowerCase();
|
|
397
|
+
if (TRUTHY.has(v)) return { enabled: true, malformed: false };
|
|
398
|
+
if (FALSY.has(v)) return { enabled: false, malformed: false };
|
|
399
|
+
return { enabled: false, malformed: true };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Keyed on the verified Supabase `sub`, explicitly NOT a fourth email list
|
|
404
|
+
* alongside PROTECTED_EMAILS / MEMBERSHIP_REVOKE_ALLOWLIST / QA_FIXTURE_EMAILS.
|
|
405
|
+
* An EMPTY allowlist denies everyone — not "no filter applied".
|
|
406
|
+
*/
|
|
407
|
+
export function parseAllowlist(raw: string | undefined): Set<string> {
|
|
408
|
+
return new Set(
|
|
409
|
+
(raw ?? '').split(/[\s,;]+/).map((s) => s.trim()).filter(Boolean),
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// --------------------------------------------------------------------------
|
|
414
|
+
// Response projection
|
|
415
|
+
// --------------------------------------------------------------------------
|
|
416
|
+
|
|
417
|
+
function isScalar(v: unknown): boolean {
|
|
418
|
+
return v === null || ['string', 'number', 'boolean'].includes(typeof v);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function pickScalars(src: Record<string, unknown>, fields: readonly string[]): Record<string, unknown> {
|
|
422
|
+
const out: Record<string, unknown> = {};
|
|
423
|
+
for (const f of fields) {
|
|
424
|
+
if (f in src && isScalar(src[f])) out[f] = src[f];
|
|
425
|
+
}
|
|
426
|
+
return out;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Mirrors doorGateOk() in membership-door-sync/index.ts. Kept identical on purpose. */
|
|
430
|
+
function doorGateOk(notBefore: string | null, now: number): boolean {
|
|
431
|
+
if (notBefore == null) return true;
|
|
432
|
+
const t = Date.parse(notBefore);
|
|
433
|
+
if (!Number.isFinite(t)) return false;
|
|
434
|
+
return t <= now;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
interface MembershipRow {
|
|
438
|
+
id: string;
|
|
439
|
+
status: string;
|
|
440
|
+
pricing_grace_ends_at: string | null;
|
|
441
|
+
door_managed: boolean | null;
|
|
442
|
+
door_access_not_before: string | null;
|
|
443
|
+
unifi_access_user_id: string | null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export async function handleMemberDoorAction(req: Request): Promise<Response> {
|
|
447
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
448
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
449
|
+
|
|
450
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
|
|
451
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';
|
|
452
|
+
if (!SUPABASE_URL || !SERVICE_ROLE_KEY) return json(503, { ok: false, error: 'not_configured' });
|
|
453
|
+
|
|
454
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
455
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
// ---- Step 1: identity, from Supabase's own verified auth context ---------
|
|
459
|
+
// Nothing below this line reads a caller-supplied subject. Note that a
|
|
460
|
+
// Supabase anon/publishable key presented as a bearer simply fails getUser,
|
|
461
|
+
// which is exactly what we want — verify_jwt at the gateway accepts it, so
|
|
462
|
+
// this check, not the gateway, is the real gate.
|
|
463
|
+
const session = await resolvePortalSession(req, admin);
|
|
464
|
+
if (!session) return json(401, { ok: false, error: 'unauthorized' });
|
|
465
|
+
|
|
466
|
+
// ---- Step 2: body shape (parsed before authorization only to know which
|
|
467
|
+
// action's buckets and rules to apply; no identity is read from it) --------
|
|
468
|
+
const declaredLen = Number(req.headers.get('content-length') ?? '');
|
|
469
|
+
if (Number.isFinite(declaredLen) && declaredLen > MAX_BODY_BYTES) {
|
|
470
|
+
return json(413, { ok: false, error: 'payload_too_large' });
|
|
471
|
+
}
|
|
472
|
+
const bodyText = await req.text().catch(() => '');
|
|
473
|
+
if (new TextEncoder().encode(bodyText).byteLength > MAX_BODY_BYTES) {
|
|
474
|
+
return json(413, { ok: false, error: 'payload_too_large' });
|
|
475
|
+
}
|
|
476
|
+
let body: Record<string, unknown> = {};
|
|
477
|
+
try {
|
|
478
|
+
const parsed = JSON.parse(bodyText || '{}');
|
|
479
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
480
|
+
body = parsed as Record<string, unknown>;
|
|
481
|
+
}
|
|
482
|
+
} catch {
|
|
483
|
+
return json(400, { ok: false, error: 'invalid_json' });
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const action = String(body.action ?? '') as MemberAction;
|
|
487
|
+
if (!(MEMBER_ACTIONS as readonly string[]).includes(action)) {
|
|
488
|
+
return json(400, { ok: false, error: 'unknown_action' });
|
|
489
|
+
}
|
|
490
|
+
const route = ROUTES[action];
|
|
491
|
+
|
|
492
|
+
// ---- Step 3: rate limits, keyed on the verified sub (never email, never a
|
|
493
|
+
// single global bucket — plan's global-lockout hazard) --------------------
|
|
494
|
+
const buckets = await Promise.all([
|
|
495
|
+
checkRateLimit(admin, 'member-door-action-ip', clientIp(req), 120, 300),
|
|
496
|
+
...route.limits.map(([name, max, win]) => checkRateLimit(admin, name, session.id, max, win)),
|
|
497
|
+
]);
|
|
498
|
+
if (buckets.some((ok) => !ok)) return json(429, { ok: false, error: 'rate_limited' });
|
|
499
|
+
|
|
500
|
+
// ---- Step 4: feature gate + allowlist ----------------------------------
|
|
501
|
+
const gate = parseEnabled(Deno.env.get('MEMBER_ACTIONS_ENABLED'));
|
|
502
|
+
if (gate.malformed) {
|
|
503
|
+
console.warn(
|
|
504
|
+
'[member-door-action] MEMBER_ACTIONS_ENABLED is not a recognized boolean; treating as false',
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (!gate.enabled) return json(503, { ok: false, error: 'not_configured' });
|
|
508
|
+
|
|
509
|
+
const allowlist = parseAllowlist(Deno.env.get('MEMBER_ACTIONS_ALLOWLIST'));
|
|
510
|
+
if (!allowlist.has(session.id)) {
|
|
511
|
+
await logOps(admin, 'member_door_action_denied', {
|
|
512
|
+
action, actor_uid: session.id, reason: 'not_allowlisted',
|
|
513
|
+
}, { severity: 'warning' });
|
|
514
|
+
return denied();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// ---- Step 5: the tenant app's half of the dual authorization check ---------------
|
|
518
|
+
// Requires a real auth_user_id linkage. Deliberately NO email fallback for
|
|
519
|
+
// still-unlinked rows (portal-resend-invite has one): an email-matched,
|
|
520
|
+
// unlinked membership is a weaker identity binding than a physical door
|
|
521
|
+
// should accept.
|
|
522
|
+
const { data: rowsRaw, error: rowsErr } = await admin
|
|
523
|
+
.from('memberships')
|
|
524
|
+
.select('id,status,pricing_grace_ends_at,door_managed,door_access_not_before,unifi_access_user_id')
|
|
525
|
+
.eq('auth_user_id', session.id)
|
|
526
|
+
.order('created_at', { ascending: true })
|
|
527
|
+
.limit(20);
|
|
528
|
+
if (rowsErr) {
|
|
529
|
+
await logOps(admin, 'member_door_action_lookup_failed', {
|
|
530
|
+
action, actor_uid: session.id, message: rowsErr.message,
|
|
531
|
+
}, { severity: 'error' });
|
|
532
|
+
return json(500, { ok: false, error: 'lookup_failed' });
|
|
533
|
+
}
|
|
534
|
+
const rows = (rowsRaw ?? []) as unknown as MembershipRow[];
|
|
535
|
+
|
|
536
|
+
const deny = async (reason: string, extra: Record<string, unknown> = {}) => {
|
|
537
|
+
await logOps(admin, 'member_door_action_denied', {
|
|
538
|
+
action, actor_uid: session.id, reason, ...extra,
|
|
539
|
+
}, { severity: 'warning' });
|
|
540
|
+
return denied();
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
// Ambiguity is evaluated across ALL of this member's rows, entitled or not: if
|
|
544
|
+
// two rows disagree about which UniFi user this human is, the mapping is not
|
|
545
|
+
// authoritative and no door decision may rest on it (plan R2-4/R2-30).
|
|
546
|
+
const mappedIds = Array.from(new Set(
|
|
547
|
+
rows.map((r) => (r.unifi_access_user_id ?? '').trim()).filter(Boolean),
|
|
548
|
+
));
|
|
549
|
+
if (mappedIds.length > 1) {
|
|
550
|
+
await logOps(admin, 'member_door_action_ambiguous_mapping', {
|
|
551
|
+
action, actor_uid: session.id, mapping_count: mappedIds.length,
|
|
552
|
+
}, { severity: 'error' });
|
|
553
|
+
return denied();
|
|
554
|
+
}
|
|
555
|
+
const unifiUserId = mappedIds[0] ?? '';
|
|
556
|
+
if (!unifiUserId) return await deny('no_unifi_mapping');
|
|
557
|
+
|
|
558
|
+
const now = Date.now();
|
|
559
|
+
const managed = rows.filter((r) => r.door_managed === true);
|
|
560
|
+
if (managed.length === 0) return await deny('not_door_managed');
|
|
561
|
+
// computeEntitlement is imported, never forked — _shared/membership.ts is the
|
|
562
|
+
// single source of truth shared with pricing and membership-door-sync. The
|
|
563
|
+
// door_access_not_before gate is layered after it, same order as the sync.
|
|
564
|
+
const entitled = managed.filter(
|
|
565
|
+
(r) => computeEntitlement(r, now) && doorGateOk(r.door_access_not_before, now),
|
|
566
|
+
);
|
|
567
|
+
if (entitled.length === 0) return await deny('not_entitled');
|
|
568
|
+
const membershipId = entitled[0].id;
|
|
569
|
+
|
|
570
|
+
// ---- Step 6: per-action parameters (still no identity from the body) ----
|
|
571
|
+
let unifiDoorId: string | null = null;
|
|
572
|
+
let gcDoorId: string | null = null;
|
|
573
|
+
let activityLimit = ACTIVITY_DEFAULT_LIMIT;
|
|
574
|
+
|
|
575
|
+
if (action === 'unlock') {
|
|
576
|
+
gcDoorId = typeof body.door_id === 'string' ? body.door_id.trim() : '';
|
|
577
|
+
// Only a malformed *shape* answers with a distinguishable 400. An id that is
|
|
578
|
+
// well-formed but unknown/unprovisioned falls through to the uniform opaque
|
|
579
|
+
// refusal, so this cannot be used to probe door inventory.
|
|
580
|
+
if (!gcDoorId || !UUID.test(gcDoorId)) return json(400, { ok: false, error: 'invalid_payload' });
|
|
581
|
+
const { data: door, error: doorErr } = await admin
|
|
582
|
+
.from('doors').select('id,name,unifi_door_id,status').eq('id', gcDoorId).maybeSingle();
|
|
583
|
+
if (doorErr) {
|
|
584
|
+
await logOps(admin, 'member_door_action_lookup_failed', {
|
|
585
|
+
action, actor_uid: session.id, message: doorErr.message,
|
|
586
|
+
}, { severity: 'error' });
|
|
587
|
+
return json(500, { ok: false, error: 'lookup_failed' });
|
|
588
|
+
}
|
|
589
|
+
const resolved = (door as { unifi_door_id?: string | null } | null)?.unifi_door_id ?? null;
|
|
590
|
+
if (!door) return await deny('door_not_found', { gc_door_id: gcDoorId });
|
|
591
|
+
if (!resolved || resolved === 'PENDING') {
|
|
592
|
+
return await deny('door_not_provisioned', { gc_door_id: gcDoorId });
|
|
593
|
+
}
|
|
594
|
+
// Outbound door_id MUST be the UniFi id — the middleware calls the controller
|
|
595
|
+
// directly and has never heard of the tenant app's doors.id.
|
|
596
|
+
unifiDoorId = resolved;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
if (action === 'activity') {
|
|
600
|
+
const raw = Number(body.limit ?? ACTIVITY_DEFAULT_LIMIT);
|
|
601
|
+
activityLimit = Number.isFinite(raw)
|
|
602
|
+
? Math.min(ACTIVITY_MAX_LIMIT, Math.max(1, Math.floor(raw)))
|
|
603
|
+
: ACTIVITY_DEFAULT_LIMIT;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// ---- Step 7: signing material ------------------------------------------
|
|
607
|
+
const baseUrl = (Deno.env.get(BASE_URL_ENV) ?? '').trim().replace(/\/+$/, '');
|
|
608
|
+
const hmacSecret = (Deno.env.get(HMAC_SECRET_ENV) ?? '').trim();
|
|
609
|
+
const signingKeyRaw = (Deno.env.get(SIGNING_KEY_ENV) ?? '').trim();
|
|
610
|
+
const iss = (Deno.env.get(ASSERTION_ISS_ENV) ?? '').trim();
|
|
611
|
+
const aud = (Deno.env.get(ASSERTION_AUD_ENV) ?? '').trim();
|
|
612
|
+
|
|
613
|
+
if (!baseUrl || !hmacSecret || !signingKeyRaw || !iss || !aud) {
|
|
614
|
+
await logOps(admin, 'member_door_action_not_configured', {
|
|
615
|
+
action,
|
|
616
|
+
missing: [
|
|
617
|
+
!baseUrl ? BASE_URL_ENV : null,
|
|
618
|
+
!hmacSecret ? HMAC_SECRET_ENV : null,
|
|
619
|
+
!signingKeyRaw ? SIGNING_KEY_ENV : null,
|
|
620
|
+
!iss ? ASSERTION_ISS_ENV : null,
|
|
621
|
+
!aud ? ASSERTION_AUD_ENV : null,
|
|
622
|
+
].filter(Boolean),
|
|
623
|
+
}, { severity: 'error' });
|
|
624
|
+
return json(503, { ok: false, error: 'not_configured' });
|
|
625
|
+
}
|
|
626
|
+
if (!/^https:\/\//i.test(baseUrl)) {
|
|
627
|
+
await logOps(admin, 'member_door_action_not_configured', {
|
|
628
|
+
action, reason: 'base_url_not_https',
|
|
629
|
+
}, { severity: 'error' });
|
|
630
|
+
return json(503, { ok: false, error: 'not_configured' });
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const violations = keyIsolationViolations(Deno.env.toObject());
|
|
634
|
+
if (violations.length > 0) {
|
|
635
|
+
await logOps(admin, 'member_door_action_key_reuse', { action, violations }, { severity: 'error' });
|
|
636
|
+
return json(500, { ok: false, error: 'signing_unavailable' });
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// ---- Step 8: mint the assertion ----------------------------------------
|
|
640
|
+
const iat = Math.floor(Date.now() / 1000);
|
|
641
|
+
const jti = crypto.randomUUID();
|
|
642
|
+
const claims: AssertionClaims = {
|
|
643
|
+
sub: session.id,
|
|
644
|
+
aud,
|
|
645
|
+
iss,
|
|
646
|
+
act: action,
|
|
647
|
+
door_id: unifiDoorId,
|
|
648
|
+
iat,
|
|
649
|
+
// nbf == iat. The +/-30s clock-skew leeway is the VERIFIER's to apply
|
|
650
|
+
// (plan R2-6); baking it in here would only widen the real validity window.
|
|
651
|
+
nbf: iat,
|
|
652
|
+
exp: iat + assertionTtlSeconds(Deno.env.get(ASSERTION_TTL_ENV)),
|
|
653
|
+
jti,
|
|
654
|
+
};
|
|
655
|
+
const assertion = await mintAssertion(signingKeyRaw, claims);
|
|
656
|
+
if (!assertion) {
|
|
657
|
+
await logOps(admin, 'member_door_action_signing_failed', { action }, { severity: 'error' });
|
|
658
|
+
return json(500, { ok: false, error: 'signing_unavailable' });
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ---- Step 9: sign and forward ------------------------------------------
|
|
662
|
+
const isGet = route.method === 'GET';
|
|
663
|
+
const canonicalQuery = isGet ? `limit=${activityLimit}` : '';
|
|
664
|
+
const rawBody = isGet ? '' : '{}';
|
|
665
|
+
const payloadHash = await sha256Hex(isGet ? canonicalQuery : rawBody);
|
|
666
|
+
const assertionHash = await sha256Hex(assertion);
|
|
667
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
668
|
+
const signature = await signD1(
|
|
669
|
+
hmacSecret,
|
|
670
|
+
canonicalMemberActionMessage(action, ts, assertionHash, payloadHash),
|
|
671
|
+
);
|
|
672
|
+
|
|
673
|
+
const url = `${baseUrl}${route.path}${canonicalQuery ? `?${canonicalQuery}` : ''}`;
|
|
674
|
+
const headers: Record<string, string> = {
|
|
675
|
+
[ASSERTION_HEADER]: assertion,
|
|
676
|
+
[SIGNATURE_HEADER]: signature,
|
|
677
|
+
[TIMESTAMP_HEADER]: ts,
|
|
678
|
+
[SCHEME_HEADER]: HMAC_SCHEME,
|
|
679
|
+
};
|
|
680
|
+
if (!isGet) headers['Content-Type'] = 'application/json';
|
|
681
|
+
|
|
682
|
+
// Audit detail is assembled explicitly, field by field. It never contains a
|
|
683
|
+
// PIN, a voucher code, or the member's email (ids and counts only).
|
|
684
|
+
const auditBase: Record<string, unknown> = {
|
|
685
|
+
action,
|
|
686
|
+
actor_uid: session.id,
|
|
687
|
+
membership_id: membershipId,
|
|
688
|
+
unifi_user_id: unifiUserId,
|
|
689
|
+
jti,
|
|
690
|
+
gc_door_id: gcDoorId,
|
|
691
|
+
unifi_door_id: unifiDoorId,
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
const audit = async (detail: Record<string, unknown>, severity: 'info' | 'error' = 'info') => {
|
|
695
|
+
const payload = { ...auditBase, ...detail };
|
|
696
|
+
const { error } = await admin.from('ops_events').insert({
|
|
697
|
+
kind: 'member_door_action', severity, booking_id: null, detail: payload,
|
|
698
|
+
} as never);
|
|
699
|
+
// Same escalation as admin-door-write: a door write with no audit trail is
|
|
700
|
+
// precisely what this row exists to prevent, so a failed insert is loud.
|
|
701
|
+
if (error) {
|
|
702
|
+
await logOps(admin, 'member_door_action_audit_failed', {
|
|
703
|
+
audit_error: error.message, ...payload,
|
|
704
|
+
}, { severity: 'error' });
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
|
|
708
|
+
// "Couldn't confirm" — never "unlocked", never "denied", never retried.
|
|
709
|
+
const unconfirmed = () => json(502, {
|
|
710
|
+
ok: false,
|
|
711
|
+
error: 'unlock_unconfirmed',
|
|
712
|
+
message: "We couldn't confirm that unlock — please use your card or fob.",
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
let res: Response;
|
|
716
|
+
try {
|
|
717
|
+
res = await fetch(url, {
|
|
718
|
+
method: route.method,
|
|
719
|
+
headers,
|
|
720
|
+
...(isGet ? {} : { body: rawBody }),
|
|
721
|
+
signal: AbortSignal.timeout(route.timeoutMs),
|
|
722
|
+
});
|
|
723
|
+
} catch (e) {
|
|
724
|
+
await audit({ outcome: 'unknown', transport_error: String(e).slice(0, 300) }, 'error');
|
|
725
|
+
await logOps(admin, 'member_door_action_call_error', {
|
|
726
|
+
action, actor_uid: session.id, jti, message: String(e).slice(0, 300),
|
|
727
|
+
}, { severity: 'error' });
|
|
728
|
+
// A write that timed out may or may not have landed upstream. For unlock the
|
|
729
|
+
// plan is explicit: report unconfirmed. For the others there is nothing to be
|
|
730
|
+
// ambiguous about from the member's point of view.
|
|
731
|
+
return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_unreachable' });
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
const text = await res.text();
|
|
735
|
+
let parsed: Record<string, unknown> | null = null;
|
|
736
|
+
try {
|
|
737
|
+
const candidate = text ? JSON.parse(text) : null;
|
|
738
|
+
if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
|
|
739
|
+
parsed = candidate as Record<string, unknown>;
|
|
740
|
+
}
|
|
741
|
+
} catch {
|
|
742
|
+
parsed = null;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (!res.ok) {
|
|
746
|
+
// 401/403 covers BOTH "the middleware rejected our signature/assertion" and
|
|
747
|
+
// "the member is not entitled". We cannot tell them apart from the status, so
|
|
748
|
+
// the member gets the uniform opaque refusal and ops_events gets the detail
|
|
749
|
+
// at error severity — a signing misconfiguration must not hide inside a
|
|
750
|
+
// stream of ordinary denials.
|
|
751
|
+
const authRejected = res.status === 401 || res.status === 403;
|
|
752
|
+
await audit({
|
|
753
|
+
outcome: authRejected ? 'denied' : 'error',
|
|
754
|
+
middleware_status: res.status,
|
|
755
|
+
middleware_body: text.slice(0, 300),
|
|
756
|
+
}, 'error');
|
|
757
|
+
await logOps(admin, 'member_door_action_call_failed', {
|
|
758
|
+
action, actor_uid: session.id, jti, status: res.status, response: text.slice(0, 300),
|
|
759
|
+
}, { severity: 'error' });
|
|
760
|
+
if (authRejected) return denied();
|
|
761
|
+
if (res.status === 429) return json(429, { ok: false, error: 'rate_limited' });
|
|
762
|
+
return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_error' });
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (!parsed) {
|
|
766
|
+
await audit({ outcome: 'unknown', middleware_status: res.status, reason: 'unparseable_body' }, 'error');
|
|
767
|
+
await logOps(admin, 'member_door_action_bad_response', {
|
|
768
|
+
action, actor_uid: session.id, jti, status: res.status, response: text.slice(0, 300),
|
|
769
|
+
}, { severity: 'error' });
|
|
770
|
+
return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_error' });
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// A 200 carrying an explicit refusal is still a refusal.
|
|
774
|
+
if (parsed.ok === false) {
|
|
775
|
+
await audit({
|
|
776
|
+
outcome: 'denied',
|
|
777
|
+
middleware_status: res.status,
|
|
778
|
+
middleware_reason: typeof parsed.error === 'string' ? parsed.error.slice(0, 120) : null,
|
|
779
|
+
}, 'error');
|
|
780
|
+
return denied();
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
if (action === 'activity') {
|
|
784
|
+
const hitsRaw = Array.isArray(parsed.hits) ? parsed.hits : null;
|
|
785
|
+
if (!hitsRaw) {
|
|
786
|
+
await audit({ outcome: 'unknown', middleware_status: res.status, reason: 'missing_hits' }, 'error');
|
|
787
|
+
await logOps(admin, 'member_door_action_bad_response', {
|
|
788
|
+
action, actor_uid: session.id, jti, status: res.status, reason: 'missing_hits',
|
|
789
|
+
}, { severity: 'error' });
|
|
790
|
+
return json(502, { ok: false, error: 'middleware_error' });
|
|
791
|
+
}
|
|
792
|
+
// Defence in depth on the middleware's own server-side actor_id forcing
|
|
793
|
+
// (plan finding #5): if a hit carries an actor id at all, it MUST be this
|
|
794
|
+
// member's. One mismatch discards the ENTIRE response — a feed that is
|
|
795
|
+
// partly someone else's history is not salvageable by filtering.
|
|
796
|
+
const hits: Record<string, unknown>[] = [];
|
|
797
|
+
for (const h of hitsRaw) {
|
|
798
|
+
if (!h || typeof h !== 'object' || Array.isArray(h)) continue;
|
|
799
|
+
const hit = h as Record<string, unknown>;
|
|
800
|
+
const hitActor = typeof hit.actor_id === 'string' ? hit.actor_id.trim() : '';
|
|
801
|
+
if (hitActor && hitActor !== unifiUserId) {
|
|
802
|
+
await audit({ outcome: 'scope_violation', middleware_status: res.status }, 'error');
|
|
803
|
+
await logOps(admin, 'member_door_action_scope_violation', {
|
|
804
|
+
action, actor_uid: session.id, jti, hit_count: hitsRaw.length,
|
|
805
|
+
}, { severity: 'error' });
|
|
806
|
+
return json(502, { ok: false, error: 'middleware_error' });
|
|
807
|
+
}
|
|
808
|
+
// actor_id is asserted above and then dropped: the browser has no use for
|
|
809
|
+
// a UniFi internal id.
|
|
810
|
+
hits.push(pickScalars(hit, ACTIVITY_HIT_FIELDS));
|
|
811
|
+
}
|
|
812
|
+
await audit({ outcome: 'ok', middleware_status: res.status, hit_count: hits.length });
|
|
813
|
+
return json(200, { ok: true, hits });
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const result = pickScalars(parsed, RESPONSE_FIELDS[action]);
|
|
817
|
+
|
|
818
|
+
if (action === 'unlock') {
|
|
819
|
+
// Success is asserted, never inferred. The middleware's post-unlock
|
|
820
|
+
// GET /doors/:id read-back is what turns `outcome` into 'unlocked'; anything
|
|
821
|
+
// else (missing, 'unconfirmed', unexpected) is reported as unconfirmed.
|
|
822
|
+
if (result.outcome !== 'unlocked') {
|
|
823
|
+
await audit({
|
|
824
|
+
outcome: 'unknown',
|
|
825
|
+
middleware_status: res.status,
|
|
826
|
+
middleware_outcome: typeof result.outcome === 'string' ? result.outcome : null,
|
|
827
|
+
}, 'error');
|
|
828
|
+
await logOps(admin, 'member_door_action_unlock_unconfirmed', {
|
|
829
|
+
action, actor_uid: session.id, jti, middleware_status: res.status,
|
|
830
|
+
middleware_outcome: typeof result.outcome === 'string' ? result.outcome : null,
|
|
831
|
+
}, { severity: 'error' });
|
|
832
|
+
return unconfirmed();
|
|
833
|
+
}
|
|
834
|
+
await audit({ outcome: 'unlocked', middleware_status: res.status });
|
|
835
|
+
return json(200, { ok: true, ...result });
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// pin_regenerate: the middleware's group reverse-index verdict is the one
|
|
839
|
+
// signal on this path that can turn a nominally-successful PIN write into a
|
|
840
|
+
// defect. Anything other than 'ok' (or absent) escalates this audit row to
|
|
841
|
+
// error severity AND raises a logOps alert — a direct ops_events insert alone
|
|
842
|
+
// does not page anyone; only logOps fans out to the webhook/Slack. The PIN
|
|
843
|
+
// itself still goes back to the member: it was really written, and withholding
|
|
844
|
+
// it would leave them locked out on top of the anomaly.
|
|
845
|
+
if (action === 'pin_regenerate') {
|
|
846
|
+
const groupCheck = typeof result.group_check === 'string' ? result.group_check : null;
|
|
847
|
+
if (groupCheck !== null && groupCheck !== 'ok') {
|
|
848
|
+
await audit({
|
|
849
|
+
outcome: 'ok', middleware_status: res.status, group_check: groupCheck,
|
|
850
|
+
}, 'error');
|
|
851
|
+
await logOps(admin, 'member_door_action_group_check_mismatch', {
|
|
852
|
+
action, actor_uid: session.id, membership_id: membershipId, jti,
|
|
853
|
+
middleware_status: res.status, group_check: groupCheck,
|
|
854
|
+
}, { severity: 'error' });
|
|
855
|
+
return json(200, { ok: true, ...result });
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// pin_regenerate (clean) / wifi_voucher: the secret value is returned to the
|
|
860
|
+
// member once and is NOT part of the audit payload (auditBase carries ids only).
|
|
861
|
+
await audit({ outcome: 'ok', middleware_status: res.status });
|
|
862
|
+
return json(200, { ok: true, ...result });
|
|
863
|
+
}
|