@kitkat-vn/kitcode 0.2.0-staging.9 → 0.3.0-staging.16

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.
@@ -32,10 +32,10 @@ button{cursor:pointer}
32
32
  ${COMPANION_HIDE_CSS}
33
33
  `;
34
34
  const script = `
35
- const API_BASE=${JSON.stringify(apiBase)};const percent=document.getElementById('percent'),countValue=document.getElementById('countValue'),workedValue=document.getElementById('workedValue'),idleValue=document.getElementById('idleValue'),progressFill=document.getElementById('progressFill'),main=document.getElementById('main'),dashboardButton=document.getElementById('dashboardButton');
35
+ const API_BASE=${JSON.stringify(apiBase)};const brandLabel=document.getElementById('brandLabel'),brandSecond=document.getElementById('brandSecond'),percent=document.getElementById('percent'),countValue=document.getElementById('countValue'),workedValue=document.getElementById('workedValue'),idleValue=document.getElementById('idleValue'),progressFill=document.getElementById('progressFill'),main=document.getElementById('main'),dashboardButton=document.getElementById('dashboardButton');
36
36
  function formatDuration(seconds){const totalSeconds=Math.max(0,Math.floor(Number(seconds)||0));if(totalSeconds<60)return totalSeconds+'s';const hours=Math.floor(totalSeconds/3600),minutes=Math.floor((totalSeconds%3600)/60);if(hours>0)return minutes>0?hours+'h '+minutes+'m':hours+'h';return minutes+'m'}
37
37
  function updateProgress(value){progressFill.style.width=Math.max(0,Math.min(100,Number(value)||0))+'%'}
38
- function render(summary){const reward=summary?.reward||{},global=summary?.global||{},value=Math.max(0,Math.min(100,Math.floor(Number(reward.progressPercent)||0)));percent.textContent=value+'%';countValue.textContent=String(Math.max(0,Math.floor(Number(reward.totalEquals)||0)));workedValue.textContent=formatDuration(global.totalActiveSeconds);idleValue.textContent=formatDuration(global.totalIdleSeconds);updateProgress(value);main.classList.remove('offline')}
38
+ function render(summary){const reward=summary?.reward||{},global=summary?.global||{},value=Math.max(0,Math.min(100,Math.floor(Number(reward.progressPercent)||0))),cycle=Number.isSafeInteger(reward.cycle)&&reward.cycle>1?reward.cycle:null,ended=reward.campaign?.ended===true;brandSecond.textContent=ended?'ENDED':cycle===null?'COUNTER':'CYCLE '+cycle;brandLabel.setAttribute('aria-label',ended?'KitCode campaign ended':cycle===null?'KitCode Counter':'KitCode cycle '+cycle);percent.textContent=value+'%';countValue.textContent=String(Math.max(0,Math.floor(Number(reward.totalEquals)||0)));workedValue.textContent=formatDuration(global.totalActiveSeconds);idleValue.textContent=formatDuration(global.totalIdleSeconds);updateProgress(value);main.classList.remove('offline')}
39
39
  function offline(){percent.textContent='--';countValue.textContent='--';workedValue.textContent='--';idleValue.textContent='--';updateProgress(0);main.classList.add('offline')}
40
40
  async function sync(){try{const response=await fetch(API_BASE+'/api/summary');if(!response.ok)throw new Error();render(await response.json())}catch{offline()}}
41
41
  const hideButton=document.getElementById('hideButton');function hideCompanion(){try{const result=window.kitcodeCompanion?.hide?.();if(result&&typeof result.catch==='function')result.catch(()=>window.close());if(!result)window.close()}catch{window.close()}}
