usebecky 0.0.0-stage → 0.2.0
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/README.md +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import type { Purchase, Subscription, User } from '../lib/types.ts';
|
|
2
|
+
import type { ServerOrder } from './payments.ts';
|
|
3
|
+
export type EventType = 'user.created' | 'user.updated' | 'user.deleted' | 'user.signed_in' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.trial_will_end' | 'subscription.gifted' | 'subscription.gift_updated' | 'subscription.gift_ended' | 'purchase.completed' | 'purchase.refunded' | 'order.paid' | 'order.refunded' | 'order.canceled' | 'order.shipped' | 'order.delivered' | 'payment.failed' | 'payment.disputed' | 'payment.dispute_closed' | 'payment.fraud_warning' | 'storage.object.created' | 'storage.object.deleted' | 'form.submitted' | 'email.failed' | 'email.sent' | 'email.delivered' | 'email.delayed' | 'email.bounced' | 'email.complained' | 'email.suppressed' | 'quota.warning' | 'quota.exceeded' | 'newsletter.subscribed' | 'newsletter.unsubscribed' | 'job.failed' | 'function.failed' | 'certificate.renewed' | 'db.row.inserted' | 'db.row.updated' | 'db.row.deleted' | 'test.ping';
|
|
4
|
+
export interface UseBeckyEvent<T = any> {
|
|
5
|
+
/** Unique event id (`evt_...`). The same event can be delivered more than once: use this to skip duplicates. */
|
|
6
|
+
id: string;
|
|
7
|
+
type: EventType | (string & {});
|
|
8
|
+
created_at: string;
|
|
9
|
+
/** Project ref. */
|
|
10
|
+
project: string;
|
|
11
|
+
data: T;
|
|
12
|
+
}
|
|
13
|
+
export interface EventDataMap {
|
|
14
|
+
'user.created': {
|
|
15
|
+
user: User;
|
|
16
|
+
};
|
|
17
|
+
'user.updated': {
|
|
18
|
+
user: User;
|
|
19
|
+
};
|
|
20
|
+
'user.deleted': {
|
|
21
|
+
user: Partial<User> & {
|
|
22
|
+
id: string;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
'user.signed_in': {
|
|
26
|
+
user: User;
|
|
27
|
+
method: string;
|
|
28
|
+
};
|
|
29
|
+
'email.failed': EmailFailedData;
|
|
30
|
+
'email.sent': EmailEventData;
|
|
31
|
+
'email.delivered': EmailEventData;
|
|
32
|
+
'email.delayed': EmailEventData;
|
|
33
|
+
'email.bounced': EmailEventData;
|
|
34
|
+
'email.complained': EmailEventData;
|
|
35
|
+
'email.suppressed': EmailEventData;
|
|
36
|
+
'form.submitted': {
|
|
37
|
+
form: {
|
|
38
|
+
id: string;
|
|
39
|
+
key: string;
|
|
40
|
+
name: string;
|
|
41
|
+
};
|
|
42
|
+
submission: {
|
|
43
|
+
id: string;
|
|
44
|
+
data: Record<string, unknown>;
|
|
45
|
+
extra: Record<string, unknown>;
|
|
46
|
+
submitter_email: string | null;
|
|
47
|
+
page_url: string | null;
|
|
48
|
+
created_at: string;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
'subscription.gifted': SubscriptionGiftEventData;
|
|
52
|
+
'subscription.gift_updated': SubscriptionGiftEventData & {
|
|
53
|
+
previous: {
|
|
54
|
+
product_key: string | null;
|
|
55
|
+
ends_at: string | null;
|
|
56
|
+
note: string | null;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
'subscription.gift_ended': SubscriptionGiftEventData & {
|
|
60
|
+
reason: 'expired' | 'revoked' | 'paid';
|
|
61
|
+
};
|
|
62
|
+
'quota.warning': QuotaEventData;
|
|
63
|
+
'quota.exceeded': QuotaEventData;
|
|
64
|
+
'job.failed': {
|
|
65
|
+
job: {
|
|
66
|
+
id: string;
|
|
67
|
+
name: string;
|
|
68
|
+
type: 'function' | 'http' | 'cleanup' | 'run_function';
|
|
69
|
+
};
|
|
70
|
+
run: {
|
|
71
|
+
id: string;
|
|
72
|
+
status: string;
|
|
73
|
+
error: string | null;
|
|
74
|
+
started_at: string;
|
|
75
|
+
finished_at: string | null;
|
|
76
|
+
[k: string]: unknown;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
/** One of your Functions failed (error, time limit, memory). At most one per function per minute; `failures_since_last_event` counts the rest. */
|
|
80
|
+
'function.failed': {
|
|
81
|
+
function: {
|
|
82
|
+
id: string;
|
|
83
|
+
name: string;
|
|
84
|
+
version: number | null;
|
|
85
|
+
};
|
|
86
|
+
invocation: {
|
|
87
|
+
id: string;
|
|
88
|
+
trigger: 'http' | 'schedule' | 'event' | 'database';
|
|
89
|
+
status: 'failed' | 'timeout' | 'out_of_memory' | 'crashed' | 'unavailable' | 'succeeded';
|
|
90
|
+
error: string;
|
|
91
|
+
duration_ms: number;
|
|
92
|
+
http_status: number | null;
|
|
93
|
+
};
|
|
94
|
+
failures_since_last_event: number;
|
|
95
|
+
};
|
|
96
|
+
/** An SSL certificate for your own server was renewed (same key unless "Replace key" was used): fetch the new files. */
|
|
97
|
+
'certificate.renewed': {
|
|
98
|
+
certificate: {
|
|
99
|
+
id: string;
|
|
100
|
+
domain: string;
|
|
101
|
+
names: string[];
|
|
102
|
+
serial: string;
|
|
103
|
+
not_before: string;
|
|
104
|
+
not_after: string;
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
'db.row.inserted': {
|
|
108
|
+
table: string;
|
|
109
|
+
record: Record<string, unknown>;
|
|
110
|
+
old_record: null;
|
|
111
|
+
};
|
|
112
|
+
'db.row.updated': {
|
|
113
|
+
table: string;
|
|
114
|
+
record: Record<string, unknown>;
|
|
115
|
+
old_record: Record<string, unknown> | null;
|
|
116
|
+
};
|
|
117
|
+
'db.row.deleted': {
|
|
118
|
+
table: string;
|
|
119
|
+
record: null;
|
|
120
|
+
old_record: Record<string, unknown>;
|
|
121
|
+
};
|
|
122
|
+
'payment.disputed': PaymentDisputedData;
|
|
123
|
+
'payment.dispute_closed': PaymentDisputeClosedData;
|
|
124
|
+
'payment.fraud_warning': PaymentFraudWarningData;
|
|
125
|
+
/** A shop order was paid. `user_id` is null for a guest. */
|
|
126
|
+
'order.paid': OrderEventData;
|
|
127
|
+
/** Money went back (a refund, or a lost dispute): `amount` now, `amount_refunded` in all; `order.status` is
|
|
128
|
+
* 'partly_refunded' or 'refunded'. */
|
|
129
|
+
'order.refunded': OrderEventData & {
|
|
130
|
+
amount: number;
|
|
131
|
+
amount_refunded: number;
|
|
132
|
+
};
|
|
133
|
+
/** A placed order was canceled: its bank payment failed, or your team canceled it (a paid one is refunded too). */
|
|
134
|
+
'order.canceled': OrderEventData;
|
|
135
|
+
/** You marked the order shipped (dashboard or `payments.updateOrder()`): `order.carrier`, `tracking_number`,
|
|
136
|
+
* `tracking_url` when you gave them. Sent once. */
|
|
137
|
+
'order.shipped': OrderEventData;
|
|
138
|
+
/** You marked the order delivered. Sent once. */
|
|
139
|
+
'order.delivered': OrderEventData;
|
|
140
|
+
'newsletter.subscribed': NewsletterEventData;
|
|
141
|
+
'newsletter.unsubscribed': NewsletterEventData & {
|
|
142
|
+
reason: 'link' | 'one_click' | 'dashboard' | 'api' | 'deleted' | 'bounced';
|
|
143
|
+
campaign_id: string | null;
|
|
144
|
+
};
|
|
145
|
+
[key: string]: any;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Data of 'subscription.gifted' / 'subscription.gift_updated' / 'subscription.gift_ended': you gave a user a
|
|
149
|
+
* product for free (dashboard or `baas.payments.gift()`). Gifts never send subscription.created / updated /
|
|
150
|
+
* canceled, so listen to 'subscription.*' to handle paid subscriptions and gifts in one place.
|
|
151
|
+
* `gift_ended.reason`: 'expired' (reached ends_at), 'revoked' (you ended it) or 'paid' (the user started paying).
|
|
152
|
+
*/
|
|
153
|
+
export interface SubscriptionGiftEventData {
|
|
154
|
+
user_id: string | null;
|
|
155
|
+
/** `source: 'gift'`; `status` is 'active' while it runs, 'canceled' once it ended. */
|
|
156
|
+
subscription: Subscription;
|
|
157
|
+
gift: {
|
|
158
|
+
active: boolean;
|
|
159
|
+
starts_at: string;
|
|
160
|
+
ends_at: string | null;
|
|
161
|
+
note: string | null;
|
|
162
|
+
gifted_by: string | null;
|
|
163
|
+
ended_at: string | null;
|
|
164
|
+
end_reason: 'expired' | 'revoked' | 'paid' | null;
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** Data of 'order.paid' / 'order.refunded' / 'order.canceled' / 'order.shipped' / 'order.delivered': the order with
|
|
168
|
+
* its lines, buyer, fulfilment and Stripe ids. */
|
|
169
|
+
export interface OrderEventData {
|
|
170
|
+
user_id: string | null;
|
|
171
|
+
order: ServerOrder;
|
|
172
|
+
}
|
|
173
|
+
/** A dispute ("chargeback") on one of your sales. Amounts are in the smallest currency unit (1500 = $15.00). */
|
|
174
|
+
export interface DisputeInfo {
|
|
175
|
+
/** Stripe's dispute id (dp_...). */
|
|
176
|
+
id: string;
|
|
177
|
+
amount: number;
|
|
178
|
+
currency: string | null;
|
|
179
|
+
/** Stripe's reason, e.g. 'fraudulent', 'product_not_received', 'subscription_canceled'. */
|
|
180
|
+
reason: string | null;
|
|
181
|
+
/** Stripe's status: needs_response, under_review, won, lost; warning_* for an inquiry (no money moved yet). */
|
|
182
|
+
status: string;
|
|
183
|
+
/** Respond in your Stripe Dashboard before this time (ISO). */
|
|
184
|
+
evidence_due_by: string | null;
|
|
185
|
+
livemode: boolean;
|
|
186
|
+
purchase_id: string | null;
|
|
187
|
+
/** Stripe's subscription id, when the payment was a subscription invoice. */
|
|
188
|
+
subscription_id: string | null;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Data of 'payment.disputed': a customer asked their bank to take a payment back. Sent once per dispute, and once
|
|
192
|
+
* more if a bank's inquiry (`inquiry: true`) becomes a chargeback (`inquiry: false, escalated: true`, same dispute id).
|
|
193
|
+
*/
|
|
194
|
+
export interface PaymentDisputedData {
|
|
195
|
+
user_id: string | null;
|
|
196
|
+
dispute: DisputeInfo;
|
|
197
|
+
purchase: Purchase | null;
|
|
198
|
+
subscription: Subscription | null;
|
|
199
|
+
/** An inquiry: the bank asks questions first; access never changes for those. */
|
|
200
|
+
inquiry: boolean;
|
|
201
|
+
/** The inquiry you were told about earlier is now a chargeback (a new deadline; access changes as for any dispute). */
|
|
202
|
+
escalated: boolean;
|
|
203
|
+
/** 'removed' with the project setting "Remove access right away", else 'kept' until the bank decides. */
|
|
204
|
+
access: 'kept' | 'removed';
|
|
205
|
+
}
|
|
206
|
+
/** Data of 'payment.dispute_closed': the bank decided. 'lost' ends access like a refund; 'won' gives back access that was removed. */
|
|
207
|
+
export interface PaymentDisputeClosedData {
|
|
208
|
+
user_id: string | null;
|
|
209
|
+
dispute: DisputeInfo;
|
|
210
|
+
purchase: Purchase | null;
|
|
211
|
+
subscription: Subscription | null;
|
|
212
|
+
outcome: 'won' | 'lost' | 'inquiry_closed' | 'prevented';
|
|
213
|
+
access: 'removed' | 'restored' | 'unchanged';
|
|
214
|
+
}
|
|
215
|
+
/** Data of 'payment.fraud_warning': the card's bank told Stripe a payment was probably made with a stolen card. */
|
|
216
|
+
export interface PaymentFraudWarningData {
|
|
217
|
+
user_id: string | null;
|
|
218
|
+
warning: {
|
|
219
|
+
id: string;
|
|
220
|
+
fraud_type: string | null;
|
|
221
|
+
amount: number | null;
|
|
222
|
+
currency: string | null;
|
|
223
|
+
livemode: boolean;
|
|
224
|
+
};
|
|
225
|
+
purchase: Purchase | null;
|
|
226
|
+
subscription: Subscription | null;
|
|
227
|
+
/** Refunded automatically (the project setting, on by default); access then ends. */
|
|
228
|
+
refunded: boolean;
|
|
229
|
+
access: 'removed' | 'kept';
|
|
230
|
+
}
|
|
231
|
+
/** Data of 'quota.warning' (80%) / 'quota.exceeded' (100%). Sent once per limit per month. */
|
|
232
|
+
export interface QuotaEventData {
|
|
233
|
+
quota: string;
|
|
234
|
+
label: string;
|
|
235
|
+
level: 'warning' | 'exceeded';
|
|
236
|
+
used: number;
|
|
237
|
+
limit: number;
|
|
238
|
+
percent: number;
|
|
239
|
+
plan: 'free' | 'pro' | 'business';
|
|
240
|
+
period: string;
|
|
241
|
+
upgrade_url: string;
|
|
242
|
+
}
|
|
243
|
+
/** Data of 'newsletter.subscribed' / 'newsletter.unsubscribed'. */
|
|
244
|
+
export interface NewsletterEventData {
|
|
245
|
+
list: {
|
|
246
|
+
id: string;
|
|
247
|
+
key: string;
|
|
248
|
+
name: string;
|
|
249
|
+
};
|
|
250
|
+
subscriber: {
|
|
251
|
+
id: string;
|
|
252
|
+
email: string;
|
|
253
|
+
name: string | null;
|
|
254
|
+
status: string;
|
|
255
|
+
source: string;
|
|
256
|
+
tags: string[];
|
|
257
|
+
user_id: string | null;
|
|
258
|
+
consent_at: string | null;
|
|
259
|
+
created_at: string;
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/** Data of 'email.failed': an email for your project could not be sent (it is in Dashboard → Emails → Sent). */
|
|
263
|
+
export interface EmailFailedData {
|
|
264
|
+
email: {
|
|
265
|
+
/** Id of the entry in Dashboard → Emails → Sent. */
|
|
266
|
+
id: string;
|
|
267
|
+
/** Recipient, masked like "a***@example.com". Use user_id to find the user. */
|
|
268
|
+
to: string;
|
|
269
|
+
/** signup, magiclink, recovery, invite, email_change, welcome; null for baas.emails.send and form notifications. */
|
|
270
|
+
template_id: string | null;
|
|
271
|
+
kind: 'auth' | 'welcome' | 'transactional' | 'form';
|
|
272
|
+
subject: string;
|
|
273
|
+
status: 'failed';
|
|
274
|
+
/** Why it failed, in plain English. */
|
|
275
|
+
error: string;
|
|
276
|
+
sender: 'platform' | 'custom_smtp';
|
|
277
|
+
created_at: string;
|
|
278
|
+
};
|
|
279
|
+
/** The user the email was for (auth and welcome emails), else null. */
|
|
280
|
+
user_id: string | null;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Data of 'email.sent' (handed to the email provider), 'email.delivered' (the receiving server accepted it),
|
|
284
|
+
* 'email.delayed' (the receiving server asked to try again later), 'email.bounced' (it couldn't be delivered),
|
|
285
|
+
* 'email.complained' (the person marked it as spam) and 'email.suppressed' (not sent: the address bounced or
|
|
286
|
+
* complained before). Bounced and complained addresses go on your suppression list (Dashboard → Emails → Sent).
|
|
287
|
+
*/
|
|
288
|
+
export interface EmailEventData {
|
|
289
|
+
email: {
|
|
290
|
+
/** Id of the entry in Dashboard → Emails → Sent (the id `baas.emails.send` returned). */
|
|
291
|
+
id: string;
|
|
292
|
+
/** Recipient, masked like "a***@example.com". Use user_id to find the user. */
|
|
293
|
+
to: string;
|
|
294
|
+
/** Built-in (signup, magiclink, ...) or your own template id; null for emails without a template. */
|
|
295
|
+
template_id: string | null;
|
|
296
|
+
kind: 'auth' | 'welcome' | 'transactional' | 'form' | 'newsletter' | (string & {});
|
|
297
|
+
subject: string;
|
|
298
|
+
status: 'sent' | 'delivered' | 'delayed' | 'bounced' | 'complained' | 'suppressed' | (string & {});
|
|
299
|
+
/** Why it bounced, was delayed or suppressed, in plain English (like "The address doesn't exist"); else null. */
|
|
300
|
+
reason?: string | null;
|
|
301
|
+
/** Why it failed ('email.failed'), in plain English; else null. */
|
|
302
|
+
error?: string | null;
|
|
303
|
+
/** 'platform' (usebecky's sender), 'domain' (your own domain) or 'custom_smtp'. */
|
|
304
|
+
sender?: string;
|
|
305
|
+
/** The tags you sent with `baas.emails.send({ tags })`. */
|
|
306
|
+
tags?: {
|
|
307
|
+
name: string;
|
|
308
|
+
value: string;
|
|
309
|
+
}[];
|
|
310
|
+
locale?: string | null;
|
|
311
|
+
created_at: string;
|
|
312
|
+
[key: string]: unknown;
|
|
313
|
+
};
|
|
314
|
+
/** The user the email was for (auth and welcome emails), else null. */
|
|
315
|
+
user_id: string | null;
|
|
316
|
+
}
|
|
317
|
+
export type EventHandler<T = any> = (event: UseBeckyEvent<T>) => void | Promise<void>;
|
|
318
|
+
export declare const SIGNATURE_HEADER = "usebecky-signature";
|
|
319
|
+
/** Compute the signature header value for a body (handy in tests). */
|
|
320
|
+
export declare function signEvent(rawBody: string, secret: string, timestamp?: number): string;
|
|
321
|
+
/**
|
|
322
|
+
* Check the signature and timestamp, then return the parsed event. Throws a UseBeckyError
|
|
323
|
+
* (`invalid_signature`, `stale_signature`, ...) when the request did not come from usebecky.
|
|
324
|
+
*/
|
|
325
|
+
export declare function verifyEvent(rawBody: string | Uint8Array | ArrayBuffer, signatureHeader: string | null | undefined, secret: string | null | undefined, options?: {
|
|
326
|
+
toleranceSeconds?: number;
|
|
327
|
+
now?: number;
|
|
328
|
+
}): UseBeckyEvent;
|
|
329
|
+
export declare class Events {
|
|
330
|
+
private handlers;
|
|
331
|
+
private getSecret;
|
|
332
|
+
constructor(getSecret?: () => string | undefined);
|
|
333
|
+
/**
|
|
334
|
+
* Run `handler` for an event type. Use `'*'` for every event, or `'subscription.*'` for a group.
|
|
335
|
+
* Returns a function that removes the handler.
|
|
336
|
+
*/
|
|
337
|
+
on<K extends EventType | '*' | `${string}.*` | (string & {})>(type: K, handler: EventHandler<K extends keyof EventDataMap ? EventDataMap[K] : any>): () => void;
|
|
338
|
+
/** Verify a raw body + signature header. Returns the event or throws. */
|
|
339
|
+
verify(rawBody: string | Uint8Array | ArrayBuffer, signatureHeader: string | null | undefined, secret?: string, options?: {
|
|
340
|
+
toleranceSeconds?: number;
|
|
341
|
+
now?: number;
|
|
342
|
+
}): UseBeckyEvent;
|
|
343
|
+
/** Run the registered handlers for an (already verified) event. */
|
|
344
|
+
dispatch(event: UseBeckyEvent): Promise<void>;
|
|
345
|
+
/**
|
|
346
|
+
* Express / Connect / node:http handler:
|
|
347
|
+
* app.post('/api/usebecky-events', baas.events.handler())
|
|
348
|
+
* Reads the raw body itself (or uses req.body when it is a Buffer/string).
|
|
349
|
+
*/
|
|
350
|
+
handler(): (req: any, res: any, next?: (err?: unknown) => void) => Promise<void>;
|
|
351
|
+
private verifyRequest;
|
|
352
|
+
/**
|
|
353
|
+
* Fetch API handler (Next.js route handlers, Remix, Hono, Bun, Deno):
|
|
354
|
+
* export const POST = baas.events.fetchHandler()
|
|
355
|
+
*/
|
|
356
|
+
fetchHandler(): (request: Request) => Promise<Response>;
|
|
357
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Signed events ("webhooks") from usebecky to your server.
|
|
2
|
+
// usebecky-signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
|
|
3
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
5
|
+
import { readEnv } from "../lib/env.js";
|
|
6
|
+
import { sendJson } from "./http-utils.js";
|
|
7
|
+
export const SIGNATURE_HEADER = 'usebecky-signature';
|
|
8
|
+
const DEFAULT_TOLERANCE = 300;
|
|
9
|
+
function sigError(code, message, hint) {
|
|
10
|
+
return new UseBeckyError({ code, message, hint, status: 400 });
|
|
11
|
+
}
|
|
12
|
+
/** Compute the signature header value for a body (handy in tests). */
|
|
13
|
+
export function signEvent(rawBody, secret, timestamp = Math.floor(Date.now() / 1000)) {
|
|
14
|
+
return `t=${timestamp},v1=${createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')}`;
|
|
15
|
+
}
|
|
16
|
+
function bodyToString(raw) {
|
|
17
|
+
if (typeof raw === 'string')
|
|
18
|
+
return raw;
|
|
19
|
+
return new TextDecoder().decode(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Check the signature and timestamp, then return the parsed event. Throws a UseBeckyError
|
|
23
|
+
* (`invalid_signature`, `stale_signature`, ...) when the request did not come from usebecky.
|
|
24
|
+
*/
|
|
25
|
+
export function verifyEvent(rawBody, signatureHeader, secret, options = {}) {
|
|
26
|
+
if (!secret) {
|
|
27
|
+
throw new UseBeckyError({
|
|
28
|
+
code: 'missing_webhook_secret',
|
|
29
|
+
message: 'Missing USEBECKY_WEBHOOK_SECRET, so events cannot be verified.',
|
|
30
|
+
hint: 'Copy the signing secret (whsec_...) from Dashboard → Settings → Webhooks into your server environment as USEBECKY_WEBHOOK_SECRET.',
|
|
31
|
+
status: 500,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
if (!signatureHeader)
|
|
35
|
+
throw sigError('missing_signature', 'This request has no usebecky-signature header.', 'Only usebecky should call this endpoint. If you are testing, use "Send test event" in the dashboard.');
|
|
36
|
+
let timestamp = null;
|
|
37
|
+
const signatures = [];
|
|
38
|
+
for (const part of String(signatureHeader).split(',')) {
|
|
39
|
+
const i = part.indexOf('=');
|
|
40
|
+
if (i < 0)
|
|
41
|
+
continue;
|
|
42
|
+
const k = part.slice(0, i).trim();
|
|
43
|
+
const v = part.slice(i + 1).trim();
|
|
44
|
+
if (k === 't')
|
|
45
|
+
timestamp = Number(v);
|
|
46
|
+
else if (k === 'v1')
|
|
47
|
+
signatures.push(v);
|
|
48
|
+
}
|
|
49
|
+
if (timestamp === null || !Number.isFinite(timestamp) || signatures.length === 0) {
|
|
50
|
+
throw sigError('invalid_signature', 'The usebecky-signature header is malformed.', 'Expected "t=<unix time>,v1=<hex>".');
|
|
51
|
+
}
|
|
52
|
+
const body = bodyToString(rawBody);
|
|
53
|
+
const expected = Buffer.from(createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex'), 'utf8');
|
|
54
|
+
const valid = signatures.some((sig) => {
|
|
55
|
+
const given = Buffer.from(sig, 'utf8');
|
|
56
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
57
|
+
});
|
|
58
|
+
if (!valid) {
|
|
59
|
+
throw sigError('invalid_signature', 'The event signature does not match.', 'Check that USEBECKY_WEBHOOK_SECRET matches the endpoint in Dashboard → Settings → Webhooks, and that the body is passed unmodified (raw).');
|
|
60
|
+
}
|
|
61
|
+
const now = options.now ?? Math.floor(Date.now() / 1000);
|
|
62
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE;
|
|
63
|
+
if (Math.abs(now - timestamp) > tolerance) {
|
|
64
|
+
throw sigError('stale_signature', 'The event timestamp is too old (or in the future), so it was rejected to prevent replays.', "Check your server's clock. usebecky retries failed deliveries with a fresh signature.");
|
|
65
|
+
}
|
|
66
|
+
let event;
|
|
67
|
+
try {
|
|
68
|
+
event = JSON.parse(body);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw sigError('invalid_payload', 'The event body is not valid JSON.');
|
|
72
|
+
}
|
|
73
|
+
if (!event || typeof event !== 'object' || typeof event.type !== 'string')
|
|
74
|
+
throw sigError('invalid_payload', 'The event body is missing a "type".');
|
|
75
|
+
return event;
|
|
76
|
+
}
|
|
77
|
+
function headerFrom(req, name) {
|
|
78
|
+
const h = req?.headers;
|
|
79
|
+
if (!h)
|
|
80
|
+
return undefined;
|
|
81
|
+
if (typeof h.get === 'function')
|
|
82
|
+
return h.get(name) ?? undefined;
|
|
83
|
+
const v = h[name] ?? h[name.toLowerCase()];
|
|
84
|
+
return Array.isArray(v) ? v[0] : v;
|
|
85
|
+
}
|
|
86
|
+
async function readStream(req) {
|
|
87
|
+
if (!req || typeof req.on !== 'function' || req.readableEnded || req.complete === true && req.readable === false)
|
|
88
|
+
return null;
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
req.on('data', (c) => chunks.push(typeof c === 'string' ? Buffer.from(c) : Buffer.from(c)));
|
|
92
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
93
|
+
req.on('error', reject);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
export class Events {
|
|
97
|
+
handlers = new Map();
|
|
98
|
+
getSecret;
|
|
99
|
+
constructor(getSecret) {
|
|
100
|
+
this.getSecret = getSecret ?? (() => readEnv('USEBECKY_WEBHOOK_SECRET'));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Run `handler` for an event type. Use `'*'` for every event, or `'subscription.*'` for a group.
|
|
104
|
+
* Returns a function that removes the handler.
|
|
105
|
+
*/
|
|
106
|
+
on(type, handler) {
|
|
107
|
+
let set = this.handlers.get(type);
|
|
108
|
+
if (!set)
|
|
109
|
+
this.handlers.set(type, (set = new Set()));
|
|
110
|
+
set.add(handler);
|
|
111
|
+
return () => {
|
|
112
|
+
set.delete(handler);
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** Verify a raw body + signature header. Returns the event or throws. */
|
|
116
|
+
verify(rawBody, signatureHeader, secret, options) {
|
|
117
|
+
return verifyEvent(rawBody, signatureHeader, secret ?? this.getSecret(), options);
|
|
118
|
+
}
|
|
119
|
+
/** Run the registered handlers for an (already verified) event. */
|
|
120
|
+
async dispatch(event) {
|
|
121
|
+
const group = event.type.includes('.') ? `${event.type.split('.')[0]}.*` : null;
|
|
122
|
+
const keys = [event.type, ...(group ? [group] : []), '*'];
|
|
123
|
+
const run = [];
|
|
124
|
+
for (const k of keys)
|
|
125
|
+
for (const h of this.handlers.get(k) ?? [])
|
|
126
|
+
run.push(h(event));
|
|
127
|
+
await Promise.all(run);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Express / Connect / node:http handler:
|
|
131
|
+
* app.post('/api/usebecky-events', baas.events.handler())
|
|
132
|
+
* Reads the raw body itself (or uses req.body when it is a Buffer/string).
|
|
133
|
+
*/
|
|
134
|
+
handler() {
|
|
135
|
+
return async (req, res) => {
|
|
136
|
+
const signature = headerFrom(req, SIGNATURE_HEADER);
|
|
137
|
+
let event;
|
|
138
|
+
try {
|
|
139
|
+
event = await this.verifyRequest(req, signature);
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
return respondError(res, err);
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
await this.dispatch(event);
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
logHandlerError(event, err);
|
|
149
|
+
return sendJson(res, 500, { error: { code: 'handler_error', message: `Your handler for "${event.type}" threw an error, so usebecky will retry this event.` } });
|
|
150
|
+
}
|
|
151
|
+
sendJson(res, 200, { received: true });
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
async verifyRequest(req, signature) {
|
|
155
|
+
const body = req?.body;
|
|
156
|
+
if (typeof body === 'string' || (body && (Buffer.isBuffer(body) || body instanceof Uint8Array)))
|
|
157
|
+
return this.verify(body, signature);
|
|
158
|
+
if (req?.rawBody && (typeof req.rawBody === 'string' || Buffer.isBuffer(req.rawBody)))
|
|
159
|
+
return this.verify(req.rawBody, signature);
|
|
160
|
+
const streamed = await readStream(req);
|
|
161
|
+
if (streamed && streamed.length > 0)
|
|
162
|
+
return this.verify(streamed, signature);
|
|
163
|
+
if (body && typeof body === 'object') {
|
|
164
|
+
// express.json() already parsed the body. usebecky signs compact JSON, so re-serializing
|
|
165
|
+
// reproduces the exact bytes in practice; the signature check still protects us.
|
|
166
|
+
try {
|
|
167
|
+
return this.verify(JSON.stringify(body), signature);
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
if (err.code === 'invalid_signature') {
|
|
171
|
+
;
|
|
172
|
+
err.hint = 'Your app parsed the body before the events handler (e.g. app.use(express.json())). Mount the events route BEFORE express.json(), or use express.raw({ type: "application/json" }) on it.';
|
|
173
|
+
}
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return this.verify('', signature);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Fetch API handler (Next.js route handlers, Remix, Hono, Bun, Deno):
|
|
181
|
+
* export const POST = baas.events.fetchHandler()
|
|
182
|
+
*/
|
|
183
|
+
fetchHandler() {
|
|
184
|
+
return async (request) => {
|
|
185
|
+
let event;
|
|
186
|
+
try {
|
|
187
|
+
const raw = await request.text();
|
|
188
|
+
event = this.verify(raw, request.headers.get(SIGNATURE_HEADER));
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
const e = toError(err);
|
|
192
|
+
return jsonResponse(e.status >= 400 ? e.status : 400, { error: e.toJSON() });
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
await this.dispatch(event);
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
logHandlerError(event, err);
|
|
199
|
+
return jsonResponse(500, { error: { code: 'handler_error', message: `Your handler for "${event.type}" threw an error, so usebecky will retry this event.` } });
|
|
200
|
+
}
|
|
201
|
+
return jsonResponse(200, { received: true });
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function toError(err) {
|
|
206
|
+
return err instanceof UseBeckyError ? err : new UseBeckyError({ code: 'invalid_request', message: err?.message ?? 'Invalid request.', status: 400 });
|
|
207
|
+
}
|
|
208
|
+
function respondError(res, err) {
|
|
209
|
+
const e = toError(err);
|
|
210
|
+
if (e.code === 'missing_webhook_secret')
|
|
211
|
+
console.error(`[usebecky] ${e.message} ${e.hint ?? ''}`);
|
|
212
|
+
sendJson(res, e.status >= 400 ? e.status : 400, { error: e.toJSON() });
|
|
213
|
+
}
|
|
214
|
+
function logHandlerError(event, err) {
|
|
215
|
+
console.error(`[usebecky] Event handler for "${event.type}" (${event.id}) failed:`, err);
|
|
216
|
+
}
|
|
217
|
+
function jsonResponse(status, body) {
|
|
218
|
+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
219
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ServerClient } from './index.ts';
|
|
2
|
+
/** What started the run. */
|
|
3
|
+
export type FunctionTrigger = 'http' | 'schedule' | 'event' | 'database' | 'test';
|
|
4
|
+
/** The signed-in user who called the function (from their verified access token). */
|
|
5
|
+
export interface FunctionUser {
|
|
6
|
+
id: string;
|
|
7
|
+
email: string | null;
|
|
8
|
+
phone: string | null;
|
|
9
|
+
role: string;
|
|
10
|
+
aal: 'aal1' | 'aal2' | null;
|
|
11
|
+
is_anonymous: boolean;
|
|
12
|
+
app_metadata: Record<string, unknown>;
|
|
13
|
+
user_metadata: Record<string, unknown>;
|
|
14
|
+
}
|
|
15
|
+
/** The second argument of your handler. */
|
|
16
|
+
export interface FunctionContext<DB = any> {
|
|
17
|
+
/**
|
|
18
|
+
* An admin client for this project, already signed in (no keys needed): `ctx.baas.admin.from('todos')`
|
|
19
|
+
* bypasses access rules, `ctx.baas.as(req)` acts as the calling user, plus `auth.admin`, `emails`, `push`...
|
|
20
|
+
*/
|
|
21
|
+
baas: ServerClient<DB>;
|
|
22
|
+
/** The signed-in user who called it, or null (anonymous calls, schedules, events). */
|
|
23
|
+
user: FunctionUser | null;
|
|
24
|
+
/** Your secrets from Functions → Secrets, e.g. ctx.env.STRIPE_SECRET_KEY. */
|
|
25
|
+
env: Readonly<Record<string, string>>;
|
|
26
|
+
/** The event when a trigger started it (a schedule's job.run, user.created, db.row.inserted, ...), else null. */
|
|
27
|
+
event: any | null;
|
|
28
|
+
trigger: FunctionTrigger;
|
|
29
|
+
function: {
|
|
30
|
+
name: string;
|
|
31
|
+
version: number | null;
|
|
32
|
+
};
|
|
33
|
+
/** Id of this run, shown in Dashboard → Logs. */
|
|
34
|
+
invocationId: string;
|
|
35
|
+
project: {
|
|
36
|
+
ref: string;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** A function: gets the request (Fetch API) and returns a Response (or a plain value: objects become JSON). */
|
|
40
|
+
export type FunctionHandler<DB = any> = (req: Request, ctx: FunctionContext<DB>) => Response | Promise<Response> | unknown;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const ACCESS_TOKEN_COOKIE = "ub-access-token";
|
|
2
|
+
/** Express (`res.status().json()`) or plain node:http (`res.end()`). */
|
|
3
|
+
export declare function sendJson(res: any, status: number, body: unknown): void;
|
|
4
|
+
export declare function parseCookies(header: string | null | undefined): Record<string, string>;
|
|
5
|
+
/**
|
|
6
|
+
* Find the user's access token in: a raw token string, an Express/Node request, a Fetch
|
|
7
|
+
* Request / NextRequest, or Next.js `cookies()` / `headers()`.
|
|
8
|
+
* Order: `Authorization: Bearer <token>` header, then the `ub-access-token` cookie.
|
|
9
|
+
*/
|
|
10
|
+
export declare function extractToken(input: unknown): string | null;
|