@molecule/api-bonds-default-express 1.0.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/LICENSE +115 -0
- package/dist/billing.d.ts +54 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +228 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/handlers.d.ts +91 -0
- package/dist/handlers.d.ts.map +1 -0
- package/dist/handlers.js +128 -0
- package/dist/index.d.ts +103 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +102 -0
- package/dist/middleware.d.ts +23 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +41 -0
- package/dist/migrate.d.ts +17 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +16 -0
- package/dist/resources.d.ts +18 -0
- package/dist/resources.d.ts.map +1 -0
- package/dist/resources.js +18 -0
- package/dist/routes.d.ts +124 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +166 -0
- package/dist/schemas.d.ts +23 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +18 -0
- package/dist/setup.d.ts +132 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +507 -0
- package/package.json +377 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default Stripe-backed billing router used by ~117 fleet apps.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the bonded Stripe payment provider with the app's plan
|
|
5
|
+
* catalogue. Each route delegates per-tier validation to the
|
|
6
|
+
* `getPricingTiers()` function the app supplies. Webhook handling
|
|
7
|
+
* is delegated to `@molecule/api-resource-user`'s
|
|
8
|
+
* `handlePaymentNotification` route, which already updates
|
|
9
|
+
* `users.planKey` / `planExpiresAt` from Stripe events.
|
|
10
|
+
*
|
|
11
|
+
* Routes:
|
|
12
|
+
* - `POST /checkout` — start a subscription (returns Stripe Checkout URL or `updated: true`)
|
|
13
|
+
* - `POST /cancel` — cancel at end of current period
|
|
14
|
+
* - `GET /status` — current tier + entitlement snapshot
|
|
15
|
+
* - `GET /tiers` — public pricing data
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
import { Router } from 'express';
|
|
20
|
+
interface PricingTier {
|
|
21
|
+
key: string;
|
|
22
|
+
name?: string;
|
|
23
|
+
prices: ReadonlyArray<{
|
|
24
|
+
stripePriceId?: string | null;
|
|
25
|
+
period?: string;
|
|
26
|
+
price?: string;
|
|
27
|
+
}>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Factory for the default billing router. The router exposes four
|
|
31
|
+
* endpoints: `POST /checkout`, `POST /cancel`, `GET /status`, `GET /tiers`.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* // api/src/routes/billing.ts
|
|
36
|
+
* import { createBillingRouter } from '@molecule/api-bonds-default-express'
|
|
37
|
+
* import { blogPlanKeys, getPricingTiers, type BlogLimits } from '../tiers.js'
|
|
38
|
+
*
|
|
39
|
+
* export default createBillingRouter<BlogLimits>({
|
|
40
|
+
* getPricingTiers,
|
|
41
|
+
* planKeys: blogPlanKeys,
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export declare function createBillingRouter<TLimits>(opts: {
|
|
46
|
+
/** Returns the app's pricing tiers (with stripePriceId per price). */
|
|
47
|
+
getPricingTiers: () => ReadonlyArray<PricingTier>;
|
|
48
|
+
/** App's plan keys object; only `.free` is read here, for the isFree flag in /status. */
|
|
49
|
+
planKeys: {
|
|
50
|
+
free: string;
|
|
51
|
+
} & Record<string, string>;
|
|
52
|
+
}): Router;
|
|
53
|
+
export {};
|
|
54
|
+
//# sourceMappingURL=billing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"billing.d.ts","sourceRoot":"","sources":["../src/billing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAA+B,MAAM,EAAE,MAAM,SAAS,CAAA;AAc7D,UAAU,WAAW;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,aAAa,CAAC;QACpB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;QAC7B,MAAM,CAAC,EAAE,MAAM,CAAA;QACf,KAAK,CAAC,EAAE,MAAM,CAAA;KACf,CAAC,CAAA;CACH;AAoED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,IAAI,EAAE;IACjD,sEAAsE;IACtE,eAAe,EAAE,MAAM,aAAa,CAAC,WAAW,CAAC,CAAA;IACjD,yFAAyF;IACzF,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACpD,GAAG,MAAM,CAoIT"}
|
package/dist/billing.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default Stripe-backed billing router used by ~117 fleet apps.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the bonded Stripe payment provider with the app's plan
|
|
5
|
+
* catalogue. Each route delegates per-tier validation to the
|
|
6
|
+
* `getPricingTiers()` function the app supplies. Webhook handling
|
|
7
|
+
* is delegated to `@molecule/api-resource-user`'s
|
|
8
|
+
* `handlePaymentNotification` route, which already updates
|
|
9
|
+
* `users.planKey` / `planExpiresAt` from Stripe events.
|
|
10
|
+
*
|
|
11
|
+
* Routes:
|
|
12
|
+
* - `POST /checkout` — start a subscription (returns Stripe Checkout URL or `updated: true`)
|
|
13
|
+
* - `POST /cancel` — cancel at end of current period
|
|
14
|
+
* - `GET /status` — current tier + entitlement snapshot
|
|
15
|
+
* - `GET /tiers` — public pricing data
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
import { Router } from 'express';
|
|
20
|
+
import { z } from 'zod';
|
|
21
|
+
import { get, getLogger } from '@molecule/api-bond';
|
|
22
|
+
import { getEffectiveTier } from '@molecule/api-entitlements';
|
|
23
|
+
import { t } from '@molecule/api-i18n';
|
|
24
|
+
import { validateBody } from '@molecule/api-middleware-validation';
|
|
25
|
+
import { registerPlans } from '@molecule/api-resource-payment';
|
|
26
|
+
import { getUserId } from './handlers.js';
|
|
27
|
+
const logger = getLogger();
|
|
28
|
+
/**
|
|
29
|
+
* Derives the app's Stripe plan catalogue from its pricing tiers and
|
|
30
|
+
* registers it with `@molecule/api-resource-payment`'s plan registry — the
|
|
31
|
+
* registry `verifyPayment` / `handlePaymentNotification` resolve grants
|
|
32
|
+
* from. Without this, the registry only holds placeholder product ids and
|
|
33
|
+
* EVERY successful payment fails plan resolution ("unknown plan"): the user
|
|
34
|
+
* is charged but never upgraded.
|
|
35
|
+
*
|
|
36
|
+
* planKey derivation follows the fleet convention: `planKeys` maps
|
|
37
|
+
* `${tier.key}Monthly` / `${tier.key}Yearly` (e.g. `proMonthly`) to the
|
|
38
|
+
* entitlements planKey stored on `users.planKey`. Tiers/prices without a
|
|
39
|
+
* Stripe price id (the free tier) are skipped; a paid price whose planKeys
|
|
40
|
+
* entry is missing is skipped WITH a warning, since that plan could never be
|
|
41
|
+
* granted.
|
|
42
|
+
*
|
|
43
|
+
* Idempotent — safe to re-run per request (registration by planKey
|
|
44
|
+
* overwrites), which also covers price-id env vars that only become
|
|
45
|
+
* available after startup secret resolution.
|
|
46
|
+
*
|
|
47
|
+
* @param getPricingTiers - The app's pricing tiers function.
|
|
48
|
+
* @param planKeys - The app's planKeys map (see convention above).
|
|
49
|
+
*/
|
|
50
|
+
function registerPlansFromTiers(getPricingTiers, planKeys) {
|
|
51
|
+
try {
|
|
52
|
+
const derived = {};
|
|
53
|
+
for (const tier of getPricingTiers()) {
|
|
54
|
+
for (const price of tier.prices) {
|
|
55
|
+
if (!price.stripePriceId)
|
|
56
|
+
continue;
|
|
57
|
+
const period = price.period === 'year' ? 'year' : 'month';
|
|
58
|
+
const planKeysKey = `${tier.key}${period === 'year' ? 'Yearly' : 'Monthly'}`;
|
|
59
|
+
const planKey = planKeys[planKeysKey];
|
|
60
|
+
if (!planKey) {
|
|
61
|
+
logger.warn(`billing: no planKeys entry "${planKeysKey}" for tier "${tier.key}" (${period}) — ` +
|
|
62
|
+
`its Stripe price ${price.stripePriceId} cannot grant a plan`);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
derived[planKey] = {
|
|
66
|
+
planKey,
|
|
67
|
+
platformKey: 'stripe',
|
|
68
|
+
platformProductId: '',
|
|
69
|
+
platformPriceIds: [price.stripePriceId],
|
|
70
|
+
alias: period === 'year' ? 'yearly' : 'monthly',
|
|
71
|
+
period,
|
|
72
|
+
price: price.price ?? '',
|
|
73
|
+
autoRenews: true,
|
|
74
|
+
title: tier.name ?? tier.key,
|
|
75
|
+
titleKey: '',
|
|
76
|
+
description: tier.name ?? tier.key,
|
|
77
|
+
descriptionKey: '',
|
|
78
|
+
capabilities: { premium: true },
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (Object.keys(derived).length > 0)
|
|
83
|
+
registerPlans(derived);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// Registration failing must not take the billing routes down — but a
|
|
87
|
+
// failure here means paid plans cannot be granted, so say it loudly.
|
|
88
|
+
logger.error('billing: failed to register plans from pricing tiers', { error });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Factory for the default billing router. The router exposes four
|
|
93
|
+
* endpoints: `POST /checkout`, `POST /cancel`, `GET /status`, `GET /tiers`.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```ts
|
|
97
|
+
* // api/src/routes/billing.ts
|
|
98
|
+
* import { createBillingRouter } from '@molecule/api-bonds-default-express'
|
|
99
|
+
* import { blogPlanKeys, getPricingTiers, type BlogLimits } from '../tiers.js'
|
|
100
|
+
*
|
|
101
|
+
* export default createBillingRouter<BlogLimits>({
|
|
102
|
+
* getPricingTiers,
|
|
103
|
+
* planKeys: blogPlanKeys,
|
|
104
|
+
* })
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export function createBillingRouter(opts) {
|
|
108
|
+
const router = Router();
|
|
109
|
+
// Register the app's plan catalogue so payment verification / webhooks can
|
|
110
|
+
// resolve grants. Done at construction AND refreshed per checkout (below)
|
|
111
|
+
// because price-id env vars may only resolve after startup secrets load.
|
|
112
|
+
registerPlansFromTiers(opts.getPricingTiers, opts.planKeys);
|
|
113
|
+
const checkoutSchema = z.object({ priceId: z.string().min(1) });
|
|
114
|
+
/**
|
|
115
|
+
* Set of valid Stripe price IDs declared in `getPricingTiers()`.
|
|
116
|
+
* Reads tiers at request-time (not module-init) so the same code
|
|
117
|
+
* works in test/staging/production where price IDs differ.
|
|
118
|
+
*/
|
|
119
|
+
const validPriceIds = () => {
|
|
120
|
+
const set = new Set();
|
|
121
|
+
for (const tier of opts.getPricingTiers()) {
|
|
122
|
+
for (const price of tier.prices) {
|
|
123
|
+
if (price.stripePriceId)
|
|
124
|
+
set.add(price.stripePriceId);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return set;
|
|
128
|
+
};
|
|
129
|
+
router.post('/checkout', validateBody(checkoutSchema), async (req, res) => {
|
|
130
|
+
// Idempotent refresh — guarantees the plan catalogue reflects the same
|
|
131
|
+
// request-time env the price validation below reads.
|
|
132
|
+
registerPlansFromTiers(opts.getPricingTiers, opts.planKeys);
|
|
133
|
+
const userId = getUserId(res);
|
|
134
|
+
if (!userId) {
|
|
135
|
+
res.status(401).json({
|
|
136
|
+
error: t('auth.unauthorized', undefined, {
|
|
137
|
+
defaultValue: 'Authentication required.',
|
|
138
|
+
}),
|
|
139
|
+
});
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const { priceId } = req.body;
|
|
143
|
+
if (!validPriceIds().has(priceId)) {
|
|
144
|
+
res.status(400).json({
|
|
145
|
+
error: t('billing.error.unknownPriceId', { priceId }, {
|
|
146
|
+
defaultValue: `Unknown priceId "${priceId}".`,
|
|
147
|
+
}),
|
|
148
|
+
});
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const provider = get('payments', 'stripe');
|
|
152
|
+
if (!provider?.updateSubscription) {
|
|
153
|
+
res.status(503).json({
|
|
154
|
+
error: t('billing.error.providerUnavailable', undefined, {
|
|
155
|
+
defaultValue: 'Billing provider unavailable. Try again later.',
|
|
156
|
+
}),
|
|
157
|
+
});
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const result = await provider.updateSubscription({ userId, newProductId: priceId });
|
|
161
|
+
if (result.checkoutUrl) {
|
|
162
|
+
res.json({ checkoutUrl: result.checkoutUrl });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (result.updated) {
|
|
166
|
+
res.json({ updated: true, subscription: result.subscription });
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
res.status(502).json({
|
|
170
|
+
error: t('billing.error.checkoutFailed', undefined, {
|
|
171
|
+
defaultValue: 'Could not start checkout. Try again later.',
|
|
172
|
+
}),
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
router.post('/cancel', async (_req, res) => {
|
|
176
|
+
const userId = getUserId(res);
|
|
177
|
+
if (!userId) {
|
|
178
|
+
res.status(401).json({
|
|
179
|
+
error: t('auth.unauthorized', undefined, {
|
|
180
|
+
defaultValue: 'Authentication required.',
|
|
181
|
+
}),
|
|
182
|
+
});
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const provider = get('payments', 'stripe');
|
|
186
|
+
if (!provider?.cancelSubscription) {
|
|
187
|
+
res.status(503).json({
|
|
188
|
+
error: t('billing.error.providerUnavailable', undefined, {
|
|
189
|
+
defaultValue: 'Billing provider unavailable. Try again later.',
|
|
190
|
+
}),
|
|
191
|
+
});
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const ok = await provider.cancelSubscription({ userId });
|
|
195
|
+
if (!ok) {
|
|
196
|
+
res.status(400).json({
|
|
197
|
+
error: t('billing.error.cancelFailed', undefined, {
|
|
198
|
+
defaultValue: 'No active subscription to cancel.',
|
|
199
|
+
}),
|
|
200
|
+
});
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
res.json({ canceled: true });
|
|
204
|
+
});
|
|
205
|
+
router.get('/status', async (_req, res) => {
|
|
206
|
+
const userId = getUserId(res);
|
|
207
|
+
if (!userId) {
|
|
208
|
+
res.status(401).json({
|
|
209
|
+
error: t('auth.unauthorized', undefined, {
|
|
210
|
+
defaultValue: 'Authentication required.',
|
|
211
|
+
}),
|
|
212
|
+
});
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const tier = await getEffectiveTier(res);
|
|
216
|
+
res.json({
|
|
217
|
+
planKey: tier.planKey,
|
|
218
|
+
category: tier.category,
|
|
219
|
+
name: tier.name,
|
|
220
|
+
limits: tier.limits,
|
|
221
|
+
isFree: tier.planKey === opts.planKeys.free,
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
router.get('/tiers', (_req, res) => {
|
|
225
|
+
res.json({ data: opts.getPricingTiers() });
|
|
226
|
+
});
|
|
227
|
+
return router;
|
|
228
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-bonds-default-express` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-bonds-default-express is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express handler helpers — extracted from the ~1200 inline duplicates
|
|
3
|
+
* across the fleet's `api/src/handlers/*.ts` files.
|
|
4
|
+
*
|
|
5
|
+
* Replaces three patterns that every fleet handler inlines verbatim:
|
|
6
|
+
* (1) `getUserId(res)` / `requireUser(res)` reading the JWT session;
|
|
7
|
+
* (2) `getParamId(req, name)` defending against the express `req.params`
|
|
8
|
+
* string-or-string[] type union;
|
|
9
|
+
* (3) `AuthzResult<T>` + `requireOwnership/requireUserOwnership` for
|
|
10
|
+
* 404-on-IDOR ownership checks against arbitrary tables.
|
|
11
|
+
*
|
|
12
|
+
* Also exports `validationError(res, issues)` and `internalError(res, err)`
|
|
13
|
+
* response helpers that ~21 apps duplicate in their per-app
|
|
14
|
+
* `api/src/lib/authz.ts`.
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
import type { Request, RequestHandler, Response } from 'express';
|
|
19
|
+
/**
|
|
20
|
+
* Read the JWT session userId off `res.locals.session`. Returns null
|
|
21
|
+
* when there is no session (the auth middleware never ran, or the
|
|
22
|
+
* request is unauthenticated).
|
|
23
|
+
*/
|
|
24
|
+
export declare function getUserId(res: Response): string | null;
|
|
25
|
+
/**
|
|
26
|
+
* Like `getUserId` but writes a 401 + returns null when there's no
|
|
27
|
+
* session. Use at the top of handler bodies to bail early:
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* const userId = requireUser(res)
|
|
31
|
+
* if (!userId) return
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function requireUser(res: Response): string | null;
|
|
35
|
+
/**
|
|
36
|
+
* Read a route param as a string, defending against the Express
|
|
37
|
+
* type union `string | string[]` (multi-value when the same param
|
|
38
|
+
* key appears more than once). Defaults to `'id'`.
|
|
39
|
+
*/
|
|
40
|
+
export declare function getParamId(req: Request, name?: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* Result of an ownership check. `ok: true` carries the resolved row;
|
|
43
|
+
* `ok: false` carries the HTTP status the handler should return —
|
|
44
|
+
* always 404 to avoid leaking row existence to non-owners (the
|
|
45
|
+
* "no IDOR" rule).
|
|
46
|
+
*/
|
|
47
|
+
export type AuthzResult<T> = {
|
|
48
|
+
ok: true;
|
|
49
|
+
row: T;
|
|
50
|
+
} | {
|
|
51
|
+
ok: false;
|
|
52
|
+
status: 404;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Look up a row by id and verify the caller owns it via `owner_id`.
|
|
56
|
+
* Returns the row on success, 404 when missing OR owned by a different
|
|
57
|
+
* user (so attackers can't probe row existence).
|
|
58
|
+
*/
|
|
59
|
+
export declare function requireOwnership<T extends {
|
|
60
|
+
owner_id?: unknown;
|
|
61
|
+
} = Record<string, unknown>>(table: string, id: string, userId: string): Promise<AuthzResult<T>>;
|
|
62
|
+
/**
|
|
63
|
+
* Variant of `requireOwnership` for tables that scope by `user_id`
|
|
64
|
+
* instead of `owner_id` (notifications, user-bound preferences, etc.).
|
|
65
|
+
*/
|
|
66
|
+
export declare function requireUserOwnership<T extends {
|
|
67
|
+
user_id?: unknown;
|
|
68
|
+
} = Record<string, unknown>>(table: string, id: string, userId: string): Promise<AuthzResult<T>>;
|
|
69
|
+
/**
|
|
70
|
+
* Express middleware that 401s any request lacking `res.locals.session.userId`.
|
|
71
|
+
* Drop-in for the fleet's 51 inline `requireAuth` copies.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* router.use(requireAuth)
|
|
76
|
+
* router.get('/private', handler)
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export declare const requireAuth: RequestHandler;
|
|
80
|
+
/**
|
|
81
|
+
* Standard 400 response for zod / schema validation failures.
|
|
82
|
+
* Used by ~21 fleet apps' `api/src/lib/authz.ts` files.
|
|
83
|
+
*/
|
|
84
|
+
export declare function validationError(res: Response, issues: unknown): void;
|
|
85
|
+
/**
|
|
86
|
+
* Standard 500 response that logs the underlying cause before responding
|
|
87
|
+
* with a generic message. Always pass the original error so silent
|
|
88
|
+
* catches don't ship to prod under green tests.
|
|
89
|
+
*/
|
|
90
|
+
export declare function internalError(res: Response, error?: unknown): void;
|
|
91
|
+
//# sourceMappingURL=handlers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAgB,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAU9E;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM,GAAG,IAAI,CAEtD;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM,GAAG,IAAI,CASxD;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,GAAE,MAAa,GAAG,MAAM,CAGpE;AAED;;;;;GAKG;AACH,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,GAAG,CAAA;CAAE,CAAA;AAE9E;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/F,KAAK,EAAE,MAAM,EACb,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAOzB;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,CAAC,SAAS;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACzD,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAOpE;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,WAAW,EAAE,cAYzB,CAAA;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAKpE;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI,CASlE"}
|
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express handler helpers — extracted from the ~1200 inline duplicates
|
|
3
|
+
* across the fleet's `api/src/handlers/*.ts` files.
|
|
4
|
+
*
|
|
5
|
+
* Replaces three patterns that every fleet handler inlines verbatim:
|
|
6
|
+
* (1) `getUserId(res)` / `requireUser(res)` reading the JWT session;
|
|
7
|
+
* (2) `getParamId(req, name)` defending against the express `req.params`
|
|
8
|
+
* string-or-string[] type union;
|
|
9
|
+
* (3) `AuthzResult<T>` + `requireOwnership/requireUserOwnership` for
|
|
10
|
+
* 404-on-IDOR ownership checks against arbitrary tables.
|
|
11
|
+
*
|
|
12
|
+
* Also exports `validationError(res, issues)` and `internalError(res, err)`
|
|
13
|
+
* response helpers that ~21 apps duplicate in their per-app
|
|
14
|
+
* `api/src/lib/authz.ts`.
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
import { findById } from '@molecule/api-database';
|
|
19
|
+
import { t } from '@molecule/api-i18n';
|
|
20
|
+
import { logger } from '@molecule/api-logger';
|
|
21
|
+
/**
|
|
22
|
+
* Read the JWT session userId off `res.locals.session`. Returns null
|
|
23
|
+
* when there is no session (the auth middleware never ran, or the
|
|
24
|
+
* request is unauthenticated).
|
|
25
|
+
*/
|
|
26
|
+
export function getUserId(res) {
|
|
27
|
+
return res.locals.session?.userId ?? null;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Like `getUserId` but writes a 401 + returns null when there's no
|
|
31
|
+
* session. Use at the top of handler bodies to bail early:
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* const userId = requireUser(res)
|
|
35
|
+
* if (!userId) return
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function requireUser(res) {
|
|
39
|
+
const id = getUserId(res);
|
|
40
|
+
if (!id) {
|
|
41
|
+
res.status(401).json({
|
|
42
|
+
error: t('auth.unauthorized', {}, { defaultValue: 'Unauthorized' }),
|
|
43
|
+
});
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
return id;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Read a route param as a string, defending against the Express
|
|
50
|
+
* type union `string | string[]` (multi-value when the same param
|
|
51
|
+
* key appears more than once). Defaults to `'id'`.
|
|
52
|
+
*/
|
|
53
|
+
export function getParamId(req, name = 'id') {
|
|
54
|
+
const v = req.params[name];
|
|
55
|
+
return Array.isArray(v) ? v[0] : v;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Look up a row by id and verify the caller owns it via `owner_id`.
|
|
59
|
+
* Returns the row on success, 404 when missing OR owned by a different
|
|
60
|
+
* user (so attackers can't probe row existence).
|
|
61
|
+
*/
|
|
62
|
+
export async function requireOwnership(table, id, userId) {
|
|
63
|
+
const row = await findById(table, id);
|
|
64
|
+
if (!row)
|
|
65
|
+
return { ok: false, status: 404 };
|
|
66
|
+
if (String(row.owner_id) !== String(userId)) {
|
|
67
|
+
return { ok: false, status: 404 };
|
|
68
|
+
}
|
|
69
|
+
return { ok: true, row };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Variant of `requireOwnership` for tables that scope by `user_id`
|
|
73
|
+
* instead of `owner_id` (notifications, user-bound preferences, etc.).
|
|
74
|
+
*/
|
|
75
|
+
export async function requireUserOwnership(table, id, userId) {
|
|
76
|
+
const row = await findById(table, id);
|
|
77
|
+
if (!row)
|
|
78
|
+
return { ok: false, status: 404 };
|
|
79
|
+
if (String(row.user_id) !== String(userId)) {
|
|
80
|
+
return { ok: false, status: 404 };
|
|
81
|
+
}
|
|
82
|
+
return { ok: true, row };
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Express middleware that 401s any request lacking `res.locals.session.userId`.
|
|
86
|
+
* Drop-in for the fleet's 51 inline `requireAuth` copies.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```ts
|
|
90
|
+
* router.use(requireAuth)
|
|
91
|
+
* router.get('/private', handler)
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
export const requireAuth = (_req, res, next) => {
|
|
95
|
+
if (!res.locals.session?.userId) {
|
|
96
|
+
res.status(401).json({
|
|
97
|
+
error: t('auth.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
98
|
+
});
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
next();
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Standard 400 response for zod / schema validation failures.
|
|
105
|
+
* Used by ~21 fleet apps' `api/src/lib/authz.ts` files.
|
|
106
|
+
*/
|
|
107
|
+
export function validationError(res, issues) {
|
|
108
|
+
res.status(400).json({
|
|
109
|
+
error: t('validation.failed', {}, { defaultValue: 'Validation failed' }),
|
|
110
|
+
issues,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Standard 500 response that logs the underlying cause before responding
|
|
115
|
+
* with a generic message. Always pass the original error so silent
|
|
116
|
+
* catches don't ship to prod under green tests.
|
|
117
|
+
*/
|
|
118
|
+
export function internalError(res, error) {
|
|
119
|
+
if (error !== undefined) {
|
|
120
|
+
logger.error(error);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
logger.error(new Error('internalError() called without an underlying cause'));
|
|
124
|
+
}
|
|
125
|
+
res.status(500).json({
|
|
126
|
+
error: t('errors.internalServer', {}, { defaultValue: 'Internal server error' }),
|
|
127
|
+
});
|
|
128
|
+
}
|