diff --git a/backend/package.json b/backend/package.json index 45e94ccd..3ddfd323 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.22.5", + "version": "2.22.6", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/restful/archives.js b/backend/src/restful/archives.js index ae10001d..71523dba 100644 --- a/backend/src/restful/archives.js +++ b/backend/src/restful/archives.js @@ -90,7 +90,9 @@ function restoreArchivedEntry(entry) { return createArtifactItem(normalizeArtifactSnapshotForRestore(snapshot)); case 'share': return createTokenItem(snapshot, { + mode: snapshot.mode, expiresIn: snapshot.expiresIn, + exp: snapshot.exp, }); default: throw new RequestInvalidError( diff --git a/backend/src/restful/token.js b/backend/src/restful/token.js index 0287ef7e..ca23b704 100644 --- a/backend/src/restful/token.js +++ b/backend/src/restful/token.js @@ -87,8 +87,91 @@ async function signToken(req, res) { } } -function createTokenItem(payload, options = {}) { +function normalizeExpirationMode(mode) { + if (mode == null || mode === '') { + return undefined; + } + if (mode === 'duration' || mode === 'datetime') { + return mode; + } + throw new RequestInvalidError( + 'INVALID_EXPIRATION_MODE', + `Unsupported expiration mode: ${mode}`, + ); +} + +function inferLegacyExpirationMode(options = {}) { + if (options?.expiresIn != null && options.expiresIn !== '') { + return 'duration'; + } + if (options?.exp != null && options.exp !== '') { + return 'datetime'; + } + return undefined; +} + +function resolveExactExpiration(options = {}) { + const rawExp = options?.exp; + if (typeof rawExp !== 'number' && typeof rawExp !== 'string') { + throw new RequestInvalidError( + 'INVALID_EXPIRATION_DATETIME', + `Invalid exp option: ${rawExp}`, + ); + } + + const normalizedRawExp = + typeof rawExp === 'string' ? rawExp.trim() : rawExp; + if (normalizedRawExp === '') { + throw new RequestInvalidError( + 'INVALID_EXPIRATION_DATETIME', + `Invalid exp option: ${rawExp}`, + ); + } + + const exp = Number(normalizedRawExp); + if ( + !Number.isSafeInteger(exp) || + exp <= 0 || + // Require an explicit millisecond Unix timestamp to avoid + // silently accepting second-based values from non-frontend callers. + exp < 1000000000000 + ) { + throw new RequestInvalidError( + 'INVALID_EXPIRATION_DATETIME', + `Invalid exp option: ${rawExp}`, + ); + } + return exp; +} + +function resolveDurationExpiration(options = {}, { required = false } = {}) { + const rawExpiresIn = options?.expiresIn; + if (rawExpiresIn == null || rawExpiresIn === '') { + if (required) { + throw new RequestInvalidError( + 'INVALID_EXPIRES_IN', + `Invalid expiresIn option: ${rawExpiresIn}`, + ); + } + return null; + } + const ms = eval(`require("ms")`); + const expiresIn = ms(rawExpiresIn); + if (expiresIn == null || isNaN(expiresIn) || expiresIn <= 0) { + throw new RequestInvalidError( + 'INVALID_EXPIRES_IN', + `Invalid expiresIn option: ${rawExpiresIn}`, + ); + } + + return { + rawExpiresIn, + exp: Date.now() + expiresIn, + }; +} + +function createTokenItem(payload, options = {}) { const type = payload?.type; const name = payload?.name; if (!type || !name) { @@ -155,15 +238,18 @@ function createTokenItem(payload, options = {}) { ); } - let expiresIn = options?.expiresIn; - if (options?.expiresIn != null) { - expiresIn = ms(options.expiresIn); - if (expiresIn == null || isNaN(expiresIn) || expiresIn <= 0) { - throw new RequestInvalidError( - 'INVALID_EXPIRES_IN', - `Invalid expiresIn option: ${options.expiresIn}`, - ); - } + const expirationMode = + normalizeExpirationMode(options?.mode) ?? + inferLegacyExpirationMode(options); + let durationExpiration = null; + let exp; + if (expirationMode === 'datetime') { + exp = resolveExactExpiration(options); + } else { + durationExpiration = resolveDurationExpiration(options, { + required: expirationMode === 'duration', + }); + exp = durationExpiration?.exp; } const nanoid = eval(`require("nanoid")`); @@ -180,12 +266,29 @@ function createTokenItem(payload, options = {}) { ) ); } + const normalizedMode = + expirationMode === 'datetime' + ? 'datetime' + : durationExpiration + ? 'duration' + : undefined; + const safePayload = { ...payload }; + delete safePayload.mode; + delete safePayload.exp; + delete safePayload.expiresIn; const tokenData = { - ...payload, + ...safePayload, token, createdAt: Date.now(), - expiresIn: expiresIn > 0 ? options?.expiresIn : undefined, - exp: expiresIn > 0 ? Date.now() + expiresIn : undefined, + ...(normalizedMode ? { mode: normalizedMode } : {}), + ...(normalizedMode === 'datetime' + ? { exp } + : durationExpiration + ? { + expiresIn: durationExpiration.rawExpiresIn, + exp, + } + : {}), }; insertByPosition(tokens, tokenData, getCreateItemPosition()); $.write(tokens, TOKENS_KEY); diff --git a/backend/src/test/restful/archive.spec.js b/backend/src/test/restful/archive.spec.js index 09299d98..22c55c6f 100644 --- a/backend/src/test/restful/archive.spec.js +++ b/backend/src/test/restful/archive.spec.js @@ -219,7 +219,7 @@ describe('archive routes', function () { expect(state[ARCHIVES_KEY]).to.deep.equal([]); }); - it('keeps archived entries when restore fails and preserves share tokens on success', async function () { + it('keeps archived entries when restore fails and preserves exact-datetime share tokens on success', async function () { state[SUBS_KEY] = [ { name: 'shared-sub', @@ -227,13 +227,15 @@ describe('archive routes', function () { process: [], }, ]; + const exactExp = Date.now() - 5 * 60 * 1000; state[TOKENS_KEY] = [ { token: 'keep-me', type: 'sub', name: 'shared-sub', displayName: 'Shared Link', - expiresIn: '1d', + mode: 'datetime', + exp: exactExp, }, ]; @@ -305,6 +307,140 @@ describe('archive routes', function () { expect(successfulRestoreRes.body.status).to.equal('success'); expect(state[TOKENS_KEY]).to.have.length(1); expect(state[TOKENS_KEY][0].token).to.equal('keep-me'); + expect(state[TOKENS_KEY][0].mode).to.equal('datetime'); + expect(state[TOKENS_KEY][0].exp).to.equal(exactExp); + expect(state[TOKENS_KEY][0]).to.not.have.property('expiresIn'); + expect(state[ARCHIVES_KEY]).to.deep.equal([]); + }); + + it('preserves legacy duration share tokens on restore', async function () { + state[SUBS_KEY] = [ + { + name: 'shared-sub', + source: 'remote', + process: [], + }, + ]; + state[TOKENS_KEY] = [ + { + token: 'legacy-duration', + type: 'sub', + name: 'shared-sub', + displayName: 'Legacy Share', + expiresIn: '1d', + }, + ]; + + const deleteHandler = getHandler( + registerTokenRoutes, + 'DELETE', + '/api/token/:token', + ); + const deleteRes = createResponse('/api/token/:token'); + + deleteHandler( + { + params: { token: 'legacy-duration' }, + query: { + mode: 'archive', + type: 'sub', + name: 'shared-sub', + }, + }, + deleteRes, + ); + + expect(deleteRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.deep.equal([]); + expect(state[ARCHIVES_KEY]).to.have.length(1); + + const restoreHandler = getHandler( + registerArchiveRoutes, + 'POST', + '/api/archives/:id/restore', + ); + const restoreRes = createResponse('/api/archives/:id/restore'); + + restoreHandler( + { + params: { id: state[ARCHIVES_KEY][0].id }, + query: {}, + }, + restoreRes, + ); + + expect(restoreRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.have.length(1); + expect(state[TOKENS_KEY][0].token).to.equal('legacy-duration'); + expect(state[TOKENS_KEY][0].mode).to.equal('duration'); + expect(state[TOKENS_KEY][0].expiresIn).to.equal('1d'); + expect(state[TOKENS_KEY][0].exp).to.be.a('number'); + expect(state[ARCHIVES_KEY]).to.deep.equal([]); + }); + + it('restores legacy exp-only share tokens as exact-datetime shares', async function () { + state[SUBS_KEY] = [ + { + name: 'shared-sub', + source: 'remote', + process: [], + }, + ]; + const exactExp = Date.now() - 5 * 60 * 1000; + state[TOKENS_KEY] = [ + { + token: 'legacy-datetime', + type: 'sub', + name: 'shared-sub', + displayName: 'Legacy Exact Share', + exp: exactExp, + }, + ]; + + const deleteHandler = getHandler( + registerTokenRoutes, + 'DELETE', + '/api/token/:token', + ); + const deleteRes = createResponse('/api/token/:token'); + + deleteHandler( + { + params: { token: 'legacy-datetime' }, + query: { + mode: 'archive', + type: 'sub', + name: 'shared-sub', + }, + }, + deleteRes, + ); + + expect(deleteRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.deep.equal([]); + expect(state[ARCHIVES_KEY]).to.have.length(1); + + const restoreHandler = getHandler( + registerArchiveRoutes, + 'POST', + '/api/archives/:id/restore', + ); + const restoreRes = createResponse('/api/archives/:id/restore'); + + restoreHandler( + { + params: { id: state[ARCHIVES_KEY][0].id }, + query: {}, + }, + restoreRes, + ); + + expect(restoreRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.have.length(1); + expect(state[TOKENS_KEY][0].token).to.equal('legacy-datetime'); + expect(state[TOKENS_KEY][0].mode).to.equal('datetime'); + expect(state[TOKENS_KEY][0].exp).to.equal(exactExp); + expect(state[TOKENS_KEY][0]).to.not.have.property('expiresIn'); expect(state[ARCHIVES_KEY]).to.deep.equal([]); }); diff --git a/backend/src/test/restful/token.spec.js b/backend/src/test/restful/token.spec.js new file mode 100644 index 00000000..3143ed33 --- /dev/null +++ b/backend/src/test/restful/token.spec.js @@ -0,0 +1,272 @@ +import { expect } from 'chai'; +import { after, before, beforeEach, describe, it } from 'mocha'; + +import { + SETTINGS_KEY, + SUBS_KEY, + TOKENS_KEY, +} from '@/constants'; + +let $; +let createTokenItem; +let state; +let originalRead; +let originalWrite; +let originalInfo; +let originalError; + +describe('token routes', function () { + before(async function () { + ({ default: $ } = require('@/core/app')); + ({ createTokenItem } = require('@/restful/token')); + + originalRead = $.read.bind($); + originalWrite = $.write.bind($); + originalInfo = $.info.bind($); + originalError = $.error.bind($); + }); + + after(function () { + if ($) { + $.read = originalRead; + $.write = originalWrite; + $.info = originalInfo; + $.error = originalError; + } + }); + + beforeEach(function () { + state = { + [SUBS_KEY]: [{ name: 'shared-sub' }], + [TOKENS_KEY]: [], + [SETTINGS_KEY]: {}, + }; + + $.read = (key) => state[key]; + $.write = (data, key) => { + state[key] = data; + return true; + }; + $.info = () => {}; + $.error = () => {}; + }); + + it('stores exact datetime shares without converting them to expiresIn', function () { + const exp = Date.now() + 5 * 60 * 1000; + + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'datetime-token', + }, + { + mode: 'datetime', + exp, + }, + ); + + expect(token.token).to.equal('datetime-token'); + expect(token.mode).to.equal('datetime'); + expect(token.exp).to.equal(exp); + expect(token).to.not.have.property('expiresIn'); + expect(state[TOKENS_KEY][0].mode).to.equal('datetime'); + expect(state[TOKENS_KEY][0].exp).to.equal(exp); + }); + + it('allows exact datetime shares in the past', function () { + const exp = Date.now() - 5 * 60 * 1000; + + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'expired-token', + }, + { + mode: 'datetime', + exp, + }, + ); + + expect(token.mode).to.equal('datetime'); + expect(token.exp).to.equal(exp); + expect(state[TOKENS_KEY]).to.have.length(1); + }); + + it('rejects invalid exact datetime shares', function () { + let capturedError; + + try { + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'bad-token', + }, + { + mode: 'datetime', + exp: 'not-a-timestamp', + }, + ); + } catch (error) { + capturedError = error; + } + + expect(capturedError).to.include({ + type: 'RequestInvalidError', + code: 'INVALID_EXPIRATION_DATETIME', + }); + expect(state[TOKENS_KEY]).to.deep.equal([]); + }); + + it('rejects exact datetime shares that are not positive millisecond timestamps', function () { + for (const invalidExp of [ + 0, + -1, + 1713753600, + '1713753600', + 1713753600000.5, + '1713753600000.5', + ]) { + let capturedError; + + try { + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: `invalid-ms-${String(invalidExp)}`, + }, + { + mode: 'datetime', + exp: invalidExp, + }, + ); + } catch (error) { + capturedError = error; + } + + expect(capturedError).to.include({ + type: 'RequestInvalidError', + code: 'INVALID_EXPIRATION_DATETIME', + }); + } + + expect(state[TOKENS_KEY]).to.deep.equal([]); + }); + + it('rejects empty exact datetime shares', function () { + for (const invalidExp of [null, '', ' ']) { + let capturedError; + + try { + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: `bad-token-${String(invalidExp)}`, + }, + { + mode: 'datetime', + exp: invalidExp, + }, + ); + } catch (error) { + capturedError = error; + } + + expect(capturedError).to.include({ + type: 'RequestInvalidError', + code: 'INVALID_EXPIRATION_DATETIME', + }); + } + + expect(state[TOKENS_KEY]).to.deep.equal([]); + }); + + it('rejects duration shares when expiresIn is missing', function () { + let capturedError; + + try { + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'duration-missing-expiration', + }, + { + mode: 'duration', + }, + ); + } catch (error) { + capturedError = error; + } + + expect(capturedError).to.include({ + type: 'RequestInvalidError', + code: 'INVALID_EXPIRES_IN', + }); + expect(state[TOKENS_KEY]).to.deep.equal([]); + }); + + it('keeps legacy duration behavior when mode is omitted', function () { + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'legacy-duration', + }, + { + expiresIn: '1d', + exp: Date.now() + 10 * 24 * 60 * 60 * 1000, + }, + ); + + expect(token.mode).to.equal('duration'); + expect(token.expiresIn).to.equal('1d'); + expect(token.exp).to.be.a('number'); + }); + + it('infers legacy exact datetime behavior when mode is omitted but exp exists', function () { + const exp = Date.now() - 5 * 60 * 1000; + + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'legacy-datetime', + }, + { + exp, + }, + ); + + expect(token.mode).to.equal('datetime'); + expect(token.exp).to.equal(exp); + expect(token).to.not.have.property('expiresIn'); + expect(state[TOKENS_KEY][0].mode).to.equal('datetime'); + expect(state[TOKENS_KEY][0].exp).to.equal(exp); + }); + + it('ignores expiration metadata injected through payload', function () { + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'payload-mode-ignored', + mode: 'datetime', + exp: Date.now() + 60 * 1000, + expiresIn: '1d', + }, + {}, + ); + + expect(token).to.not.have.property('mode'); + expect(token).to.not.have.property('exp'); + expect(token).to.not.have.property('expiresIn'); + expect(state[TOKENS_KEY][0]).to.not.have.property('mode'); + expect(state[TOKENS_KEY][0]).to.not.have.property('exp'); + expect(state[TOKENS_KEY][0]).to.not.have.property('expiresIn'); + }); +});