@stacksjs/commerce 0.75.544 → 0.75.551
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +18 -0
- package/dist/index.js +1 -1
- package/dist/licensing/client.d.ts +62 -0
- package/dist/licensing/client.js +1 -0
- package/dist/licensing/index.d.ts +11 -0
- package/dist/licensing/index.js +1 -0
- package/dist/licensing/keys.d.ts +41 -0
- package/dist/licensing/keys.js +1 -0
- package/dist/licensing/resend.d.ts +25 -0
- package/dist/licensing/resend.js +1 -0
- package/dist/licensing/service.d.ts +187 -0
- package/dist/licensing/service.js +1 -0
- package/dist/licensing/token.d.ts +90 -0
- package/dist/licensing/token.js +1 -0
- package/dist/orders/webhook.d.ts +2 -1
- package/dist/orders/webhook.js +1 -1
- package/dist/shippings/license-keys/validate-write.js +1 -1
- package/package.json +14 -14
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import * as customers from './customers/index';
|
|
|
7
7
|
import * as devices from './devices/index';
|
|
8
8
|
import * as errors from './errors/index';
|
|
9
9
|
import * as giftCards from './gift-cards/index';
|
|
10
|
+
import * as licensing from './licensing/index';
|
|
10
11
|
import * as money from './money';
|
|
11
12
|
import * as orders from './orders/index';
|
|
12
13
|
import * as payments from './payments/index';
|
|
@@ -21,6 +22,17 @@ import * as waitlists from './waitlists/index';
|
|
|
21
22
|
export type { MoneyInputOptions } from './money';
|
|
22
23
|
export type { TaxRateRow } from './sales-tax';
|
|
23
24
|
export type { SalesTaxSetup, SalesTaxInputOptions } from './tax-input';
|
|
25
|
+
export type {
|
|
26
|
+
ActivateLicenseResult,
|
|
27
|
+
CheckLicenseResult,
|
|
28
|
+
License,
|
|
29
|
+
LicenseDeviceSummary,
|
|
30
|
+
LicenseSeatSummary,
|
|
31
|
+
LicenseStandingSummary,
|
|
32
|
+
LicenseStatus,
|
|
33
|
+
LicensingOptions,
|
|
34
|
+
} from './licensing/service';
|
|
35
|
+
export type { LicensePublicKeys, LicenseSigningKey, LicenseSigningKeypair, LicenseTier, LicenseTokenPayload } from './licensing/token';
|
|
24
36
|
export declare const commerce: CommerceNamespace;
|
|
25
37
|
export declare interface CommerceNamespace {
|
|
26
38
|
auctions: AuctionsModule
|
|
@@ -30,6 +42,7 @@ export declare interface CommerceNamespace {
|
|
|
30
42
|
customers: CustomersModule
|
|
31
43
|
errors: ErrorsModule
|
|
32
44
|
giftCards: GiftCardsModule
|
|
45
|
+
licensing: LicensingModule
|
|
33
46
|
orders: OrdersModule
|
|
34
47
|
payments: PaymentsModule
|
|
35
48
|
products: ProductsModule
|
|
@@ -52,6 +65,7 @@ declare type CustomersModule = typeof customers;
|
|
|
52
65
|
declare type ErrorsModule = typeof errors;
|
|
53
66
|
declare type ShippingsModule = typeof shippings;
|
|
54
67
|
declare type GiftCardsModule = typeof giftCards;
|
|
68
|
+
declare type LicensingModule = typeof licensing;
|
|
55
69
|
declare type OrdersModule = typeof orders;
|
|
56
70
|
declare type PaymentsModule = typeof payments;
|
|
57
71
|
declare type ProductsModule = typeof products;
|
|
@@ -106,4 +120,8 @@ export { breakdownFor, multiplierOf } from './sales-tax';
|
|
|
106
120
|
export { restockedQuantity } from './inventory';
|
|
107
121
|
export { receiptLinesText, type ReceiptTextLine } from './receipt-text';
|
|
108
122
|
export { parseSalesTaxSetup, parseTaxRateWriteData } from './tax-input';
|
|
123
|
+
// Software licensing's shapes, for code that takes a license as an argument.
|
|
124
|
+
// The functions are `licensing.*`; a desktop app's agent imports the client
|
|
125
|
+
// half from `@stacksjs/commerce/licensing/client`, which pulls in none of this.
|
|
126
|
+
export { licensing };
|
|
109
127
|
export default commerce;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as auctions from"./auctions";import*as carts from"./carts";import*as catalog from"./catalog";import*as catalogImport from"./imports";import*as coupons from"./coupons";import*as customers from"./customers";import*as devices from"./devices";import*as errors from"./errors";import*as giftCards from"./gift-cards";import*as money from"./money";import*as orders from"./orders";import*as payments from"./payments";import*as products from"./products";import*as register from"./register";import*as releases from"./releases";import*as receipts from"./receipts";import*as shippings from"./shippings";import*as tax from"./tax";import*as waitlists from"./waitlists";import*as restaurant from"./waitlists/restaurant";export const commerce={auctions,carts,catalog,coupons,customers,devices,errors,giftCards,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export default commerce;export{auctions,carts,catalog,catalogImport,coupons,customers,devices,errors,giftCards,money,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export{currencyExponent,decimalToMinor,formatCurrency,formatMinor,minorToDecimal,minorToInput,minorToMajor,moneyInputError,moneyInputStep,parseMoneyInput,PriceFormatError}from"./money";export{breakdownFor,multiplierOf}from"./sales-tax";export{restockedQuantity}from"./inventory";export{receiptLinesText}from"./receipt-text";export{parseSalesTaxSetup,parseTaxRateWriteData}from"./tax-input";
|
|
1
|
+
import*as auctions from"./auctions";import*as carts from"./carts";import*as catalog from"./catalog";import*as catalogImport from"./imports";import*as coupons from"./coupons";import*as customers from"./customers";import*as devices from"./devices";import*as errors from"./errors";import*as giftCards from"./gift-cards";import*as licensing from"./licensing";import*as money from"./money";import*as orders from"./orders";import*as payments from"./payments";import*as products from"./products";import*as register from"./register";import*as releases from"./releases";import*as receipts from"./receipts";import*as shippings from"./shippings";import*as tax from"./tax";import*as waitlists from"./waitlists";import*as restaurant from"./waitlists/restaurant";export const commerce={auctions,carts,catalog,coupons,customers,devices,errors,giftCards,licensing,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export default commerce;export{auctions,carts,catalog,catalogImport,coupons,customers,devices,errors,giftCards,money,orders,payments,products,receipts,register,releases,restaurant,shippings,tax,waitlists};export{currencyExponent,decimalToMinor,formatCurrency,formatMinor,minorToDecimal,minorToInput,minorToMajor,moneyInputError,moneyInputStep,parseMoneyInput,PriceFormatError}from"./money";export{breakdownFor,multiplierOf}from"./sales-tax";export{restockedQuantity}from"./inventory";export{receiptLinesText}from"./receipt-text";export{parseSalesTaxSetup,parseTaxRateWriteData}from"./tax-input";export{licensing};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { hashDeviceId, LicenseTokenError, tokenStanding } from './token';
|
|
2
|
+
import type { LicensePublicKeys, LicenseTier, LicenseTokenPayload, TokenStandingReason } from './token';
|
|
3
|
+
export type { LicensePublicKeys, LicenseTier, LicenseTokenPayload, TokenStanding } from './token';
|
|
4
|
+
/** The payload of a token signed by one of `publicKeys`. Throws a {@link LicenseTokenError} otherwise. */
|
|
5
|
+
export declare function verifyToken(token: string, publicKeys: LicensePublicKeys, deviceHash?: string): LicenseTokenPayload;
|
|
6
|
+
export declare function createLicenseClient(options: LicenseClientOptions): LicenseClient;
|
|
7
|
+
/** Where the key and token are kept. Back it with `Bun.secrets`, a keychain, or a file. */
|
|
8
|
+
export declare interface LicenseStorage {
|
|
9
|
+
get: (name: string) => MaybePromise<string | null | undefined>
|
|
10
|
+
set: (name: string, value: string) => MaybePromise<unknown>
|
|
11
|
+
delete: (name: string) => MaybePromise<unknown>
|
|
12
|
+
}
|
|
13
|
+
export declare interface LicenseDevice {
|
|
14
|
+
id: string
|
|
15
|
+
name?: string
|
|
16
|
+
platform?: string
|
|
17
|
+
appVersion?: string
|
|
18
|
+
email?: string
|
|
19
|
+
}
|
|
20
|
+
export declare interface LicenseClientOptions {
|
|
21
|
+
endpoint: string
|
|
22
|
+
publicKeys: LicensePublicKeys
|
|
23
|
+
storage: LicenseStorage
|
|
24
|
+
buildDate: Date | string
|
|
25
|
+
fetcher?: LicenseFetcher
|
|
26
|
+
now?: () => Date
|
|
27
|
+
storageName?: string
|
|
28
|
+
}
|
|
29
|
+
/** A device already using the license, as the server names it. */
|
|
30
|
+
export declare interface LicenseDeviceInUse {
|
|
31
|
+
name: string | null
|
|
32
|
+
platform: string | null
|
|
33
|
+
lastSeenAt: string | null
|
|
34
|
+
}
|
|
35
|
+
/** What the app acts on. `pro` is the only field a feature gate needs. */
|
|
36
|
+
export declare interface LicenseStanding {
|
|
37
|
+
licensed: boolean
|
|
38
|
+
pro: boolean
|
|
39
|
+
tier: LicenseTier | null
|
|
40
|
+
reason: LicenseStandingReason
|
|
41
|
+
updatesUntil: string | null
|
|
42
|
+
expiresAt: string | null
|
|
43
|
+
lastCheckedAt: string | null
|
|
44
|
+
offline: boolean
|
|
45
|
+
}
|
|
46
|
+
export declare interface LicenseClient {
|
|
47
|
+
activate: (key: string, device: LicenseDevice) => Promise<ActivateResult>
|
|
48
|
+
release: () => Promise<{ ok: boolean, message?: string }>
|
|
49
|
+
standing: (options?: { online?: boolean, force?: boolean }) => Promise<LicenseStanding>
|
|
50
|
+
verifyToken: (token: string) => LicenseTokenPayload
|
|
51
|
+
}
|
|
52
|
+
declare type MaybePromise<T> = T | Promise<T>;
|
|
53
|
+
export type LicenseFetcher = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
54
|
+
export type LicenseStandingReason = | TokenStandingReason
|
|
55
|
+
| 'unlicensed'
|
|
56
|
+
| 'invalid-token'
|
|
57
|
+
| 'revoked'
|
|
58
|
+
| 'refunded'
|
|
59
|
+
| 'released';
|
|
60
|
+
export type ActivateResult = | { ok: true, standing: LicenseStanding }
|
|
61
|
+
| { ok: false, reason: string, message: string, devices?: LicenseDeviceInUse[] }
|
|
62
|
+
export { hashDeviceId, isEntitled, LicenseTokenError, OFFLINE_GRACE_DAYS, RECHECK_DAYS, tokenStanding } from './token';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{hashDeviceId,LicenseTokenError,tokenStanding,verifyLicenseToken}from"./token";export{hashDeviceId,isEntitled,LicenseTokenError,OFFLINE_GRACE_DAYS,RECHECK_DAYS,tokenStanding}from"./token";const UNLICENSED={licensed:false,pro:false,tier:null,reason:"unlicensed",updatesUntil:null,expiresAt:null,lastCheckedAt:null,offline:false};export function verifyToken(token,publicKeys,deviceHash){return verifyLicenseToken(token,publicKeys,deviceHash)}export function createLicenseClient(options){const fetcher=options.fetcher??fetch;const now=options.now??(()=>new Date);const name=options.storageName??"license";const endpoint=options.endpoint.replace(/\/+$/,"");async function load(){const raw=await options.storage.get(name);if(!raw)return null;try{const state=JSON.parse(raw);return typeof state?.key==="string"&&typeof state.deviceId==="string"&&typeof state.token==="string"?state:null}catch{return null}}async function post(path,body){const response=await fetcher(`${endpoint}${path}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body)});let data={};try{data=await response.json()}catch{data={}}return{status:response.status,data}}function read(state,offline){let payload;try{payload=verifyLicenseToken(state.token,options.publicKeys,hashDeviceId(state.deviceId))}catch(error){if(!(error instanceof LicenseTokenError))throw error;return{...UNLICENSED,reason:"invalid-token",lastCheckedAt:state.lastCheckedAt,offline}}const standing=tokenStanding(payload,{buildDate:options.buildDate,now:now(),lastCheckedAt:state.lastCheckedAt});return{licensed:standing.licensed,pro:standing.pro,tier:payload.tier,reason:standing.reason,updatesUntil:payload.updatesUntil,expiresAt:payload.expiresAt,lastCheckedAt:state.lastCheckedAt,offline}}function recheckDue(state){try{const payload=verifyLicenseToken(state.token,options.publicKeys,hashDeviceId(state.deviceId));return tokenStanding(payload,{buildDate:options.buildDate,now:now(),lastCheckedAt:state.lastCheckedAt}).recheckDue}catch{return true}}return{verifyToken:(token)=>verifyLicenseToken(token,options.publicKeys),async activate(key,device){let answer;try{answer=await post("/activate",{key,deviceHash:hashDeviceId(device.id),deviceName:device.name??null,platform:device.platform??null,appVersion:device.appVersion??null,...device.email?{email:device.email}:{}})}catch(error){return{ok:false,reason:"network",message:`The license server could not be reached: ${error instanceof Error?error.message:String(error)}`}}const{data}=answer;if(!data.ok||typeof data.token!=="string"){return{ok:false,reason:typeof data.reason==="string"?data.reason:"failed",message:typeof data.message==="string"?data.message:`Activation failed with HTTP ${answer.status}`,...Array.isArray(data.devices)?{devices:data.devices}:{}}}const state={key:typeof data.key==="string"?data.key:key,deviceId:device.id,token:data.token,lastCheckedAt:now().toISOString(),...device.email?{email:device.email}:{}};const standing=read(state,false);if(standing.reason==="invalid-token")return{ok:false,reason:"invalid-token",message:"The server answered with a license token this build does not trust."};await options.storage.set(name,JSON.stringify(state));return{ok:true,standing}},async release(){const state=await load();if(!state)return{ok:true};try{const{data,status}=await post("/deactivate",{key:state.key,deviceHash:hashDeviceId(state.deviceId)});if(!data.ok&&status!==404)return{ok:false,message:typeof data.message==="string"?data.message:`Release failed with HTTP ${status}`}}catch(error){return{ok:false,message:`The license server could not be reached: ${error instanceof Error?error.message:String(error)}`}}await options.storage.delete(name);return{ok:true}},async standing(request={}){const state=await load();if(!state)return UNLICENSED;if(request.online===false||!(request.force||recheckDue(state)))return read(state,request.online===false);let answer;try{answer=await post("/check",{key:state.key,deviceHash:hashDeviceId(state.deviceId)})}catch{return read(state,true)}const{data,status}=answer;if(status>=500||typeof data.ok!=="boolean")return read(state,true);if(data.ok&&data.valid===true&&typeof data.token==="string"){const next={...state,token:data.token,lastCheckedAt:now().toISOString()};const standing=read(next,false);if(standing.reason==="invalid-token")return read(state,true);await options.storage.set(name,JSON.stringify(next));return standing}if(data.valid===false||status===403||status===404){await options.storage.delete(name);const reason=["revoked","refunded","released","expired"].includes(data.reason)?data.reason:"unlicensed";return{...UNLICENSED,reason}}return read(state,true)}}}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Software licensing: `import { licensing } from '@stacksjs/commerce'`.
|
|
3
|
+
*
|
|
4
|
+
* The server half: issuing from payment events, activations, seats, refunds
|
|
5
|
+
* and the signed offline token. A desktop app's agent imports the client half
|
|
6
|
+
* from `@stacksjs/commerce/licensing/client`, which needs none of this.
|
|
7
|
+
*/
|
|
8
|
+
export * from './keys';
|
|
9
|
+
export * from './resend';
|
|
10
|
+
export * from './service';
|
|
11
|
+
export * from './token';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./keys";export*from"./resend";export*from"./service";export*from"./token";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { LicenseTier } from './token';
|
|
2
|
+
/**
|
|
3
|
+
* `XXXX-XXXX-XXXX-XXXX-XXXX`: 100 random bits in an alphabet with no 0/O or
|
|
4
|
+
* 1/I, in the five groups of four the `LicenseKey` model validates.
|
|
5
|
+
*/
|
|
6
|
+
export declare function generateLicenseKey(bytes?: Uint8Array): string;
|
|
7
|
+
/** A key as typed or pasted: case, spaces and missing dashes forgiven. Null when it cannot be one. */
|
|
8
|
+
export declare function normalizeLicenseKey(input: unknown): string | null;
|
|
9
|
+
/**
|
|
10
|
+
* An address as typed, trimmed and lower-cased, or null when it cannot be
|
|
11
|
+
* one. Deliberately loose (the real check is whether mail arrives), except
|
|
12
|
+
* that it refuses `%`, which no buyer's address has and which a LIKE lookup
|
|
13
|
+
* would read as a wildcard.
|
|
14
|
+
*/
|
|
15
|
+
export declare function normalizeEmail(input: unknown): string | null;
|
|
16
|
+
/**
|
|
17
|
+
* The `reference` to start a license checkout with:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* await paymentDriver().checkout(payer, {
|
|
21
|
+
* mode: 'payment',
|
|
22
|
+
* lines: [{ name: 'Pro', unitAmount: 3900, quantity: 1 }],
|
|
23
|
+
* successUrl,
|
|
24
|
+
* reference: licensePurchaseReference({ tier: 'standard' }),
|
|
25
|
+
* })
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Every payment driver echoes a checkout's reference in its webhook, so this
|
|
29
|
+
* is how a paid event says "issue a license, of this tier" without the
|
|
30
|
+
* framework knowing the provider. It is unique per checkout, which is what
|
|
31
|
+
* makes issuing idempotent, and uses only letters, digits, `_` and `-`,
|
|
32
|
+
* the characters every provider accepts.
|
|
33
|
+
*/
|
|
34
|
+
export declare function licensePurchaseReference(purchase: { tier: LicenseTier, seats?: number, productId?: number | null }): string;
|
|
35
|
+
/** What a purchase reference asks for, or null when the reference is not a license purchase. */
|
|
36
|
+
export declare function parseLicensePurchaseReference(reference: unknown): LicensePurchase | null;
|
|
37
|
+
export declare interface LicensePurchase {
|
|
38
|
+
tier: LicenseTier
|
|
39
|
+
seats: number
|
|
40
|
+
productId: number | null
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomBytes}from"node:crypto";const ALPHABET="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";const TIERS=["standard","lifetime","team"];export function generateLicenseKey(bytes=randomBytes(13)){if(bytes.length<13)throw new Error("A license key needs 13 random bytes");let bits=0;let value=0;let out="";for(const byte of bytes){value=(value&(1<<bits)-1)<<8|byte;bits+=8;while(bits>=5){out+=ALPHABET[value>>>bits-5&31];bits-=5}}return out.slice(0,20).match(/.{4}/g).join("-")}export function normalizeLicenseKey(input){if(typeof input!=="string")return null;const compact=input.toUpperCase().replace(/[^A-Z0-9]/g,"");if(!/^[A-Z0-9]{20}$/.test(compact))return null;return compact.match(/.{4}/g).join("-")}export function normalizeEmail(input){if(typeof input!=="string")return null;const email=input.trim().toLowerCase();if(email.length>254||!/^[^\s@%]+@[^\s@%]+\.[^\s@%]+$/.test(email))return null;return email}export function licensePurchaseReference(purchase){if(!TIERS.includes(purchase.tier))throw new Error(`Not a license tier: ${String(purchase.tier)}`);const seats=purchase.seats??1;if(!Number.isSafeInteger(seats)||seats<1)throw new Error("A license covers at least one seat");const productId=purchase.productId??0;if(!Number.isSafeInteger(productId)||productId<0)throw new Error("A product id is a positive integer");return`lic_${purchase.tier}_${seats}_${productId}_${randomBytes(12).toString("hex")}`}export function parseLicensePurchaseReference(reference){if(typeof reference!=="string")return null;const match=reference.match(/^lic_(standard|lifetime|team)_(\d{1,6})_(\d{1,15})_[a-f0-9]{24}$/);if(!match)return null;const seats=Number(match[2]);if(seats<1)return null;const productId=Number(match[3]);return{tier:match[1],seats,productId:productId>0?productId:null}}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { License } from './service';
|
|
2
|
+
export declare function requestLicenseResend(rawEmail: unknown, deps: ResendDeps, ip?: string): Promise<ResendRequest>;
|
|
3
|
+
export declare const RESEND_LIMITS: {
|
|
4
|
+
/** Per client IP, counted before anything else, so junk costs the sender too. */
|
|
5
|
+
readonly ip: {
|
|
6
|
+
readonly max: 10;
|
|
7
|
+
readonly windowSeconds: number
|
|
8
|
+
};
|
|
9
|
+
/** Per address, found or not, so the answer cannot be probed through the limit either. */
|
|
10
|
+
readonly email: {
|
|
11
|
+
readonly max: 3;
|
|
12
|
+
readonly windowSeconds: number
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
export declare interface ResendDeps {
|
|
16
|
+
allow: (bucket: ResendBucket, identity?: string) => Promise<boolean>
|
|
17
|
+
active: (email: string) => Promise<License[]>
|
|
18
|
+
send: (licenses: License[]) => Promise<void>
|
|
19
|
+
}
|
|
20
|
+
export declare interface ResendRequest {
|
|
21
|
+
outcome: ResendOutcome
|
|
22
|
+
delivery: Promise<void>
|
|
23
|
+
}
|
|
24
|
+
export type ResendOutcome = 'accepted' | 'invalid' | 'limited';
|
|
25
|
+
export type ResendBucket = keyof typeof RESEND_LIMITS;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{normalizeEmail}from"./keys";export const RESEND_LIMITS={ip:{max:10,windowSeconds:60*60},email:{max:3,windowSeconds:60*60}};const NOTHING=Promise.resolve();export async function requestLicenseResend(rawEmail,deps,ip){if(!await deps.allow("ip",ip))return{outcome:"limited",delivery:NOTHING};const email=normalizeEmail(rawEmail);if(!email)return{outcome:"invalid",delivery:NOTHING};if(!await deps.allow("email",email))return{outcome:"limited",delivery:NOTHING};const delivery=(async()=>{const licenses=await deps.active(email);if(licenses.length)await deps.send(licenses)})().catch((error)=>{console.error(`[licensing] could not resend keys: ${error instanceof Error?error.message:String(error)}`)});return{outcome:"accepted",delivery}}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { LicenseSigningKey, LicenseTier } from './token';
|
|
2
|
+
import type { PaymentEvent } from '@stacksjs/payments';
|
|
3
|
+
/**
|
|
4
|
+
* Defaults for every licensing call in this process. An option passed to a
|
|
5
|
+
* call wins. Set `onIssued` here to send your own license email in place of
|
|
6
|
+
* the framework's.
|
|
7
|
+
*/
|
|
8
|
+
export declare function configureLicensing(options: LicensingOptions): void;
|
|
9
|
+
/**
|
|
10
|
+
* What `onIssued` falls back to when an app configured none: the framework's
|
|
11
|
+
* route files register the default license email here.
|
|
12
|
+
*/
|
|
13
|
+
export declare function registerDefaultLicenseMailer(onIssued: OnLicenseIssued): void;
|
|
14
|
+
/** The signing key from the environment, or null when none is set. */
|
|
15
|
+
export declare function licenseSigningKeyFromEnv(): LicenseSigningKey | null;
|
|
16
|
+
/** The license with this key, however it was typed. */
|
|
17
|
+
export declare function findLicenseByKey(rawKey: unknown): Promise<License | null>;
|
|
18
|
+
/** The license issued for a purchase, for a thank-you page that shows the key. */
|
|
19
|
+
export declare function findLicenseByPurchase(purchaseReference: string): Promise<License | null>;
|
|
20
|
+
/**
|
|
21
|
+
* The license for a purchase, created on first sight. `created` is false when
|
|
22
|
+
* the purchase already had one, in which case nothing is sent again.
|
|
23
|
+
*/
|
|
24
|
+
export declare function issueLicense(input: IssueLicenseInput, options?: LicensingOptions): Promise<{ license: License, created: boolean }>;
|
|
25
|
+
/**
|
|
26
|
+
* The buyer's address, read from what each provider puts in its event. A
|
|
27
|
+
* checkout that sets `metadata.email` is read on any driver; otherwise this
|
|
28
|
+
* knows where Stripe, Lemon Squeezy and Adyen state it.
|
|
29
|
+
*/
|
|
30
|
+
export declare function buyerEmailFromEvent(event: PaymentEvent): string | null;
|
|
31
|
+
/**
|
|
32
|
+
* Apply a verified payment event to licensing, from whichever driver verified
|
|
33
|
+
* it. The framework's `POST /webhooks/payments` calls this for every event.
|
|
34
|
+
*
|
|
35
|
+
* - `checkout.completed` or `payment.succeeded` whose `merchantReference` is a
|
|
36
|
+
* {@link licensePurchaseReference}: the license is issued, once. A later
|
|
37
|
+
* event about the same purchase fills in what the first did not carry (the
|
|
38
|
+
* buyer's address, the payment's id) and sends the email if it could not be
|
|
39
|
+
* sent before.
|
|
40
|
+
* - `refund.succeeded` for a license's payment: the refund is added, and the
|
|
41
|
+
* license is marked `refunded` once it covers what was paid.
|
|
42
|
+
*
|
|
43
|
+
* Anything else answers `ignored`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function handleLicensePaymentEvent(event: PaymentEvent, options?: LicensingOptions & { email?: string | null }): Promise<LicenseEventResult>;
|
|
46
|
+
/**
|
|
47
|
+
* Activate a license on a device and answer with its token. Activating a
|
|
48
|
+
* device that is already active refreshes it. Beyond `maxDevices` the answer
|
|
49
|
+
* is `device-limit`, naming the devices in use so the owner knows which to
|
|
50
|
+
* release.
|
|
51
|
+
*/
|
|
52
|
+
export declare function activateLicense(input: ActivateLicenseInput, options?: LicensingOptions): Promise<ActivateLicenseResult>;
|
|
53
|
+
/** Release a device's slot. `released` is false when it held none. */
|
|
54
|
+
export declare function deactivateLicense(input: { key: unknown, deviceHash: unknown }, options?: LicensingOptions): Promise<{ ok: boolean, released: boolean }>;
|
|
55
|
+
/**
|
|
56
|
+
* Where a license stands for a device that activated it, with a fresh token
|
|
57
|
+
* when it is good. `released` means this device holds no slot (it was
|
|
58
|
+
* released, or never activated) and has to activate again.
|
|
59
|
+
*/
|
|
60
|
+
export declare function checkLicense(input: { key: unknown, deviceHash: unknown, appVersion?: unknown }, options?: LicensingOptions): Promise<CheckLicenseResult>;
|
|
61
|
+
/** The devices active on a license, for an account page. */
|
|
62
|
+
export declare function licenseDevices(rawKey: unknown): Promise<LicenseDeviceSummary[]>;
|
|
63
|
+
/** Stop a license working: `revoked` by hand, or `refunded`. Its devices learn at their next check. */
|
|
64
|
+
export declare function revokeLicense(rawKey: unknown, options?: LicensingOptions & { status?: 'revoked' | 'refunded' }): Promise<License | null>;
|
|
65
|
+
/** Move a team license's end, and a standard license's updates, on renewal. */
|
|
66
|
+
export declare function extendLicense(rawKey: unknown, until: Date, options?: LicensingOptions): Promise<License | null>;
|
|
67
|
+
/**
|
|
68
|
+
* Hand a license to another person. The caller proves they own it by naming
|
|
69
|
+
* the address it is registered to; every device is released, so the new owner
|
|
70
|
+
* starts with all of its slots, and later resends go to the new address.
|
|
71
|
+
*/
|
|
72
|
+
export declare function transferLicense(input: { key: unknown, fromEmail: unknown, toEmail: unknown }, options?: LicensingOptions): Promise<TransferLicenseResult>;
|
|
73
|
+
/** The licenses registered to an address that are good right now, for sending their keys again. */
|
|
74
|
+
export declare function activeLicensesFor(rawEmail: unknown, options?: LicensingOptions): Promise<License[]>;
|
|
75
|
+
/** Who holds a seat on a team license. */
|
|
76
|
+
export declare function licenseSeats(rawKey: unknown): Promise<LicenseSeatSummary[]>;
|
|
77
|
+
/**
|
|
78
|
+
* Give a member of the license's team a seat. The member must be an active
|
|
79
|
+
* `TeamMember` of the `Team` the license belongs to; assigning someone who
|
|
80
|
+
* already has a seat answers with it. Beyond `seats` the answer is
|
|
81
|
+
* `seat-limit`.
|
|
82
|
+
*/
|
|
83
|
+
export declare function assignLicenseSeat(input: { key: unknown, userId: number }, options?: LicensingOptions): Promise<AssignSeatResult>;
|
|
84
|
+
/** Take a member's seat back, releasing the devices activated under it. */
|
|
85
|
+
export declare function unassignLicenseSeat(input: { key: unknown, userId: number }, options?: LicensingOptions): Promise<{ ok: boolean, removed: boolean }>;
|
|
86
|
+
/** A license, in the application's terms. */
|
|
87
|
+
export declare interface License {
|
|
88
|
+
id: string
|
|
89
|
+
rowId: number
|
|
90
|
+
key: string
|
|
91
|
+
tier: LicenseTier
|
|
92
|
+
status: LicenseStatus
|
|
93
|
+
email: string | null
|
|
94
|
+
maxDevices: number
|
|
95
|
+
seats: number
|
|
96
|
+
updatesUntil: string | null
|
|
97
|
+
expiresAt: string | null
|
|
98
|
+
purchaseReference: string | null
|
|
99
|
+
paymentReference: string | null
|
|
100
|
+
provider: string | null
|
|
101
|
+
amountPaid: number | null
|
|
102
|
+
amountRefunded: number
|
|
103
|
+
currency: string | null
|
|
104
|
+
customerId: number | null
|
|
105
|
+
productId: number | null
|
|
106
|
+
orderId: number | null
|
|
107
|
+
teamId: number | null
|
|
108
|
+
revokedAt: string | null
|
|
109
|
+
}
|
|
110
|
+
export declare interface LicenseDeviceSummary {
|
|
111
|
+
name: string | null
|
|
112
|
+
platform: string | null
|
|
113
|
+
lastSeenAt: string | null
|
|
114
|
+
}
|
|
115
|
+
/** What a device is told about its license. */
|
|
116
|
+
export declare interface LicenseStandingSummary {
|
|
117
|
+
id: string
|
|
118
|
+
tier: LicenseTier
|
|
119
|
+
status: LicenseStatus
|
|
120
|
+
updatesUntil: string | null
|
|
121
|
+
expiresAt: string | null
|
|
122
|
+
maxDevices: number
|
|
123
|
+
devices: number
|
|
124
|
+
seats: number
|
|
125
|
+
}
|
|
126
|
+
export declare interface LicenseSeatSummary {
|
|
127
|
+
userId: number
|
|
128
|
+
teamMemberId: number | null
|
|
129
|
+
email: string
|
|
130
|
+
assignedAt: string | null
|
|
131
|
+
}
|
|
132
|
+
export declare interface LicensingOptions {
|
|
133
|
+
now?: () => Date
|
|
134
|
+
signingKey?: LicenseSigningKey
|
|
135
|
+
onIssued?: OnLicenseIssued
|
|
136
|
+
termYears?: number
|
|
137
|
+
}
|
|
138
|
+
export declare interface IssueLicenseInput {
|
|
139
|
+
purchaseReference: string
|
|
140
|
+
tier: LicenseTier
|
|
141
|
+
email?: string | null
|
|
142
|
+
seats?: number
|
|
143
|
+
maxDevices?: number
|
|
144
|
+
updatesUntil?: Date | null
|
|
145
|
+
expiresAt?: Date | null
|
|
146
|
+
productId?: number | null
|
|
147
|
+
customerId?: number | null
|
|
148
|
+
orderId?: number | null
|
|
149
|
+
teamId?: number | null
|
|
150
|
+
provider?: string | null
|
|
151
|
+
paymentReference?: string | null
|
|
152
|
+
amountPaid?: number | null
|
|
153
|
+
currency?: string | null
|
|
154
|
+
}
|
|
155
|
+
export declare interface LicenseEventResult {
|
|
156
|
+
action: LicenseEventAction
|
|
157
|
+
license?: License
|
|
158
|
+
}
|
|
159
|
+
export declare interface ActivateLicenseInput {
|
|
160
|
+
key: unknown
|
|
161
|
+
deviceHash: unknown
|
|
162
|
+
deviceName?: unknown
|
|
163
|
+
platform?: unknown
|
|
164
|
+
appVersion?: unknown
|
|
165
|
+
email?: unknown
|
|
166
|
+
}
|
|
167
|
+
export type LicenseStatus = 'active' | 'inactive' | 'unassigned' | 'revoked' | 'refunded';
|
|
168
|
+
export type OnLicenseIssued = (license: License) => Promise<void> | void;
|
|
169
|
+
export type LicenseEventAction = 'issued' | 'existing' | 'refunded' | 'partially-refunded' | 'ignored';
|
|
170
|
+
export type ActivateLicenseResult = | { ok: true, key: string, token: string, license: LicenseStandingSummary }
|
|
171
|
+
| {
|
|
172
|
+
ok: false
|
|
173
|
+
reason: 'not-found' | 'invalid-device' | 'revoked' | 'refunded' | 'inactive' | 'expired' | 'no-seat' | 'device-limit'
|
|
174
|
+
message: string
|
|
175
|
+
/** With `device-limit`: the devices holding the slots. */
|
|
176
|
+
devices?: LicenseDeviceSummary[]
|
|
177
|
+
}
|
|
178
|
+
export type CheckLicenseResult = | { valid: true, token: string, license: LicenseStandingSummary }
|
|
179
|
+
| { valid: false, reason: 'not-found' | 'revoked' | 'refunded' | 'inactive' | 'expired' | 'released', message: string }
|
|
180
|
+
export type TransferLicenseResult = | { ok: true, license: License }
|
|
181
|
+
| { ok: false, reason: 'not-found' | 'not-owner' | 'invalid-email' | 'revoked' | 'refunded' | 'inactive' | 'expired', message: string }
|
|
182
|
+
export type AssignSeatResult = | { ok: true, seat: LicenseSeatSummary }
|
|
183
|
+
| { ok: false, reason: 'not-found' | 'not-a-team-license' | 'not-a-member' | 'seat-limit', message: string }
|
|
184
|
+
/** The signing key is not configured, so no token can be issued. */
|
|
185
|
+
export declare class LicensingNotConfiguredError extends Error {
|
|
186
|
+
constructor();
|
|
187
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUIDv7}from"bun";import{db as typedDb,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{generateLicenseKey,normalizeEmail,normalizeLicenseKey,parseLicensePurchaseReference}from"./keys";import{signLicenseToken}from"./token";const db=typedDb;export class LicensingNotConfiguredError extends Error{constructor(){super("Licenses cannot be signed without a key: run `buddy license:keygen` and set LICENSE_SIGNING_KEY and LICENSE_SIGNING_KEY_ID.");this.name="LicensingNotConfiguredError"}}const TEMPLATES={standard:"Standard License",lifetime:"Premium License",team:"Enterprise License"};let configured={};let fallbackOnIssued;export function configureLicensing(options){configured={...configured,...options}}export function registerDefaultLicenseMailer(onIssued){fallbackOnIssued=onIssued}export function licenseSigningKeyFromEnv(){const source=env;const privateKey=source.LICENSE_SIGNING_KEY;if(!privateKey)return null;return{privateKey,keyId:source.LICENSE_SIGNING_KEY_ID||"license-1"}}function resolve(options){const merged={...configured,...options};return{now:merged.now??(()=>new Date),signingKey:()=>{const key=merged.signingKey??licenseSigningKeyFromEnv();if(!key)throw new LicensingNotConfiguredError;return key},onIssued:merged.onIssued??fallbackOnIssued,termYears:merged.termYears??1}}function isoOrNull(value){return parseSqlDateTime(value)?.toISOString()??null}function numberOrNull(value){return value===null||value===undefined?null:Number(value)}function toLicense(row){return{id:String(row.uuid),rowId:Number(row.id),key:String(row.key),tier:row.tier??"standard",status:row.status??"unassigned",email:row.email??null,maxDevices:Number(row.max_devices??2),seats:Number(row.seats??1),updatesUntil:isoOrNull(row.updates_until),expiresAt:isoOrNull(row.expiry_date),purchaseReference:row.purchase_reference??null,paymentReference:row.payment_reference??null,provider:row.provider??null,amountPaid:numberOrNull(row.amount_paid),amountRefunded:Number(row.amount_refunded??0),currency:row.currency??null,customerId:numberOrNull(row.customer_id),productId:numberOrNull(row.product_id),orderId:numberOrNull(row.order_id),teamId:numberOrNull(row.team_id),revokedAt:isoOrNull(row.revoked_at)}}function isUniqueViolation(error){const e=error;const message=e?.message??"";return e?.code==="23505"||message.includes("UNIQUE constraint")||message.includes("Duplicate entry")||/duplicate key value/i.test(message)}function addYears(date,years){const next=new Date(date.getTime());next.setUTCFullYear(next.getUTCFullYear()+years);return next}async function emit(name,license){try{const mod=await import("@stacksjs/events");mod.dispatch?.(name,{license})}catch{}}async function rowByKey(key,trx=db){return await trx.selectFrom("license_keys").where("key","=",key).selectAll().executeTakeFirst()??null}async function rowById(id,trx=db){return await trx.selectFrom("license_keys").where("id","=",id).selectAll().executeTakeFirst()??null}export async function findLicenseByKey(rawKey){const key=normalizeLicenseKey(rawKey);const row=key?await rowByKey(key):null;return row?toLicense(row):null}export async function findLicenseByPurchase(purchaseReference){if(!purchaseReference)return null;const row=await db.selectFrom("license_keys").where("purchase_reference","=",purchaseReference).selectAll().executeTakeFirst();return row?toLicense(row):null}async function announce(license,onIssued){await emit("license:issued",license);if(!onIssued||!license.email)return;try{await onIssued(license)}catch(error){console.error(`[licensing] ${license.key.slice(-4)}: could not send the license email: ${error instanceof Error?error.message:String(error)}`)}}export async function issueLicense(input,options){const{now,onIssued,termYears}=resolve(options);if(!input.purchaseReference)throw new Error("A license is issued for a purchase reference");const existing=await findLicenseByPurchase(input.purchaseReference);if(existing)return{license:existing,created:false};const seats=input.seats??1;const maxDevices=input.maxDevices??2;if(!Number.isSafeInteger(seats)||seats<1||!Number.isSafeInteger(maxDevices)||maxDevices<1)throw new Error("A license needs at least one seat and one device");if(input.amountPaid!==undefined&&input.amountPaid!==null&&(!Number.isSafeInteger(input.amountPaid)||input.amountPaid<0))throw new Error("amountPaid is an integer in minor units (cents)");const at=now();const updatesUntil=input.updatesUntil!==undefined?input.updatesUntil:input.tier==="standard"?addYears(at,termYears):null;const expiresAt=input.expiresAt!==undefined?input.expiresAt:input.tier==="team"?addYears(at,termYears):null;const stamp=sqlDateTime(at);for(let attempt=0;;attempt++){try{await db.insertInto("license_keys").values({uuid:randomUUIDv7(),key:generateLicenseKey(),template:TEMPLATES[input.tier],tier:input.tier,status:"active",email:normalizeEmail(input.email),seats,max_devices:maxDevices,updates_until:updatesUntil?sqlDateTime(updatesUntil):null,expiry_date:expiresAt?sqlDateTime(expiresAt):null,purchase_reference:input.purchaseReference,payment_reference:input.paymentReference??null,provider:input.provider??null,amount_paid:input.amountPaid??null,amount_refunded:0,currency:input.currency?.toLowerCase()??null,customer_id:input.customerId??null,product_id:input.productId??null,order_id:input.orderId??null,team_id:input.teamId??null,created_at:stamp,updated_at:stamp}).execute();break}catch(error){if(!isUniqueViolation(error))throw error;const raced=await findLicenseByPurchase(input.purchaseReference);if(raced)return{license:raced,created:false};if(attempt>=3)throw error}}const license=await findLicenseByPurchase(input.purchaseReference);await announce(license,onIssued);return{license,created:true}}export function buyerEmailFromEvent(event){const raw=event.raw??{};const object=raw.data?.object??raw.data??raw;const candidates=[object?.metadata?.email,object?.custom_data?.email,raw.meta?.custom_data?.email,object?.customer_details?.email,object?.customer_email,object?.receipt_email,object?.billing_details?.email,object?.attributes?.user_email,raw.additionalData?.shopperEmail];for(const candidate of candidates){const email=normalizeEmail(candidate);if(email)return email}return null}export async function handleLicensePaymentEvent(event,options){if(event.type==="refund.succeeded")return applyRefund(event,options);if(event.type!=="checkout.completed"&&event.type!=="payment.succeeded")return{action:"ignored"};const purchase=parseLicensePurchaseReference(event.merchantReference);if(!purchase)return{action:"ignored"};const paymentStatus=event.raw?.data?.object?.payment_status;if(event.type==="checkout.completed"&&paymentStatus==="unpaid")return{action:"ignored"};const reference=event.merchantReference;const email=normalizeEmail(options?.email)??buyerEmailFromEvent(event);const isPayment=event.type==="payment.succeeded";const{license,created}=await issueLicense({purchaseReference:reference,tier:purchase.tier,seats:purchase.seats,productId:purchase.productId,email,provider:event.provider,paymentReference:event.reference,amountPaid:event.amount?.amount??null,currency:event.amount?.currency??null},options);if(created)return{action:"issued",license};const patch={};if(!license.email&&email)patch.email=email;if(event.reference&&(isPayment?license.paymentReference!==event.reference&&license.provider===event.provider:!license.paymentReference))patch.payment_reference=event.reference;if(license.amountPaid===null&&event.amount){patch.amount_paid=event.amount.amount;patch.currency=event.amount.currency}if(!Object.keys(patch).length)return{action:"existing",license};const{now,onIssued}=resolve(options);await db.updateTable("license_keys").set({...patch,updated_at:sqlDateTime(now())}).where("id","=",license.rowId).execute();const updated=toLicense(await rowById(license.rowId));if(patch.email&&onIssued){try{await onIssued(updated)}catch(error){console.error(`[licensing] ${updated.key.slice(-4)}: could not send the license email: ${error instanceof Error?error.message:String(error)}`)}}return{action:"existing",license:updated}}async function applyRefund(event,options){const{now}=resolve(options);let row=null;if(event.reference)row=await db.selectFrom("license_keys").where("payment_reference","=",event.reference).selectAll().executeTakeFirst()??null;if(!row&&parseLicensePurchaseReference(event.merchantReference))row=await db.selectFrom("license_keys").where("purchase_reference","=",event.merchantReference).selectAll().executeTakeFirst()??null;if(!row)return{action:"ignored"};const licenseId=Number(row.id);let outcome="ignored";await db.transaction(async(trx)=>{const stamp=sqlDateTime(now());try{await trx.insertInto("payment_webhook_events").values({provider:event.provider,event_id:`license:${event.id}`.slice(0,512),processed_at:stamp,created_at:stamp}).execute()}catch(error){if(isUniqueViolation(error))return;throw error}const current=await rowById(licenseId,trx);if(!current||current.status==="refunded")return;const already=Number(current.amount_refunded??0);const paid=numberOrNull(current.amount_paid);const stated=event.refundedTotal?.amount;const total=stated!==undefined?Math.max(stated,already):already+(event.amount?.amount??0);const full=paid===null||stated===undefined&&!event.amount||total>=paid;if(!full&&total===already)return;await trx.updateTable("license_keys").set({amount_refunded:total,...full?{status:"refunded",revoked_at:stamp}:{},updated_at:stamp}).where("id","=",licenseId).execute();outcome=full?"refunded":"partially-refunded"});if(outcome==="ignored")return{action:"ignored"};const license=toLicense(await rowById(licenseId));if(outcome==="refunded")await emit("license:revoked",license);return{action:outcome,license}}function blocked(license,at){if(license.status==="revoked"||license.status==="refunded"||license.status==="inactive")return license.status;if(license.expiresAt&&at.getTime()>Date.parse(license.expiresAt))return"expired";return null}const BLOCKED_MESSAGES={revoked:"This license has been revoked.",refunded:"This license was refunded.",inactive:"This license is not active.",expired:"This license has expired.","not-found":"That license key was not found."};function isTeam(license){return license.tier==="team"}async function activeActivations(licenseId,seatId,trx=db){let query=trx.selectFrom("license_activations").where("license_key_id","=",licenseId).whereNull("released_at");if(seatId!==null)query=query.where("license_seat_id","=",seatId);return await query.selectAll().execute()}function summary(license,devices){return{id:license.id,tier:license.tier,status:license.status,updatesUntil:license.updatesUntil,expiresAt:license.expiresAt,maxDevices:license.maxDevices,devices,seats:license.seats}}function sign(license,deviceHash,at,key){return signLicenseToken({licenseId:license.id,tier:license.tier,updatesUntil:license.updatesUntil,expiresAt:license.expiresAt,deviceHash,issuedAt:at},key)}function clip(value,max){return typeof value==="string"&&value.trim()?value.trim().slice(0,max):null}export async function activateLicense(input,options){const{now,signingKey}=resolve(options);const key=normalizeLicenseKey(input.key);if(!key)return{ok:false,reason:"not-found",message:BLOCKED_MESSAGES["not-found"]};if(typeof input.deviceHash!=="string"||!/^[a-f0-9]{64}$/.test(input.deviceHash))return{ok:false,reason:"invalid-device",message:"A device is identified by the SHA-256 of its id."};const deviceHash=input.deviceHash;const signer=signingKey();const at=now();const stamp=sqlDateTime(at);return await db.transaction(async(trx)=>{const row=await rowByKey(key,trx);if(!row)return{ok:false,reason:"not-found",message:BLOCKED_MESSAGES["not-found"]};let license=toLicense(row);const reason=blocked(license,at);if(reason)return{ok:false,reason,message:BLOCKED_MESSAGES[reason]};let seatId=null;if(isTeam(license)){const email=normalizeEmail(input.email);const seat=email?await trx.selectFrom("license_seats").where("license_key_id","=",license.rowId).where("email","=",email).selectAll().executeTakeFirst():null;if(!seat)return{ok:false,reason:"no-seat",message:"This is a team license. Ask the team's owner to assign you a seat, then activate with that address."};seatId=Number(seat.id)}const existing=await trx.selectFrom("license_activations").where("license_key_id","=",license.rowId).where("device_hash","=",deviceHash).selectAll().executeTakeFirst();const others=(await activeActivations(license.rowId,seatId,trx)).filter((activation)=>activation.device_hash!==deviceHash);if(others.length>=license.maxDevices){const devices=others.map((activation)=>({name:activation.device_name??null,platform:activation.platform??null,lastSeenAt:isoOrNull(activation.last_seen_at)}));const names=devices.map((device)=>device.name||"an unnamed device").join(" and ");return{ok:false,reason:"device-limit",message:`This license is already in use on ${devices.length} ${devices.length===1?"device":"devices"}: ${names}. Release one of them to activate here.`,devices}}const fields={device_name:clip(input.deviceName,255),platform:clip(input.platform,32),app_version:clip(input.appVersion,64),license_seat_id:seatId,last_seen_at:stamp,released_at:null,updated_at:stamp};if(existing){await trx.updateTable("license_activations").set(fields).where("id","=",existing.id).execute()}else{await trx.insertInto("license_activations").values({...fields,license_key_id:license.rowId,device_hash:deviceHash,first_seen_at:stamp,created_at:stamp}).execute()}if(license.status==="unassigned"){await trx.updateTable("license_keys").set({status:"active",updated_at:stamp}).where("id","=",license.rowId).execute();license={...license,status:"active"}}return{ok:true,key:license.key,token:sign(license,deviceHash,at,signer),license:summary(license,others.length+1)}})}export async function deactivateLicense(input,options){const{now}=resolve(options);const license=await findLicenseByKey(input.key);if(!license||typeof input.deviceHash!=="string")return{ok:false,released:false};const activation=await db.selectFrom("license_activations").where("license_key_id","=",license.rowId).where("device_hash","=",input.deviceHash).whereNull("released_at").selectAll().executeTakeFirst();if(!activation)return{ok:true,released:false};const stamp=sqlDateTime(now());await db.updateTable("license_activations").set({released_at:stamp,updated_at:stamp}).where("id","=",activation.id).execute();return{ok:true,released:true}}export async function checkLicense(input,options){const{now,signingKey}=resolve(options);const license=await findLicenseByKey(input.key);if(!license)return{valid:false,reason:"not-found",message:BLOCKED_MESSAGES["not-found"]};const at=now();const reason=blocked(license,at);if(reason)return{valid:false,reason,message:BLOCKED_MESSAGES[reason]};const activation=typeof input.deviceHash==="string"?await db.selectFrom("license_activations").where("license_key_id","=",license.rowId).where("device_hash","=",input.deviceHash).whereNull("released_at").selectAll().executeTakeFirst():null;if(!activation)return{valid:false,reason:"released",message:"This device is not activated on this license."};const signer=signingKey();const stamp=sqlDateTime(at);const appVersion=clip(input.appVersion,64);await db.updateTable("license_activations").set({last_seen_at:stamp,updated_at:stamp,...appVersion?{app_version:appVersion}:{}}).where("id","=",activation.id).execute();const seatId=numberOrNull(activation.license_seat_id);const devices=(await activeActivations(license.rowId,isTeam(license)?seatId:null)).length;return{valid:true,token:sign(license,String(activation.device_hash),at,signer),license:summary(license,devices)}}export async function licenseDevices(rawKey){const license=await findLicenseByKey(rawKey);if(!license)return[];return(await activeActivations(license.rowId,null)).map((activation)=>({name:activation.device_name??null,platform:activation.platform??null,lastSeenAt:isoOrNull(activation.last_seen_at)}))}export async function revokeLicense(rawKey,options){const{now}=resolve(options);const license=await findLicenseByKey(rawKey);if(!license)return null;const stamp=sqlDateTime(now());await db.updateTable("license_keys").set({status:options?.status??"revoked",revoked_at:stamp,updated_at:stamp}).where("id","=",license.rowId).execute();const revoked=toLicense(await rowById(license.rowId));await emit("license:revoked",revoked);return revoked}export async function extendLicense(rawKey,until,options){const{now}=resolve(options);const license=await findLicenseByKey(rawKey);if(!license)return null;const column=license.expiresAt?"expiry_date":license.updatesUntil?"updates_until":null;if(!column)return license;await db.updateTable("license_keys").set({[column]:sqlDateTime(until),updated_at:sqlDateTime(now())}).where("id","=",license.rowId).execute();return toLicense(await rowById(license.rowId))}export async function transferLicense(input,options){const{now,onIssued}=resolve(options);const license=await findLicenseByKey(input.key);const from=normalizeEmail(input.fromEmail);if(!license||!from||license.email!==from)return{ok:false,reason:license?"not-owner":"not-found",message:"That key and address do not match a license."};const to=normalizeEmail(input.toEmail);if(!to)return{ok:false,reason:"invalid-email",message:"The new owner needs a valid email address."};const at=now();const reason=blocked(license,at);if(reason)return{ok:false,reason,message:BLOCKED_MESSAGES[reason]};const stamp=sqlDateTime(at);await db.transaction(async(trx)=>{await trx.updateTable("license_keys").set({email:to,customer_id:null,updated_at:stamp}).where("id","=",license.rowId).execute();await trx.updateTable("license_activations").set({released_at:stamp,updated_at:stamp}).where("license_key_id","=",license.rowId).whereNull("released_at").execute()});const moved=toLicense(await rowById(license.rowId));await emit("license:transferred",moved);if(onIssued){try{await onIssued(moved)}catch(error){console.error(`[licensing] ${moved.key.slice(-4)}: could not send the license email: ${error instanceof Error?error.message:String(error)}`)}}return{ok:true,license:moved}}export async function activeLicensesFor(rawEmail,options){const{now}=resolve(options);const email=normalizeEmail(rawEmail);if(!email)return[];const rows=await db.selectFrom("license_keys").where("email","=",email).selectAll().execute();const at=now();return rows.map(toLicense).filter((license)=>license.status==="active"&&!blocked(license,at))}function toSeat(row){return{userId:Number(row.user_id),teamMemberId:numberOrNull(row.team_member_id),email:String(row.email),assignedAt:isoOrNull(row.assigned_at)}}export async function licenseSeats(rawKey){const license=await findLicenseByKey(rawKey);if(!license)return[];const rows=await db.selectFrom("license_seats").where("license_key_id","=",license.rowId).selectAll().execute();return rows.map(toSeat)}export async function assignLicenseSeat(input,options){const{now}=resolve(options);const license=await findLicenseByKey(input.key);if(!license)return{ok:false,reason:"not-found",message:BLOCKED_MESSAGES["not-found"]};if(!isTeam(license)||!license.teamId)return{ok:false,reason:"not-a-team-license",message:"Seats are assigned on a team license that belongs to a team."};const userId=Number(input.userId);return await db.transaction(async(trx)=>{const member=await trx.selectFrom("team_members").where("team_id","=",license.teamId).where("user_id","=",userId).where("status","=","active").selectAll().executeTakeFirst();const user=member?await trx.selectFrom("users").where("id","=",userId).select(["id","email"]).executeTakeFirst():null;const email=normalizeEmail(user?.email);if(!member||!email)return{ok:false,reason:"not-a-member",message:"Only an active member of the license's team can hold a seat."};const seats=await trx.selectFrom("license_seats").where("license_key_id","=",license.rowId).selectAll().execute();const held=seats.find((seat)=>Number(seat.user_id)===userId);if(held)return{ok:true,seat:toSeat(held)};if(seats.length>=license.seats)return{ok:false,reason:"seat-limit",message:`All ${license.seats} ${license.seats===1?"seat is":"seats are"} assigned. Free one, or add seats to the license.`};const stamp=sqlDateTime(now());await trx.insertInto("license_seats").values({license_key_id:license.rowId,team_member_id:member.id,user_id:userId,email,assigned_at:stamp,created_at:stamp,updated_at:stamp}).execute();const seat=await trx.selectFrom("license_seats").where("license_key_id","=",license.rowId).where("user_id","=",userId).selectAll().executeTakeFirst();return{ok:true,seat:toSeat(seat)}})}export async function unassignLicenseSeat(input,options){const{now}=resolve(options);const license=await findLicenseByKey(input.key);if(!license)return{ok:false,removed:false};return await db.transaction(async(trx)=>{const seat=await trx.selectFrom("license_seats").where("license_key_id","=",license.rowId).where("user_id","=",Number(input.userId)).selectAll().executeTakeFirst();if(!seat)return{ok:true,removed:false};const stamp=sqlDateTime(now());await trx.updateTable("license_activations").set({released_at:stamp,updated_at:stamp}).where("license_key_id","=",license.rowId).where("license_seat_id","=",seat.id).whereNull("released_at").execute();await trx.deleteFrom("license_seats").where("id","=",seat.id).execute();return{ok:true,removed:true}})}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** A new signing keypair, encoded the way `signLicenseToken` and `verifyLicenseToken` read them. */
|
|
2
|
+
export declare function generateLicenseSigningKeypair(keyId?: string): LicenseSigningKeypair;
|
|
3
|
+
/** The SHA-256 of a device id, hex. The server never sees or stores the id itself. */
|
|
4
|
+
export declare function hashDeviceId(deviceId: string): string;
|
|
5
|
+
/** `<base64url payload>.<base64url signature>`. The signature covers the payload bytes exactly as sent. */
|
|
6
|
+
export declare function signLicenseToken(input: SignLicenseTokenInput, key: LicenseSigningKey): string;
|
|
7
|
+
/**
|
|
8
|
+
* The payload of a token signed by a key the app trusts. Throws a
|
|
9
|
+
* {@link LicenseTokenError} naming why not: `malformed`, `unknown-key`,
|
|
10
|
+
* `bad-signature`, or `wrong-device` when `deviceHash` is given and differs.
|
|
11
|
+
*
|
|
12
|
+
* It says nothing about time. Whether the token is still good now is
|
|
13
|
+
* {@link tokenStanding}; which builds it unlocks is {@link isEntitled}.
|
|
14
|
+
*/
|
|
15
|
+
export declare function verifyLicenseToken(token: string, publicKeys: LicensePublicKeys, deviceHash?: string): LicenseTokenPayload;
|
|
16
|
+
/**
|
|
17
|
+
* The entitlement rule: does this license unlock the paid features of a build
|
|
18
|
+
* released on `buildDate`?
|
|
19
|
+
*
|
|
20
|
+
* Yes for a lifetime license, and for any license with no end to its updates.
|
|
21
|
+
* Otherwise yes exactly when the build was released on or before
|
|
22
|
+
* `updatesUntil`: a standard license keeps every build from its year of
|
|
23
|
+
* updates for good (the perpetual fallback) and none after it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isEntitled(license: EntitlementFields, buildDate: Date | string): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Where a verified token stands at `now` for a build released on `buildDate`.
|
|
28
|
+
*
|
|
29
|
+
* - A token for a license that is owned outright (no `expiresAt`) never
|
|
30
|
+
* expires for the builds it covers, online or not.
|
|
31
|
+
* - Any other token works until its license expires, and offline until
|
|
32
|
+
* `checkBy` (30 days after it was issued).
|
|
33
|
+
* - `recheckDue` turns true 7 days after the last successful check.
|
|
34
|
+
*/
|
|
35
|
+
export declare function tokenStanding(payload: LicenseTokenPayload, options: { buildDate: Date | string, now?: Date, lastCheckedAt?: Date | string | null }): TokenStanding;
|
|
36
|
+
/** How long a token works with no check-in. */
|
|
37
|
+
export declare const OFFLINE_GRACE_DAYS: 30;
|
|
38
|
+
/** How often an online app asks the server again. */
|
|
39
|
+
export declare const RECHECK_DAYS: 7;
|
|
40
|
+
/** What the signature covers. Dates are ISO 8601 UTC strings. */
|
|
41
|
+
export declare interface LicenseTokenPayload {
|
|
42
|
+
v: 1
|
|
43
|
+
kid: string
|
|
44
|
+
licenseId: string
|
|
45
|
+
tier: LicenseTier
|
|
46
|
+
updatesUntil: string | null
|
|
47
|
+
expiresAt: string | null
|
|
48
|
+
deviceHash: string
|
|
49
|
+
issuedAt: string
|
|
50
|
+
checkBy: string
|
|
51
|
+
}
|
|
52
|
+
export declare interface LicenseSigningKey {
|
|
53
|
+
privateKey: string
|
|
54
|
+
keyId: string
|
|
55
|
+
}
|
|
56
|
+
export declare interface LicenseSigningKeypair {
|
|
57
|
+
keyId: string
|
|
58
|
+
privateKey: string
|
|
59
|
+
publicKey: string
|
|
60
|
+
}
|
|
61
|
+
export declare interface SignLicenseTokenInput {
|
|
62
|
+
licenseId: string
|
|
63
|
+
tier: LicenseTier
|
|
64
|
+
updatesUntil: Date | string | null
|
|
65
|
+
expiresAt?: Date | string | null
|
|
66
|
+
deviceHash: string
|
|
67
|
+
issuedAt?: Date
|
|
68
|
+
graceDays?: number
|
|
69
|
+
}
|
|
70
|
+
export declare interface TokenStanding {
|
|
71
|
+
licensed: boolean
|
|
72
|
+
pro: boolean
|
|
73
|
+
reason: TokenStandingReason
|
|
74
|
+
perpetual: boolean
|
|
75
|
+
recheckDue: boolean
|
|
76
|
+
}
|
|
77
|
+
export type LicenseTier = 'standard' | 'lifetime' | 'team';
|
|
78
|
+
/** Key id to `ed25519-public:` key, the same shape the updater's `trustedKeys` takes. */
|
|
79
|
+
export type LicensePublicKeys = Record<string, string>;
|
|
80
|
+
export type LicenseTokenFailure = | 'malformed'
|
|
81
|
+
| 'unknown-key'
|
|
82
|
+
| 'bad-signature'
|
|
83
|
+
| 'wrong-device';
|
|
84
|
+
declare type EntitlementFields = Pick<LicenseTokenPayload, 'tier' | 'updatesUntil'>;
|
|
85
|
+
export type TokenStandingReason = 'ok' | 'expired' | 'check-overdue' | 'not-entitled';
|
|
86
|
+
export declare class LicenseTokenError extends Error {
|
|
87
|
+
readonly reason: LicenseTokenFailure;
|
|
88
|
+
constructor(reason: LicenseTokenFailure, message: string);
|
|
89
|
+
}
|
|
90
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash,createPrivateKey,createPublicKey,generateKeyPairSync,sign,verify}from"node:crypto";export class LicenseTokenError extends Error{reason;constructor(reason,message){super(message);this.name="LicenseTokenError";this.reason=reason}}const PUBLIC_PREFIX="ed25519-public:";const PRIVATE_PREFIX="ed25519-private:";const KEY_ID=/^[\w.-]+$/;const DAY_MS=24*60*60*1000;export const OFFLINE_GRACE_DAYS=30;export const RECHECK_DAYS=7;export function generateLicenseSigningKeypair(keyId=`license-${new Date().toISOString().slice(0,10)}`){if(!KEY_ID.test(keyId))throw new Error("A license signing key id may only use letters, numbers, dots, dashes and underscores");const{privateKey,publicKey}=generateKeyPairSync("ed25519");return{keyId,privateKey:`${PRIVATE_PREFIX}${privateKey.export({format:"der",type:"pkcs8"}).toString("base64url")}`,publicKey:`${PUBLIC_PREFIX}${publicKey.export({format:"der",type:"spki"}).toString("base64url")}`}}export function hashDeviceId(deviceId){return createHash("sha256").update(deviceId,"utf8").digest("hex")}function iso(value){if(value===null||value===undefined)return null;const date=value instanceof Date?value:new Date(value);if(Number.isNaN(date.getTime()))throw new Error(`Not a date: ${String(value)}`);return date.toISOString()}export function signLicenseToken(input,key){if(!KEY_ID.test(key.keyId))throw new Error("The license signing key id is not valid");if(!key.privateKey.startsWith(PRIVATE_PREFIX))throw new Error("The license signing key has an invalid encoding: expected ed25519-private:<base64url>");if(!/^[a-f0-9]{64}$/.test(input.deviceHash))throw new Error("A license token needs the SHA-256 of a device id");const privateKey=createPrivateKey({key:Buffer.from(key.privateKey.slice(PRIVATE_PREFIX.length),"base64url"),format:"der",type:"pkcs8"});if(privateKey.asymmetricKeyType!=="ed25519")throw new Error("The license signing key is not an Ed25519 key");const issuedAt=input.issuedAt??new Date;const payload={v:1,kid:key.keyId,licenseId:input.licenseId,tier:input.tier,updatesUntil:iso(input.updatesUntil),expiresAt:iso(input.expiresAt),deviceHash:input.deviceHash,issuedAt:issuedAt.toISOString(),checkBy:new Date(issuedAt.getTime()+(input.graceDays??OFFLINE_GRACE_DAYS)*DAY_MS).toISOString()};const body=Buffer.from(JSON.stringify(payload),"utf8");return`${body.toString("base64url")}.${sign(null,body,privateKey).toString("base64url")}`}function isIsoOrNull(value){return value===null||typeof value==="string"&&!Number.isNaN(Date.parse(value))}export function verifyLicenseToken(token,publicKeys,deviceHash){const parts=typeof token==="string"?token.split("."):[];if(parts.length!==2||!parts.every((part)=>/^[\w-]+$/.test(part)))throw new LicenseTokenError("malformed","The license token is not in the expected format");const body=Buffer.from(parts[0],"base64url");let payload;try{payload=JSON.parse(body.toString("utf8"))}catch{throw new LicenseTokenError("malformed","The license token payload is not JSON")}if(!payload||typeof payload!=="object"||payload.v!==1||typeof payload.kid!=="string"||!KEY_ID.test(payload.kid))throw new LicenseTokenError("malformed","The license token payload is not a version 1 payload");const encodedKey=Object.hasOwn(publicKeys,payload.kid)?publicKeys[payload.kid]:undefined;if(!encodedKey)throw new LicenseTokenError("unknown-key",`The license token is signed by a key this app does not trust: ${payload.kid}`);if(!encodedKey.startsWith(PUBLIC_PREFIX))throw new LicenseTokenError("unknown-key","The license public key has an invalid encoding: expected ed25519-public:<base64url>");let good=false;try{const publicKey=createPublicKey({key:Buffer.from(encodedKey.slice(PUBLIC_PREFIX.length),"base64url"),format:"der",type:"spki"});const signature=Buffer.from(parts[1],"base64url");good=publicKey.asymmetricKeyType==="ed25519"&&signature.length===64&&verify(null,body,publicKey,signature)}catch{good=false}if(!good)throw new LicenseTokenError("bad-signature","The license token signature does not verify");const shapeOk=typeof payload.licenseId==="string"&&["standard","lifetime","team"].includes(payload.tier)&&isIsoOrNull(payload.updatesUntil)&&isIsoOrNull(payload.expiresAt)&&typeof payload.deviceHash==="string"&&typeof payload.issuedAt==="string"&&isIsoOrNull(payload.issuedAt)&&typeof payload.checkBy==="string"&&isIsoOrNull(payload.checkBy);if(!shapeOk)throw new LicenseTokenError("malformed","The license token payload is missing fields");if(deviceHash!==undefined&&payload.deviceHash!==deviceHash)throw new LicenseTokenError("wrong-device","The license token was issued to another device");return payload}export function isEntitled(license,buildDate){if(license.tier==="lifetime"||license.updatesUntil===null)return true;const build=buildDate instanceof Date?buildDate.getTime():Date.parse(buildDate);const until=Date.parse(license.updatesUntil);if(Number.isNaN(build)||Number.isNaN(until))return false;return build<=until}export function tokenStanding(payload,options){const now=(options.now??new Date).getTime();const entitled=isEntitled(payload,options.buildDate);const perpetual=payload.expiresAt===null;const last=options.lastCheckedAt?new Date(options.lastCheckedAt).getTime():Date.parse(payload.issuedAt);const recheckDue=Number.isNaN(last)||now-last>=RECHECK_DAYS*DAY_MS;if(perpetual){return{licensed:true,pro:entitled,reason:entitled?"ok":"not-entitled",perpetual,recheckDue}}if(now>Date.parse(payload.expiresAt))return{licensed:false,pro:false,reason:"expired",perpetual,recheckDue:true};if(now>Date.parse(payload.checkBy))return{licensed:false,pro:false,reason:"check-overdue",perpetual,recheckDue:true};return{licensed:true,pro:entitled,reason:entitled?"ok":"not-entitled",perpetual,recheckDue}}
|
package/dist/orders/webhook.d.ts
CHANGED
|
@@ -33,7 +33,8 @@ declare function handleRefundSucceeded(event: PaymentEvent): Promise<void>;
|
|
|
33
33
|
export declare function handleCommercePaymentEvent(event: PaymentEvent): Promise<boolean>;
|
|
34
34
|
/**
|
|
35
35
|
* A provider's webhook delivery, start to finish: verified by the payment
|
|
36
|
-
* driver, applied to orders, answered the way the provider
|
|
36
|
+
* driver, applied to orders and to licenses, answered the way the provider
|
|
37
|
+
* expects. This is
|
|
37
38
|
* what the framework mounts at `POST /webhooks/payments`.
|
|
38
39
|
*
|
|
39
40
|
* - No webhook secret configured: 401 `missing-config`, so nothing
|
package/dist/orders/webhook.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{canTransition,emitOrderCancelled,emitOrderPaid,emitOrderRefunded}from"./events";async function findOrderByPaymentIntent(paymentIntentId){const payment=await db.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return null;const order=await db.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();return order??null}let warnedAboutMissingDedupTable=false;async function recordEventOrSkip(event,trx){try{const now=formatDate(new Date);await trx.insertInto("payment_webhook_events").values({provider:event.provider,event_id:event.id,processed_at:now,created_at:now}).execute();return true}catch(err){if(isUniqueViolation(err))return false;if(isMissingTableError(err)){if(!warnedAboutMissingDedupTable){warnedAboutMissingDedupTable=true;console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.")}return true}throw err}}function isMissingTableError(err){const e=err;const msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isUniqueViolation(err){const e=err;const msg=e?.message??"";return e?.code==="23505"||msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry")||/duplicate key value/i.test(msg)}async function handlePaymentSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"succeeded",updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"PROCESSING",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderPaid(order)}async function handlePaymentFailed(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const reason=event.reason??"payment failed";await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"failed",failure_reason:reason.slice(0,1000),updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"CANCELLED",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderCancelled(order,reason)}async function handleRefundSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const statedTotal=event.refundedTotal?.amount;const given=statedTotal??event.amount?.amount??0;if(!Number.isSafeInteger(given)||given<=0)return;let fullyRefunded=false;let applied=false;let refundAmount=0;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const already=Number(payment.refund_amount??0);refundAmount=statedTotal===undefined?given:statedTotal-already;if(refundAmount<=0)return;const total=already+refundAmount;if(total>Number(payment.amount)){console.warn(`[commerce/webhook] ${event.provider} refunded ${refundAmount} of payment ${payment.id}, which has ${Number(payment.amount)-already} left to refund; not recorded.`);return}fullyRefunded=total===Number(payment.amount);const now=formatDate(new Date);await trx.updateTable("payments").set({status:fullyRefunded?"refunded":"partiallyRefunded",refund_amount:total,updated_at:now}).where("id","=",payment.id).execute();applied=true;if(!fullyRefunded)return;const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&canTransition(order.status,"REFUNDED")){await trx.updateTable("orders").set({status:"REFUNDED",updated_at:now}).where("id","=",order.id).execute()}});if(!applied)return;const order=await findOrderByPaymentIntent(paymentIntentId);if(order&&fullyRefunded)await emitOrderRefunded(order,refundAmount)}export async function handleCommercePaymentEvent(event){switch(event.type){case"payment.succeeded":await handlePaymentSucceeded(event);return true;case"payment.failed":await handlePaymentFailed(event);return true;case"refund.succeeded":await handleRefundSucceeded(event);return true;default:return false}}export async function receivePaymentWebhook(request,driver){const{paymentDriver,WebhookNotConfiguredError,WebhookSignatureError}=await import("@stacksjs/payments");const payments=driver??paymentDriver();let events;try{events=await payments.verifyWebhook({payload:await request.text(),headers:request.headers})}catch(error){if(error instanceof WebhookNotConfiguredError)return Response.json({ok:false,reason:"missing-config"},{status:401});if(error instanceof WebhookSignatureError)return Response.json({ok:false,reason:"invalid-signature"},{status:400});throw error}for(const event of events)await handleCommercePaymentEvent(event);return payments.acknowledgeWebhook()}export{handlePaymentFailed,handlePaymentSucceeded,handleRefundSucceeded};
|
|
1
|
+
import{db}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{canTransition,emitOrderCancelled,emitOrderPaid,emitOrderRefunded}from"./events";import{handleLicensePaymentEvent}from"../licensing/service";async function findOrderByPaymentIntent(paymentIntentId){const payment=await db.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return null;const order=await db.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();return order??null}let warnedAboutMissingDedupTable=false;async function recordEventOrSkip(event,trx){try{const now=formatDate(new Date);await trx.insertInto("payment_webhook_events").values({provider:event.provider,event_id:event.id,processed_at:now,created_at:now}).execute();return true}catch(err){if(isUniqueViolation(err))return false;if(isMissingTableError(err)){if(!warnedAboutMissingDedupTable){warnedAboutMissingDedupTable=true;console.warn("[commerce/webhook] payment_webhook_events table missing - provider retries will be applied again. Run `buddy migrate` to enable dedup.")}return true}throw err}}function isMissingTableError(err){const e=err;const msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isUniqueViolation(err){const e=err;const msg=e?.message??"";return e?.code==="23505"||msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry")||/duplicate key value/i.test(msg)}async function handlePaymentSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"succeeded",updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"PROCESSING",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderPaid(order)}async function handlePaymentFailed(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const reason=event.reason??"payment failed";await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const now=formatDate(new Date);await trx.updateTable("payments").set({status:"failed",failure_reason:reason.slice(0,1000),updated_at:now}).where("id","=",payment.id).execute();const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&order.status==="PENDING"){await trx.updateTable("orders").set({status:"CANCELLED",updated_at:now}).where("id","=",order.id).execute()}});const order=await findOrderByPaymentIntent(paymentIntentId);if(order)await emitOrderCancelled(order,reason)}async function handleRefundSucceeded(event){const paymentIntentId=event.reference;if(!paymentIntentId)return;const statedTotal=event.refundedTotal?.amount;const given=statedTotal??event.amount?.amount??0;if(!Number.isSafeInteger(given)||given<=0)return;let fullyRefunded=false;let applied=false;let refundAmount=0;await db.transaction(async(trx)=>{const isNew=await recordEventOrSkip(event,trx);if(!isNew)return;const payment=await trx.selectFrom("payments").where("transaction_id","=",paymentIntentId).selectAll().executeTakeFirst();if(!payment)return;const already=Number(payment.refund_amount??0);refundAmount=statedTotal===undefined?given:statedTotal-already;if(refundAmount<=0)return;const total=already+refundAmount;if(total>Number(payment.amount)){console.warn(`[commerce/webhook] ${event.provider} refunded ${refundAmount} of payment ${payment.id}, which has ${Number(payment.amount)-already} left to refund; not recorded.`);return}fullyRefunded=total===Number(payment.amount);const now=formatDate(new Date);await trx.updateTable("payments").set({status:fullyRefunded?"refunded":"partiallyRefunded",refund_amount:total,updated_at:now}).where("id","=",payment.id).execute();applied=true;if(!fullyRefunded)return;const order=await trx.selectFrom("orders").where("id","=",payment.order_id).selectAll().executeTakeFirst();if(order&&canTransition(order.status,"REFUNDED")){await trx.updateTable("orders").set({status:"REFUNDED",updated_at:now}).where("id","=",order.id).execute()}});if(!applied)return;const order=await findOrderByPaymentIntent(paymentIntentId);if(order&&fullyRefunded)await emitOrderRefunded(order,refundAmount)}export async function handleCommercePaymentEvent(event){switch(event.type){case"payment.succeeded":await handlePaymentSucceeded(event);return true;case"payment.failed":await handlePaymentFailed(event);return true;case"refund.succeeded":await handleRefundSucceeded(event);return true;default:return false}}export async function receivePaymentWebhook(request,driver){const{paymentDriver,WebhookNotConfiguredError,WebhookSignatureError}=await import("@stacksjs/payments");const payments=driver??paymentDriver();let events;try{events=await payments.verifyWebhook({payload:await request.text(),headers:request.headers})}catch(error){if(error instanceof WebhookNotConfiguredError)return Response.json({ok:false,reason:"missing-config"},{status:401});if(error instanceof WebhookSignatureError)return Response.json({ok:false,reason:"invalid-signature"},{status:400});throw error}for(const event of events){await handleCommercePaymentEvent(event);await handleLicensePaymentEvent(event)}return payments.acknowledgeWebhook()}export{handlePaymentFailed,handlePaymentSucceeded,handleRefundSucceeded};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";const templates=["Standard License","Premium License","Enterprise License"];const statuses=["active","inactive","unassigned"];export class LicenseKeyInputError extends TypeError{constructor(message){super(message);this.name="LicenseKeyInputError"}}function mergedValue(input,current,key){return input[key]!==undefined?input[key]:current?.[key]}function optionalId(input,current,key,label){const value=mergedValue(input,current,key);if(value===undefined||value===null||value==="")return null;const id=Number(value);if(!Number.isSafeInteger(id)||id<1)throw new LicenseKeyInputError(`${label} must be a positive integer or null.`);return id}function expiryTimestamp(value){if(value instanceof Date)return Math.floor(value.getTime()/1000);if(typeof value==="number")return value>2147483647?Math.floor(value/1000):value;if(typeof value==="string"&&/^\d{10,13}$/.test(value))return value.length===13?Math.floor(Number(value)/1000):Number(value);if(typeof value==="string"){const parsed=parseSqlDateTime(value);return parsed?Math.floor(parsed.getTime()/1000):Number.NaN}return Number.NaN}export async function validateLicenseKeyWrite(input,current){const key=String(mergedValue(input,current,"key")||"").trim().toUpperCase();const template=String(mergedValue(input,current,"template")||"");const status=String(mergedValue(input,current,"status")||"");const
|
|
1
|
+
import{db,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";const templates=["Standard License","Premium License","Enterprise License"];const statuses=["active","inactive","unassigned","revoked","refunded"];export class LicenseKeyInputError extends TypeError{constructor(message){super(message);this.name="LicenseKeyInputError"}}function mergedValue(input,current,key){return input[key]!==undefined?input[key]:current?.[key]}function optionalId(input,current,key,label){const value=mergedValue(input,current,key);if(value===undefined||value===null||value==="")return null;const id=Number(value);if(!Number.isSafeInteger(id)||id<1)throw new LicenseKeyInputError(`${label} must be a positive integer or null.`);return id}function expiryTimestamp(value){if(value instanceof Date)return Math.floor(value.getTime()/1000);if(typeof value==="number")return value>2147483647?Math.floor(value/1000):value;if(typeof value==="string"&&/^\d{10,13}$/.test(value))return value.length===13?Math.floor(Number(value)/1000):Number(value);if(typeof value==="string"){const parsed=parseSqlDateTime(value);return parsed?Math.floor(parsed.getTime()/1000):Number.NaN}return Number.NaN}export async function validateLicenseKeyWrite(input,current){const key=String(mergedValue(input,current,"key")||"").trim().toUpperCase();const template=String(mergedValue(input,current,"template")||"");const status=String(mergedValue(input,current,"status")||"");const rawExpiry=mergedValue(input,current,"expiry_date");const expiryDate=rawExpiry===null||rawExpiry===undefined||rawExpiry===""?null:expiryTimestamp(rawExpiry);const customerId=optionalId(input,current,"customer_id","Customer");const productId=optionalId(input,current,"product_id","Product");const orderId=optionalId(input,current,"order_id","Order");if(!/^[A-Z0-9]{4}(?:-[A-Z0-9]{4}){4}$/.test(key))throw new LicenseKeyInputError("License key must use five groups of four uppercase letters or numbers.");if(!templates.includes(template))throw new LicenseKeyInputError(`Template must be one of: ${templates.join(", ")}.`);if(!statuses.includes(status))throw new LicenseKeyInputError(`Status must be one of: ${statuses.join(", ")}.`);if(expiryDate!==null&&(!Number.isSafeInteger(expiryDate)||expiryDate<0||expiryDate>2147483647))throw new LicenseKeyInputError("Expiry date must be a Unix timestamp between 1970 and 2038.");const[customer,product,order]=await Promise.all([customerId?db.selectFrom("customers").where("id","=",customerId).select("id").executeTakeFirst():null,productId?db.selectFrom("products").where("id","=",productId).select("id").executeTakeFirst():null,orderId?db.selectFrom("orders").where("id","=",orderId).select(["id","customer_id"]).executeTakeFirst():null]);if(customerId&&!customer)throw new LicenseKeyInputError(`Customer ${customerId} was not found.`);if(productId&&!product)throw new LicenseKeyInputError(`Product ${productId} was not found.`);if(orderId&&!order)throw new LicenseKeyInputError(`Order ${orderId} was not found.`);if(customerId&&order?.customer_id&&Number(order.customer_id)!==customerId){throw new LicenseKeyInputError(`Order ${orderId} belongs to Customer ${order.customer_id}, not Customer ${customerId}.`)}return{...input,key,template,expiry_date:expiryDate===null?null:sqlDateTime(new Date(expiryDate*1000)),status,customer_id:customerId,product_id:productId,order_id:orderId}}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/commerce",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.75.
|
|
4
|
+
"version": "0.75.551",
|
|
5
5
|
"description": "Stacks commerce utilities.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -57,19 +57,19 @@
|
|
|
57
57
|
"prepublishOnly": "bun run build"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@stacksjs/cache": "0.75.
|
|
61
|
-
"@stacksjs/config": "0.75.
|
|
62
|
-
"@stacksjs/database": "0.75.
|
|
63
|
-
"@stacksjs/env": "0.75.
|
|
64
|
-
"@stacksjs/error-handling": "0.75.
|
|
65
|
-
"@stacksjs/events": "0.75.
|
|
66
|
-
"@stacksjs/logging": "0.75.
|
|
67
|
-
"@stacksjs/orm": "0.75.
|
|
68
|
-
"@stacksjs/payments": "0.75.
|
|
69
|
-
"@stacksjs/realtime": "0.75.
|
|
70
|
-
"@stacksjs/slug": "0.75.
|
|
71
|
-
"@stacksjs/strings": "0.75.
|
|
72
|
-
"@stacksjs/validation": "0.75.
|
|
60
|
+
"@stacksjs/cache": "0.75.551",
|
|
61
|
+
"@stacksjs/config": "0.75.551",
|
|
62
|
+
"@stacksjs/database": "0.75.551",
|
|
63
|
+
"@stacksjs/env": "0.75.551",
|
|
64
|
+
"@stacksjs/error-handling": "0.75.551",
|
|
65
|
+
"@stacksjs/events": "0.75.551",
|
|
66
|
+
"@stacksjs/logging": "0.75.551",
|
|
67
|
+
"@stacksjs/orm": "0.75.551",
|
|
68
|
+
"@stacksjs/payments": "0.75.551",
|
|
69
|
+
"@stacksjs/realtime": "0.75.551",
|
|
70
|
+
"@stacksjs/slug": "0.75.551",
|
|
71
|
+
"@stacksjs/strings": "0.75.551",
|
|
72
|
+
"@stacksjs/validation": "0.75.551",
|
|
73
73
|
"ts-spreadsheets": "^0.2.0"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|