@jchat/runtime 0.0.2 → 1.0.0-alpha.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/CHANGELOG.md +12 -0
- package/LICENSE +14 -7
- package/README.md +1 -1
- package/dist/index.d.mts +84 -1
- package/dist/index.mjs +1 -1
- package/package.json +25 -5
- package/src/audit.test.ts +25 -0
- package/src/audit.ts +25 -0
- package/src/check.test.ts +77 -0
- package/src/check.ts +202 -0
- package/src/domain.test.ts +45 -0
- package/src/domain.ts +75 -0
- package/src/env.test.ts +146 -0
- package/src/env.ts +261 -0
- package/src/index.test.ts +117 -0
- package/src/index.ts +206 -0
- package/src/install.ts +62 -0
- package/src/paths.test.ts +49 -0
- package/src/paths.ts +74 -0
- package/src/runtime.test.ts +21 -0
- package/src/runtime.ts +31 -0
- package/src/state.test.ts +54 -0
- package/src/state.ts +129 -0
package/CHANGELOG.md
ADDED
package/LICENSE
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
JChat Runtime License Agreement
|
|
2
|
-
Version 1.0 - July 29, 2026
|
|
1
|
+
JChat Runtime License Agreement - July 29, 2026
|
|
3
2
|
|
|
4
3
|
Copyright (c) 2026 Md. Jabarullah. All rights reserved.
|
|
5
4
|
|
|
@@ -14,7 +13,9 @@ Runtime open-source software and does not grant any rights except those stated b
|
|
|
14
13
|
|
|
15
14
|
"Vendor License" means a valid standard, extended, or vendor-issued development license for JChat
|
|
16
15
|
obtained from JChat Hub, Envato Market, Codester, or another channel expressly authorized by the
|
|
17
|
-
copyright owner.
|
|
16
|
+
copyright owner. A one-time marketplace purchase (including from Envato Market or Codester)
|
|
17
|
+
constitutes a perpetual Vendor License for the purchased edition, provided the purchase remains
|
|
18
|
+
valid and compliant with the applicable marketplace terms.
|
|
18
19
|
|
|
19
20
|
"Authorized Deployment" means a JChat installation that complies with its Vendor License,
|
|
20
21
|
including its domain, installation, environment, and usage restrictions.
|
|
@@ -37,7 +38,10 @@ c. make reasonable technical copies required for private package caches, continu
|
|
|
37
38
|
Authorized Deployment; and
|
|
38
39
|
|
|
39
40
|
d. provide those copies to a client only as an integral part of an end product and only when that
|
|
40
|
-
transfer is permitted by the applicable Vendor License.
|
|
41
|
+
transfer is permitted by the applicable Vendor License. Distributing JChat (including this
|
|
42
|
+
Runtime as a dependency) as a purchased item on Envato Market or another authorized marketplace
|
|
43
|
+
constitutes permitted redistribution under this section, provided the recipient is the
|
|
44
|
+
end-product client and not a downstream redistributor.
|
|
41
45
|
|
|
42
46
|
A vendor-issued development license may additionally authorize local development use according to
|
|
43
47
|
the conditions encoded in that license. No right is granted to use the Runtime independently from
|
|
@@ -87,9 +91,12 @@ the Runtime, the more specific written terms supplied by JChat control.
|
|
|
87
91
|
7. Term and Termination
|
|
88
92
|
|
|
89
93
|
This agreement remains effective while you comply with it and maintain the required Vendor License.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
94
|
+
For one-time marketplace purchases (Envato Market, Codester, or equivalent), the Vendor License
|
|
95
|
+
does not expire; this agreement terminates only if the purchase is invalidated by the marketplace,
|
|
96
|
+
or if you materially breach this agreement. For subscription or time-limited licenses issued
|
|
97
|
+
directly by JChat Hub, this agreement terminates when that license expires or is revoked. On
|
|
98
|
+
termination, you must stop using the Runtime and remove all copies except copies retained solely
|
|
99
|
+
where applicable law requires archival retention.
|
|
93
100
|
|
|
94
101
|
Sections 3, 4, 5, 8, 9, and 10 survive termination.
|
|
95
102
|
|
package/README.md
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
1
2
|
//#region src/domain.d.ts
|
|
2
3
|
type Plan = "standard" | "extended";
|
|
3
4
|
type RoutingMode = "path" | "subdomain";
|
|
@@ -93,6 +94,7 @@ declare function createIdentity(machineFingerprint?: string): {
|
|
|
93
94
|
declare function readTokenSync(filePath?: string): string;
|
|
94
95
|
declare function readState(filePath?: string): Promise<LocalState | null>;
|
|
95
96
|
declare function writeState(state: LocalState, filePath?: string): Promise<void>;
|
|
97
|
+
declare function updateInstanceToken(instanceToken: string, statePath?: string): Promise<void>;
|
|
96
98
|
declare function acquireProcessLock(statePath?: string): Promise<() => Promise<void>>;
|
|
97
99
|
//#endregion
|
|
98
100
|
//#region src/runtime.d.ts
|
|
@@ -105,6 +107,87 @@ declare function getRuntimeStatus(): {
|
|
|
105
107
|
};
|
|
106
108
|
declare function isApplicationDisabled(): boolean;
|
|
107
109
|
//#endregion
|
|
110
|
+
//#region src/install.d.ts
|
|
111
|
+
type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
112
|
+
type LicenseVerificationResult = {
|
|
113
|
+
valid: true;
|
|
114
|
+
buyer: string;
|
|
115
|
+
token: string;
|
|
116
|
+
domain: string;
|
|
117
|
+
state: Omit<LocalState, "instanceToken" | "version">;
|
|
118
|
+
} | {
|
|
119
|
+
valid: false;
|
|
120
|
+
error: string;
|
|
121
|
+
};
|
|
122
|
+
declare function installAndActivate(purchaseCode: string, domain: string, siteSlug: string | undefined, domainScope: DomainScope | undefined, routingMode: RoutingMode, provider?: PurchaseProvider, fetchImpl?: FetchLike): Promise<LicenseVerificationResult>;
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/paths.d.ts
|
|
125
|
+
interface RuntimePathOptions {
|
|
126
|
+
cwd?: string;
|
|
127
|
+
env?: Record<string, string | undefined>;
|
|
128
|
+
}
|
|
129
|
+
declare function resolveRuntimePaths(options?: RuntimePathOptions): {
|
|
130
|
+
repoRoot: string | null;
|
|
131
|
+
runtimeRoot: string;
|
|
132
|
+
uploadsDir: string;
|
|
133
|
+
addonBundlesDir: string;
|
|
134
|
+
addonSourceDir: string;
|
|
135
|
+
migrationsDir: string;
|
|
136
|
+
};
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/env.d.ts
|
|
139
|
+
declare function makeTypedEnv<T>(schema: {
|
|
140
|
+
parse: (data: unknown) => T;
|
|
141
|
+
}): (args: Record<string, unknown>) => T;
|
|
142
|
+
declare const ServerConfigSchema: z.ZodObject<{
|
|
143
|
+
JCHAT_PORT: z.ZodDefault<z.ZodPipe<z.ZodString, z.ZodTransform<number, string>>>;
|
|
144
|
+
JCHAT_COOKIE_SECRET: z.ZodString;
|
|
145
|
+
JCHAT_DATABASE_URL: z.ZodURL;
|
|
146
|
+
JCHAT_REDIS_DATABASE_URL: z.ZodURL;
|
|
147
|
+
JCHAT_STORAGE_TYPE: z.ZodEnum<{
|
|
148
|
+
readonly LOCAL: "LOCAL";
|
|
149
|
+
readonly MINIO: "MINIO";
|
|
150
|
+
readonly CLOUDFLARE_R2: "CLOUDFLARE_R2";
|
|
151
|
+
readonly AWS_S3: "AWS_S3";
|
|
152
|
+
readonly GCS: "GCS";
|
|
153
|
+
}>;
|
|
154
|
+
JCHAT_MINIO_ENDPOINT: z.ZodOptional<z.ZodString>;
|
|
155
|
+
JCHAT_MINIO_BUCKET_NAME: z.ZodOptional<z.ZodString>;
|
|
156
|
+
JCHAT_MINIO_ACCESS_KEY_ID: z.ZodOptional<z.ZodString>;
|
|
157
|
+
JCHAT_MINIO_SECRET_ACCESS_KEY: z.ZodOptional<z.ZodString>;
|
|
158
|
+
JCHAT_MINIO_PUBLIC_URL: z.ZodOptional<z.ZodString>;
|
|
159
|
+
JCHAT_AWS_REGION: z.ZodOptional<z.ZodString>;
|
|
160
|
+
JCHAT_AWS_BUCKET_NAME: z.ZodOptional<z.ZodString>;
|
|
161
|
+
JCHAT_AWS_ACCESS_KEY_ID: z.ZodOptional<z.ZodString>;
|
|
162
|
+
JCHAT_AWS_SECRET_ACCESS_KEY: z.ZodOptional<z.ZodString>;
|
|
163
|
+
JCHAT_CLOUDFLARE_ACCOUNT_ID: z.ZodOptional<z.ZodString>;
|
|
164
|
+
JCHAT_CLOUDFLARE_BUCKET_NAME: z.ZodOptional<z.ZodString>;
|
|
165
|
+
JCHAT_CLOUDFLARE_ACCESS_KEY_ID: z.ZodOptional<z.ZodString>;
|
|
166
|
+
JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY: z.ZodOptional<z.ZodString>;
|
|
167
|
+
JCHAT_CLOUDFLARE_PUBLIC_URL: z.ZodOptional<z.ZodString>;
|
|
168
|
+
JCHAT_GCS_BUCKET_NAME: z.ZodOptional<z.ZodString>;
|
|
169
|
+
JCHAT_GCS_PROJECT_ID: z.ZodOptional<z.ZodString>;
|
|
170
|
+
JCHAT_GCS_CLIENT_EMAIL: z.ZodOptional<z.ZodString>;
|
|
171
|
+
JCHAT_GCS_PRIVATE_KEY: z.ZodOptional<z.ZodString>;
|
|
172
|
+
JCHAT_GCS_KEY_FILE: z.ZodOptional<z.ZodString>;
|
|
173
|
+
JCHAT_BOT_NAME: z.ZodString;
|
|
174
|
+
JCHAT_BOT_EMAIL: z.ZodEmail;
|
|
175
|
+
JCHAT_DOMAIN: z.ZodOptional<z.ZodString>;
|
|
176
|
+
JCHAT_SITE_URL: z.ZodOptional<z.ZodURL>;
|
|
177
|
+
JCHAT_ROUTING_MODE: z.ZodDefault<z.ZodEnum<{
|
|
178
|
+
path: "path";
|
|
179
|
+
subdomain: "subdomain";
|
|
180
|
+
}>>;
|
|
181
|
+
JCHAT_ADDON_ENCRYPTION_KEY: z.ZodString;
|
|
182
|
+
NODE_ENV: z.ZodDefault<z.ZodEnum<{
|
|
183
|
+
development: "development";
|
|
184
|
+
production: "production";
|
|
185
|
+
test: "test";
|
|
186
|
+
}>>;
|
|
187
|
+
SYSTEM_BOOTSTRAP_COMPLETE: z.ZodOptional<z.ZodBoolean>;
|
|
188
|
+
}, z.core.$strip>;
|
|
189
|
+
type ServerConfig = z.infer<typeof ServerConfigSchema>;
|
|
190
|
+
//#endregion
|
|
108
191
|
//#region src/index.d.ts
|
|
109
192
|
type PurchaseProvider = "envato" | "jchat";
|
|
110
193
|
type RuntimeEnvironment = "production" | "development";
|
|
@@ -134,4 +217,4 @@ declare function verifySignature(token: string, currentDomain: string, options:
|
|
|
134
217
|
declare function verifyEntitlement(token: string, currentDomain: string, installationId: string, machineFingerprint: string, options: RuntimeOptions): boolean;
|
|
135
218
|
declare function hasEntitlement(token: string, currentDomain: string, entitlement: string, options: RuntimeOptions): boolean;
|
|
136
219
|
//#endregion
|
|
137
|
-
export { ActivationInput, ActivationResult, AuditEvent, CheckInput, CheckResult, ConfigPayload, DEFAULT_STATE_PATH, DomainScope, LocalState, NormalizedDomain, Plan, PurchaseProvider, RegistryProvider, RegistryRoutingMode, RoutingMode, RuntimeEnvironment, RuntimeOptions, RuntimeStatus, acquireProcessLock, activateRegistry, checkRegistry, createIdentity, createMachineFingerprint, getRuntimeStatus, hasEntitlement, isAllowedConfiguredDomain, isApplicationDisabled, isPublicDomain, normalizeDomain, parsePayload, readState, readTokenSync, recordAudit, registerInvalidationHandler, resolveActivationDomain, setRuntimeStatus, verifyEntitlement, verifySignature, writeState };
|
|
220
|
+
export { ActivationInput, ActivationResult, AuditEvent, CheckInput, CheckResult, ConfigPayload, DEFAULT_STATE_PATH, DomainScope, FetchLike, LicenseVerificationResult, LocalState, NormalizedDomain, Plan, PurchaseProvider, RegistryProvider, RegistryRoutingMode, RoutingMode, RuntimeEnvironment, RuntimeOptions, RuntimeStatus, ServerConfig, ServerConfigSchema, acquireProcessLock, activateRegistry, checkRegistry, createIdentity, createMachineFingerprint, getRuntimeStatus, hasEntitlement, installAndActivate, isAllowedConfiguredDomain, isApplicationDisabled, isPublicDomain, makeTypedEnv, normalizeDomain, parsePayload, readState, readTokenSync, recordAudit, registerInvalidationHandler, resolveActivationDomain, resolveRuntimePaths, setRuntimeStatus, updateInstanceToken, verifyEntitlement, verifySignature, writeState };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:crypto";import t from"node:net";import n from"node:fs/promises";import r from"node:path";import i from"node:fs";import a from"node:os";const o=new Set([`localhost`,`127.0.0.1`,`::1`]),s=[`.local`,`.test`,`.invalid`,`.example`];function c(e){let t=e.trim();if(!t)throw Error(`Instance domain is required`);let n=new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLowerCase().replace(/\.$/,``),r=n===`www.localhost`?`localhost`:n.replace(/^www\./,``);if(!r||r.includes(`@`)||/\s/.test(r))throw Error(`Invalid instance domain`);return{host:r,isLocalhost:o.has(r)}}function l(e){let{host:n,isLocalhost:r}=c(e);return!r&&t.isIP(n)===0&&n.includes(`.`)&&!s.some(e=>n.endsWith(e))}function u(e){try{return c(e).isLocalhost||l(e)}catch{return!1}}function d(e){let{host:n,isLocalhost:r}=c(e);if(r||t.isIP(n)!==0)return null;let i=n.split(`.`);if(i.length<=2)return n;let a=new Set([`co`,`com`,`org`,`net`,`gov`,`edu`,`ac`,`sch`]),o=i.at(-1)??``,s=i.at(-2)??``;return a.has(s)&&o.length===2&&i.length>=3?i.slice(-3).join(`.`):i.slice(-2).join(`.`)}function f(e,t,n,r=`current-host`){let i=c(e).host;return n===`subdomain`&&t===`extended`&&r===`parent-domain`?d(i)??i:i}function p(e){if(e)return e.length<=8?`redacted`:`${e.slice(0,4)}…${e.slice(-4)}`}async function m(e,t,i=r.resolve(process.cwd(),`data/license-events.log`)){await n.mkdir(r.dirname(i),{recursive:!0});let a=JSON.stringify({at:new Date().toISOString(),event:e,domain:p(t.domain),installationId:p(t.installationId),reference:p(t.reference)});await n.appendFile(i,`${a}\n`,`utf8`)}let h=`unavailable`,g=`startup`,_;function v(e){_=e}function y(t,n=e.randomUUID()){h=t,g=n,t===`invalid`&&_?.()}function b(){return{status:h,reference:g}}function x(){return h===`invalid`}const S=Buffer.from(`aHR0cDovL2xvY2FsaG9zdDo0MDAw`,`base64`).toString(`utf8`);async function C(e){try{let t=await(e.fetchImpl??fetch)(`${e.registryEndpoint??S}/api/activate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({purchaseCode:e.purchaseCode,domain:c(e.domain).host,siteSlug:e.siteSlug,domainScope:e.domainScope,provider:e.provider,routingMode:e.routingMode,installationId:e.installationId,installationPublicKey:e.installationPublicKey,machineFingerprint:e.machineFingerprint})}),n=await t.json();return t.ok===!1||!n.success||!n.token?{success:!1,message:n.message??`This license is already active on another domain. Please deactivate it first.`}:{success:!0,buyer:n.buyer??`Customer`,token:n.token,domain:n.domain??c(e.domain).host}}catch{return{success:!1,message:`Failed to connect to the central registry. Please try again later.`}}}async function w(t){let n=t.fetchImpl??fetch,r=t.localTokenValidator??((e,n,r,i)=>t.runtimeOptions?z(e,n,r,i,t.runtimeOptions):!1),i=(n,r)=>{let i=e.randomUUID();return y(`invalid`,i),m(`check_rejected`,{domain:n,reference:i},t.auditPath),{status:`invalid`,error:r,reference:i}},a=e=>{let n=c(t.domain).host;return r(t.token,n,t.installationId,t.machineFingerprint)?(y(`unreachable-fallback`),m(`check_unreachable`,{domain:n},t.auditPath),{status:`unreachable-fallback`,token:t.token,error:e}):i(n,`Local license validation failed.`)};try{let e=c(t.domain).host,r=await n(`${t.registryEndpoint??S}/api/check`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:t.token,domain:e,routingMode:t.routingMode,installationId:t.installationId,machineFingerprint:t.machineFingerprint})});if(!r.ok)return r.status>=500?a(`HTTP ${r.status}`):i(e,`License rejected by jchat service.`);let o=await r.json();if(!o.success||!o.token||!(t.runtimeOptions&&z(o.token,e,t.installationId,t.machineFingerprint,t.runtimeOptions))&&!t.localTokenValidator||t.localTokenValidator&&!t.localTokenValidator(o.token,e,t.installationId,t.machineFingerprint))return i(e,`License rejected by jchat service.`);let s=L(o.token);return!s||s.installationId!==t.installationId||s.machineFingerprint!==t.machineFingerprint||s.routingMode!==t.routingMode?i(e,`License binding rejected by jchat service.`):(y(`valid`),m(`check_success`,{domain:e},t.auditPath),{status:`valid`,token:o.token})}catch{return a(`License service unreachable.`)}}const T=r.resolve(process.cwd(),`data/instance.json`);function E(){return e.createHash(`sha256`).update([a.hostname(),a.platform(),a.arch()].join(`|`)).digest(`hex`)}function D(t=E()){let n=e.generateKeyPairSync(`ed25519`);return{installationId:e.randomUUID(),machineFingerprint:t,privateKeyPem:n.privateKey.export({type:`pkcs8`,format:`pem`}).toString(),publicKeyPem:n.publicKey.export({type:`spki`,format:`pem`}).toString()}}function O(e=T){try{if(!i.existsSync(e))return``;let t=i.readFileSync(e,`utf8`);return JSON.parse(t)?.instanceToken??``}catch{return``}}async function k(e=T){try{let t=JSON.parse(await Bun.file(e).text());if(!t||typeof t!=`object`)return null;let n=t;return n.version!==1||typeof n.installationId!=`string`||!n.installationId||typeof n.privateKeyPem!=`string`||!n.privateKeyPem||typeof n.publicKeyPem!=`string`||!n.publicKeyPem||typeof n.machineFingerprint!=`string`||!n.machineFingerprint||typeof n.instanceToken!=`string`||!n.instanceToken||n.lastSuccessfulCheckAt!==void 0&&(typeof n.lastSuccessfulCheckAt!=`string`||!n.lastSuccessfulCheckAt)?null:n}catch{return null}}async function A(t,i=T){let a=r.dirname(i);await n.mkdir(a,{recursive:!0});let o=`${i}.${process.pid}.${e.randomUUID()}.tmp`;await Bun.write(o,`${JSON.stringify(t,null,2)}\n`),await n.rename(o,i)}async function j(e=T){let t=`${e}.lock`;await n.mkdir(r.dirname(t),{recursive:!0});let i;try{i=await n.open(t,`wx`)}catch(e){if(!(e instanceof Error)||!(`code`in e)||e.code!==`EEXIST`)throw e;let r=Number.parseInt(await Bun.file(t).text().catch(()=>``),10),a=!1;if(Number.isInteger(r)&&r>0)try{process.kill(r,0),a=!0}catch{a=!1}if(a)throw Error(`Another JChat process already owns the license lock`);await n.rm(t,{force:!0}),i=await n.open(t,`wx`)}return await i.writeFile(`${process.pid}\n`),async()=>{await i.close(),await n.rm(t,{force:!0})}}function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e){return typeof e==`string`&&e.trim().length>0}function P(e){if(!e)return null;try{return JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`))}catch{return null}}function F(e){let t=e.split(`.`);if(t.length!==3)return null;let n=P(t[0]);return!M(n)||n.alg!==`RS256`||n.typ!==`JWT`?null:{alg:`RS256`,typ:`JWT`}}function I(e){if(!M(e))return null;let{iss:t,aud:n,licenseId:r,domain:i,buyer:a,installationId:o,machineFingerprint:s,plan:u,entitlements:d,purchaseProvider:f,environment:p,routingMode:m,iat:h}=e;if(!N(t)||!N(n)||!N(r)||!N(i)||!N(a)||!N(o)||!N(s)||u!==`standard`&&u!==`extended`||!Array.isArray(d)||!d.every(N)||f!==`envato`&&f!==`jchat`||p!==`production`&&p!==`development`||m!==`path`&&m!==`subdomain`||typeof h!=`number`||!Number.isSafeInteger(h)||h<0)return null;let g;try{g=c(i)}catch{return null}if(p===`development`&&!g.isLocalhost||p===`production`&&!l(i))return null;let _=d.includes(`site.create.multi`);return u===`extended`&&!_||u===`standard`&&_?null:{iss:t,aud:n,licenseId:r,domain:i,buyer:a,installationId:o,machineFingerprint:s,plan:u,entitlements:d,purchaseProvider:f,environment:p,routingMode:m,iat:h}}function L(e){let t=e.split(`.`);return t.length!==3||!t.every(Boolean)||!F(e)?null:I(P(t[1]))}function R(t,n,r){if(!t||t===`YOUR_LICENSE_KEY_PLACEHOLDER`)return!1;try{let i=t.split(`.`);if(i.length!==3||!F(t))return!1;let a=L(t);if(!a||a.iss!==(r.issuer??`https://license.jchat.local`)||a.aud!==(r.audience??`jchat-chat`)||c(a.domain).host!==c(n).host)return!1;let o=Buffer.from(`${i[0]}.${i[1]}`),s=Buffer.from(i[2].replace(/-/g,`+`).replace(/_/g,`/`),`base64`);return e.verify(`sha256`,o,r.publicKeyPem,s)}catch{return!1}}function z(e,t,n,r,i){if(!R(e,t,i))return!1;let a=L(e);return a?a.installationId===n&&a.machineFingerprint===r:!1}function B(e,t,n,r){return R(e,t,r)?L(e)?.entitlements?.includes(n)??!1:!1}export{T as DEFAULT_STATE_PATH,j as acquireProcessLock,C as activateRegistry,w as checkRegistry,D as createIdentity,E as createMachineFingerprint,b as getRuntimeStatus,B as hasEntitlement,u as isAllowedConfiguredDomain,x as isApplicationDisabled,l as isPublicDomain,c as normalizeDomain,L as parsePayload,k as readState,O as readTokenSync,m as recordAudit,v as registerInvalidationHandler,f as resolveActivationDomain,y as setRuntimeStatus,z as verifyEntitlement,R as verifySignature,A as writeState};
|
|
1
|
+
import e from"node:crypto";import t from"node:net";import n from"node:fs/promises";import r from"node:path";import i from"node:fs";import a from"node:os";import{replaceKeys as o}from"string-ts";import*as s from"zod";const c=new Set([`localhost`,`127.0.0.1`,`::1`]),l=[`.local`,`.test`,`.invalid`,`.example`];function u(e){let t=e.trim();if(!t)throw Error(`Instance domain is required`);let n=new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLowerCase().replace(/\.$/,``),r=n===`www.localhost`?`localhost`:n.replace(/^www\./,``);if(!r||r.includes(`@`)||/\s/.test(r))throw Error(`Invalid instance domain`);return{host:r,isLocalhost:c.has(r)}}function d(e){let{host:n,isLocalhost:r}=u(e);return!r&&t.isIP(n)===0&&n.includes(`.`)&&!l.some(e=>n.endsWith(e))}function f(e){try{return u(e).isLocalhost||d(e)}catch{return!1}}function p(e){let{host:n,isLocalhost:r}=u(e);if(r||t.isIP(n)!==0)return null;let i=n.split(`.`);if(i.length<=2)return n;let a=new Set([`co`,`com`,`org`,`net`,`gov`,`edu`,`ac`,`sch`]),o=i.at(-1)??``,s=i.at(-2)??``;return a.has(s)&&o.length===2&&i.length>=3?i.slice(-3).join(`.`):i.slice(-2).join(`.`)}function m(e,t,n,r=`current-host`){let i=u(e).host;return n===`subdomain`&&t===`extended`&&r===`parent-domain`?p(i)??i:i}function h(e){if(e)return e.length<=8?`redacted`:`${e.slice(0,4)}…${e.slice(-4)}`}async function g(e,t,i=r.resolve(process.cwd(),`data/license-events.log`)){await n.mkdir(r.dirname(i),{recursive:!0});let a=JSON.stringify({at:new Date().toISOString(),event:e,domain:h(t.domain),installationId:h(t.installationId),reference:h(t.reference)});await n.appendFile(i,`${a}\n`,`utf8`)}let _=`unavailable`,v=`startup`,y;function ee(e){y=e}function b(t,n=e.randomUUID()){_=t,v=n,t===`invalid`&&y?.()}function x(){return{status:_,reference:v}}function S(){return _===`invalid`}const C=Buffer.from(`aHR0cDovL2xvY2FsaG9zdDo0MDAw`,`base64`).toString(`utf8`);async function w(e){try{let t=await(e.fetchImpl??fetch)(`${e.registryEndpoint??C}/api/activate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({purchaseCode:e.purchaseCode,domain:u(e.domain).host,siteSlug:e.siteSlug,domainScope:e.domainScope,provider:e.provider,routingMode:e.routingMode,installationId:e.installationId,installationPublicKey:e.installationPublicKey,machineFingerprint:e.machineFingerprint})}),n=await t.json();return t.ok===!1||!n.success||!n.token?{success:!1,message:n.message??`This license is already active on another domain. Please deactivate it first.`}:{success:!0,buyer:n.buyer??`Customer`,token:n.token,domain:n.domain??u(e.domain).host}}catch{return{success:!1,message:`Failed to connect to the central registry. Please try again later.`}}}async function te(t){let n=t.fetchImpl??fetch,r=t.localTokenValidator??((e,n,r,i)=>t.runtimeOptions?$(e,n,r,i,t.runtimeOptions):!1),i=(n,r)=>{let i=e.randomUUID();return b(`invalid`,i),g(`check_rejected`,{domain:n,reference:i},t.auditPath),{status:`invalid`,error:r,reference:i}},a=e=>{let n=u(t.domain).host;return r(t.token,n,t.installationId,t.machineFingerprint)?(b(`unreachable-fallback`),g(`check_unreachable`,{domain:n},t.auditPath),{status:`unreachable-fallback`,token:t.token,error:e}):i(n,`Local license validation failed.`)};try{let e=u(t.domain).host,r=await n(`${t.registryEndpoint??C}/api/check`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:t.token,domain:e,routingMode:t.routingMode,installationId:t.installationId,machineFingerprint:t.machineFingerprint})});if(!r.ok)return r.status>=500?a(`HTTP ${r.status}`):i(e,`License rejected by jchat service.`);let o=await r.json();if(!o.success||!o.token||!(t.runtimeOptions&&$(o.token,e,t.installationId,t.machineFingerprint,t.runtimeOptions))&&!t.localTokenValidator||t.localTokenValidator&&!t.localTokenValidator(o.token,e,t.installationId,t.machineFingerprint))return i(e,`License rejected by jchat service.`);let s=Z(o.token);return!s||s.installationId!==t.installationId||s.machineFingerprint!==t.machineFingerprint||s.routingMode!==t.routingMode?i(e,`License binding rejected by jchat service.`):(b(`valid`),g(`check_success`,{domain:e},t.auditPath),{status:`valid`,token:o.token})}catch{return a(`License service unreachable.`)}}const T=r.resolve(process.cwd(),`data/instance.json`);function E(){return e.createHash(`sha256`).update([a.hostname(),a.platform(),a.arch()].join(`|`)).digest(`hex`)}function D(t=E()){let n=e.generateKeyPairSync(`ed25519`);return{installationId:e.randomUUID(),machineFingerprint:t,privateKeyPem:n.privateKey.export({type:`pkcs8`,format:`pem`}).toString(),publicKeyPem:n.publicKey.export({type:`spki`,format:`pem`}).toString()}}function ne(e=T){try{if(!i.existsSync(e))return``;let t=i.readFileSync(e,`utf8`);return JSON.parse(t)?.instanceToken??``}catch{return``}}async function O(e=T){try{let t=JSON.parse(await Bun.file(e).text());if(!t||typeof t!=`object`)return null;let n=t;return n.version!==1||typeof n.installationId!=`string`||!n.installationId||typeof n.privateKeyPem!=`string`||!n.privateKeyPem||typeof n.publicKeyPem!=`string`||!n.publicKeyPem||typeof n.machineFingerprint!=`string`||!n.machineFingerprint||typeof n.instanceToken!=`string`||!n.instanceToken||n.lastSuccessfulCheckAt!==void 0&&(typeof n.lastSuccessfulCheckAt!=`string`||!n.lastSuccessfulCheckAt)?null:n}catch{return null}}async function k(t,i=T){let a=r.dirname(i);await n.mkdir(a,{recursive:!0});let o=`${i}.${process.pid}.${e.randomUUID()}.tmp`;await Bun.write(o,`${JSON.stringify(t,null,2)}\n`),await n.rename(o,i)}async function A(e,t=T){let n=await O(t);if(!n)throw Error(`Local license state is missing`);await k({...n,instanceToken:e,lastSuccessfulCheckAt:new Date().toISOString()},t)}async function j(e=T){let t=`${e}.lock`;await n.mkdir(r.dirname(t),{recursive:!0});let i;try{i=await n.open(t,`wx`)}catch(e){if(!(e instanceof Error)||!(`code`in e)||e.code!==`EEXIST`)throw e;let r=Number.parseInt(await Bun.file(t).text().catch(()=>``),10),a=!1;if(Number.isInteger(r)&&r>0)try{process.kill(r,0),a=!0}catch{a=!1}if(a)throw Error(`Another JChat process already owns the license lock`);await n.rm(t,{force:!0}),i=await n.open(t,`wx`)}return await i.writeFile(`${process.pid}\n`),async()=>{await i.close(),await n.rm(t,{force:!0})}}async function M(e,t,n,r,i,a=`envato`,o=fetch){let s=D();try{let c=await w({purchaseCode:e,domain:t,siteSlug:n,domainScope:r,routingMode:i,provider:a,installationId:s.installationId,installationPublicKey:s.publicKeyPem,machineFingerprint:s.machineFingerprint,fetchImpl:o});return c.success?{valid:!0,buyer:c.buyer,token:c.token,domain:c.domain,state:s}:{valid:!1,error:c.message}}catch{return{valid:!1,error:`Failed to verify license. Check your internet connection.`}}}function N(e={}){let t=r.resolve(e.cwd??process.cwd()),n=e.env??process.env,i=F(t);return{repoRoot:i,runtimeRoot:t,uploadsDir:I(n.JCHAT_UPLOADS_DIR,t,i,`uploads`,`uploads`),addonBundlesDir:I(n.JCHAT_ADDONS_DIR,t,i,`addons`,`addons`),addonSourceDir:i?r.join(i,`addons-dev`):r.join(t,`addons-dev`),migrationsDir:I(n.JCHAT_MIGRATIONS_DIR,t,i,r.join(`packages`,`db`,`migrations`),`migrations`)}}function P(e){return i.existsSync(r.join(e,`package.json`))&&i.existsSync(r.join(e,`apps`))&&i.existsSync(r.join(e,`packages`))}function F(e){let t=r.resolve(e);for(;;){if(P(t))return t;let e=r.dirname(t);if(e===t)return null;t=e}}function I(e,t,n,i,a){return e?r.resolve(e):n?r.join(n,i):r.join(t,a)}`${[`manage`,`www`].join(`|`)}`;const L={PERMISSIONS:`permissions`,USERS:`users`,BOTS:`bots`,CORES:`cores`,SETTINGS:`settings`,MEMBERSHIPS:`memberships`,ROOMS:`rooms`,SITES:`sites`,RANKS:`ranks`,BLOCKS:`blocks`,BLOCKERS:`blockers`,SPAMS:`spams`,SOCIALS:`socials`,XPS:`xps`,JOINS:`joins`,DAILIES:`dailies`,SESSIONS:`sessions`,MEMBERS:`members`,STREAMS:`streams`,AUDITS:`audits`,ACTIONS:`actions`,UPDATES:`updates`,LOGS:`logs`,ERRORS:`errors`,CONFIGS:`configs`,BANS:`bans`};`${L.STREAMS}${L.AUDITS}${L.ACTIONS}`,`${L.STREAMS}${L.XPS}${L.UPDATES}`,`${L.STREAMS}${L.LOGS}${L.ERRORS}`;const R={MESSAGING:`Messaging`,PRIVATE_MESSAGING:`Private Messaging`,ROOMS:`Rooms`,MODERATION:`Moderation`,PROFILE:`Profile`,POSTS:`Posts`,GIFTS:`Gifts`,FRIENDS:`Friends`,SITE_ADMIN:`Site Admin`,ADDONS:`Addons`,COMMANDS:`Commands`},z={ALL:{value:`*`,label:`Super Admin`,description:`Grants absolute access to every feature and setting. Use with extreme caution.`,category:R.SITE_ADMIN},MESSAGE_SEND:{value:`message.send`,label:`Send Messages`,description:`Allows the user to send messages in public chat rooms.`,category:R.MESSAGING},MESSAGE_DELETE_OWN:{value:`message.delete.own`,label:`Delete Own Messages`,description:`Allows the user to remove their own sent messages.`,category:R.MESSAGING},MESSAGE_DELETE_ANY:{value:`message.delete.any`,label:`Delete Any Message`,description:`Moderator tool: delete messages sent by any user.`,category:R.MESSAGING},MESSAGE_CLEAR:{value:`message.clear`,label:`Clear Chat`,description:`Allows clearing the entire message history of a room.`,category:R.MESSAGING},MESSAGE_UPLOAD:{value:`message.upload`,label:`Upload Files`,description:`Allows attaching images and files to messages.`,category:R.MESSAGING},MESSAGE_USE_COMMANDS:{value:`message.use_commands`,label:`Use Slash Commands`,description:`Allows executing chat commands (e.g., /me, /shrug).`,category:R.MESSAGING},MESSAGE_WILDCARD:{value:`message.*`,label:`Full Messaging Access`,description:`Grants all message-related permissions in a room.`,category:R.MESSAGING},PM_SEND:{value:`pm.send`,label:`Send Private Messages`,description:`Allows starting and participating in 1-on-1 private conversations.`,category:R.PRIVATE_MESSAGING},PM_DELETE_OWN:{value:`pm.delete.own`,label:`Delete Own PMs`,description:`Allows deleting messages sent in private chats.`,category:R.PRIVATE_MESSAGING},PM_READ_ANY:{value:`pm.read.any`,label:`Read Any PM`,description:`Administrative tool: View all private conversations on the site.`,category:R.PRIVATE_MESSAGING},PM_DELETE_ANY:{value:`pm.delete.any`,label:`Delete Any PM`,description:`Moderator tool: Remove private messages sent by any user.`,category:R.PRIVATE_MESSAGING},PM_BYPASS:{value:`pm.bypass`,label:`Bypass Privacy Settings`,description:`Allows bypassing receiver's privacy settings (e.g. not accepting PMs or friends only).`,category:R.PRIVATE_MESSAGING},PM_WILDCARD:{value:`pm.*`,label:`Full PM Access`,description:`Grants all private-messaging related permissions.`,category:R.PRIVATE_MESSAGING},ROOM_JOIN:{value:`room.join`,label:`Join Rooms`,description:`Allows users to enter and view public or restricted chat rooms.`,category:R.ROOMS},ROOM_CREATE:{value:`room.create`,label:`Create Rooms`,description:`Allows users to create new chat rooms.`,category:R.ROOMS},ROOM_EDIT:{value:`room.edit`,label:`Edit Room Settings`,description:`Allows changing room names, descriptions, and settings.`,category:R.ROOMS},ROOM_DELETE:{value:`room.delete`,label:`Delete Rooms`,description:`Allows permanently removing chat rooms and their history.`,category:R.ROOMS},ROOM_LOCK:{value:`room.lock`,label:`Lock/Unlock Rooms`,description:`Allows moderators to temporarily prevent new messages in a room.`,category:R.ROOMS},ROOM_SET_TOPIC:{value:`room.set_topic`,label:`Change Room Topic`,description:`Allows updating the current topic/announcement displayed in a room.`,category:R.ROOMS},ROOM_WILDCARD:{value:`room.*`,label:`Full Room Management`,description:`Grants all room-related administration permissions.`,category:R.ROOMS},USER_KICK:{value:`user.kick`,label:`Kick Users`,description:`Allows removing a user from a room temporarily.`,category:R.MODERATION},USER_BAN:{value:`user.ban`,label:`Ban Users`,description:`Allows permanently banning users from the site or specific rooms.`,category:R.MODERATION},USER_UNBAN:{value:`user.unban`,label:`Unban Users`,description:`Allows lifting previously imposed bans.`,category:R.MODERATION},USER_MUTE:{value:`user.mute`,label:`Mute Users`,description:`Allows preventing a user from sending messages for a duration.`,category:R.MODERATION},USER_UNMUTE:{value:`user.unmute`,label:`Unmute Users`,description:`Allows lifting mutes early.`,category:R.MODERATION},USER_EDIT_RANK:{value:`user.edit_rank`,label:`Manage User Ranks`,description:`Allows assigning or removing ranks for other users.`,category:R.MODERATION},USER_VIEW_PROFILE:{value:`user.view_profile`,label:`View Profiles`,description:`Allows viewing detailed user profiles and settings.`,category:R.MODERATION},USER_WILDCARD:{value:`user.*`,label:`Full Moderation Access`,description:`Grants all user-management and moderation permissions.`,category:R.MODERATION},PROFILE_EDIT:{value:`profile.edit`,label:`Edit Own Profile`,description:`Allows users to change their display name, bio, and avatar.`,category:R.PROFILE},PROFILE_CUSTOMIZE:{value:`profile.customize`,label:`Profile Customization`,description:`Allows advanced styling like custom fonts, themes, and backgrounds.`,category:R.PROFILE},PROFILE_SET_STATUS:{value:`profile.set_status`,label:`Set Status`,description:`Allows setting custom status messages and status indicators.`,category:R.PROFILE},POST_CREATE:{value:`post.create`,label:`Create Posts`,description:`Allows sharing updates and media in the activity feed.`,category:R.POSTS},POST_CREATE_ANNOUNCEMENT:{value:`post.create.announcement`,label:`Create Announcements`,description:`Allows creating official site announcements.`,category:R.POSTS},POST_EDIT_OWN:{value:`post.edit.own`,label:`Edit Own Posts`,description:`Allows modifying previously shared feed posts.`,category:R.POSTS},POST_EDIT_ANY:{value:`post.edit.any`,label:`Edit Any Post`,description:`Administrative tool: Edit posts shared by any user.`,category:R.POSTS},POST_DELETE_OWN:{value:`post.delete.own`,label:`Delete Own Posts`,description:`Allows removing personal feed posts.`,category:R.POSTS},POST_DELETE_ANY:{value:`post.delete.any`,label:`Delete Any Post`,description:`Moderator tool: Remove posts shared by any user.`,category:R.POSTS},POST_REACT:{value:`post.react`,label:`React to Posts`,description:`Allows adding emoji reactions to feed posts.`,category:R.POSTS},POST_COMMENT:{value:`post.comment`,label:`Comment on Posts`,description:`Allows joining the conversation on shared feed items.`,category:R.POSTS},POST_COMMENT_DELETE_OWN:{value:`post.comment.delete.own`,label:`Delete Own Comments`,description:`Allows removing personal comments from feed posts.`,category:R.POSTS},POST_COMMENT_DELETE_ANY:{value:`post.comment.delete.any`,label:`Delete Any Comment`,description:`Moderator tool: Remove comments left by any user.`,category:R.POSTS},POST_WILDCARD:{value:`post.*`,label:`Full Feed Access`,description:`Grants all permissions related to the activity feed.`,category:R.POSTS},USER_BLOCK:{value:`user.block`,label:`Block Users`,description:`Allows preventing specific users from contacting the user.`,category:R.MODERATION},USER_UNBLOCK:{value:`user.unblock`,label:`Unblock Users`,description:`Allows lifting previously imposed user blocks.`,category:R.MODERATION},USER_IGNORE:{value:`user.ignore`,label:`Ignore Users`,description:`Allows hiding messages and notifications from specific users.`,category:R.MODERATION},USER_UNIGNORE:{value:`user.unignore`,label:`Stop Ignoring`,description:`Allows showing messages from previously ignored users again.`,category:R.MODERATION},SITE_EDIT:{value:`site.edit`,label:`Edit Site Settings`,description:`Allows changing site name, branding, and global configuration.`,category:R.SITE_ADMIN},SITE_CREATE:{value:`site.create`,label:`Create New Sites`,description:`Master Admin tool: Create independent Jchat site instances.`,category:R.SITE_ADMIN},SITE_MANAGE_RANKS:{value:`site.manage_ranks`,label:`Manage Ranks & Perms`,description:`Allows creating ranks and configuring their permission sets.`,category:R.SITE_ADMIN},SITE_MANAGE_ADDONS:{value:`site.manage_addons`,label:`Manage Addons`,description:`Allows installing, configuring, and removing jchat Addons.`,category:R.SITE_ADMIN},SITE_VIEW_AUDIT:{value:`site.view_audit`,label:`View Audit Logs`,description:`Administrative tool: See a detailed record of all admin actions.`,category:R.SITE_ADMIN},SITE_VIEW_REPORTS:{label:`View Reports`,value:`site.view_reports`,description:`Allows seeing reports filed by users against content or people.`,category:R.SITE_ADMIN},SITE_MANAGE_REPORTS:{value:`site.manage_reports`,label:`Handle Reports`,description:`Allows resolving or dismissing user reports.`,category:R.SITE_ADMIN},SITE_MANAGE_SPAM:{value:`site.manage_spam`,label:`Manage Anti-Spam`,description:`Allows configuring the anti-spam engine, thresholds, and per-module settings.`,category:R.SITE_ADMIN},SITE_WILDCARD:{value:`site.*`,label:`Full Site Administration`,description:`Grants all technical administration and site discovery permissions.`,category:R.SITE_ADMIN},FRIEND_REQUEST_SEND:{value:`friend.request.send`,label:`Send Friend Requests`,description:`Allows the user to send friend requests to other users.`,category:R.FRIENDS},FRIEND_REQUEST_MANAGE:{value:`friend.request.manage`,label:`Manage Friend Requests`,description:`Allows the user to accept or reject incoming friend requests.`,category:R.FRIENDS},FRIEND_REMOVE:{value:`friend.remove`,label:`Remove Friends`,description:`Allows the user to remove accepted friends from their list.`,category:R.FRIENDS},FRIEND_LIST:{value:`friend.list`,label:`View Friend List`,description:`Allows the user to view their own friends list.`,category:R.FRIENDS},ADDON_WILDCARD:{value:`addon.*`,label:`Full Addon System Access`,description:`Grants access to use every installed addon regardless of specific gates.`,category:R.ADDONS},COMMAND_CLEAR:{value:`command.clear`,label:`Clear Chat Command`,description:`Allows using the /clear slash command to clear chat history.`,category:R.COMMANDS},COMMAND_HELP:{value:`command.help`,label:`View Commands Help`,description:`Allows using the /help slash command.`,category:R.COMMANDS}},B=Object.fromEntries(Object.entries(z).map(([e,t])=>[e,t.value])),V=Object.fromEntries(Object.entries(z).map(([e,t])=>[t.value,{name:t.value,label:t.label,description:t.description,category:t.category}]));Object.values(V);const H=[B.MESSAGE_SEND,B.MESSAGE_UPLOAD,B.MESSAGE_DELETE_OWN,B.PM_SEND,B.PM_DELETE_OWN,B.ROOM_JOIN,B.POST_REACT,B.POST_COMMENT,B.POST_COMMENT_DELETE_OWN,B.PROFILE_EDIT,B.PROFILE_SET_STATUS,B.COMMAND_HELP];B.ALL,[B.SITE_EDIT,B.SITE_MANAGE_RANKS,B.SITE_MANAGE_ADDONS,B.SITE_VIEW_AUDIT,B.SITE_VIEW_REPORTS,B.SITE_MANAGE_REPORTS,B.SITE_MANAGE_SPAM,B.USER_WILDCARD,B.ROOM_EDIT,B.ROOM_DELETE,B.ROOM_LOCK,B.ROOM_SET_TOPIC,B.MESSAGE_WILDCARD,B.POST_WILDCARD,B.PM_WILDCARD,B.PROFILE_CUSTOMIZE,B.MESSAGE_USE_COMMANDS,B.POST_CREATE,B.POST_EDIT_OWN,B.POST_DELETE_OWN,B.FRIEND_REQUEST_SEND,B.FRIEND_REQUEST_MANAGE,B.FRIEND_REMOVE,B.FRIEND_LIST,B.COMMAND_CLEAR,...H],[B.ROOM_EDIT,B.ROOM_LOCK,B.ROOM_SET_TOPIC,B.MESSAGE_WILDCARD,B.POST_WILDCARD,B.PM_SEND,B.PM_DELETE_OWN,B.PM_READ_ANY,B.PM_DELETE_ANY,B.USER_KICK,B.USER_MUTE,B.USER_UNMUTE,B.USER_BAN,B.USER_UNBAN,B.PROFILE_CUSTOMIZE,B.MESSAGE_USE_COMMANDS,B.POST_CREATE,B.POST_EDIT_OWN,B.POST_DELETE_OWN,B.FRIEND_REQUEST_SEND,B.FRIEND_REQUEST_MANAGE,B.FRIEND_REMOVE,B.FRIEND_LIST,B.COMMAND_CLEAR,...H],[B.USER_KICK,B.USER_MUTE,B.USER_UNMUTE,B.MESSAGE_DELETE_ANY,B.MESSAGE_CLEAR,B.PROFILE_CUSTOMIZE,B.MESSAGE_USE_COMMANDS,B.POST_CREATE,B.POST_EDIT_OWN,B.POST_DELETE_OWN,B.FRIEND_REQUEST_SEND,B.FRIEND_REQUEST_MANAGE,B.FRIEND_REMOVE,B.FRIEND_LIST,B.COMMAND_CLEAR,...H],[B.PROFILE_CUSTOMIZE,B.MESSAGE_USE_COMMANDS,B.POST_CREATE,B.POST_EDIT_OWN,B.POST_DELETE_OWN,B.FRIEND_REQUEST_SEND,B.FRIEND_REQUEST_MANAGE,B.FRIEND_REMOVE,B.FRIEND_LIST,...H],[B.MESSAGE_USE_COMMANDS,B.POST_CREATE,B.POST_EDIT_OWN,B.POST_DELETE_OWN,B.FRIEND_REQUEST_SEND,B.FRIEND_REQUEST_MANAGE,B.FRIEND_REMOVE,B.FRIEND_LIST,...H],[...H];const U={LOCAL:`LOCAL`,MINIO:`MINIO`,CLOUDFLARE_R2:`CLOUDFLARE_R2`,AWS_S3:`AWS_S3`,GCS:`GCS`};function W(e){let t=e?.trim().replace(/^https?:\/\//,``).split(`/`)[0].split(`:`)[0].replace(/^\.+/,``);if(!t||t===`localhost`||t.endsWith(`.localhost`)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return;let n=t.split(`.`);if(n.length>2){let e=[`co`,`com`,`org`,`net`,`gov`,`edu`,`ac`,`sch`],t=n[n.length-1],r=n[n.length-2];return e.includes(r)&&t.length===2&&n.length>=3?n.slice(-3).join(`.`):n.slice(-2).join(`.`)}return t}function re(e){let t=e?.trim().replace(/^https?:\/\//,``).split(`/`)[0].split(`:`)[0].replace(/^\.+/,``).toLowerCase();return t?t===`localhost`||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)?!0:W(t)===t:!1}new Map([{label:`Default`,value:`lato`,family:`'Lato', sans-serif`,googleName:`Lato`,scale:1},{label:`Elegant`,value:`playfair`,family:`'Playfair Display', serif`,googleName:`Playfair Display`,scale:1.1},{label:`Cursive`,value:`dancing`,family:`'Dancing Script', cursive`,googleName:`Dancing Script`,scale:1.2},{label:`Modern`,value:`poppins`,family:`'Poppins', sans-serif`,googleName:`Poppins`,scale:1},{label:`Monospace`,value:`jetbrains`,family:`'JetBrains Mono', monospace`,googleName:`JetBrains Mono`,scale:.95},{label:`Rounded`,value:`quicksand`,family:`'Quicksand', sans-serif`,googleName:`Quicksand`,scale:1},{label:`Serif`,value:`roboto-serif`,family:`'Roboto Serif', serif`,googleName:`Roboto Serif`,scale:1.05},{label:`Sci-Fi`,value:`audiowide`,family:`'Audiowide', cursive`,googleName:`Audiowide`,scale:.95},{label:`Type`,value:`special-elite`,family:`'Special Elite', cursive`,googleName:`Special Elite`,scale:1.15},{label:`Pixel`,value:`press-start`,family:`'Press Start 2P', cursive`,googleName:`Press Start 2P`,scale:.75},{label:`Gothic`,value:`grenze`,family:`'Grenze Gotisch', cursive`,googleName:`Grenze Gotisch`,scale:1.15},{label:`Deco`,value:`righteous`,family:`'Righteous', cursive`,googleName:`Righteous`,scale:1},{label:`Spooky`,value:`creepster`,family:`'Creepster', cursive`,googleName:`Creepster`,scale:1.1},{label:`Shadow`,value:`vast-shadow`,family:`'Vast Shadow', cursive`,googleName:`Vast Shadow`,scale:1.05},{label:`Tech`,value:`syncopate`,family:`'Syncopate', sans-serif`,googleName:`Syncopate`,scale:.9},{label:`Script`,value:`lobster`,family:`'Lobster', cursive`,googleName:`Lobster`,scale:1.05}].map(e=>[e.value,e.scale]));const ie=typeof window<`u`&&window.document!==void 0&&!window.process,G={brand:`color: #06b6d4; font-weight: bold;`,timestamp:`color: #888; font-size: 10px; font-family: monospace;`,info:`color: #3b82f6; font-weight: bold;`,success:`color: #10b981; font-weight: bold;`,warn:`color: #f59e0b; font-weight: bold;`,error:`color: #ef4444; font-weight: bold;`,debug:`color: #6366f1; font-style: italic;`,content:`color: inherit; font-family: inherit;`},K={reset:`\x1B[0m`,brand:`\x1B[1m\x1B[36m`,timestamp:`\x1B[90m`,info:`\x1B[1m\x1B[34m`,success:`\x1B[1m\x1B[32m`,warn:`\x1B[1m\x1B[33m`,error:`\x1B[1m\x1B[31m`,debug:`\x1B[3m\x1B[35m`};new Proxy(console,{get(e,t){if([`info`,`success`,`warn`,`error`,`debug`].includes(t)){let e=new Date().toLocaleTimeString();if(ie)return import.meta.env?.PROD&&t===`debug`?()=>{}:console.log.bind(console,`%c${e} %c[jchat]%c ${t}%c`,G.timestamp,G.brand,G[t],G.content);{let n=K[t]||``,r=K.brand,i=K.timestamp,a=K.reset;return console.log.bind(console,`${i}${e}${a} ${r}[jchat]${a} ${n}${t}${a}${i}`)}}return e[t]}});function ae(e){return t=>e.parse(o(t,`VITE_`,``))}const oe=s.object({JCHAT_PORT:s.string().regex(/^\d+$/).transform(Number).refine(e=>e>=1&&e<=65535,{message:`Port must be between 1 and 65535`}).refine(e=>e!==80&&e!==443,{message:`Avoid ports 80/443 (reserved for HTTP/HTTPS)`}).default(3e3),JCHAT_COOKIE_SECRET:s.string().min(1),JCHAT_DATABASE_URL:s.url().startsWith(`postgresql://`).regex(/^postgresql:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/([^?]+)(\?.*)?$/,{message:`Must be in format: postgresql://username:password@host:port/database?schema`}),JCHAT_REDIS_DATABASE_URL:s.url().refine(e=>e.startsWith(`rediss://`)||e.startsWith(`redis://`),{message:`Must use redis:// or rediss:// protocol`}).refine(e=>/^(rediss?):\/\/(?:([^:]+):([^@]+)@)?([^:]+):(\d+)$/.test(e),{message:`Must be in format: rediss://default:<password>@<host>:<port>`}),JCHAT_STORAGE_TYPE:s.enum(U),JCHAT_MINIO_ENDPOINT:s.string().optional(),JCHAT_MINIO_BUCKET_NAME:s.string().optional(),JCHAT_MINIO_ACCESS_KEY_ID:s.string().optional(),JCHAT_MINIO_SECRET_ACCESS_KEY:s.string().optional(),JCHAT_MINIO_PUBLIC_URL:s.string().optional(),JCHAT_AWS_REGION:s.string().optional(),JCHAT_AWS_BUCKET_NAME:s.string().optional(),JCHAT_AWS_ACCESS_KEY_ID:s.string().optional(),JCHAT_AWS_SECRET_ACCESS_KEY:s.string().optional(),JCHAT_CLOUDFLARE_ACCOUNT_ID:s.string().optional(),JCHAT_CLOUDFLARE_BUCKET_NAME:s.string().optional(),JCHAT_CLOUDFLARE_ACCESS_KEY_ID:s.string().optional(),JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY:s.string().optional(),JCHAT_CLOUDFLARE_PUBLIC_URL:s.string().optional(),JCHAT_GCS_BUCKET_NAME:s.string().optional(),JCHAT_GCS_PROJECT_ID:s.string().optional(),JCHAT_GCS_CLIENT_EMAIL:s.string().optional(),JCHAT_GCS_PRIVATE_KEY:s.string().optional(),JCHAT_GCS_KEY_FILE:s.string().optional(),JCHAT_BOT_NAME:s.string().trim().min(3),JCHAT_BOT_EMAIL:s.email(),JCHAT_DOMAIN:s.string().optional(),JCHAT_SITE_URL:s.url().optional(),JCHAT_ROUTING_MODE:s.enum([`path`,`subdomain`]).default(`subdomain`),JCHAT_ADDON_ENCRYPTION_KEY:s.string().min(16),NODE_ENV:s.enum([`development`,`test`,`production`]).default(`development`),SYSTEM_BOOTSTRAP_COMPLETE:s.boolean().optional()}).superRefine((e,t)=>{if(e.JCHAT_SITE_URL){let n;try{n=new URL(e.JCHAT_SITE_URL).hostname}catch{}n&&!re(n)&&t.addIssue({path:[`JCHAT_SITE_URL`],code:`custom`,message:`JCHAT_SITE_URL must use the client main/root domain`})}e.JCHAT_STORAGE_TYPE===`MINIO`&&!(e.JCHAT_MINIO_ENDPOINT&&e.JCHAT_MINIO_BUCKET_NAME&&e.JCHAT_MINIO_ACCESS_KEY_ID&&e.JCHAT_MINIO_SECRET_ACCESS_KEY&&e.JCHAT_MINIO_PUBLIC_URL)&&(e.JCHAT_MINIO_ENDPOINT||t.addIssue({path:[`JCHAT_MINIO_ENDPOINT`],code:`custom`,message:`JCHAT_MINIO_ENDPOINT is required when JCHAT_STORAGE_TYPE is MINIO`}),e.JCHAT_MINIO_BUCKET_NAME||t.addIssue({path:[`JCHAT_MINIO_BUCKET_NAME`],code:`custom`,message:`JCHAT_MINIO_BUCKET_NAME is required when JCHAT_STORAGE_TYPE is MINIO`}),e.JCHAT_MINIO_ACCESS_KEY_ID||t.addIssue({path:[`JCHAT_MINIO_ACCESS_KEY_ID`],code:`custom`,message:`JCHAT_MINIO_ACCESS_KEY_ID is required when JCHAT_STORAGE_TYPE is MINIO`}),e.JCHAT_MINIO_SECRET_ACCESS_KEY||t.addIssue({path:[`JCHAT_MINIO_SECRET_ACCESS_KEY`],code:`custom`,message:`JCHAT_MINIO_SECRET_ACCESS_KEY is required when JCHAT_STORAGE_TYPE is MINIO`}),e.JCHAT_MINIO_PUBLIC_URL||t.addIssue({path:[`JCHAT_MINIO_PUBLIC_URL`],code:`custom`,message:`JCHAT_MINIO_PUBLIC_URL is required when JCHAT_STORAGE_TYPE is MINIO`})),e.JCHAT_STORAGE_TYPE===`AWS_S3`&&!(e.JCHAT_AWS_REGION&&e.JCHAT_AWS_ACCESS_KEY_ID&&e.JCHAT_AWS_SECRET_ACCESS_KEY&&e.JCHAT_AWS_BUCKET_NAME)&&(e.JCHAT_AWS_REGION||t.addIssue({path:[`JCHAT_AWS_REGION`],code:`custom`,message:`JCHAT_AWS_REGION is required when JCHAT_STORAGE_TYPE is AWS_S3`}),e.JCHAT_AWS_ACCESS_KEY_ID||t.addIssue({path:[`JCHAT_AWS_ACCESS_KEY_ID`],code:`custom`,message:`JCHAT_AWS_ACCESS_KEY_ID is required when JCHAT_STORAGE_TYPE is AWS_S3`}),e.JCHAT_AWS_SECRET_ACCESS_KEY||t.addIssue({path:[`JCHAT_AWS_SECRET_ACCESS_KEY`],code:`custom`,message:`JCHAT_AWS_SECRET_ACCESS_KEY is required when JCHAT_STORAGE_TYPE is AWS_S3`}),e.JCHAT_AWS_BUCKET_NAME||t.addIssue({path:[`JCHAT_AWS_BUCKET_NAME`],code:`custom`,message:`JCHAT_AWS_BUCKET_NAME is required when JCHAT_STORAGE_TYPE is AWS_S3`})),e.JCHAT_STORAGE_TYPE===`CLOUDFLARE_R2`&&!(e.JCHAT_CLOUDFLARE_ACCOUNT_ID&&e.JCHAT_CLOUDFLARE_ACCESS_KEY_ID&&e.JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY&&e.JCHAT_CLOUDFLARE_BUCKET_NAME&&e.JCHAT_CLOUDFLARE_PUBLIC_URL)&&(e.JCHAT_CLOUDFLARE_ACCOUNT_ID||t.addIssue({path:[`JCHAT_CLOUDFLARE_ACCOUNT_ID`],code:`custom`,message:`JCHAT_CLOUDFLARE_ACCOUNT_ID is required when JCHAT_STORAGE_TYPE is CLOUDFLARE_R2`}),e.JCHAT_CLOUDFLARE_ACCESS_KEY_ID||t.addIssue({path:[`JCHAT_CLOUDFLARE_ACCESS_KEY_ID`],code:`custom`,message:`JCHAT_CLOUDFLARE_ACCESS_KEY_ID is required when JCHAT_STORAGE_TYPE is CLOUDFLARE_R2`}),e.JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY||t.addIssue({path:[`JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY`],code:`custom`,message:`JCHAT_CLOUDFLARE_SECRET_ACCESS_KEY is required when JCHAT_STORAGE_TYPE is CLOUDFLARE_R2`}),e.JCHAT_CLOUDFLARE_BUCKET_NAME||t.addIssue({path:[`JCHAT_CLOUDFLARE_BUCKET_NAME`],code:`custom`,message:`JCHAT_CLOUDFLARE_BUCKET_NAME is required when JCHAT_STORAGE_TYPE is CLOUDFLARE_R2`}),e.JCHAT_CLOUDFLARE_PUBLIC_URL||t.addIssue({path:[`JCHAT_CLOUDFLARE_PUBLIC_URL`],code:`custom`,message:`JCHAT_CLOUDFLARE_PUBLIC_URL is required when JCHAT_STORAGE_TYPE is CLOUDFLARE_R2`})),e.JCHAT_STORAGE_TYPE===`GCS`&&!(e.JCHAT_GCS_PROJECT_ID&&e.JCHAT_GCS_BUCKET_NAME&&e.JCHAT_GCS_CLIENT_EMAIL&&e.JCHAT_GCS_PRIVATE_KEY)&&(e.JCHAT_GCS_PROJECT_ID||t.addIssue({path:[`JCHAT_GCS_PROJECT_ID`],code:`custom`,message:`JCHAT_GCS_PROJECT_ID is required when JCHAT_STORAGE_TYPE is GCS`}),e.JCHAT_GCS_BUCKET_NAME||t.addIssue({path:[`JCHAT_GCS_BUCKET_NAME`],code:`custom`,message:`JCHAT_GCS_BUCKET_NAME is required when JCHAT_STORAGE_TYPE is GCS`}),e.JCHAT_GCS_CLIENT_EMAIL||t.addIssue({path:[`JCHAT_GCS_CLIENT_EMAIL`],code:`custom`,message:`JCHAT_GCS_CLIENT_EMAIL is required when JCHAT_STORAGE_TYPE is GCS`}),e.JCHAT_GCS_PRIVATE_KEY||t.addIssue({path:[`JCHAT_GCS_PRIVATE_KEY`],code:`custom`,message:`JCHAT_GCS_PRIVATE_KEY is required when JCHAT_STORAGE_TYPE is GCS`}))});function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e){return typeof e==`string`&&e.trim().length>0}function Y(e){if(!e)return null;try{return JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`))}catch{return null}}function X(e){let t=e.split(`.`);if(t.length!==3)return null;let n=Y(t[0]);return!q(n)||n.alg!==`RS256`||n.typ!==`JWT`?null:{alg:`RS256`,typ:`JWT`}}function se(e){if(!q(e))return null;let{iss:t,aud:n,licenseId:r,domain:i,buyer:a,installationId:o,machineFingerprint:s,plan:c,entitlements:l,purchaseProvider:f,environment:p,routingMode:m,iat:h}=e;if(!J(t)||!J(n)||!J(r)||!J(i)||!J(a)||!J(o)||!J(s)||c!==`standard`&&c!==`extended`||!Array.isArray(l)||!l.every(J)||f!==`envato`&&f!==`jchat`||p!==`production`&&p!==`development`||m!==`path`&&m!==`subdomain`||typeof h!=`number`||!Number.isSafeInteger(h)||h<0)return null;let g;try{g=u(i)}catch{return null}if(p===`development`&&!g.isLocalhost||p===`production`&&!d(i))return null;let _=l.includes(`site.create.multi`);return c===`extended`&&!_||c===`standard`&&_?null:{iss:t,aud:n,licenseId:r,domain:i,buyer:a,installationId:o,machineFingerprint:s,plan:c,entitlements:l,purchaseProvider:f,environment:p,routingMode:m,iat:h}}function Z(e){let t=e.split(`.`);return t.length!==3||!t.every(Boolean)||!X(e)?null:se(Y(t[1]))}function Q(t,n,r){if(!t||t===`YOUR_LICENSE_KEY_PLACEHOLDER`)return!1;try{let i=t.split(`.`);if(i.length!==3||!X(t))return!1;let a=Z(t);if(!a||a.iss!==(r.issuer??`https://license.jchat.local`)||a.aud!==(r.audience??`jchat-chat`)||u(a.domain).host!==u(n).host)return!1;let o=Buffer.from(`${i[0]}.${i[1]}`),s=Buffer.from(i[2].replace(/-/g,`+`).replace(/_/g,`/`),`base64`);return e.verify(`sha256`,o,r.publicKeyPem,s)}catch{return!1}}function $(e,t,n,r,i){if(!Q(e,t,i))return!1;let a=Z(e);return a?a.installationId===n&&a.machineFingerprint===r:!1}function ce(e,t,n,r){return Q(e,t,r)?Z(e)?.entitlements?.includes(n)??!1:!1}export{T as DEFAULT_STATE_PATH,oe as ServerConfigSchema,j as acquireProcessLock,w as activateRegistry,te as checkRegistry,D as createIdentity,E as createMachineFingerprint,x as getRuntimeStatus,ce as hasEntitlement,M as installAndActivate,f as isAllowedConfiguredDomain,S as isApplicationDisabled,d as isPublicDomain,ae as makeTypedEnv,u as normalizeDomain,Z as parsePayload,O as readState,ne as readTokenSync,g as recordAudit,ee as registerInvalidationHandler,m as resolveActivationDomain,N as resolveRuntimePaths,b as setRuntimeStatus,A as updateInstanceToken,$ as verifyEntitlement,Q as verifySignature,k as writeState};
|
package/package.json
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jchat/runtime",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "1.0.0-alpha.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Runtime support package for JChat deployments.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"chat",
|
|
8
|
+
"jchat",
|
|
9
|
+
"runtime"
|
|
10
|
+
],
|
|
6
11
|
"license": "SEE LICENSE",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/mjjabarullah/jchat.git",
|
|
15
|
+
"directory": "packages/runtime"
|
|
16
|
+
},
|
|
7
17
|
"files": [
|
|
8
18
|
"dist",
|
|
9
|
-
"
|
|
19
|
+
"src",
|
|
20
|
+
"README.md",
|
|
21
|
+
"CHANGELOG.md"
|
|
10
22
|
],
|
|
11
23
|
"type": "module",
|
|
12
24
|
"main": "./dist/index.mjs",
|
|
@@ -28,10 +40,18 @@
|
|
|
28
40
|
"test": "bun --config ./bunfig.toml test",
|
|
29
41
|
"prepack": "bun run build"
|
|
30
42
|
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"string-ts": "^2.3.1"
|
|
45
|
+
},
|
|
31
46
|
"devDependencies": {
|
|
32
|
-
"@
|
|
33
|
-
"
|
|
47
|
+
"@jchat/shared": "workspace:*",
|
|
48
|
+
"@types/node": "catalog:",
|
|
49
|
+
"bun-types": "catalog:",
|
|
34
50
|
"tsdown": "^0.22.14",
|
|
35
|
-
"typescript": "
|
|
51
|
+
"typescript": "catalog:",
|
|
52
|
+
"zod": "catalog:"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"zod": "catalog:"
|
|
36
56
|
}
|
|
37
57
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import fs from "node:fs/promises"
|
|
3
|
+
import os from "node:os"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
import { recordAudit } from "./audit"
|
|
6
|
+
|
|
7
|
+
describe("license audit", () => {
|
|
8
|
+
test("writes redacted non-sensitive events", async () => {
|
|
9
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "jchat-audit-runtime-"))
|
|
10
|
+
const filePath = path.join(directory, "events.log")
|
|
11
|
+
await recordAudit(
|
|
12
|
+
"check_rejected",
|
|
13
|
+
{
|
|
14
|
+
domain: "example.com",
|
|
15
|
+
installationId: "installation-secret-123",
|
|
16
|
+
reference: "reference-secret-123"
|
|
17
|
+
},
|
|
18
|
+
filePath
|
|
19
|
+
)
|
|
20
|
+
const content = await Bun.file(filePath).text()
|
|
21
|
+
expect(content).toContain('"event":"check_rejected"')
|
|
22
|
+
expect(content).not.toContain("installation-secret-123")
|
|
23
|
+
expect(content).not.toContain("reference-secret-123")
|
|
24
|
+
})
|
|
25
|
+
})
|
package/src/audit.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from "node:fs/promises"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
|
|
4
|
+
export type AuditEvent = "check_success" | "check_unreachable" | "check_rejected"
|
|
5
|
+
|
|
6
|
+
function redact(value: string | undefined): string | undefined {
|
|
7
|
+
if (!value) return undefined
|
|
8
|
+
return value.length <= 8 ? "redacted" : `${value.slice(0, 4)}…${value.slice(-4)}`
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function recordAudit(
|
|
12
|
+
event: AuditEvent,
|
|
13
|
+
details: { domain?: string; installationId?: string; reference?: string },
|
|
14
|
+
filePath = path.resolve(process.cwd(), "data/license-events.log")
|
|
15
|
+
): Promise<void> {
|
|
16
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true })
|
|
17
|
+
const line = JSON.stringify({
|
|
18
|
+
at: new Date().toISOString(),
|
|
19
|
+
event,
|
|
20
|
+
domain: redact(details.domain),
|
|
21
|
+
installationId: redact(details.installationId),
|
|
22
|
+
reference: redact(details.reference)
|
|
23
|
+
})
|
|
24
|
+
await fs.appendFile(filePath, `${line}\n`, "utf8")
|
|
25
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { activateRegistry, checkRegistry } from "./check"
|
|
3
|
+
|
|
4
|
+
describe("license check", () => {
|
|
5
|
+
test("activates through the default registry endpoint", async () => {
|
|
6
|
+
let request: Request | undefined
|
|
7
|
+
const result = await activateRegistry({
|
|
8
|
+
purchaseCode: "purchase-code",
|
|
9
|
+
domain: "www.example.com:8080",
|
|
10
|
+
provider: "envato",
|
|
11
|
+
routingMode: "path",
|
|
12
|
+
installationId: "installation-1",
|
|
13
|
+
installationPublicKey: "public-key",
|
|
14
|
+
machineFingerprint: "machine-1",
|
|
15
|
+
fetchImpl: async (input, init) => {
|
|
16
|
+
request = new Request(input, init)
|
|
17
|
+
return Response.json({ success: true, buyer: "Buyer", token: "signed-token" })
|
|
18
|
+
}
|
|
19
|
+
})
|
|
20
|
+
expect(result).toEqual({
|
|
21
|
+
success: true,
|
|
22
|
+
buyer: "Buyer",
|
|
23
|
+
token: "signed-token",
|
|
24
|
+
domain: "example.com"
|
|
25
|
+
})
|
|
26
|
+
expect(request?.url).toBe("http://localhost:4000/api/activate")
|
|
27
|
+
expect((await request?.json())?.domain).toBe("example.com")
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test("uses the local registry endpoint by default", async () => {
|
|
31
|
+
let requestedUrl = ""
|
|
32
|
+
await checkRegistry({
|
|
33
|
+
token: "local-token",
|
|
34
|
+
domain: "example.com",
|
|
35
|
+
routingMode: "path",
|
|
36
|
+
installationId: "installation-1",
|
|
37
|
+
machineFingerprint: "machine-1",
|
|
38
|
+
localTokenValidator: () => true,
|
|
39
|
+
fetchImpl: async (input) => {
|
|
40
|
+
requestedUrl = String(input)
|
|
41
|
+
return new Response("down", { status: 503 })
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
expect(requestedUrl).toBe("http://localhost:4000/api/check")
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test("falls back to the local token on server errors", async () => {
|
|
48
|
+
const result = await checkRegistry({
|
|
49
|
+
token: "local-token",
|
|
50
|
+
domain: "example.com",
|
|
51
|
+
routingMode: "path",
|
|
52
|
+
registryEndpoint: "https://license.example",
|
|
53
|
+
installationId: "installation-1",
|
|
54
|
+
machineFingerprint: "machine-1",
|
|
55
|
+
localTokenValidator: () => true,
|
|
56
|
+
fetchImpl: async () => new Response("down", { status: 503 })
|
|
57
|
+
})
|
|
58
|
+
expect(result).toEqual({
|
|
59
|
+
status: "unreachable-fallback",
|
|
60
|
+
token: "local-token",
|
|
61
|
+
error: "HTTP 503"
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test("fails closed on an explicit client error", async () => {
|
|
66
|
+
const result = await checkRegistry({
|
|
67
|
+
token: "local-token",
|
|
68
|
+
domain: "example.com",
|
|
69
|
+
routingMode: "path",
|
|
70
|
+
registryEndpoint: "https://license.example",
|
|
71
|
+
installationId: "installation-1",
|
|
72
|
+
machineFingerprint: "machine-1",
|
|
73
|
+
fetchImpl: async () => new Response("invalid", { status: 403 })
|
|
74
|
+
})
|
|
75
|
+
expect(result.status).toBe("invalid")
|
|
76
|
+
})
|
|
77
|
+
})
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import crypto from "node:crypto"
|
|
2
|
+
import { recordAudit } from "./audit"
|
|
3
|
+
import { normalizeDomain } from "./domain"
|
|
4
|
+
import { parsePayload, verifyEntitlement, type RuntimeOptions } from "./index"
|
|
5
|
+
import { setRuntimeStatus } from "./runtime"
|
|
6
|
+
|
|
7
|
+
const DEFAULT_REGISTRY_ENDPOINT = Buffer.from("aHR0cDovL2xvY2FsaG9zdDo0MDAw", "base64").toString(
|
|
8
|
+
"utf8"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
export type CheckResult =
|
|
12
|
+
| { status: "valid"; token: string }
|
|
13
|
+
| { status: "unreachable-fallback"; token: string; error: string }
|
|
14
|
+
| { status: "invalid"; error: string; reference: string }
|
|
15
|
+
|
|
16
|
+
export type RegistryProvider = "envato" | "jchat"
|
|
17
|
+
export type RegistryRoutingMode = "path" | "subdomain"
|
|
18
|
+
|
|
19
|
+
export type ActivationInput = {
|
|
20
|
+
purchaseCode: string
|
|
21
|
+
domain: string
|
|
22
|
+
siteSlug?: string
|
|
23
|
+
domainScope?: "current-host" | "parent-domain"
|
|
24
|
+
provider: RegistryProvider
|
|
25
|
+
routingMode: RegistryRoutingMode
|
|
26
|
+
installationId: string
|
|
27
|
+
installationPublicKey: string
|
|
28
|
+
machineFingerprint: string
|
|
29
|
+
registryEndpoint?: string
|
|
30
|
+
fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ActivationResult =
|
|
34
|
+
| { success: true; buyer: string; token: string; domain: string }
|
|
35
|
+
| { success: false; message: string }
|
|
36
|
+
|
|
37
|
+
export async function activateRegistry(input: ActivationInput): Promise<ActivationResult> {
|
|
38
|
+
try {
|
|
39
|
+
const response = await (input.fetchImpl ?? fetch)(
|
|
40
|
+
`${input.registryEndpoint ?? DEFAULT_REGISTRY_ENDPOINT}/api/activate`,
|
|
41
|
+
{
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "Content-Type": "application/json" },
|
|
44
|
+
body: JSON.stringify({
|
|
45
|
+
purchaseCode: input.purchaseCode,
|
|
46
|
+
domain: normalizeDomain(input.domain).host,
|
|
47
|
+
siteSlug: input.siteSlug,
|
|
48
|
+
domainScope: input.domainScope,
|
|
49
|
+
provider: input.provider,
|
|
50
|
+
routingMode: input.routingMode,
|
|
51
|
+
installationId: input.installationId,
|
|
52
|
+
installationPublicKey: input.installationPublicKey,
|
|
53
|
+
machineFingerprint: input.machineFingerprint
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
const body = (await response.json()) as {
|
|
58
|
+
success?: boolean
|
|
59
|
+
buyer?: string
|
|
60
|
+
token?: string
|
|
61
|
+
domain?: string
|
|
62
|
+
message?: string
|
|
63
|
+
}
|
|
64
|
+
if (response.ok === false || !body.success || !body.token) {
|
|
65
|
+
return {
|
|
66
|
+
success: false,
|
|
67
|
+
message:
|
|
68
|
+
body.message ??
|
|
69
|
+
"This license is already active on another domain. Please deactivate it first."
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
success: true,
|
|
74
|
+
buyer: body.buyer ?? "Customer",
|
|
75
|
+
token: body.token,
|
|
76
|
+
domain: body.domain ?? normalizeDomain(input.domain).host
|
|
77
|
+
}
|
|
78
|
+
} catch {
|
|
79
|
+
return {
|
|
80
|
+
success: false,
|
|
81
|
+
message: "Failed to connect to the central registry. Please try again later."
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export type CheckInput = {
|
|
87
|
+
token: string
|
|
88
|
+
domain: string
|
|
89
|
+
routingMode: RegistryRoutingMode
|
|
90
|
+
installationId: string
|
|
91
|
+
machineFingerprint: string
|
|
92
|
+
registryEndpoint?: string
|
|
93
|
+
runtimeOptions?: RuntimeOptions
|
|
94
|
+
auditPath?: string
|
|
95
|
+
fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
|
96
|
+
localTokenValidator?: (
|
|
97
|
+
token: string,
|
|
98
|
+
domain: string,
|
|
99
|
+
installationId: string,
|
|
100
|
+
machineFingerprint: string
|
|
101
|
+
) => boolean
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function checkRegistry(input: CheckInput): Promise<CheckResult> {
|
|
105
|
+
const fetchImpl = input.fetchImpl ?? fetch
|
|
106
|
+
const localTokenValidator =
|
|
107
|
+
input.localTokenValidator ??
|
|
108
|
+
((token, domain, installationId, machineFingerprint) =>
|
|
109
|
+
input.runtimeOptions
|
|
110
|
+
? verifyEntitlement(token, domain, installationId, machineFingerprint, input.runtimeOptions)
|
|
111
|
+
: false)
|
|
112
|
+
|
|
113
|
+
const reject = (domain: string, error: string): CheckResult => {
|
|
114
|
+
const reference = crypto.randomUUID()
|
|
115
|
+
setRuntimeStatus("invalid", reference)
|
|
116
|
+
void recordAudit("check_rejected", { domain, reference }, input.auditPath)
|
|
117
|
+
return { status: "invalid", error, reference }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const useLocalFallback = (error: string): CheckResult => {
|
|
121
|
+
const normalizedDomain = normalizeDomain(input.domain).host
|
|
122
|
+
if (
|
|
123
|
+
!localTokenValidator(
|
|
124
|
+
input.token,
|
|
125
|
+
normalizedDomain,
|
|
126
|
+
input.installationId,
|
|
127
|
+
input.machineFingerprint
|
|
128
|
+
)
|
|
129
|
+
) {
|
|
130
|
+
return reject(normalizedDomain, "Local license validation failed.")
|
|
131
|
+
}
|
|
132
|
+
setRuntimeStatus("unreachable-fallback")
|
|
133
|
+
void recordAudit("check_unreachable", { domain: normalizedDomain }, input.auditPath)
|
|
134
|
+
return { status: "unreachable-fallback", token: input.token, error }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const normalizedDomain = normalizeDomain(input.domain).host
|
|
139
|
+
const registryEndpoint = input.registryEndpoint ?? DEFAULT_REGISTRY_ENDPOINT
|
|
140
|
+
const response = await fetchImpl(`${registryEndpoint}/api/check`, {
|
|
141
|
+
method: "POST",
|
|
142
|
+
headers: { "Content-Type": "application/json" },
|
|
143
|
+
body: JSON.stringify({
|
|
144
|
+
token: input.token,
|
|
145
|
+
domain: normalizedDomain,
|
|
146
|
+
routingMode: input.routingMode,
|
|
147
|
+
installationId: input.installationId,
|
|
148
|
+
machineFingerprint: input.machineFingerprint
|
|
149
|
+
})
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
if (response.status >= 500) return useLocalFallback(`HTTP ${response.status}`)
|
|
154
|
+
return reject(normalizedDomain, "License rejected by jchat service.")
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const body = (await response.json()) as { success?: boolean; token?: string }
|
|
158
|
+
if (!body.success || !body.token) {
|
|
159
|
+
return reject(normalizedDomain, "License rejected by jchat service.")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const isValid = input.runtimeOptions
|
|
163
|
+
? verifyEntitlement(
|
|
164
|
+
body.token,
|
|
165
|
+
normalizedDomain,
|
|
166
|
+
input.installationId,
|
|
167
|
+
input.machineFingerprint,
|
|
168
|
+
input.runtimeOptions
|
|
169
|
+
)
|
|
170
|
+
: false
|
|
171
|
+
if (!isValid && !input.localTokenValidator) {
|
|
172
|
+
return reject(normalizedDomain, "License rejected by jchat service.")
|
|
173
|
+
}
|
|
174
|
+
if (
|
|
175
|
+
input.localTokenValidator &&
|
|
176
|
+
!input.localTokenValidator(
|
|
177
|
+
body.token,
|
|
178
|
+
normalizedDomain,
|
|
179
|
+
input.installationId,
|
|
180
|
+
input.machineFingerprint
|
|
181
|
+
)
|
|
182
|
+
) {
|
|
183
|
+
return reject(normalizedDomain, "License rejected by jchat service.")
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const payload = parsePayload(body.token)
|
|
187
|
+
if (
|
|
188
|
+
!payload ||
|
|
189
|
+
payload.installationId !== input.installationId ||
|
|
190
|
+
payload.machineFingerprint !== input.machineFingerprint ||
|
|
191
|
+
payload.routingMode !== input.routingMode
|
|
192
|
+
) {
|
|
193
|
+
return reject(normalizedDomain, "License binding rejected by jchat service.")
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
setRuntimeStatus("valid")
|
|
197
|
+
void recordAudit("check_success", { domain: normalizedDomain }, input.auditPath)
|
|
198
|
+
return { status: "valid", token: body.token }
|
|
199
|
+
} catch {
|
|
200
|
+
return useLocalFallback("License service unreachable.")
|
|
201
|
+
}
|
|
202
|
+
}
|