@aglyn/plugins-commerce 1.25.0 → 1.26.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-commerce",
3
- "version": "1.25.0",
3
+ "version": "1.26.1",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,18 +25,18 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.25.0",
29
- "@aglyn/shared-data-mdi": "1.25.0",
30
- "@aglyn/shared-ui-jsx": "1.25.0",
31
- "@aglyn/shared-ui-next": "1.25.0",
32
- "@aglyn/shared-ui-snackstack": "1.25.0",
33
- "@aglyn/shared-util-email": "1.25.0",
34
- "@aglyn/shared-util-http": "1.25.0",
35
- "@aglyn/shared-util-timestamp": "1.25.0",
36
- "@aglyn/shared-util-tools": "1.25.0",
37
- "@aglyn/tenant-data-admin": "1.25.0",
38
- "@aglyn/tenant-feature-instance": "1.25.0",
39
- "@aglyn/tenant-runtime": "1.25.0",
28
+ "@aglyn/aglyn": "1.26.1",
29
+ "@aglyn/shared-data-mdi": "1.26.1",
30
+ "@aglyn/shared-ui-jsx": "1.26.1",
31
+ "@aglyn/shared-ui-next": "1.26.1",
32
+ "@aglyn/shared-ui-snackstack": "1.26.1",
33
+ "@aglyn/shared-util-email": "1.26.1",
34
+ "@aglyn/shared-util-http": "1.26.1",
35
+ "@aglyn/shared-util-timestamp": "1.26.1",
36
+ "@aglyn/shared-util-tools": "1.26.1",
37
+ "@aglyn/tenant-data-admin": "1.26.1",
38
+ "@aglyn/tenant-feature-instance": "1.26.1",
39
+ "@aglyn/tenant-runtime": "1.26.1",
40
40
  "@stripe/react-stripe-js": "^7.0.1",
41
41
  "@stripe/stripe-js": "^10.2.1",
42
42
  "@swc/helpers": "0.5.24",
@@ -24,6 +24,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
24
24
  * documentation promises.
