Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(cloud): support short generated and custom redemption codes
Timothy Yine74e4f0ebd14
diff --git a/apps/cloud/app/pages/account/redeem.vue b/apps/cloud/app/pages/account/redeem.vueindex a260a970..1d48877e 100644--- a/apps/cloud/app/pages/account/redeem.vue+++ b/apps/cloud/app/pages/account/redeem.vue@@ -74,6 +74,9 @@ async function redeem() {busy.value = false}}+watch(code, (value) => {+ if (value !== value.toUpperCase()) code.value = value.toUpperCase()+})const date = (time: number) => new Date(time).toLocaleString(locale.value)</script><template>@@ -111,7 +114,7 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)maxlength="128"autocomplete="off"spellcheck="false"- placeholder="CF-…"+ placeholder="RB6CQ4TAE5GL":disabled="busy || !!receipt"/></label><p class="cf-field-hint">{{ $t('cloud.billing.codeHelp') }}</p>diff --git a/packages/platform/src/activation.ts b/packages/platform/src/activation.tsindex 61fee027..67188c8e 100644--- a/packages/platform/src/activation.ts+++ b/packages/platform/src/activation.ts@@ -14,10 +14,16 @@ function invalid(): never {const uuid = (v: unknown) =>typeof v === 'string' &&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(v)+export function normalizeActivationCode(value: unknown) {+ if (typeof value !== 'string' || value.length > 256) invalid()+ const code = value.trim().toUpperCase()+ if (!code || code.length > 128 || /[\p{Cc}\p{Cf}]/u.test(code)) invalid()+ // Keep the digest identity of previously issued formatted codes.+ const legacy = code.replace(/[-\s]/g, '')+ return /^CF[0-9A-F]{32}$/.test(legacy) ? legacy : code+}export async function activationHash(value: unknown) {- if (typeof value !== 'string' || value.length > 128) invalid()- const code = value.trim().toUpperCase().replace(/[-\s]/g, '')- if (!/^CF[0-9A-F]{32}$/.test(code)) invalid()+ const code = normalizeActivationCode(value)const hash = await crypto.subtle.digest('SHA-256',new TextEncoder().encode(code),@@ -26,6 +32,17 @@ export async function activationHash(value: unknown) {.map((n) => n.toString(16).padStart(2, '0')).join('')}+function randomCode() {+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'+ let code = ''+ while (code.length < 12) {+ for (const byte of crypto.getRandomValues(new Uint8Array(24))) {+ if (byte < 252) code += alphabet[byte % 36]+ if (code.length === 12) break+ }+ }+ return code+}/** Raw codes are returned only to the generating operator; only digests are stored. */export async function generateActivationCodes(input: {@@ -34,6 +51,7 @@ export async function generateActivationCodes(duration: unknownredeemUntil?: unknownmaxUses?: unknown+ code?: unknown},actor: number,now = Date.now(),@@ -45,6 +63,12 @@ export async function generateActivationCodes(typeof input.planId !== 'string')throw new SubscriptionError(400, 'invalid_code_batch')+ const custom =+ input.code === undefined || input.code === ''+ ? null+ : normalizeActivationCode(input.code)+ if (custom && input.count !== 1)+ throw new SubscriptionError(400, 'invalid_code_batch')const term = duration(input.duration),until = input.redeemUntil ?? null,max = input.maxUses ?? null@@ -58,19 +82,27 @@ export async function generateActivationCodes()throw new SubscriptionError(400, 'invalid_code_batch')const batchId = crypto.randomUUID(),- codes = []+ codes: {+ id: string+ code: string+ hash: string+ display: string+ batchId: string+ planId: string+ duration: Duration+ redeemUntil: number | null+ maxUses: number | null+ createdAt: number+ createdBy: number+ }[] = []for (let i = 0; i < Number(input.count); i++) {- const bytes = crypto.getRandomValues(new Uint8Array(16)),- hex = [...bytes]- .map((n) => n.toString(16).padStart(2, '0'))- .join('')- .toUpperCase(),- raw = 'CF-' + hex.match(/.{4}/g)!.join('-')+ let raw = custom ?? randomCode()+ while (codes.some((c) => c.code === raw)) raw = randomCode()codes.push({id: crypto.randomUUID(),code: raw,hash: await activationHash(raw),- display: 'CF-…-' + hex.slice(-4),+ display: raw.length >= 8 ? '…' + raw.slice(-4) : '…',batchId,planId: input.planId,duration: term,diff --git a/tests/platform-subscriptions.test.ts b/tests/platform-subscriptions.test.tsindex e134ee86..82b6e421 100644--- a/tests/platform-subscriptions.test.ts+++ b/tests/platform-subscriptions.test.ts@@ -20,6 +20,8 @@ import {} from '../packages/platform/src/subscriptions.ts'import {generateActivationCodes,+ activationHash,+ normalizeActivationCode,previewActivation,redeemActivation,} from '../packages/platform/src/activation.ts'@@ -31,6 +33,56 @@ const require = createRequire(import.meta.url),{ Miniflare, convertV4MiniflareOptions } = createRequire(require.resolve('wrangler/package.json'),)('miniflare')+test('Activation codes generate 12 alphanumeric characters and normalize custom and legacy identities', async () => {+ const batch = await generateActivationCodes(+ { count: 500, planId: 'free', duration: { unit: 'days', value: 1 } },+ 1,+ )+ assert.equal(new Set(batch.codes.map((c) => c.code)).size, 500)+ assert.ok(batch.codes.every((c) => /^[A-Z0-9]{12}$/.test(c.code)))+ const custom = await generateActivationCodes(+ {+ count: 1,+ planId: 'free',+ duration: { unit: 'days', value: 1 },+ code: ' launch-春,2026! ',+ },+ 1,+ )+ assert.equal(custom.codes[0]!.code, 'LAUNCH-春,2026!')+ assert.equal(+ await activationHash(' launch-春,2026! '),+ await activationHash('LAUNCH-春,2026!'),+ )+ const canonical = 'CF' + 'A1'.repeat(16),+ formatted = 'CF-' + 'a1'.repeat(16).match(/.{4}/g)!.join('-')+ const legacyDigest = await crypto.subtle.digest(+ 'SHA-256',+ new TextEncoder().encode(canonical),+ )+ assert.equal(+ await activationHash(formatted),+ Array.from(new Uint8Array(legacyDigest), (n) =>+ n.toString(16).padStart(2, '0'),+ ).join(''),+ )+ assert.equal(normalizeActivationCode('a-b'), 'A-B')+ assert.notEqual(await activationHash('A-B'), await activationHash('AB'))+ await assert.rejects(+ generateActivationCodes(+ {+ count: 2,+ planId: 'free',+ duration: { unit: 'days', value: 1 },+ code: 'Manual',+ },+ 1,+ ),+ { code: 'invalid_code_batch' },+ )+ assert.throws(() => normalizeActivationCode('a\nb'))+ assert.throws(() => normalizeActivationCode('a'.repeat(129)))+})test('Calendar subscription periods clamp UTC month ends without multiplying stock quotas', () => {const jan = Date.UTC(2024, 0, 31, 12)assert.equal(addMonths(jan, 1), Date.UTC(2024, 1, 29, 12))