@codeo-engineering/licenserail-youtrack 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ // LicenseRail admin endpoints for the License page (widget "licenserail-license"). Administrators only; responses never
2
+ // contain the license key or the token (Marketplace rule: open endpoints don't expose license data).
3
+
4
+ const licenserail = require('./licenserail');
5
+
6
+ function isAdmin(ctx) {
7
+ try { return ctx.currentUser.hasPermission('ADMIN_UPDATE_APP'); } catch (e) { return false; }
8
+ }
9
+
10
+ function guard(ctx, run) {
11
+ if (!isAdmin(ctx)) {
12
+ ctx.response.statusCode = 403;
13
+ ctx.response.json({ error: 'forbidden', message: 'Only administrators can manage the license.' });
14
+ return;
15
+ }
16
+ try {
17
+ run();
18
+ } catch (e) {
19
+ ctx.response.statusCode = 400;
20
+ ctx.response.json({ error: 'bad_request', message: e && e.message ? e.message : String(e) });
21
+ }
22
+ }
23
+
24
+ function body(ctx) {
25
+ try { return ctx.request.json() || {}; } catch (e) { return {}; }
26
+ }
27
+
28
+ function remember(ctx) {
29
+ const id = body(ctx).installationId;
30
+ if (id) licenserail.setInstallation(ctx, id);
31
+ }
32
+
33
+ exports.httpHandler = {
34
+ endpoints: [
35
+ {
36
+ method: 'GET',
37
+ path: 'status',
38
+ permissions: ['ADMIN_UPDATE_APP'],
39
+ handle: function (ctx) {
40
+ guard(ctx, function () { ctx.response.json(licenserail.status(ctx)); });
41
+ },
42
+ },
43
+ {
44
+ method: 'POST',
45
+ path: 'activate',
46
+ permissions: ['ADMIN_UPDATE_APP'],
47
+ handle: function (ctx) {
48
+ guard(ctx, function () {
49
+ remember(ctx);
50
+ licenserail.activate(ctx);
51
+ ctx.response.statusCode = 202;
52
+ ctx.response.json(licenserail.status(ctx));
53
+ });
54
+ },
55
+ },
56
+ {
57
+ method: 'POST',
58
+ path: 'trial',
59
+ permissions: ['ADMIN_UPDATE_APP'],
60
+ handle: function (ctx) {
61
+ guard(ctx, function () {
62
+ remember(ctx);
63
+ licenserail.startTrial(ctx);
64
+ ctx.response.statusCode = 202;
65
+ ctx.response.json(licenserail.status(ctx));
66
+ });
67
+ },
68
+ },
69
+ {
70
+ method: 'POST',
71
+ path: 'refresh',
72
+ permissions: ['ADMIN_UPDATE_APP'],
73
+ handle: function (ctx) {
74
+ guard(ctx, function () {
75
+ remember(ctx);
76
+ licenserail.refresh(ctx);
77
+ ctx.response.statusCode = 202;
78
+ ctx.response.json(licenserail.status(ctx));
79
+ });
80
+ },
81
+ },
82
+ {
83
+ method: 'POST',
84
+ path: 'deactivate',
85
+ permissions: ['ADMIN_UPDATE_APP'],
86
+ handle: function (ctx) {
87
+ guard(ctx, function () {
88
+ licenserail.deactivate(ctx);
89
+ ctx.response.statusCode = 202;
90
+ ctx.response.json(licenserail.status(ctx));
91
+ });
92
+ },
93
+ },
94
+ ],
95
+ asyncFunctions: licenserail.asyncFunctions,
96
+ };
@@ -0,0 +1,232 @@
1
+ // LicenseRail for YouTrack apps: license checks for your own handlers, plus the async functions that talk to the license
2
+ // server. Readable on purpose (JetBrains Marketplace rule: verify signed license data in readable code).
3
+ //
4
+ // const licenserail = require('./licenserail');
5
+ // exports.httpHandler = {
6
+ // endpoints: [{ method: 'GET', path: 'report', handle(ctx) {
7
+ // const license = licenserail.check(ctx);
8
+ // if (!license.valid) { ctx.response.statusCode = 402; ctx.response.json({ error: 'license_required' }); return; }
9
+ // ...
10
+ // } }],
11
+ // asyncFunctions: licenserail.asyncFunctions, // lets check() schedule the daily refresh
12
+ // };
13
+
14
+ const core = require('./licenserail-core');
15
+ const config = require('./licenserail-config');
16
+
17
+ const PROPERTY = {
18
+ token: 'licenserailToken',
19
+ lastSeen: 'licenserailLastSeen',
20
+ installation: 'licenserailInstallation',
21
+ state: 'licenserailState',
22
+ };
23
+ const PLATFORM = 'youtrack';
24
+ const REFRESH = 'licenserailRefresh';
25
+ const RESPONSE = 'licenserailResponse';
26
+ const RELEASED = 'licenserailReleased';
27
+ const LAST_SEEN_WRITE_MS = 60 * 60 * 1000; // store "last run" at most hourly: few writes, enough for the clock check
28
+
29
+ function props(ctx) {
30
+ return ctx.globalStorage.extensionProperties;
31
+ }
32
+
33
+ function readState(ctx) {
34
+ try { return JSON.parse(props(ctx)[PROPERTY.state] || '{}'); } catch (e) { return {}; }
35
+ }
36
+
37
+ function writeState(ctx, change) {
38
+ const next = Object.assign(readState(ctx), change);
39
+ props(ctx)[PROPERTY.state] = JSON.stringify(next);
40
+ return next;
41
+ }
42
+
43
+ /** The YouTrack instance's number of users (for licenses priced per user), or undefined if not available. */
44
+ function hostUsers() {
45
+ try { return require('@jetbrains/youtrack-scripting-api/license').licenseInfo.currentUserCount; } catch (e) { return undefined; }
46
+ }
47
+
48
+ function installationId(ctx) {
49
+ return props(ctx)[PROPERTY.installation] || null;
50
+ }
51
+
52
+ function fingerprint(ctx) {
53
+ const id = installationId(ctx);
54
+ return id ? core.installationFingerprint(config.vendor, config.product, PLATFORM, id) : null;
55
+ }
56
+
57
+ function target(ctx) {
58
+ return { apiUrl: config.apiUrl, product: config.product, fingerprint: fingerprint(ctx) };
59
+ }
60
+
61
+ /**
62
+ * Sends a request description with YouTrack's async HTTP (required for Marketplace apps). The response arrives later in the
63
+ * named async function. With `withKey`, the license key from the secret setting goes in `Authorization: Bearer`.
64
+ */
65
+ function send(ctx, request, callback, withKey) {
66
+ const http = require('@jetbrains/youtrack-scripting-api/http');
67
+ const connection = new http.Connection(config.apiUrl.replace(/\/+$/, ''), null, 20000);
68
+ Object.keys(request.headers).forEach(function (name) { connection.addHeader(name, request.headers[name]); });
69
+ if (withKey) connection.bearerAuth(ctx.settings.licenseKey);
70
+ const path = request.url.substring(config.apiUrl.replace(/\/+$/, '').length);
71
+ connection.postAsync(path, {}, request.body, callback);
72
+ }
73
+
74
+ /**
75
+ * The license, checked offline from app storage (no network). `valid` is true for a valid license or trial.
76
+ * Schedules the daily refresh when the token asks for it (needs `asyncFunctions: licenserail.asyncFunctions` in the
77
+ * calling handler).
78
+ */
79
+ function check(ctx) {
80
+ return inspect(ctx, true);
81
+ }
82
+
83
+ function inspect(ctx, scheduleRefresh) {
84
+ const token = props(ctx)[PROPERTY.token];
85
+ const fp = fingerprint(ctx);
86
+ if (!token || !fp) return { valid: false, status: 'Missing', summary: null };
87
+ const payload = core.verifyToken(token, config.publicKeyPem);
88
+ const seenText = props(ctx)[PROPERTY.lastSeen];
89
+ const lastSeen = seenText ? new Date(Number(seenText)) : null;
90
+ const now = new Date();
91
+ const status = core.evaluate(payload, config.product, fp, now, lastSeen);
92
+ if (status === 'Valid' && (!lastSeen || now.getTime() - lastSeen.getTime() > LAST_SEEN_WRITE_MS)) props(ctx)[PROPERTY.lastSeen] = String(now.getTime());
93
+ if (payload) {
94
+ const due = core.refreshDueAt(payload);
95
+ if (scheduleRefresh && due && due.getTime() <= now.getTime() && typeof ctx.invokeAsync === 'function') {
96
+ try { ctx.invokeAsync(REFRESH, 0, 'licenserail-refresh'); } catch (e) { /* the calling handler doesn't declare the async functions */ }
97
+ }
98
+ }
99
+ return { valid: status === 'Valid', status: status, summary: payload ? core.summarize(payload, hostUsers()) : null };
100
+ }
101
+
102
+ /** Feature flag from the license (entitlements set in LicenseRail). */
103
+ function hasFeature(ctx, code) {
104
+ const license = inspect(ctx, false);
105
+ return license.valid && license.summary.entitlements.indexOf(code) >= 0;
106
+ }
107
+
108
+ /** Remembers this YouTrack instance's id (read by the admin page from /api/config). */
109
+ function setInstallation(ctx, id) {
110
+ if (typeof id !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(id)) throw new Error('Invalid installation id.');
111
+ if (props(ctx)[PROPERTY.installation] !== id) props(ctx)[PROPERTY.installation] = id;
112
+ }
113
+
114
+ function common(ctx) {
115
+ return { machineName: 'YouTrack', appVersion: config.appVersion, hostUsers: hostUsers() };
116
+ }
117
+
118
+ function activate(ctx) {
119
+ const t = target(ctx);
120
+ if (!t.fingerprint) throw new Error('Open the license page once so the app knows this YouTrack instance.');
121
+ writeState(ctx, { pending: 'activate', lastAttemptAt: new Date().toISOString() });
122
+ send(ctx, core.activateRequest(Object.assign(t, common(ctx))), RESPONSE, true);
123
+ }
124
+
125
+ function startTrial(ctx) {
126
+ const t = target(ctx);
127
+ if (!t.fingerprint) throw new Error('Open the license page once so the app knows this YouTrack instance.');
128
+ writeState(ctx, { pending: 'trial', lastAttemptAt: new Date().toISOString() });
129
+ send(ctx, core.trialRequest(Object.assign(t, common(ctx), { keyId: config.keyId })), RESPONSE, false);
130
+ }
131
+
132
+ function refresh(ctx) {
133
+ const token = props(ctx)[PROPERTY.token];
134
+ const t = target(ctx);
135
+ if (!token || !t.fingerprint) return false;
136
+ const payload = core.verifyToken(token, config.publicKeyPem);
137
+ if (!payload || payload.trial) return false;
138
+ writeState(ctx, { pending: 'refresh', lastAttemptAt: new Date().toISOString() });
139
+ send(ctx, core.refreshRequest(Object.assign(t, { token: token, appVersion: config.appVersion, hostUsers: hostUsers(), floating: payload.floating === true })), RESPONSE, false);
140
+ return true;
141
+ }
142
+
143
+ function deactivate(ctx) {
144
+ const token = props(ctx)[PROPERTY.token];
145
+ const t = target(ctx);
146
+ const payload = token ? core.verifyToken(token, config.publicKeyPem) : null;
147
+ if (!token || !t.fingerprint || !payload || payload.trial) {
148
+ props(ctx)[PROPERTY.token] = null;
149
+ writeState(ctx, { pending: null, lastError: null });
150
+ return false;
151
+ }
152
+ writeState(ctx, { pending: 'deactivate', lastAttemptAt: new Date().toISOString() });
153
+ send(ctx, core.deactivateRequest(Object.assign(t, { token: token, floating: payload.floating === true })), RELEASED, false);
154
+ return true;
155
+ }
156
+
157
+ /** Admin page data: never the token or the key. */
158
+ function status(ctx) {
159
+ const license = inspect(ctx, false);
160
+ const state = readState(ctx);
161
+ const s = license.summary;
162
+ return {
163
+ status: license.status,
164
+ valid: license.valid,
165
+ isTrial: s ? s.isTrial : false,
166
+ isTest: s ? s.isTest : false,
167
+ expiresAt: s && s.expiresAt ? s.expiresAt.toISOString() : null,
168
+ entitlements: s ? s.entitlements : [],
169
+ hostUsers: hostUsers() === undefined ? null : hostUsers(),
170
+ maxHostUsers: s ? s.maxHostUsers : null,
171
+ hostUsersOverLimit: s ? s.hostUsersOverLimit : false,
172
+ installationKnown: !!installationId(ctx),
173
+ keyConfigured: !!ctx.settings.licenseKey,
174
+ pending: state.pending || null,
175
+ lastAttemptAt: state.lastAttemptAt || null,
176
+ lastError: state.lastError || null,
177
+ };
178
+ }
179
+
180
+ function responseOf(ctx) {
181
+ const r = ctx.response;
182
+ if (!r) return { status: 0, body: '' };
183
+ return { status: r.code || 0, body: typeof r.body === 'string' ? r.body : (r.response || '') };
184
+ }
185
+
186
+ const asyncFunctions = {};
187
+
188
+ asyncFunctions[REFRESH] = function (ctx) {
189
+ refresh(ctx);
190
+ };
191
+
192
+ asyncFunctions[RESPONSE] = function (ctx) {
193
+ const res = responseOf(ctx);
194
+ const r = core.readResponse(res.status, res.body);
195
+ if (r.ok && r.token) {
196
+ if (!core.verifyToken(r.token, config.publicKeyPem)) {
197
+ writeState(ctx, { pending: null, lastError: { code: 'invalid_token', message: 'The license server returned a token that does not verify.' } });
198
+ return;
199
+ }
200
+ props(ctx)[PROPERTY.token] = r.token;
201
+ props(ctx)[PROPERTY.lastSeen] = String(Date.now());
202
+ writeState(ctx, { pending: null, lastError: null, lastSuccessAt: new Date().toISOString() });
203
+ return;
204
+ }
205
+ if (!r.ok) {
206
+ if (r.revokesLocalLicense) props(ctx)[PROPERTY.token] = null;
207
+ writeState(ctx, { pending: null, lastError: { code: r.code, message: r.message } });
208
+ }
209
+ };
210
+
211
+ asyncFunctions[RELEASED] = function (ctx) {
212
+ const res = responseOf(ctx);
213
+ const r = core.readResponse(res.status, res.body);
214
+ if (r.ok || r.revokesLocalLicense) {
215
+ props(ctx)[PROPERTY.token] = null;
216
+ writeState(ctx, { pending: null, lastError: null });
217
+ } else {
218
+ writeState(ctx, { pending: null, lastError: { code: r.code, message: r.message } });
219
+ }
220
+ };
221
+
222
+ module.exports = {
223
+ check: check,
224
+ hasFeature: hasFeature,
225
+ setInstallation: setInstallation,
226
+ activate: activate,
227
+ startTrial: startTrial,
228
+ refresh: refresh,
229
+ deactivate: deactivate,
230
+ status: status,
231
+ asyncFunctions: asyncFunctions,
232
+ };
@@ -0,0 +1,29 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <link rel="stylesheet" href="license.css">
6
+ </head>
7
+ <body>
8
+ <main id="root">
9
+ <h1>License</h1>
10
+ <section id="status" class="card" aria-live="polite">Loading…</section>
11
+ <section class="card">
12
+ <h2>Activate a license key</h2>
13
+ <p id="key-hint"></p>
14
+ <div class="actions">
15
+ <button id="activate" class="primary" disabled>Activate</button>
16
+ <button id="refresh" disabled>Check now</button>
17
+ <button id="deactivate" disabled>Release this instance</button>
18
+ </div>
19
+ </section>
20
+ <section class="card" id="trial-card" hidden>
21
+ <h2>Trial</h2>
22
+ <p>Try the app on this YouTrack instance without a key. One trial per instance.</p>
23
+ <div class="actions"><button id="trial">Start trial</button></div>
24
+ </section>
25
+ <p id="message" class="message" role="status"></p>
26
+ </main>
27
+ <script type="module" src="license.js"></script>
28
+ </body>
29
+ </html>
@@ -0,0 +1,21 @@
1
+ body { margin: 0; font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #1f2329; background: transparent; }
2
+ main { max-width: 640px; padding: 16px 24px; }
3
+ h1 { font-size: 20px; margin: 0 0 16px; }
4
+ h2 { font-size: 15px; margin: 0 0 8px; }
5
+ .card { border: 1px solid #dfe1e5; border-radius: 6px; padding: 12px 16px; margin-bottom: 12px; }
6
+ .card p { margin: 4px 0; }
7
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
8
+ button { font: inherit; padding: 4px 12px; border-radius: 4px; border: 1px solid #c4c7cc; background: #fff; cursor: pointer; }
9
+ button.primary { background: #1a73e8; border-color: #1a73e8; color: #fff; }
10
+ button:disabled { opacity: .5; cursor: default; }
11
+ .state { font-weight: 600; }
12
+ .ok { color: #1e7e34; }
13
+ .bad { color: #c5221f; }
14
+ .warn { color: #b06000; }
15
+ .muted, .message { color: #5f6368; }
16
+ @media (prefers-color-scheme: dark) {
17
+ body { color: #e8eaed; }
18
+ .card { border-color: #3c4043; }
19
+ button { background: #2a2d31; color: #e8eaed; border-color: #5f6368; }
20
+ .muted, .message { color: #9aa0a6; }
21
+ }
@@ -0,0 +1,93 @@
1
+ // LicenseRail License page (administration menu). Talks to the app's own "licenserail-license" handler; the license key
2
+ // itself is entered in the app's settings (a secret setting the page can't read).
3
+
4
+ const host = await YTApp.register()
5
+ const $ = (id) => document.getElementById(id)
6
+ const HANDLER = 'licenserail-license'
7
+
8
+ let installationId = null
9
+ try {
10
+ installationId = (await host.fetchYouTrack('config?fields=uuid', { method: 'GET' })).uuid ?? null
11
+ } catch {
12
+ installationId = null
13
+ }
14
+
15
+ async function call(path, method = 'GET') {
16
+ return host.fetchApp(`${HANDLER}/${path}`, method === 'GET' ? { method } : { method, body: { installationId } })
17
+ }
18
+
19
+ const LABELS = {
20
+ Valid: 'Licensed',
21
+ Missing: 'Not activated',
22
+ Expired: 'Expired',
23
+ OfflineTooLong: 'Not verified for too long',
24
+ WrongMachine: 'Activated for another YouTrack instance',
25
+ Suspended: 'Suspended',
26
+ ClockTampered: 'The server clock looks wrong',
27
+ Unverified: 'Waiting for the first check',
28
+ InvalidSignature: 'Invalid license data',
29
+ WrongProduct: 'The license is for another app',
30
+ }
31
+
32
+ function render(s) {
33
+ const lines = []
34
+ const label = s.valid && s.isTrial ? 'Trial' : (LABELS[s.status] ?? s.status)
35
+ lines.push(`<p class="state ${s.valid ? 'ok' : 'bad'}">${label}${s.isTest ? ' (test)' : ''}</p>`)
36
+ if (s.expiresAt) lines.push(`<p>${s.valid ? 'Valid until' : 'Ended'} ${new Date(s.expiresAt).toLocaleDateString()}</p>`)
37
+ if (s.maxHostUsers !== null) {
38
+ lines.push(`<p${s.hostUsersOverLimit ? ' class="warn"' : ''}>Users: ${s.hostUsers ?? '?'} of ${s.maxHostUsers} allowed</p>`)
39
+ }
40
+ if (s.pending) lines.push('<p class="muted">Contacting the license server…</p>')
41
+ if (s.lastError) lines.push(`<p class="bad">${escapeHtml(s.lastError.message)}</p>`)
42
+ $('status').innerHTML = lines.join('')
43
+ $('key-hint').textContent = s.keyConfigured
44
+ ? 'A license key is set in this app\'s settings.'
45
+ : 'Enter the license key in this app\'s settings (Administration → Apps → this app → Settings), then activate.'
46
+ $('activate').disabled = !s.keyConfigured || !installationId || !!s.pending
47
+ $('refresh').disabled = s.status === 'Missing' || s.isTrial || !!s.pending
48
+ $('deactivate').disabled = s.status === 'Missing' || !!s.pending
49
+ $('trial-card').hidden = (s.valid && !s.isTrial) || s.isTrial
50
+ $('trial').disabled = !installationId || !!s.pending
51
+ }
52
+
53
+ function escapeHtml(text) {
54
+ return String(text).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
55
+ }
56
+
57
+ async function load() {
58
+ try {
59
+ const s = await call('status')
60
+ render(s)
61
+ return s
62
+ } catch (e) {
63
+ $('status').textContent = 'The license status could not be loaded.'
64
+ return null
65
+ }
66
+ }
67
+
68
+ async function act(path, done) {
69
+ $('message').textContent = ''
70
+ try {
71
+ render(await call(path, 'POST'))
72
+ } catch (e) {
73
+ $('message').textContent = e?.message ?? 'The request failed.'
74
+ return
75
+ }
76
+ // The license server answers asynchronously: poll until the pending request is finished (up to 30 s).
77
+ for (let i = 0; i < 15; i++) {
78
+ await new Promise((r) => setTimeout(r, 2000))
79
+ const s = await load()
80
+ if (s && !s.pending) {
81
+ $('message').textContent = s.lastError ? '' : done
82
+ return
83
+ }
84
+ }
85
+ }
86
+
87
+ $('activate').onclick = () => act('activate', 'The license is active.')
88
+ $('trial').onclick = () => act('trial', 'The trial has started.')
89
+ $('refresh').onclick = () => act('refresh', 'The license was checked.')
90
+ $('deactivate').onclick = () => act('deactivate', 'This instance no longer uses the license.')
91
+
92
+ if (!installationId) $('message').textContent = 'This YouTrack instance\'s id could not be read; activation is unavailable.'
93
+ await load()
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@codeo-engineering/licenserail-youtrack",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "LicenseRail for YouTrack apps: license keys, keyless trials and per-user limits for apps sold outside JetBrains Marketplace billing. Adds readable backend modules and a License admin page to your app.",
5
+ "license": "MIT",
6
+ "publishConfig": { "access": "public" },
7
+ "author": "Codeo Solutions Limited",
8
+ "homepage": "https://licenserail.com",
9
+ "repository": { "type": "git", "url": "git+https://github.com/codeo-engineering/licenserail-sdks.git", "directory": "youtrack" },
10
+ "type": "module",
11
+ "bin": { "licenserail-youtrack": "bin/licenserail-youtrack.mjs" },
12
+ "files": ["bin", "dist"],
13
+ "scripts": {
14
+ "build": "node scripts/build.mjs",
15
+ "test": "npm run build && node --test test/"
16
+ },
17
+ "devDependencies": {
18
+ "esbuild": "^0.25.0"
19
+ }
20
+ }