25
25
  */ export const PRODUCTS_API_V1_DESCRIPTION = {
26
26
  tag: 'Products',
27
+ docsPage: 'products',
27
28
  description: 'A site’s catalog. Read-only over the API.',
28
29
  schemaName: 'Product',
29
30
  required: [
@@ -66,10 +67,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
66
67
  path: '/v1/sites/{siteId}/products',
67
68
  method: 'get',
68
69
  operationId: 'listProducts',
69
- summary: 'List products',
70
+ summary: 'List a site’s products',
70
71
  list: true,
71
72
  returns: 'Product',
72
- description: 'Rows deleted since they were written are dropped after the read, so pages can come back short.',
73
+ description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites. Read only: products are edited in the console.',
73
74
  pathParams: [
74
75
  SITE_ID_PATH_PARAM
75
76
  ]
@@ -78,7 +79,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
78
79
  path: '/v1/sites/{siteId}/products/{productId}',
79
80
  method: 'get',
80
81
  operationId: 'getProduct',
81
- summary: 'Retrieve a product',
82
+ summary: 'Get a product',
83
+ description: 'Returns one product with its variants. Needs `siteId` from List sites and `productId` from List a site’s products.',
82
84
  returns: 'Product',
83
85
  pathParams: [
84
86
  SITE_ID_PATH_PARAM,
@@ -92,6 +94,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
92
94
  };
93
95
  export const ORDERS_API_V1_DESCRIPTION = {
94
96
  tag: 'Orders',
97
+ docsPage: 'orders',
95
98
  description: 'A site’s orders. Status moves are constrained.',
96
99
  schemaName: 'Order',
97
100
  required: [
@@ -189,11 +192,12 @@ export const ORDERS_API_V1_DESCRIPTION = {
189
192
  path: '/v1/sites/{siteId}/orders',
190
193
  method: 'get',
191
194
  operationId: 'listOrders',
192
- summary: 'List orders',
195
+ summary: 'List a site’s orders',
196
+ description: 'Lists the orders placed in one site’s store, with status, items, totals and shipments. Needs `siteId` from List sites. Filter by status or channel.',
193
197
  list: true,
194
198
  returns: 'Order',
195
199
  filters: [
196
- q('channel', '`online` is a default rather than a stored value, so filtering on it drops older orders after the read.'),
200
+ q('channel', 'Orders from one sales channel, such as `online`.'),
197
201
  q('status', 'Order status.')
198
202
  ],
199
203
  pathParams: [
@@ -204,7 +208,8 @@ export const ORDERS_API_V1_DESCRIPTION = {
204
208
  path: '/v1/sites/{siteId}/orders/{orderId}',
205
209
  method: 'get',
206
210
  operationId: 'getOrder',
207
- summary: 'Retrieve an order',
211
+ summary: 'Get an order',
212
+ description: 'Returns one order with its items, totals and shipments. Needs `siteId` from List sites and `orderId` from List a site’s orders.',
208
213
  returns: 'Order',
209
214
  pathParams: [
210
215
  SITE_ID_PATH_PARAM,
@@ -214,21 +219,23 @@ export const ORDERS_API_V1_DESCRIPTION = {
214
219
  }
215
220
  ]
216
221
  },
222
+ // openWorld: it emails the buyer about the shipment unless `notify` is false.
217
223
  {
218
224
  path: '/v1/sites/{siteId}/orders/{orderId}',
219
225
  method: 'patch',
220
226
  operationId: 'updateOrder',
221
- summary: 'Move an order’s status',
227
+ summary: 'Mark an order shipped or delivered',
222
228
  accepts: 'OrderWrite',
223
229
  returns: 'Order',
224
- description: 'An illegal transition is `409 conflict` (`code: "order_transition"`), and the message names the status it is in.',
230
+ description: 'Records a shipment: sets `status` to `fulfilled` (shipped) or `delivered`, with optional carrier, tracking number and the items shipped. The buyer is emailed about it unless `notify` is false. An order cannot be cancelled or refunded here; that is done in the console. Needs `siteId` and `orderId`. Returns the order.',
225
231
  pathParams: [
226
232
  SITE_ID_PATH_PARAM,
227
233
  {
228
234
  name: 'orderId',
229
235
  description: 'Order id.'
230
236
  }
231
- ]
237
+ ],
238
+ openWorld: true
232
239
  }
233
240
  ]
234
241
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/openapi.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n openObjectField as objectOf,\n postalAddressField as ADDRESS,\n queryParam as q,\n RECORD_STAMPS as STAMPS,\n stringField as str,\n stringListField as strList,\n SITE_ID_PATH_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * A site's products and orders as the customer API's OpenAPI document\n * describes them — what the console's builder turns into paths, tags and\n * schemas, and the MCP tools derive from. Transcribed unchanged from the\n * builder's own list when the resources moved here (AGL-3080);\n * `api-v1-openapi.spec.ts` holds the document to every endpoint the\n * documentation promises.\n */\nexport const PRODUCTS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Products',\n description: 'A site’s catalog. Read-only over the API.',\n schemaName: 'Product',\n required: ['id', 'object', 'name'],\n fields: {\n id: str('Product id.'),\n object: OBJECT_FIELD('product'),\n name: str('Product name.'),\n slug: str('URL slug.'),\n description: nullable(str('Description.')),\n type: str('Product type.'),\n status: str('Publication status.'),\n tags: strList('Free-form tags.'),\n categoryIds: strList('Categories this product belongs to.'),\n mediaUrls: strList('Image URLs.'),\n options: { type: 'array', description: 'Option definitions, e.g. size.', items: { type: 'object', additionalProperties: true } },\n variants: { type: 'array', description: 'Purchasable variants.', items: { type: 'object', additionalProperties: true } },\n inventory: nullable(int('Stock on hand, when tracked.')),\n subscription: nullable(objectOf('Subscription terms, when the product is one.')),\n ...STAMPS,\n },\n ops: [\n { path: '/v1/sites/{siteId}/products', method: 'get', operationId: 'listProducts', summary: 'List products', list: true, returns: 'Product', description: 'Rows deleted since they were written are dropped after the read, so pages can come back short.', pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'get', operationId: 'getProduct', summary: 'Retrieve a product', returns: 'Product', pathParams: [SITE_ID_PATH_PARAM, { name: 'productId', description: 'Product id.' }] },\n ],\n}\n\nexport const ORDERS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Orders',\n description: 'A site’s orders. Status moves are constrained.',\n schemaName: 'Order',\n required: ['id', 'object', 'number', 'status'],\n writable: ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify'],\n writeOnly: {\n status: { type: 'string', enum: ['fulfilled', 'delivered'], description: 'The status to move the order to.' },\n carrier: str('Free text, e.g. `UPS`. Trimmed to 40 characters. USPS, UPS, FedEx, DHL, Canada Post, Royal Mail and Australia Post get a tracking link.'),\n trackingNumber: str('Free text. Trimmed to 60 characters.'),\n trackingUrl: str('An https tracking link, for a carrier the link is not derived for.'),\n lineItems: {\n type: 'array',\n description:\n 'With `status: fulfilled`, the units this shipment covers: `[{ lineItemId, quantity }]`, where `lineItemId` is the line’s index. Omitted, the shipment covers everything still to ship. More than is left is `409 conflict` (`code: \"over_fulfilled\"`). Send an `Idempotency-Key` header so a retried partial shipment is recorded once.',\n items: { type: 'object', additionalProperties: true },\n },\n notify: bool('Whether the buyer is told about this shipment. Defaults to true.'),\n },\n writeRequired: ['status'],\n fields: {\n id: str('Order id.'),\n object: OBJECT_FIELD('order'),\n number: int('Human-facing order number.'),\n status: str('Order status.'),\n channel: str('`online` by default. Older orders carry no stored value, so `?channel=online` drops them after the read.'),\n currency: str('ISO 4217 code.'),\n customerEmail: nullable(str('Customer email.')),\n customerName: nullable(str('Customer name.')),\n lineItems: { type: 'array', description: 'What was bought.', items: { type: 'object', additionalProperties: true } },\n totals: objectOf('Money totals, in the smallest unit of `currency`. `extrasCents` is the optional lines the buyer added at checkout, inside `totalCents` and outside `itemsCents`.'),\n extras: { type: 'array', description: 'Optional lines the buyer added at checkout, such as package protection: `[{ id, pluginId, key, label, amountCents, quoteRef }]`. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n credits: { type: 'array', description: 'Store credit another plugin kept that paid part of the sale, such as rewards: `[{ providerId, pluginId, reference, label, last4, amountCents, appliedAs }]`. `appliedAs` is `discount` for a checkout redemption and `tender` for a register payment. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n refundedCents: int('Amount refunded so far.'),\n livemode: bool('Whether real money moved: `false` for an order paid in Stripe test mode, such as a store rehearsal.'),\n disputed: bool('Whether a chargeback is open.'),\n taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax, collected and remitted by the platform as marketplace facilitator), `manual` (your own rate) or `none`. `null` on an order from before it was recorded.')),\n taxEngine: nullable(objectOf('The tax service you connected, when one was asked for this sale’s tax: `provider` (`avalara` or `taxjar`), `providerLabel`, `status` (`quoted` when its tax was charged, `fallback` when it did not answer and your own rate was charged), `reason` (`timeout` or `error` on a fallback) and `sandbox`. `null` when no service was asked.')),\n shippingAddress: ADDRESS(),\n couponCode: nullable(str('Coupon applied.')),\n fulfillments: { type: 'array', description: 'Shipments and deliveries.', items: { type: 'object', additionalProperties: true } },\n created: STAMPS.created,\n },\n ops: [\n { path: '/v1/sites/{siteId}/orders', method: 'get', operationId: 'listOrders', summary: 'List orders', list: true, returns: 'Order', filters: [q('channel', '`online` is a default rather than a stored value, so filtering on it drops older orders after the read.'), q('status', 'Order status.')], pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'get', operationId: 'getOrder', summary: 'Retrieve an order', returns: 'Order', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }] },\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'patch', operationId: 'updateOrder', summary: 'Move an order’s status', accepts: 'OrderWrite', returns: 'Order', description: 'An illegal transition is `409 conflict` (`code: \"order_transition\"`), and the message names the status it is in.', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }] },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","nullableField","nullable","objectKindField","OBJECT_FIELD","openObjectField","objectOf","postalAddressField","ADDRESS","queryParam","q","RECORD_STAMPS","STAMPS","stringField","str","stringListField","strList","SITE_ID_PATH_PARAM","PRODUCTS_API_V1_DESCRIPTION","tag","description","schemaName","required","fields","id","object","name","slug","type","status","tags","categoryIds","mediaUrls","options","items","additionalProperties","variants","inventory","subscription","ops","path","method","operationId","summary","list","returns","pathParams","ORDERS_API_V1_DESCRIPTION","writable","writeOnly","enum","carrier","trackingNumber","trackingUrl","lineItems","notify","writeRequired","number","channel","currency","customerEmail","customerName","totals","extras","credits","refundedCents","livemode","disputed","taxMode","taxEngine","shippingAddress","couponCode","fulfillments","created","filters","accepts"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgBC,IAAI,EACpBC,gBAAgBC,GAAG,EACnBC,iBAAiBC,QAAQ,EACzBC,mBAAmBC,YAAY,EAC/BC,mBAAmBC,QAAQ,EAC3BC,sBAAsBC,OAAO,EAC7BC,cAAcC,CAAC,EACfC,iBAAiBC,MAAM,EACvBC,eAAeC,GAAG,EAClBC,mBAAmBC,OAAO,EAC1BC,kBAAkB,QACb,qDAAoD;AAE3D;;;;;;;CAOC,GACD,OAAO,MAAMC,8BAAwD;IACnEC,KAAK;IACLC,aAAa;IACbC,YAAY;IACZC,UAAU;QAAC;QAAM;QAAU;KAAO;IAClCC,QAAQ;QACNC,IAAIV,IAAI;QACRW,QAAQrB,aAAa;QACrBsB,MAAMZ,IAAI;QACVa,MAAMb,IAAI;QACVM,aAAalB,SAASY,IAAI;QAC1Bc,MAAMd,IAAI;QACVe,QAAQf,IAAI;QACZgB,MAAMd,QAAQ;QACde,aAAaf,QAAQ;QACrBgB,WAAWhB,QAAQ;QACnBiB,SAAS;YAAEL,MAAM;YAASR,aAAa;YAAkCc,OAAO;gBAAEN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;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EN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;QACnH2B,QAAQxD,SAAS;QACjByD,QAAQ;YAAEnC,MAAM;YAASR,aAAa;YAAgKc,OAAO;gBAAEN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;QAC5P6B,SAAS;YAAEpC,MAAM;YAASR,aAAa;YAAqRc,OAAO;gBAAEN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;QAClX8B,eAAejE,IAAI;QACnBkE,UAAUpE,KAAK;QACfqE,UAAUrE,KAAK;QACfsE,SAASlE,SAASY,IAAI;QACtBuD,WAAWnE,SAASI,SAAS;QAC7BgE,iBAAiB9D;QACjB+D,YAAYrE,SAASY,IAAI;QACzB0D,cAAc;YAAE5C,MAAM;YAASR,aAAa;YAA6Bc,OAAO;gBAAEN,MAAM;gBAAUO,sBAAsB;YAAK;QAAE;QAC/HsC,SAAS7D,OAAO6D,OAAO;IACzB;IACAlC,KAAK;QACH;YAAEC,MAAM;YAA6BC,QAAQ;YAAOC,aAAa;YAAcC,SAAS;YAAeC,MAAM;YAAMC,SAAS;YAAS6B,SAAS;gBAAChE,EAAE,WAAW;gBAA4GA,EAAE,UAAU;aAAiB;YAAEoC,YAAY;gBAAC7B;aAAmB;QAAC;QACxU;YAAEuB,MAAM;YAAuCC,QAAQ;YAAOC,aAAa;YAAYC,SAAS;YAAqBE,SAAS;YAASC,YAAY;gBAAC7B;gBAAoB;oBAAES,MAAM;oBAAWN,aAAa;gBAAY;aAAE;QAAC;QACvN;YAAEoB,MAAM;YAAuCC,QAAQ;YAASC,aAAa;YAAeC,SAAS;YAA0BgC,SAAS;YAAc9B,SAAS;YAASzB,aAAa;YAAoH0B,YAAY;gBAAC7B;gBAAoB;oBAAES,MAAM;oBAAWN,aAAa;gBAAY;aAAE;QAAC;KAC1X;AACH,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/openapi.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n openObjectField as objectOf,\n postalAddressField as ADDRESS,\n queryParam as q,\n RECORD_STAMPS as STAMPS,\n stringField as str,\n stringListField as strList,\n SITE_ID_PATH_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * A site's products and orders as the customer API's OpenAPI document\n * describes them — what the console's builder turns into paths, tags and\n * schemas, and the MCP tools derive from. Transcribed unchanged from the\n * builder's own list when the resources moved here (AGL-3080);\n * `api-v1-openapi.spec.ts` holds the document to every endpoint the\n * documentation promises.\n */\nexport const PRODUCTS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Products',\n docsPage: 'products',\n description: 'A site’s catalog. Read-only over the API.',\n schemaName: 'Product',\n required: ['id', 'object', 'name'],\n fields: {\n id: str('Product id.'),\n object: OBJECT_FIELD('product'),\n name: str('Product name.'),\n slug: str('URL slug.'),\n description: nullable(str('Description.')),\n type: str('Product type.'),\n status: str('Publication status.'),\n tags: strList('Free-form tags.'),\n categoryIds: strList('Categories this product belongs to.'),\n mediaUrls: strList('Image URLs.'),\n options: { type: 'array', description: 'Option definitions, e.g. size.', items: { type: 'object', additionalProperties: true } },\n variants: { type: 'array', description: 'Purchasable variants.', items: { type: 'object', additionalProperties: true } },\n inventory: nullable(int('Stock on hand, when tracked.')),\n subscription: nullable(objectOf('Subscription terms, when the product is one.')),\n ...STAMPS,\n },\n ops: [\n { path: '/v1/sites/{siteId}/products', method: 'get', operationId: 'listProducts', summary: 'List a site’s products', list: true, returns: 'Product', description: 'Lists the products in one site’s store, with prices, stock and variants. Needs `siteId` from List sites. Read only: products are edited in the console.', pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/products/{productId}', method: 'get', operationId: 'getProduct', summary: 'Get a product', description: 'Returns one product with its variants. Needs `siteId` from List sites and `productId` from List a site’s products.', returns: 'Product', pathParams: [SITE_ID_PATH_PARAM, { name: 'productId', description: 'Product id.' }] },\n ],\n}\n\nexport const ORDERS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Orders',\n docsPage: 'orders',\n description: 'A site’s orders. Status moves are constrained.',\n schemaName: 'Order',\n required: ['id', 'object', 'number', 'status'],\n writable: ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify'],\n writeOnly: {\n status: { type: 'string', enum: ['fulfilled', 'delivered'], description: 'The status to move the order to.' },\n carrier: str('Free text, e.g. `UPS`. Trimmed to 40 characters. USPS, UPS, FedEx, DHL, Canada Post, Royal Mail and Australia Post get a tracking link.'),\n trackingNumber: str('Free text. Trimmed to 60 characters.'),\n trackingUrl: str('An https tracking link, for a carrier the link is not derived for.'),\n lineItems: {\n type: 'array',\n description:\n 'With `status: fulfilled`, the units this shipment covers: `[{ lineItemId, quantity }]`, where `lineItemId` is the line’s index. Omitted, the shipment covers everything still to ship. More than is left is `409 conflict` (`code: \"over_fulfilled\"`). Send an `Idempotency-Key` header so a retried partial shipment is recorded once.',\n items: { type: 'object', additionalProperties: true },\n },\n notify: bool('Whether the buyer is told about this shipment. Defaults to true.'),\n },\n writeRequired: ['status'],\n fields: {\n id: str('Order id.'),\n object: OBJECT_FIELD('order'),\n number: int('Human-facing order number.'),\n status: str('Order status.'),\n channel: str('`online` by default. Older orders carry no stored value, so `?channel=online` drops them after the read.'),\n currency: str('ISO 4217 code.'),\n customerEmail: nullable(str('Customer email.')),\n customerName: nullable(str('Customer name.')),\n lineItems: { type: 'array', description: 'What was bought.', items: { type: 'object', additionalProperties: true } },\n totals: objectOf('Money totals, in the smallest unit of `currency`. `extrasCents` is the optional lines the buyer added at checkout, inside `totalCents` and outside `itemsCents`.'),\n extras: { type: 'array', description: 'Optional lines the buyer added at checkout, such as package protection: `[{ id, pluginId, key, label, amountCents, quoteRef }]`. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n credits: { type: 'array', description: 'Store credit another plugin kept that paid part of the sale, such as rewards: `[{ providerId, pluginId, reference, label, last4, amountCents, appliedAs }]`. `appliedAs` is `discount` for a checkout redemption and `tender` for a register payment. Empty when there were none.', items: { type: 'object', additionalProperties: true } },\n refundedCents: int('Amount refunded so far.'),\n livemode: bool('Whether real money moved: `false` for an order paid in Stripe test mode, such as a store rehearsal.'),\n disputed: bool('Whether a chargeback is open.'),\n taxMode: nullable(str('The tax regime: `stripe-automatic` (Stripe Tax, collected and remitted by the platform as marketplace facilitator), `manual` (your own rate) or `none`. `null` on an order from before it was recorded.')),\n taxEngine: nullable(objectOf('The tax service you connected, when one was asked for this sale’s tax: `provider` (`avalara` or `taxjar`), `providerLabel`, `status` (`quoted` when its tax was charged, `fallback` when it did not answer and your own rate was charged), `reason` (`timeout` or `error` on a fallback) and `sandbox`. `null` when no service was asked.')),\n shippingAddress: ADDRESS(),\n couponCode: nullable(str('Coupon applied.')),\n fulfillments: { type: 'array', description: 'Shipments and deliveries.', items: { type: 'object', additionalProperties: true } },\n created: STAMPS.created,\n },\n ops: [\n { path: '/v1/sites/{siteId}/orders', method: 'get', operationId: 'listOrders', summary: 'List a site’s orders', description: 'Lists the orders placed in one site’s store, with status, items, totals and shipments. Needs `siteId` from List sites. Filter by status or channel.', list: true, returns: 'Order', filters: [q('channel', 'Orders from one sales channel, such as `online`.'), q('status', 'Order status.')], pathParams: [SITE_ID_PATH_PARAM] },\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'get', operationId: 'getOrder', summary: 'Get an order', description: 'Returns one order with its items, totals and shipments. Needs `siteId` from List sites and `orderId` from List a site’s orders.', returns: 'Order', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }] },\n // openWorld: it emails the buyer about the shipment unless `notify` is false.\n { path: '/v1/sites/{siteId}/orders/{orderId}', method: 'patch', operationId: 'updateOrder', summary: 'Mark an order shipped or delivered', accepts: 'OrderWrite', returns: 'Order', description: 'Records a shipment: sets `status` to `fulfilled` (shipped) or `delivered`, with optional carrier, tracking number and the items shipped. The buyer is emailed about it unless `notify` is false. An order cannot be cancelled or refunded here; that is done in the console. Needs `siteId` and `orderId`. Returns the order.', pathParams: [SITE_ID_PATH_PARAM, { name: 'orderId', description: 'Order id.' }], openWorld: true },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","nullableField","nullable","objectKindField","OBJECT_FIELD","openObjectField","objectOf","postalAddressField","ADDRESS","queryParam","q","RECORD_STAMPS","STAMPS","stringField","str","stringListField","strList","SITE_ID_PATH_PARAM","PRODUCTS_API_V1_DESCRIPTION","tag","docsPage","description","schemaName","required","fields","id","object","name","slug","type","status","tags","categoryIds","mediaUrls","options","items","additionalProperties","variants","inventory","subscription","ops","path","method","operationId","summary","list","returns","pathParams","ORDERS_API_V1_DESCRIPTION","writable","writeOnly","enum","carrier","trackingNumber","trackingUrl","lineItems","notify","writeRequired","number","channel","currency","customerEmail","customerName","totals","extras","credits","refundedCents","livemode","disputed","taxMode","taxEngine","shippingAddress","couponCode","fulfillments","created","filters","accepts","openWorld"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgBC,IAAI,EACpBC,gBAAgBC,GAAG,EACnBC,iBAAiBC,QAAQ,EACzBC,mBAAmBC,YAAY,EAC/BC,mBAAmBC,QAAQ,EAC3BC,sBAAsBC,OAAO,EAC7BC,cAAcC,CAAC,EACfC,iBAAiBC,MAAM,EACvBC,eAAeC,GAAG,EAClBC,mBAAmBC,OAAO,EAC1BC,kBAAkB,QACb,qDAAoD;AAE3D;;;;;;;CAOC,GACD,OAAO,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AAC9B;aAAmB;QAAC;QAC9b;YAAEwB,MAAM;YAAuCC,QAAQ;YAAOC,aAAa;YAAYC,SAAS;YAAgBvB,aAAa;YAAmIyB,SAAS;YAASC,YAAY;gBAAC9B;gBAAoB;oBAAEU,MAAM;oBAAWN,aAAa;gBAAY;aAAE;QAAC;QAClW,8EAA8E;QAC9E;YAAEoB,MAAM;YAAuCC,QAAQ;YAASC,aAAa;YAAeC,SAAS;YAAsCgC,SAAS;YAAc9B,SAAS;YAASzB,aAAa;YAAiU0B,YAAY;gBAAC9B;gBAAoB;oBAAEU,MAAM;oBAAWN,aAAa;gBAAY;aAAE;YAAEwD,WAAW;QAAK;KACpmB;AACH,EAAC"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from "crypto";
17
- import { signedInHintCookieName } from "@aglyn/aglyn/app-utils/sign-in-visibility";
17
+ import { memberSessionCookieName, signedInHintCookieName } from "@aglyn/aglyn/app-utils/sign-in-hint-cookie";
18
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
19
  /**
20
20
  * Site membership primitives (AGL-109): visitor accounts per host with
@@ -127,7 +127,9 @@ export function mintMemberSession(hostId, memberId) {
127
127
  return timingSafeEqual(new Uint8Array(a), new Uint8Array(b));
128
128
  }
129
129
  export function memberCookieName(hostId) {
130
- return `aglyn_member_${hostId.replace(/[^A-Za-z0-9_-]/g, '')}`;
130
+ // Named where the readable sign-in hint is (AGL-4231), so the tenant
131
+ // middleware that keeps the two in step reads the same name.
132
+ return memberSessionCookieName(hostId);
131
133
  }
132
134
  export function setMemberCookie(res, hostId, token) {
133
135
  const name = memberCookieName(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createHash,\n createHmac,\n randomBytes,\n scryptSync,\n timingSafeEqual,\n} from 'crypto'\nimport type { PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { signedInHintCookieName } from '@aglyn/aglyn/app-utils/sign-in-visibility'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Site membership primitives (AGL-109): visitor accounts per host with\n * scrypt-hashed passwords and an HMAC-signed httpOnly session cookie.\n * Per-site Firebase Auth is a future infra decision (AGL-45 class); this\n * keeps member content out of static HTML the same way AGL-87 does.\n */\n\nconst SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000\n\n// A per-boot fallback keeps dev working; production must set the env so\n// sessions survive deploys and instances agree.\n//\n// `||`, NOT `??`, and on a self-host install that is the whole difference\n// (AGL-2014). `.env.selfhost.example` ships `MEMBER_SESSION_SECRET=` blank and\n// compose `env_file` sets a blank line as the EMPTY STRING rather than leaving\n// it unset — so `??` did not fire, `SESSION_SECRET` was `''`, and `createHmac`\n// signs happily with an empty key. Every storefront member session cookie on a\n// template-following deployment was therefore signed with a key any reader of\n// this repository already has, i.e. forgeable. `||` restores the per-boot\n// random the comment above describes and the env template already promises\n// (\"without it, sessions don't survive a restart and disagree across\n// instances\") — unforgeable, and visibly degraded rather than silently open.\n//\n// Nothing caught it because `tools/scripts/selfhost-ci-env.mjs` FILLS this\n// variable before the image build, so the one job that builds these images\n// tests a configuration no operator following the template has.\nconst SESSION_SECRET =\n process.env.MEMBER_SESSION_SECRET || randomBytes(32).toString('hex')\n\nexport function hashMemberPassword(password: string): string {\n const salt = randomBytes(16).toString('hex')\n const hash = scryptSync(password, salt, 64).toString('hex')\n return `${salt}:${hash}`\n}\n\nexport function verifyMemberPassword(\n password: string,\n stored: string | undefined,\n): boolean {\n const [salt, hash] = String(stored ?? '').split(':')\n if (!salt || !hash) return false\n const candidate = scryptSync(password, salt, 64)\n const expected = Buffer.from(hash, 'hex')\n return (\n candidate.length === expected.length &&\n timingSafeEqual(new Uint8Array(candidate), new Uint8Array(expected))\n )\n}\n\nfunction sign(payload: string): string {\n return createHmac('sha256', SESSION_SECRET).update(payload).digest('hex')\n}\n\nexport function mintMemberSession(hostId: string, memberId: string): string {\n const payload = `${hostId}.${memberId}.${Date.now() + SESSION_TTL_MS}`\n return `${payload}.${sign(payload)}`\n}\n\n/**\n * Verified session contents. `issuedAtMs` is derived, not stored: the\n * payload carries `now + TTL`, so subtracting the TTL recovers the mint\n * time. That is what lets sessions be revoked in bulk (AGL-914) without\n * changing the token format or invalidating cookies already in the wild.\n */\nexport interface MemberSessionToken {\n memberId: string\n issuedAtMs: number\n}\n\n/** Returns the session contents when the cookie verifies for this host. */\nexport function parseMemberSession(\n hostId: string,\n token: string | undefined,\n): MemberSessionToken | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId) return null\n if (Number(expires) < Date.now()) return null\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(payload)\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return null\n if (!timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n return { memberId, issuedAtMs: Number(expires) - SESSION_TTL_MS }\n}\n\n/** Returns the memberId when the cookie verifies for this host. */\nexport function verifyMemberSession(\n hostId: string,\n token: string | undefined,\n): string | null {\n return parseMemberSession(hostId, token)?.memberId ?? null\n}\n\n/** Password-reset links live for one hour (AGL-552). */\nconst RESET_TOKEN_TTL_MS = 60 * 60 * 1000\n\n/**\n * Fingerprint of the member's CURRENT scrypt hash, folded into the reset\n * token signature (AGL-552): completing a reset rewrites `passwordScrypt`,\n * so every token minted before it stops verifying — single-use without any\n * server-side token storage.\n */\nfunction passwordFingerprint(passwordScrypt: string | undefined): string {\n return createHash('sha256')\n .update(String(passwordScrypt ?? ''))\n .digest('hex')\n}\n\n/**\n * Single-use, time-boxed password-reset token (AGL-552):\n * `hostId.memberId.expiry.HMAC(payload + password-fingerprint)`. Same\n * secret as sessions; the fingerprint binding is what makes it one-shot.\n */\nexport function mintPasswordResetToken(\n hostId: string,\n memberId: string,\n passwordScrypt: string | undefined,\n): string {\n const payload = `${hostId}.${memberId}.${Date.now() + RESET_TOKEN_TTL_MS}`\n return `${payload}.${sign(\n `${payload}.${passwordFingerprint(passwordScrypt)}`,\n )}`\n}\n\n/**\n * First step of reset verification: extract the memberId from a\n * well-formed, unexpired token for THIS host. The signature is NOT checked\n * here (it binds to the member's current password hash, which the caller\n * has to load first) — never trust the result without a follow-up\n * {@link verifyPasswordResetToken}.\n */\nexport function passwordResetTokenMemberId(\n hostId: string,\n token: string | undefined,\n): string | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires] = parts\n if (tokenHost !== hostId) return null\n if (!memberId) return null\n if (Number(expires) < Date.now()) return null\n return memberId\n}\n\n/** Full reset-token check: host, expiry, and password-hash binding. */\nexport function verifyPasswordResetToken(\n hostId: string,\n token: string | undefined,\n currentPasswordScrypt: string | undefined,\n): boolean {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return false\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId || !memberId) return false\n if (Number(expires) < Date.now()) return false\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(\n `${payload}.${passwordFingerprint(currentPasswordScrypt)}`,\n )\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\nexport function memberCookieName(hostId: string): string {\n return `aglyn_member_${hostId.replace(/[^A-Za-z0-9_-]/g, '')}`\n}\n\nexport function setMemberCookie(\n res: PluginApiResponse,\n hostId: string,\n token: string | null,\n): void {\n const name = memberCookieName(hostId)\n // Secure in production (AGL-500): the member session is an HMAC-signed\n // credential, so it must never travel over plaintext HTTP on a tenant\n // custom domain. Omit only in local dev (http://localhost), matching the\n // console __session cookie.\n const secure = process.env.NODE_ENV === 'production' ? '; Secure' : ''\n const base = `${name}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax${secure}`\n const maxAge = token ? `; Max-Age=${30 * 24 * 60 * 60}` : '; Max-Age=0'\n // The readable sign-in HINT beside it (AGL-4231): a `1` the page reads\n // before its first paint to show \"Account\" rather than \"Sign in\". It\n // carries nothing and grants nothing — the session above stays HttpOnly\n // and is what every endpoint checks — so it may be readable, and it lives\n // and dies with the session.\n const hint = `${signedInHintCookieName(hostId)}=${token ? '1' : ''}; Path=/; SameSite=Lax${secure}`\n res.setHeader('Set-Cookie', [`${base}${maxAge}`, `${hint}${maxAge}`])\n}\n\nexport function readMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): string | null {\n const raw = req.cookies?.[memberCookieName(hostId)]\n return verifyMemberSession(hostId, raw)\n}\n\n/**\n * Field name for the bulk session cut-off (AGL-914). Set to `Date.now()`\n * whenever every existing session for a member must stop working — today\n * only when an admin sets their password from the console, since a rewritten\n * `passwordScrypt` does NOT invalidate sessions on its own (unlike a reset\n * TOKEN, which binds to the hash by design).\n */\nexport const MEMBER_SESSIONS_VALID_FROM_FIELD = 'sessionsValidFromMs'\n\n/** Suspension rejection body — matches the login flow's AGL-546 message. */\nexport const MEMBER_SUSPENDED_ERROR =\n 'This account has been suspended. Contact the site owner.'\n\n/** Resolved member-session state, see {@link readActiveMemberSession}. */\nexport type MemberSessionCheck =\n | { status: 'anonymous' }\n | { status: 'suspended'; memberId: string }\n | {\n status: 'active'\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n }\n\n/**\n * Session + member-doc resolution for cookie-authenticated endpoints\n * (AGL-550). A verified cookie alone stopped being enough once console\n * suspension (AGL-546) landed: the HMAC session outlives the member's\n * standing, so every endpoint must also load the doc and check\n * `suspended`. That is one doc read per request — acceptable, and most\n * endpoints needed the member doc anyway. A deleted member doc reads as\n * `anonymous` (same as no cookie).\n */\nexport async function readActiveMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): Promise<MemberSessionCheck> {\n const session = parseMemberSession(\n hostId,\n req.cookies?.[memberCookieName(hostId)],\n )\n if (!session) return { status: 'anonymous' }\n const { memberId, issuedAtMs } = session\n const member = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('siteMembers')\n .doc(memberId)\n .get()\n if (!member.exists) return { status: 'anonymous' }\n // Revoked in bulk (AGL-914): a session minted before the cut-off is dead\n // even though its signature is still good. Reads as `anonymous` rather\n // than `suspended` — the account is fine, this browser just holds a stale\n // cookie, and signing in again is the correct next step.\n const validFrom = Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0)\n if (validFrom && issuedAtMs < validFrom) return { status: 'anonymous' }\n if (member.get('suspended') === true) {\n return { status: 'suspended', memberId }\n }\n return { status: 'active', memberId, member }\n}\n\n/**\n * Guard for cookie-authenticated member endpoints (AGL-550): resolves\n * the session AND the member doc, writing the rejection itself — 401\n * (`signInError`) when there is no usable session, 403 with the session\n * cookie cleared (mirroring membership-account's AGL-546 handling, so\n * the site stops presenting a signed-in shell) when the member is\n * suspended. Returns null after responding; handlers `if (!auth) return`.\n */\nexport async function requireActiveMember(\n req: PluginApiRequest,\n res: PluginApiResponse,\n hostId: string,\n signInError = 'Not signed in',\n): Promise<{\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n} | null> {\n const session = await readActiveMemberSession(req, hostId)\n if (session.status === 'suspended') {\n setMemberCookie(res, hostId, null)\n res.status(403).json({ error: MEMBER_SUSPENDED_ERROR })\n return null\n }\n if (session.status !== 'active') {\n res.status(401).json({ error: signInError })\n return null\n }\n return { memberId: session.memberId, member: session.member }\n}\n"],"names":["createHash","createHmac","randomBytes","scryptSync","timingSafeEqual","signedInHintCookieName","firebaseAdmin","SESSION_TTL_MS","SESSION_SECRET","process","env","MEMBER_SESSION_SECRET","toString","hashMemberPassword","password","salt","hash","verifyMemberPassword","stored","String","split","candidate","expected","Buffer","from","length","Uint8Array","sign","payload","update","digest","mintMemberSession","hostId","memberId","Date","now","parseMemberSession","token","parts","tokenHost","expires","signature","Number","a","b","issuedAtMs","verifyMemberSession","RESET_TOKEN_TTL_MS","passwordFingerprint","passwordScrypt","mintPasswordResetToken","passwordResetTokenMemberId","verifyPasswordResetToken","currentPasswordScrypt","memberCookieName","replace","setMemberCookie","res","name","secure","NODE_ENV","base","maxAge","hint","setHeader","readMemberSession","req","raw","cookies","MEMBER_SESSIONS_VALID_FROM_FIELD","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","member","session","status","app","firestore","collection","doc","get","exists","validFrom","requireActiveMember","signInError","json","error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,UAAU,EACVC,eAAe,QACV,SAAQ;AAEf,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;CAKC,GAED,MAAMC,iBAAiB,KAAK,KAAK,KAAK,KAAK;AAE3C,wEAAwE;AACxE,gDAAgD;AAChD,EAAE;AACF,0EAA0E;AAC1E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,qEAAqE;AACrE,6EAA6E;AAC7E,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,gEAAgE;AAChE,MAAMC,iBACJC,QAAQC,GAAG,CAACC,qBAAqB,IAAIT,YAAY,IAAIU,QAAQ,CAAC;AAEhE,OAAO,SAASC,mBAAmBC,QAAgB;IACjD,MAAMC,OAAO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IAAY;IACtE,IAAIF,OAAOO,GAAG,CAAC,iBAAiB,MAAM;QACpC,OAAO;YAAEL,QAAQ;YAAazC;QAAS;IACzC;IACA,OAAO;QAAEyC,QAAQ;QAAUzC;QAAUuC;IAAO;AAC9C;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeU,oBACpBhB,GAAqB,EACrBT,GAAsB,EACtBzB,MAAc,EACdmD,cAAc,eAAe;IAK7B,MAAMV,UAAU,MAAMF,wBAAwBL,KAAKlC;IACnD,IAAIyC,QAAQC,MAAM,KAAK,aAAa;QAClClB,gBAAgBC,KAAKzB,QAAQ;QAC7ByB,IAAIiB,MAAM,CAAC,KAAKU,IAAI,CAAC;YAAEC,OAAOf;QAAuB;QACrD,OAAO;IACT;IACA,IAAIG,QAAQC,MAAM,KAAK,UAAU;QAC/BjB,IAAIiB,MAAM,CAAC,KAAKU,IAAI,CAAC;YAAEC,OAAOF;QAAY;QAC1C,OAAO;IACT;IACA,OAAO;QAAElD,UAAUwC,QAAQxC,QAAQ;QAAEuC,QAAQC,QAAQD,MAAM;IAAC;AAC9D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createHash,\n createHmac,\n randomBytes,\n scryptSync,\n timingSafeEqual,\n} from 'crypto'\nimport type { PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { memberSessionCookieName, signedInHintCookieName } from '@aglyn/aglyn/app-utils/sign-in-hint-cookie'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Site membership primitives (AGL-109): visitor accounts per host with\n * scrypt-hashed passwords and an HMAC-signed httpOnly session cookie.\n * Per-site Firebase Auth is a future infra decision (AGL-45 class); this\n * keeps member content out of static HTML the same way AGL-87 does.\n */\n\nconst SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000\n\n// A per-boot fallback keeps dev working; production must set the env so\n// sessions survive deploys and instances agree.\n//\n// `||`, NOT `??`, and on a self-host install that is the whole difference\n// (AGL-2014). `.env.selfhost.example` ships `MEMBER_SESSION_SECRET=` blank and\n// compose `env_file` sets a blank line as the EMPTY STRING rather than leaving\n// it unset — so `??` did not fire, `SESSION_SECRET` was `''`, and `createHmac`\n// signs happily with an empty key. Every storefront member session cookie on a\n// template-following deployment was therefore signed with a key any reader of\n// this repository already has, i.e. forgeable. `||` restores the per-boot\n// random the comment above describes and the env template already promises\n// (\"without it, sessions don't survive a restart and disagree across\n// instances\") — unforgeable, and visibly degraded rather than silently open.\n//\n// Nothing caught it because `tools/scripts/selfhost-ci-env.mjs` FILLS this\n// variable before the image build, so the one job that builds these images\n// tests a configuration no operator following the template has.\nconst SESSION_SECRET =\n process.env.MEMBER_SESSION_SECRET || randomBytes(32).toString('hex')\n\nexport function hashMemberPassword(password: string): string {\n const salt = randomBytes(16).toString('hex')\n const hash = scryptSync(password, salt, 64).toString('hex')\n return `${salt}:${hash}`\n}\n\nexport function verifyMemberPassword(\n password: string,\n stored: string | undefined,\n): boolean {\n const [salt, hash] = String(stored ?? '').split(':')\n if (!salt || !hash) return false\n const candidate = scryptSync(password, salt, 64)\n const expected = Buffer.from(hash, 'hex')\n return (\n candidate.length === expected.length &&\n timingSafeEqual(new Uint8Array(candidate), new Uint8Array(expected))\n )\n}\n\nfunction sign(payload: string): string {\n return createHmac('sha256', SESSION_SECRET).update(payload).digest('hex')\n}\n\nexport function mintMemberSession(hostId: string, memberId: string): string {\n const payload = `${hostId}.${memberId}.${Date.now() + SESSION_TTL_MS}`\n return `${payload}.${sign(payload)}`\n}\n\n/**\n * Verified session contents. `issuedAtMs` is derived, not stored: the\n * payload carries `now + TTL`, so subtracting the TTL recovers the mint\n * time. That is what lets sessions be revoked in bulk (AGL-914) without\n * changing the token format or invalidating cookies already in the wild.\n */\nexport interface MemberSessionToken {\n memberId: string\n issuedAtMs: number\n}\n\n/** Returns the session contents when the cookie verifies for this host. */\nexport function parseMemberSession(\n hostId: string,\n token: string | undefined,\n): MemberSessionToken | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId) return null\n if (Number(expires) < Date.now()) return null\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(payload)\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return null\n if (!timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n return { memberId, issuedAtMs: Number(expires) - SESSION_TTL_MS }\n}\n\n/** Returns the memberId when the cookie verifies for this host. */\nexport function verifyMemberSession(\n hostId: string,\n token: string | undefined,\n): string | null {\n return parseMemberSession(hostId, token)?.memberId ?? null\n}\n\n/** Password-reset links live for one hour (AGL-552). */\nconst RESET_TOKEN_TTL_MS = 60 * 60 * 1000\n\n/**\n * Fingerprint of the member's CURRENT scrypt hash, folded into the reset\n * token signature (AGL-552): completing a reset rewrites `passwordScrypt`,\n * so every token minted before it stops verifying — single-use without any\n * server-side token storage.\n */\nfunction passwordFingerprint(passwordScrypt: string | undefined): string {\n return createHash('sha256')\n .update(String(passwordScrypt ?? ''))\n .digest('hex')\n}\n\n/**\n * Single-use, time-boxed password-reset token (AGL-552):\n * `hostId.memberId.expiry.HMAC(payload + password-fingerprint)`. Same\n * secret as sessions; the fingerprint binding is what makes it one-shot.\n */\nexport function mintPasswordResetToken(\n hostId: string,\n memberId: string,\n passwordScrypt: string | undefined,\n): string {\n const payload = `${hostId}.${memberId}.${Date.now() + RESET_TOKEN_TTL_MS}`\n return `${payload}.${sign(\n `${payload}.${passwordFingerprint(passwordScrypt)}`,\n )}`\n}\n\n/**\n * First step of reset verification: extract the memberId from a\n * well-formed, unexpired token for THIS host. The signature is NOT checked\n * here (it binds to the member's current password hash, which the caller\n * has to load first) — never trust the result without a follow-up\n * {@link verifyPasswordResetToken}.\n */\nexport function passwordResetTokenMemberId(\n hostId: string,\n token: string | undefined,\n): string | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires] = parts\n if (tokenHost !== hostId) return null\n if (!memberId) return null\n if (Number(expires) < Date.now()) return null\n return memberId\n}\n\n/** Full reset-token check: host, expiry, and password-hash binding. */\nexport function verifyPasswordResetToken(\n hostId: string,\n token: string | undefined,\n currentPasswordScrypt: string | undefined,\n): boolean {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return false\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId || !memberId) return false\n if (Number(expires) < Date.now()) return false\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(\n `${payload}.${passwordFingerprint(currentPasswordScrypt)}`,\n )\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\nexport function memberCookieName(hostId: string): string {\n // Named where the readable sign-in hint is (AGL-4231), so the tenant\n // middleware that keeps the two in step reads the same name.\n return memberSessionCookieName(hostId)\n}\n\nexport function setMemberCookie(\n res: PluginApiResponse,\n hostId: string,\n token: string | null,\n): void {\n const name = memberCookieName(hostId)\n // Secure in production (AGL-500): the member session is an HMAC-signed\n // credential, so it must never travel over plaintext HTTP on a tenant\n // custom domain. Omit only in local dev (http://localhost), matching the\n // console __session cookie.\n const secure = process.env.NODE_ENV === 'production' ? '; Secure' : ''\n const base = `${name}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax${secure}`\n const maxAge = token ? `; Max-Age=${30 * 24 * 60 * 60}` : '; Max-Age=0'\n // The readable sign-in HINT beside it (AGL-4231): a `1` the page reads\n // before its first paint to show \"Account\" rather than \"Sign in\". It\n // carries nothing and grants nothing — the session above stays HttpOnly\n // and is what every endpoint checks — so it may be readable, and it lives\n // and dies with the session.\n const hint = `${signedInHintCookieName(hostId)}=${token ? '1' : ''}; Path=/; SameSite=Lax${secure}`\n res.setHeader('Set-Cookie', [`${base}${maxAge}`, `${hint}${maxAge}`])\n}\n\nexport function readMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): string | null {\n const raw = req.cookies?.[memberCookieName(hostId)]\n return verifyMemberSession(hostId, raw)\n}\n\n/**\n * Field name for the bulk session cut-off (AGL-914). Set to `Date.now()`\n * whenever every existing session for a member must stop working — today\n * only when an admin sets their password from the console, since a rewritten\n * `passwordScrypt` does NOT invalidate sessions on its own (unlike a reset\n * TOKEN, which binds to the hash by design).\n */\nexport const MEMBER_SESSIONS_VALID_FROM_FIELD = 'sessionsValidFromMs'\n\n/** Suspension rejection body — matches the login flow's AGL-546 message. */\nexport const MEMBER_SUSPENDED_ERROR =\n 'This account has been suspended. Contact the site owner.'\n\n/** Resolved member-session state, see {@link readActiveMemberSession}. */\nexport type MemberSessionCheck =\n | { status: 'anonymous' }\n | { status: 'suspended'; memberId: string }\n | {\n status: 'active'\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n }\n\n/**\n * Session + member-doc resolution for cookie-authenticated endpoints\n * (AGL-550). A verified cookie alone stopped being enough once console\n * suspension (AGL-546) landed: the HMAC session outlives the member's\n * standing, so every endpoint must also load the doc and check\n * `suspended`. That is one doc read per request — acceptable, and most\n * endpoints needed the member doc anyway. A deleted member doc reads as\n * `anonymous` (same as no cookie).\n */\nexport async function readActiveMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): Promise<MemberSessionCheck> {\n const session = parseMemberSession(\n hostId,\n req.cookies?.[memberCookieName(hostId)],\n )\n if (!session) return { status: 'anonymous' }\n const { memberId, issuedAtMs } = session\n const member = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('siteMembers')\n .doc(memberId)\n .get()\n if (!member.exists) return { status: 'anonymous' }\n // Revoked in bulk (AGL-914): a session minted before the cut-off is dead\n // even though its signature is still good. Reads as `anonymous` rather\n // than `suspended` — the account is fine, this browser just holds a stale\n // cookie, and signing in again is the correct next step.\n const validFrom = Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0)\n if (validFrom && issuedAtMs < validFrom) return { status: 'anonymous' }\n if (member.get('suspended') === true) {\n return { status: 'suspended', memberId }\n }\n return { status: 'active', memberId, member }\n}\n\n/**\n * Guard for cookie-authenticated member endpoints (AGL-550): resolves\n * the session AND the member doc, writing the rejection itself — 401\n * (`signInError`) when there is no usable session, 403 with the session\n * cookie cleared (mirroring membership-account's AGL-546 handling, so\n * the site stops presenting a signed-in shell) when the member is\n * suspended. Returns null after responding; handlers `if (!auth) return`.\n */\nexport async function requireActiveMember(\n req: PluginApiRequest,\n res: PluginApiResponse,\n hostId: string,\n signInError = 'Not signed in',\n): Promise<{\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n} | null> {\n const session = await readActiveMemberSession(req, hostId)\n if (session.status === 'suspended') {\n setMemberCookie(res, hostId, null)\n res.status(403).json({ error: MEMBER_SUSPENDED_ERROR })\n return null\n }\n if (session.status !== 'active') {\n res.status(401).json({ error: signInError })\n return null\n }\n return { memberId: session.memberId, member: session.member }\n}\n"],"names":["createHash","createHmac","randomBytes","scryptSync","timingSafeEqual","memberSessionCookieName","signedInHintCookieName","firebaseAdmin","SESSION_TTL_MS","SESSION_SECRET","process","env","MEMBER_SESSION_SECRET","toString","hashMemberPassword","password","salt","hash","verifyMemberPassword","stored","String","split","candidate","expected","Buffer","from","length","Uint8Array","sign","payload","update","digest","mintMemberSession","hostId","memberId","Date","now","parseMemberSession","token","parts","tokenHost","expires","signature","Number","a","b","issuedAtMs","verifyMemberSession","RESET_TOKEN_TTL_MS","passwordFingerprint","passwordScrypt","mintPasswordResetToken","passwordResetTokenMemberId","verifyPasswordResetToken","currentPasswordScrypt","memberCookieName","setMemberCookie","res","name","secure","NODE_ENV","base","maxAge","hint","setHeader","readMemberSession","req","raw","cookies","MEMBER_SESSIONS_VALID_FROM_FIELD","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","member","session","status","app","firestore","collection","doc","get","exists","validFrom","requireActiveMember","signInError","json","error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,UAAU,EACVC,eAAe,QACV,SAAQ;AAEf,SAASC,uBAAuB,EAAEC,sBAAsB,QAAQ,6CAA4C;AAC5G,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;CAKC,GAED,MAAMC,iBAAiB,KAAK,KAAK,KAAK,KAAK;AAE3C,wEAAwE;AACxE,gDAAgD;AAChD,EAAE;AACF,0EAA0E;AAC1E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,qEAAqE;AACrE,6EAA6E;AAC7E,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,gEAAgE;AAChE,MAAMC,iBACJC,QAAQC,GAAG,CAACC,qBAAqB,IAAIV,YAAY,IAAIW,QAAQ,CAAC;AAEhE,OAAO,SAASC,mBAAmBC,QAAgB;IACjD,MAAMC,OAAOd,YAAY,IAAIW,QAAQ,CAAC;IACtC,MAAMI,OAAOd,WAAWY,UAAUC,MAAM,IAAIH,QAAQ,CAAC;IACrD,OAAO,GAAGG,KAAK,CAAC,EAAEC,MAAM;AAC1B;AAEA,OAAO,SAASC,qBACdH,QAAgB,EAChBI,MAA0B;IAE1B,MAAM,CAACH,MAAMC,KAAK,GAAGG,OAAOD,iBAAAA,SAAU,IAAIE,KAAK,CAAC;IAChD,IAAI,CAACL,QAAQ,CAACC,MAAM,OAAO;IAC3B,MAAMK,YAAYnB,WAAWY,UAA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