@@ -45,6 +45,12 @@ dashboardButton.addEventListener('click',()=>{if(window.kitcodeCompanion?.openDa
45
45
  sync();const events=new EventSource(API_BASE+'/api/events');events.addEventListener('summary',(event)=>{try{render(JSON.parse(event.data))}catch{offline()}});events.onerror=offline;
46
46
  `;
47
47
 
48
+ // Since 2026-10-22 its label names the cycle counted in from cycle 2 on, "KITCODE CYCLE 2" where it says "KITCODE COUNTER",
49
+ // on the same two lines, so that the counters keep their room (docs/reward-rules.md §2, "Cycles"); its percent is that
50
+ // cycle's, as the summary's is. Since 2026-10-23 (tracking/2-cli; D4 of docs/plans/2026-10-22-server-tracking-config.md) it
51
+ // reads "KITCODE ENDED" once the summary says the campaign has ended, `reward.campaign.ended`, whatever the cycle; the counters
52
+ // go on, as counting does.
53
+ //
48
54
  // The button opens the dashboard, where each milestone reached shows its message: "See more". Until 2026-10-01 it was
49
55
  // "Show code", and lit while a 10–30 % code was ready to show there; the break codes are gone (the operator's decision
50
56
  // 6), and a milestone reached stays reached, so nothing lights it now. The Mini cannot show a message itself: the
@@ -55,5 +61,5 @@ sync();const events=new EventSource(API_BASE+'/api/events');events.addEventListe
55
61
  return `<!doctype html>
56
62
  <html lang="en"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${contentSecurityPolicy({script, style, connect: [apiBase || "'self'"]})}"><meta name="viewport" content="width=device-width, initial-scale=1">
57
63
  <title>KitCode Counter</title><style>${style}</style></head>
58
- <body><main class="widget-window" id="main" data-testid="companion-counter-bar">${renderCompanionTitleBar()}<div class="widget-body"><div class="brand-label" aria-label="KitCode Counter">KITCODE<br>COUNTER</div><strong class="percentage" id="percent" data-testid="mini-percent">--</strong><div class="progress-box" aria-hidden="true"><div class="progress-fill" id="progressFill"><div class="progress-row">========================</div><div class="progress-row">========================</div></div></div><div class="metrics-group" aria-label="KitCode counters"><div class="metric-item"><div class="metric-value" id="countValue" data-testid="mini-count">--</div><div class="metric-label">= COUNT</div></div><div class="metric-item"><div class="metric-value" id="workedValue" data-testid="mini-worked">--</div><div class="metric-label">WORKED</div></div><div class="metric-item"><div class="metric-value" id="idleValue" data-testid="mini-idle">--</div><div class="metric-label">IDLE</div></div></div><button class="claim-btn" id="dashboardButton" data-testid="companion-dashboard" type="button" title="Open the dashboard, where each milestone reached shows its message">See more</button></div></main><script>${script}</script></body></html>`;
64
+ <body><main class="widget-window" id="main" data-testid="companion-counter-bar">${renderCompanionTitleBar()}<div class="widget-body"><div class="brand-label" id="brandLabel" aria-label="KitCode Counter" data-testid="mini-brand">KITCODE<br><span id="brandSecond">COUNTER</span></div><strong class="percentage" id="percent" data-testid="mini-percent">--</strong><div class="progress-box" aria-hidden="true"><div class="progress-fill" id="progressFill"><div class="progress-row">========================</div><div class="progress-row">========================</div></div></div><div class="metrics-group" aria-label="KitCode counters"><div class="metric-item"><div class="metric-value" id="countValue" data-testid="mini-count">--</div><div class="metric-label">= COUNT</div></div><div class="metric-item"><div class="metric-value" id="workedValue" data-testid="mini-worked">--</div><div class="metric-label">WORKED</div></div><div class="metric-item"><div class="metric-value" id="idleValue" data-testid="mini-idle">--</div><div class="metric-label">IDLE</div></div></div><button class="claim-btn" id="dashboardButton" data-testid="companion-dashboard" type="button" title="Open the dashboard, where each milestone reached shows its message">See more</button></div></main><script>${script}</script></body></html>`;
59
65
  }
package/src/cors.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // The origins a tracker allows with nothing configured: the hosted dashboard's and the local development
2
- // servers'. Pinned by local-api.test.mjs.
2
+ // servers'. Pinned by local-api.test.mjs. Since 2026-10-22 (production/1-cli) the hosted dashboard is production's,
3
+ // https://kitcode.vn, where it was https://kitcode.vercel.app, the previous project's site; a tester build's copy has the
4
+ // staging site's in its place (scripts/tester-build.mjs).
3
5
  export const DEFAULT_ALLOWED_ORIGINS = new Set([
4
6
  // The staging dashboard this tester build is for (scripts/tester-build.mjs in the repository).
5
7
  "https://staging.kitcode.vn",
@@ -0,0 +1,97 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ // A cycle receipt (docs/backend.md, "The cycle receipt"; the plan of 2026-10-21, phase 2): what the claim backend signs once it
4
+ // has issued a voucher, and the dashboard hands to this tracker, so that the tracker begins the next cycle, whose milestones
5
+ // count fresh from that moment (decision 1). Its words are the server's: the install id the claim's bundle carried, the cycle
6
+ // the server counted for it, the claim's id and when its voucher was issued, signed with an Ed25519 key that exists on the
7
+ // claim backend's server alone. This file only reads one, with the matching public key, which a tester build carries
8
+ // (integration-spec.mjs, CYCLE_RECEIPT_PUBLIC_KEY). Pure: it reads no file, keeps nothing, and asks nothing of the network;
9
+ // whether the receipt is this install's, and of the cycle it is in, is the caller's to judge, against the record
10
+ // (milestones-reached.mjs, beginNextCycle).
11
+ //
12
+ // <payload>.<signature>
13
+ //
14
+ // `payload` is base64url (no padding) of the UTF-8 JSON {"v":1,"installId":…,"cycle":…,"claimId":…,"issuedAt":…}, those five
15
+ // fields alone; `signature`, base64url of the 64-byte Ed25519 signature of the ASCII text `kitcode-cycle-receipt-1.` followed
16
+ // by `payload` as it stands. The signature is checked over the bytes as they came, before anything in them is read: nothing is
17
+ // put in a canonical form, and no field the server did not sign is read. The text names what it is, so that the key signs
18
+ // nothing else that could pass for one. The server's side is apps/api/src/cycle-receipts.ts.
19
+
20
+ export const CYCLE_RECEIPT_CONTEXT = 'kitcode-cycle-receipt-1.';
21
+
22
+ // The longest text read: a receipt is about 300 characters.
23
+ export const MAX_CYCLE_RECEIPT_LENGTH = 1024;
24
+
25
+ const RECEIPT_TEXT = /^([A-Za-z0-9_-]{16,900})\.([A-Za-z0-9_-]{86})$/u;
26
+ const PUBLIC_KEY_TEXT = /^[A-Za-z0-9_-]{43}$/u;
27
+ const INSTALL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
28
+ const CLAIM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
29
+ const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
30
+ const PAYLOAD_KEYS = ['v', 'installId', 'cycle', 'claimId', 'issuedAt'];
31
+
32
+ function isInstant(value) {
33
+ if (typeof value !== 'string' || !INSTANT.test(value)) {
34
+ return false;
35
+ }
36
+
37
+ const time = Date.parse(value);
38
+ return Number.isFinite(time) && new Date(time).toISOString() === value;
39
+ }
40
+
41
+ // The public key a build carries: base64url of its 32 raw bytes, the JWK's `x`. Null when it is not one.
42
+ export function cycleReceiptKey(text) {
43
+ if (typeof text !== 'string' || !PUBLIC_KEY_TEXT.test(text)) {
44
+ return null;
45
+ }
46
+
47
+ try {
48
+ const key = crypto.createPublicKey({key: {kty: 'OKP', crv: 'Ed25519', x: text}, format: 'jwk'});
49
+ return key.asymmetricKeyType === 'ed25519' && key.export({format: 'jwk'}).x === text ? key : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ // Reads `text` with `publicKey` (a KeyObject, cycleReceiptKey's): {ok: true, receipt: {installId, cycle, claimId, issuedAt}},
56
+ // or {ok: false, problem}: 'unreadable', not the shape of a receipt, or its signed words not a receipt's; 'signature', not
57
+ // signed with the key's pair.
58
+ export function readCycleReceipt(text, publicKey) {
59
+ const parts = typeof text === 'string' && text.length <= MAX_CYCLE_RECEIPT_LENGTH ? RECEIPT_TEXT.exec(text) : null;
60
+
61
+ if (parts === null) {
62
+ return {ok: false, problem: 'unreadable'};
63
+ }
64
+
65
+ const [, payload, signature] = parts;
66
+ let signed;
67
+
68
+ try {
69
+ signed = crypto.verify(null, Buffer.from(`${CYCLE_RECEIPT_CONTEXT}${payload}`, 'ascii'), publicKey, Buffer.from(signature, 'base64url'));
70
+ } catch {
71
+ signed = false;
72
+ }
73
+
74
+ if (!signed) {
75
+ return {ok: false, problem: 'signature'};
76
+ }
77
+
78
+ let words;
79
+
80
+ try {
81
+ words = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
82
+ } catch {
83
+ return {ok: false, problem: 'unreadable'};
84
+ }
85
+
86
+ const shaped = words !== null && typeof words === 'object' && !Array.isArray(words)
87
+ && Object.keys(words).length === PAYLOAD_KEYS.length && PAYLOAD_KEYS.every((key) => Object.hasOwn(words, key))
88
+ && words.v === 1
89
+ && typeof words.installId === 'string' && INSTALL_ID.test(words.installId)
90
+ && Number.isSafeInteger(words.cycle) && words.cycle >= 1
91
+ && typeof words.claimId === 'string' && CLAIM_ID.test(words.claimId)
92
+ && isInstant(words.issuedAt);
93
+
94
+ return shaped
95
+ ? {ok: true, receipt: {installId: words.installId, cycle: words.cycle, claimId: words.claimId, issuedAt: words.issuedAt}}
96
+ : {ok: false, problem: 'unreadable'};
97
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+
5
+ This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -7,6 +7,7 @@ import {getDiskRewardSummary, getReadyUnannouncedTiers, markTiersAnnounced} from
7
7
  import {STORE_DIR, StateLockError, withStateLock} from './store.mjs';
8
8
  import {isProcessAlive, readTrackerRecord} from './tracker-instance.mjs';
9
9
  import {problemSentences, TRACKER_STOPPED} from './tracker-problems.mjs';
10
+ import {campaignEnded, trackingConfigInForce} from './tracking-config.mjs';
10
11
 
11
12
  export const HOOK_LOG_PATH = path.join(STORE_DIR, 'hook.log');
12
13
 
@@ -104,11 +105,21 @@ function notify(title, message) {
104
105
  // A milestone reached is said in neutral words (the operator's decisions 5 and 6 of 2026-10-01): its message, from the
105
106
  // campaign, is on the dashboard, and no milestone is a reward ready, or a code. Until then this said "Reward ready at",
106
107
  // and the announcement below "KitCode break code ready".
108
+ //
109
+ // Since 2026-10-22 (rewards/3-repeat-vouchers, phase 2) the milestones are those of the cycle counted in (reward.mjs): from cycle
110
+ // 2 on the context names it, "KitCode progress (cycle 2): …", and the milestones it lists and announces are that cycle's; the =
111
+ // and the time are the totals, which keep counting. Cycle 1 reads as it always has. The cycle is the record's, read with the
112
+ // rest of the file: no receipt is checked here (hard rule 7).
113
+ function cycleOf(reward) {
114
+ return Number.isSafeInteger(reward?.cycle) && reward.cycle > 1 ? reward.cycle : null;
115
+ }
116
+
107
117
  function progressContextFor(reward) {
108
118
  const nextBreak = reward.nextBreak ?? nextBreakReminder(reward);
109
119
  const ready = reward.milestones.filter((entry) => entry.status === 'ready' && !entry.redeemed);
120
+ const cycle = cycleOf(reward);
110
121
  const parts = [
111
- `KitCode progress: ${reward.totalEquals} = counted, ${formatBreakDuration(reward.earnedSeconds)} active.`,
122
+ `KitCode progress${cycle === null ? '' : ` (cycle ${cycle})`}: ${reward.totalEquals} = counted, ${formatBreakDuration(reward.earnedSeconds)} active.`,
112
123
  ];
113
124
 
114
125
  if (ready.length > 0) {
@@ -140,7 +151,8 @@ function hookOutputFor({tiers = [], reward = null}) {
140
151
  };
141
152
  }
142
153
 
143
- const labels = tiers.map((tier) => `${tier.percent}%`).join(', ');
154
+ const cycle = cycleOf(reward);
155
+ const labels = `${tiers.map((tier) => `${tier.percent}%`).join(', ')}${cycle === null ? '' : `, cycle ${cycle}`}`;
144
156
  const command = 'kitcode dashboard';
145
157
  const additionalContext = [
146
158
  progressContext,
@@ -198,6 +210,14 @@ export async function runPromptHook({source}) {
198
210
  return;
199
211
  }
200
212
 
213
+ // After the campaign's end, by this computer's clock (since 2026-10-23, tracking/2-cli; D4 of
214
+ // docs/plans/2026-10-22-server-tracking-config.md), the hook adds nothing: no progress, no milestone, no notification, and nothing
215
+ // written. The end is the last good copy's, read from disk with its bounds checked and no signature: the hook never fetches
216
+ // (src/tracking-config.mjs; hard rule 7). Counting goes on in the tracker, so an end moved later brings every word back.
217
+ if (campaignEnded(trackingConfigInForce())) {
218
+ return;
219
+ }
220
+
201
221
  const {reward, announced} = collectPromptProgress(source);
202
222
 
203
223
  if (announced.length === 0) {
@@ -206,7 +226,8 @@ export async function runPromptHook({source}) {
206
226
  }
207
227
 
208
228
  const label = announced.map((tier) => `${tier.percent}%`).join(', ');
209
- notify('KitCode milestone reached', `Milestone ${label} unlocked. Open kitcode dashboard.`);
229
+ const cycle = cycleOf(reward);
230
+ notify('KitCode milestone reached', `Milestone ${label}${cycle === null ? '' : ` of cycle ${cycle}`} unlocked. Open kitcode dashboard.`);
210
231
  process.stdout.write(`${JSON.stringify(hookOutputFor({tiers: announced, reward}))}\n`);
211
232
  } catch (error) {
212
233
  failure = error;