@softistx/janus-redis 0.0.0-stage → 0.10.3
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/LICENSE +21 -0
- package/README.md +167 -2
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +416 -0
- package/dist/index.js.map +16 -0
- package/dist/replies.d.ts +24 -0
- package/dist/replies.d.ts.map +1 -0
- package/dist/runner.d.ts +8 -0
- package/dist/runner.d.ts.map +1 -0
- package/dist/scripts/index.d.ts +17 -0
- package/dist/scripts/index.d.ts.map +1 -0
- package/dist/scripts/sessions.d.ts +48 -0
- package/dist/scripts/sessions.d.ts.map +1 -0
- package/dist/scripts/shared.d.ts +18 -0
- package/dist/scripts/shared.d.ts.map +1 -0
- package/dist/scripts/tokens.d.ts +34 -0
- package/dist/scripts/tokens.d.ts.map +1 -0
- package/dist/session-store.d.ts +4 -0
- package/dist/session-store.d.ts.map +1 -0
- package/dist/stores.d.ts +38 -0
- package/dist/stores.d.ts.map +1 -0
- package/docs/README.md +10 -0
- package/docs/guide/wiring.md +126 -0
- package/docs/roadmap.md +53 -0
- package/docs/troubleshooting.md +187 -0
- package/package.json +63 -5
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/stores.ts", "../src/replies.ts", "../src/runner.ts", "../src/scripts/shared.ts", "../src/scripts/sessions.ts", "../src/scripts/tokens.ts", "../src/session-store.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { JanusStores, TokenStore } from '@softistx/janus';\nimport { StoreFailure } from '@softistx/janus';\nimport type { RedisConnection } from '@softistx/redis';\nimport type { RedisClient } from 'bun';\nimport { count, stamp, stampOrEmpty, toToken } from './replies';\nimport { type Evaluate, ignore, runner } from './runner';\nimport {\n\tCONSUME_TOKEN,\n\tCOUNT_ATTEMPT,\n\tDELETE_USER_TOKENS,\n\tINSERT_TOKEN,\n\tSPEND_USER_TOKENS,\n} from './scripts';\nimport { sessionStore } from './session-store';\n\n/** What the stores take besides the connection. */\nexport interface RedisStoresOptions {\n\t/**\n\t * What every key starts with — `janus:` unless you say otherwise. Two\n\t * applications sharing one Redis each take their own.\n\t */\n\treadonly prefix?: string;\n}\n\n/** The two slots of `janus()`'s `store` that Redis serves. */\nexport type RedisStores = Pick<JanusStores, 'sessions' | 'tokens'>;\n\n/**\n * Sessions and one-time tokens, over one Redis, on `@softistx/redis`'s\n * connection. **Users stay in another store**: a user is written once and\n * read on sign-in; a session is read on every request, which is what Redis\n * is for.\n *\n * ```ts\n * const redis = await connectRedis(process.env.REDIS_URL);\n * const auth = janus({\n * user, password: { login: 'email' }, hasher,\n * store: { ...createMongoStores(db), ...createRedisStores(redis) },\n * });\n * ```\n *\n * **Redis expires them itself**: every session and token key expires at its\n * own `expiresAt`. So `sessions.deleteExpiredSessions` and\n * `tokens.deleteExpiredTokens` are not implemented, and\n * `auth.collectExpired()` answers `UNSUPPORTED` — there is nothing to\n * collect. **Every method that writes is one Lua script**, atomic as the port\n * asks, so `consumeToken` is never a read and then a write.\n *\n * It creates nothing and needs no schema: the keys are made by the first\n * write.\n */\nexport function createRedisStores(\n\tredis: RedisConnection,\n\toptions: RedisStoresOptions = {},\n): RedisStores {\n\tconst prefix = options.prefix ?? 'janus:';\n\tconst scripts = scriptsOver(redis.client);\n\treturn {\n\t\tsessions: sessionStore(scripts, prefix),\n\t\ttokens: tokenStore(scripts, prefix),\n\t};\n}\n\n/**\n * Each script is sent once by its SHA — `EVALSHA` — and in full only when\n * Redis answers `NOSCRIPT`: after a restart, a failover, or a `SCRIPT FLUSH`.\n * Every other error is a failure, and nothing is ever answered as an absence.\n */\nfunction scriptsOver(client: RedisClient): Evaluate {\n\tconst shas = new Map<string, string>();\n\tconst shaOf = (script: string) => {\n\t\tlet sha = shas.get(script);\n\t\tif (sha === undefined) {\n\t\t\tsha = new Bun.CryptoHasher('sha1').update(script).digest('hex');\n\t\t\tshas.set(script, sha);\n\t\t}\n\t\treturn sha;\n\t};\n\n\treturn async ({ slot, operation }, script, args) => {\n\t\ttry {\n\t\t\ttry {\n\t\t\t\treturn await client.send('EVALSHA', [shaOf(script), '0', ...args]);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isNoScript(error)) throw error;\n\t\t\t\treturn await client.send('EVAL', [script, '0', ...args]);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new StoreFailure(\n\t\t\t\t`${slot}.${operation}: the store could not answer`,\n\t\t\t\t{ slot, operation, cause: error },\n\t\t\t);\n\t\t}\n\t};\n}\n\nfunction isNoScript(error: unknown): boolean {\n\treturn error instanceof Error && error.message.startsWith('NOSCRIPT');\n}\n\nfunction tokenStore(evaluate: Evaluate, prefix: string): TokenStore {\n\tconst run = runner(evaluate, 'tokens', prefix);\n\n\treturn {\n\t\tinsertToken: (record) =>\n\t\t\trun(\n\t\t\t\t'insertToken',\n\t\t\t\tINSERT_TOKEN,\n\t\t\t\t[\n\t\t\t\t\trecord.tokenHash,\n\t\t\t\t\trecord.kind,\n\t\t\t\t\trecord.userId,\n\t\t\t\t\trecord.address,\n\t\t\t\t\tstamp(record.expiresAt),\n\t\t\t\t\tstampOrEmpty(record.spentAt),\n\t\t\t\t\tstamp(record.createdAt),\n\t\t\t\t\trecord.codeHash ?? '',\n\t\t\t\t\tString(record.attempts),\n\t\t\t\t\t(record.amr ?? []).join(' '),\n\t\t\t\t],\n\t\t\t\tignore,\n\t\t\t),\n\n\t\tconsumeToken: (tokenHash, kind, at, userId) =>\n\t\t\trun(\n\t\t\t\t'consumeToken',\n\t\t\t\tCONSUME_TOKEN,\n\t\t\t\t[\n\t\t\t\t\ttokenHash,\n\t\t\t\t\tkind,\n\t\t\t\t\tstamp(at),\n\t\t\t\t\tuserId === undefined ? '0' : '1',\n\t\t\t\t\tuserId ?? '',\n\t\t\t\t],\n\t\t\t\t(reply, call) => toToken(reply, tokenHash, kind, call),\n\t\t\t),\n\n\t\tcountAttempt: (tokenHash, kind) =>\n\t\t\trun('countAttempt', COUNT_ATTEMPT, [tokenHash, kind], (reply, call) =>\n\t\t\t\ttoToken(reply, tokenHash, kind, call),\n\t\t\t),\n\n\t\tspendUserTokens: (userId, kind, at, except) =>\n\t\t\trun(\n\t\t\t\t'spendUserTokens',\n\t\t\t\tSPEND_USER_TOKENS,\n\t\t\t\t[userId, kind, stamp(at), except ?? ''],\n\t\t\t\tcount,\n\t\t\t),\n\n\t\tdeleteUserTokens: (userId) =>\n\t\t\trun('deleteUserTokens', DELETE_USER_TOKENS, [userId], count),\n\t};\n}\n",
|
|
6
|
+
"import type { SessionRecord, TokenRecord } from '@softistx/janus';\nimport { StoreFailure } from '@softistx/janus';\n\n/**\n * What a script answers, read back into the port's records. **A reply this\n * adapter did not write is a failure, never an absence**: a key of the prefix\n * changed by hand, or written by another version, rejects with\n * `StoreFailure` — naming the call it failed, as every other failure does.\n *\n * Dates travel as milliseconds since the epoch, and `null` as `''`.\n */\n\n/** The call a reply answers: what a failure names. */\nexport interface Call {\n\treadonly slot: 'sessions' | 'tokens';\n\treadonly operation: string;\n}\n\nexport function stamp(at: Date): string {\n\treturn String(at.getTime());\n}\n\nexport function stampOrEmpty(at: Date | null): string {\n\treturn at === null ? '' : stamp(at);\n}\n\n/** `[id, field, value, …]` as a session, or `null`. */\nexport function toSession(reply: unknown, call: Call): SessionRecord | null {\n\tif (reply === null) return null;\n\tif (!Array.isArray(reply) || typeof reply[0] !== 'string') {\n\t\tthrow unreadable(call, 'a session');\n\t}\n\tconst [id, ...rest] = reply as [string, ...unknown[]];\n\tconst read = readerOf(rest, call);\n\treturn {\n\t\tid,\n\t\ttokenHash: read.text('tokenHash'),\n\t\tuserId: read.text('userId'),\n\t\tauthenticatedAt: read.date('authenticatedAt'),\n\t\texpiresAt: read.date('expiresAt'),\n\t\trevokedAt: read.dateOrNull('revokedAt'),\n\t\tcreatedAt: read.date('createdAt'),\n\t\t// Absent fields are not written, so a session from before them has none.\n\t\t...(read.optional('device') === ''\n\t\t\t? {}\n\t\t\t: { device: read.optional('device') }),\n\t\t...(read.optional('lastUsedAt') === ''\n\t\t\t? {}\n\t\t\t: { lastUsedAt: read.date('lastUsedAt') }),\n\t\t// Space-separated; RFC 8176 values hold no space. Absent reads as none.\n\t\t...(read.optional('amr') === ''\n\t\t\t? {}\n\t\t\t: { amr: read.optional('amr').split(' ') }),\n\t};\n}\n\n/** Each element of a list reply as a session; anything else is a failure. */\nexport function toSessions(reply: unknown, call: Call): SessionRecord[] {\n\tif (!Array.isArray(reply)) throw unreadable(call, 'a list of sessions');\n\treturn reply.map((one) => {\n\t\tconst session = toSession(one, call);\n\t\tif (session === null) throw unreadable(call, 'a session');\n\t\treturn session;\n\t});\n}\n\n/** `[field, value, …]` as the token `tokenHash` names, or `null`. */\nexport function toToken(\n\treply: unknown,\n\ttokenHash: string,\n\tkind: TokenRecord['kind'],\n\tcall: Call,\n): TokenRecord | null {\n\tif (reply === null) return null;\n\tconst read = readerOf(reply, call);\n\tif (read.text('kind') !== kind) throw unreadable(call, `a ${kind} token`);\n\treturn {\n\t\ttokenHash,\n\t\tkind,\n\t\tuserId: read.text('userId'),\n\t\taddress: read.text('address'),\n\t\t// Absent on a token an earlier version wrote: read as none, and no attempt.\n\t\tcodeHash: read.optional('codeHash') || null,\n\t\tattempts: read.count('attempts'),\n\t\t...(read.optional('amr') === ''\n\t\t\t? {}\n\t\t\t: { amr: read.optional('amr').split(' ') }),\n\t\texpiresAt: read.date('expiresAt'),\n\t\tspentAt: read.dateOrNull('spentAt'),\n\t\tcreatedAt: read.date('createdAt'),\n\t};\n}\n\nexport function count(reply: unknown, call: Call): number {\n\tif (typeof reply !== 'number') throw unreadable(call, 'a count');\n\treturn reply;\n}\n\n/** The fields of `[field, value, …]`, as Redis answers a hash from a script. */\nfunction readerOf(reply: unknown, call: Call) {\n\tif (!Array.isArray(reply)) throw unreadable(call, 'a hash');\n\tconst fields = new Map<string, string>();\n\tfor (let i = 0; i + 1 < reply.length; i += 2) {\n\t\tfields.set(String(reply[i]), String(reply[i + 1]));\n\t}\n\tconst text = (name: string): string => {\n\t\tconst value = fields.get(name);\n\t\tif (value === undefined) throw unreadable(call, `a hash with \\`${name}\\``);\n\t\treturn value;\n\t};\n\tconst date = (name: string): Date => {\n\t\tconst value = text(name);\n\t\tconst at = new Date(Number(value));\n\t\tif (value === '' || Number.isNaN(at.getTime())) {\n\t\t\tthrow unreadable(call, `a date in \\`${name}\\``);\n\t\t}\n\t\treturn at;\n\t};\n\treturn {\n\t\ttext,\n\t\tdate,\n\t\toptional: (name: string): string => fields.get(name) ?? '',\n\t\tcount: (name: string): number => {\n\t\t\tconst value = fields.get(name);\n\t\t\tif (value === undefined) return 0;\n\t\t\t// Only what this adapter writes: `String(n)` or `HINCRBY`'s answer.\n\t\t\t// `Number()` would also take '', '0x10' and '1e1'.\n\t\t\tconst counted = /^(0|[1-9]\\d*)$/.test(value) ? Number(value) : Number.NaN;\n\t\t\tif (!Number.isSafeInteger(counted)) {\n\t\t\t\tthrow unreadable(call, `a count in \\`${name}\\``);\n\t\t\t}\n\t\t\treturn counted;\n\t\t},\n\t\tdateOrNull: (name: string): Date | null =>\n\t\t\ttext(name) === '' ? null : date(name),\n\t};\n}\n\nfunction unreadable({ slot, operation }: Call, what: string): StoreFailure {\n\treturn new StoreFailure(\n\t\t`${slot}.${operation}: a reply that is not ${what} — a key under the prefix this adapter did not write`,\n\t\t{ slot, operation },\n\t);\n}\n",
|
|
7
|
+
"import type { Call } from './replies';\n\n/** Runs a script, and makes every rejection one the port allows. */\nexport type Evaluate = (\n\tcall: Call,\n\tscript: string,\n\targs: readonly string[],\n) => Promise<unknown>;\n\n/** What a slot's methods call: a script's reply, already decoded. */\nexport type Run = <T>(\n\toperation: string,\n\tscript: string,\n\targs: readonly string[],\n\tdecode: (reply: unknown, call: Call) => T,\n) => Promise<T>;\n\nexport function runner(\n\tevaluate: Evaluate,\n\tslot: Call['slot'],\n\tprefix: string,\n): Run {\n\treturn async (operation, script, args, decode) => {\n\t\tconst call = { slot, operation };\n\t\treturn decode(await evaluate(call, script, [prefix, ...args]), call);\n\t};\n}\n\nexport const ignore = () => undefined;\n",
|
|
8
|
+
"/**\n * What the scripts of both stores share: keeping a user's set of keys alive,\n * and pruning it of the keys Redis already expired.\n */\n\n/**\n * Sets `key` to expire at `at`, or later if it already expires later — the\n * set of a user's sessions lives as long as their longest session. `GT`\n * treats a key with no expiry as expiring never, so a new key gets a plain\n * `PEXPIREAT` first.\n */\nexport const EXTEND_SET = `\nlocal function extendSet(key, at)\n\tif redis.call('PTTL', key) < 0 then\n\t\tredis.call('PEXPIREAT', key, at)\n\telse\n\t\tredis.call('PEXPIREAT', key, at, 'GT')\n\tend\nend\n`;\n\n/**\n * Drops from `set` every member whose key, `prefix .. member`, Redis already\n * expired. Run on every insert, so a user's set holds their live sessions or\n * tokens and the few that lapsed since — never every one they ever had.\n */\nexport const PRUNE = `\nlocal function prune(set, prefix)\n\tfor _, member in ipairs(redis.call('SMEMBERS', set)) do\n\t\tif redis.call('EXISTS', prefix .. member) == 0 then\n\t\t\tredis.call('SREM', set, member)\n\t\tend\n\tend\nend\n`;\n",
|
|
9
|
+
"/** The scripts of the session store: one per method that reads more than one key or writes. */\n\nimport { EXTEND_SET, PRUNE } from './shared';\n\n/** A hash as `{ field, value, … }` for a reply: what `HGETALL` answers. */\nconst SESSION_FIELDS = `\nlocal function session(key, id)\n\tlocal fields = redis.call('HGETALL', key)\n\tif #fields == 0 then return false end\n\ttable.insert(fields, 1, id)\n\treturn fields\nend\n`;\n\n/**\n * `ARGV`: prefix, id, tokenHash, userId, authenticatedAt, expiresAt,\n * revokedAt, createdAt, device, lastUsedAt and amr (space-separated; `''` for\n * none, and then the field is not written). Answers `1` when written, `0` for a retry. A token\n * hash another session holds is an error: it is not a retry.\n */\nexport const INSERT_SESSION = `${EXTEND_SET}${PRUNE}\nlocal p, id, tokenHash, userId = ARGV[1], ARGV[2], ARGV[3], ARGV[4]\nlocal key = p .. 'session:' .. id\nif redis.call('EXISTS', key) == 1 then return 0 end\nlocal tokenKey = p .. 'session:token:' .. tokenHash\nlocal holder = redis.call('GET', tokenKey)\nif holder and holder ~= id then\n\treturn redis.error_reply('JANUS a session token hash is held by another session')\nend\nredis.call('HSET', key,\n\t'tokenHash', tokenHash, 'userId', userId, 'authenticatedAt', ARGV[5],\n\t'expiresAt', ARGV[6], 'revokedAt', ARGV[7], 'createdAt', ARGV[8])\nif ARGV[9] ~= '' then redis.call('HSET', key, 'device', ARGV[9]) end\nif ARGV[10] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[10]) end\nif ARGV[11] ~= '' then redis.call('HSET', key, 'amr', ARGV[11]) end\nredis.call('PEXPIREAT', key, ARGV[6])\nredis.call('SET', tokenKey, id, 'PXAT', ARGV[6])\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nprune(sessions, p .. 'session:')\nredis.call('SADD', sessions, id)\nextendSet(sessions, ARGV[6])\nreturn 1\n`;\n\n/** `ARGV`: prefix, tokenHash. Answers `[id, field, value, …]`, or `nil`. */\nexport const FIND_SESSION = `${SESSION_FIELDS}\nlocal p = ARGV[1]\nlocal id = redis.call('GET', p .. 'session:token:' .. ARGV[2])\nif not id then return false end\nreturn session(p .. 'session:' .. id, id)\n`;\n\n/**\n * `ARGV`: prefix, id, expiresAt, lastUsedAt (`''` for none). Moves the expiry of a standing session, and\n * answers it as written; `nil` for a session absent or revoked — an\n * extension racing a revocation never brings the session back.\n */\nexport const EXTEND_SESSION = `${EXTEND_SET}${SESSION_FIELDS}\nlocal p, id, expiresAt = ARGV[1], ARGV[2], ARGV[3]\nlocal key = p .. 'session:' .. id\nif redis.call('EXISTS', key) == 0 then return false end\nif redis.call('HGET', key, 'revokedAt') ~= '' then return false end\nredis.call('HSET', key, 'expiresAt', expiresAt)\nif ARGV[4] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[4]) end\nlocal written = session(key, id)\nlocal tokenHash = redis.call('HGET', key, 'tokenHash')\nlocal userId = redis.call('HGET', key, 'userId')\nredis.call('PEXPIREAT', key, expiresAt)\nredis.call('PEXPIREAT', p .. 'session:token:' .. tokenHash, expiresAt)\nextendSet(p .. 'user:' .. userId .. ':sessions', expiresAt)\nreturn written\n`;\n\n/**\n * `ARGV`: prefix, id, at, set (`'1'` to replace `amr`), amr (space-separated).\n * Moves `authenticatedAt` of a standing session — a\n * step-up — and answers it as written; `nil` for a session absent or\n * revoked, so a confirmation racing a revocation never brings it back. The\n * expiry, and so every key's, stays as it was.\n */\nexport const REAUTHENTICATE_SESSION = `${SESSION_FIELDS}\nlocal key = ARGV[1] .. 'session:' .. ARGV[2]\nif redis.call('EXISTS', key) == 0 then return false end\nif redis.call('HGET', key, 'revokedAt') ~= '' then return false end\nredis.call('HSET', key, 'authenticatedAt', ARGV[3])\nif ARGV[4] == '1' then redis.call('HSET', key, 'amr', ARGV[5]) end\nreturn session(key, ARGV[2])\n`;\n\n/**\n * `ARGV`: prefix, id, at. `1` when the session exists — revoked now or\n * already, keeping its first `revokedAt` — and `0` when there is none.\n */\nexport const REVOKE_SESSION = `\nlocal key = ARGV[1] .. 'session:' .. ARGV[2]\nif redis.call('EXISTS', key) == 0 then return 0 end\nif redis.call('HGET', key, 'revokedAt') == '' then\n\tredis.call('HSET', key, 'revokedAt', ARGV[3])\nend\nreturn 1\n`;\n\n/**\n * `ARGV`: prefix, userId, now (epoch ms). The user's standing sessions — not\n * revoked, expiring after `now` — each as `[id, field, value, …]`. An id whose\n * session Redis already expired is dropped from the set on the way.\n */\nexport const LIST_USER_SESSIONS = `${SESSION_FIELDS}\nlocal p, userId, now = ARGV[1], ARGV[2], tonumber(ARGV[3])\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal listed = {}\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tif redis.call('EXISTS', key) == 0 then\n\t\tredis.call('SREM', sessions, id)\n\telseif redis.call('HGET', key, 'revokedAt') == ''\n\t\tand tonumber(redis.call('HGET', key, 'expiresAt')) > now then\n\t\ttable.insert(listed, session(key, id))\n\tend\nend\nreturn listed\n`;\n\n/**\n * `ARGV`: prefix, userId, at, except (`''` for none), issuedBefore (epoch\n * ms, `''` for none). Revokes every standing session of the user but\n * `except`, created before `issuedBefore` when given, and answers how many. An id whose\n * session Redis already expired is dropped from the set on the way.\n */\nexport const REVOKE_USER_SESSIONS = `\nlocal p, userId, at, except, before = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal revoked = 0\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tif redis.call('EXISTS', key) == 0 then\n\t\tredis.call('SREM', sessions, id)\n\telseif id ~= except and redis.call('HGET', key, 'revokedAt') == ''\n\t\tand (before == '' or tonumber(redis.call('HGET', key, 'createdAt')) < tonumber(before)) then\n\t\tredis.call('HSET', key, 'revokedAt', at)\n\t\trevoked = revoked + 1\n\tend\nend\nreturn revoked\n`;\n\n/**\n * `ARGV`: prefix, userId. Deletes every session of the user, standing,\n * revoked or lapsed, and answers how many were there.\n */\nexport const DELETE_USER_SESSIONS = `\nlocal p, userId = ARGV[1], ARGV[2]\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal deleted = 0\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tlocal tokenHash = redis.call('HGET', key, 'tokenHash')\n\tif tokenHash then\n\t\tlocal tokenKey = p .. 'session:token:' .. tokenHash\n\t\tif redis.call('GET', tokenKey) == id then redis.call('DEL', tokenKey) end\n\t\tredis.call('DEL', key)\n\t\tdeleted = deleted + 1\n\tend\nend\nredis.call('DEL', sessions)\nreturn deleted\n`;\n",
|
|
10
|
+
"/** The scripts of the token store: one per method that reads more than one key or writes. */\n\nimport { EXTEND_SET, PRUNE } from './shared';\n\n/**\n * `ARGV`: prefix, tokenHash, kind, userId, address, expiresAt, spentAt,\n * createdAt, codeHash, attempts, amr (space-separated, `''` for none). The hash is the key, so a token already\n * there is a retry.\n */\nexport const INSERT_TOKEN = `${EXTEND_SET}${PRUNE}\nlocal p, tokenHash, userId = ARGV[1], ARGV[2], ARGV[4]\nlocal key = p .. 'token:' .. tokenHash\nif redis.call('EXISTS', key) == 1 then return 0 end\nredis.call('HSET', key,\n\t'kind', ARGV[3], 'userId', userId, 'address', ARGV[5],\n\t'expiresAt', ARGV[6], 'spentAt', ARGV[7], 'createdAt', ARGV[8],\n\t'codeHash', ARGV[9], 'attempts', ARGV[10], 'amr', ARGV[11])\nredis.call('PEXPIREAT', key, ARGV[6])\nlocal tokens = p .. 'user:' .. userId .. ':tokens'\nprune(tokens, p .. 'token:')\nredis.call('SADD', tokens, tokenHash)\nextendSet(tokens, ARGV[6])\nreturn 1\n`;\n\n/**\n * `ARGV`: prefix, tokenHash, kind, at, bound (`'1'` when `userId` is given,\n * else `'0'`), userId. **Spends the\n * token and answers it as it was before**: `[field, value, …]`, or `nil` for\n * no token of this kind, or of another user than `userId`, which is not spent.\n * A first `spentAt` is kept, so exactly one call ever reads it empty.\n */\nexport const CONSUME_TOKEN = `\nlocal key = ARGV[1] .. 'token:' .. ARGV[2]\nif redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end\nif ARGV[5] == '1' and redis.call('HGET', key, 'userId') ~= ARGV[6] then return false end\nlocal before = redis.call('HGETALL', key)\nif redis.call('HGET', key, 'spentAt') == '' then\n\tredis.call('HSET', key, 'spentAt', ARGV[4])\nend\nreturn before\n`;\n\n/**\n * `ARGV`: prefix, tokenHash, kind. **Counts one attempt and answers the token\n * as it is after**: an unspent token's `attempts` goes up by one, in the same\n * step as the read, so twenty concurrent calls answer twenty counts. A spent\n * token is answered as it is; `nil` for no token of this kind.\n */\nexport const COUNT_ATTEMPT = `\nlocal key = ARGV[1] .. 'token:' .. ARGV[2]\nif redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end\nif redis.call('HGET', key, 'spentAt') == '' then\n\tredis.call('HINCRBY', key, 'attempts', 1)\nend\nreturn redis.call('HGETALL', key)\n`;\n\n/**\n * `ARGV`: prefix, userId, kind, at, except. **Spends every unspent token of\n * the user of this kind** — but the one whose hash is `except`, `''` for\n * none — and answers how many. One script, so a `consumeToken` of\n * the same token runs wholly before or wholly after it: exactly one of the\n * two spends it. A token Redis already expired is a member of the set no\n * more than a key, and is not counted.\n */\nexport const SPEND_USER_TOKENS = `\nlocal p, userId, kind, at, except = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]\nlocal spent = 0\nfor _, tokenHash in ipairs(redis.call('SMEMBERS', p .. 'user:' .. userId .. ':tokens')) do\n\tlocal key = p .. 'token:' .. tokenHash\n\tif tokenHash ~= except and redis.call('HGET', key, 'kind') == kind and redis.call('HGET', key, 'spentAt') == '' then\n\t\tredis.call('HSET', key, 'spentAt', at)\n\t\tspent = spent + 1\n\tend\nend\nreturn spent\n`;\n\n/** `ARGV`: prefix, userId. Deletes every token of the user, and answers how many. */\nexport const DELETE_USER_TOKENS = `\nlocal p, userId = ARGV[1], ARGV[2]\nlocal tokens = p .. 'user:' .. userId .. ':tokens'\nlocal deleted = 0\nfor _, tokenHash in ipairs(redis.call('SMEMBERS', tokens)) do\n\tdeleted = deleted + redis.call('DEL', p .. 'token:' .. tokenHash)\nend\nredis.call('DEL', tokens)\nreturn deleted\n`;\n",
|
|
11
|
+
"import type { SessionStore } from '@softistx/janus';\nimport { count, stamp, stampOrEmpty, toSession, toSessions } from './replies';\nimport { type Evaluate, ignore, runner } from './runner';\nimport {\n\tDELETE_USER_SESSIONS,\n\tEXTEND_SESSION,\n\tFIND_SESSION,\n\tINSERT_SESSION,\n\tLIST_USER_SESSIONS,\n\tREAUTHENTICATE_SESSION,\n\tREVOKE_SESSION,\n\tREVOKE_USER_SESSIONS,\n} from './scripts';\n\nexport function sessionStore(evaluate: Evaluate, prefix: string): SessionStore {\n\tconst run = runner(evaluate, 'sessions', prefix);\n\n\treturn {\n\t\tinsertSession: (record) =>\n\t\t\trun(\n\t\t\t\t'insertSession',\n\t\t\t\tINSERT_SESSION,\n\t\t\t\t[\n\t\t\t\t\trecord.id,\n\t\t\t\t\trecord.tokenHash,\n\t\t\t\t\trecord.userId,\n\t\t\t\t\tstamp(record.authenticatedAt),\n\t\t\t\t\tstamp(record.expiresAt),\n\t\t\t\t\tstampOrEmpty(record.revokedAt),\n\t\t\t\t\tstamp(record.createdAt),\n\t\t\t\t\trecord.device ?? '',\n\t\t\t\t\trecord.lastUsedAt === undefined ? '' : stamp(record.lastUsedAt),\n\t\t\t\t\t(record.amr ?? []).join(' '),\n\t\t\t\t],\n\t\t\t\tignore,\n\t\t\t),\n\n\t\tfindSessionByTokenHash: (tokenHash) =>\n\t\t\trun('findSessionByTokenHash', FIND_SESSION, [tokenHash], toSession),\n\n\t\textendSession: (id, expiresAt, lastUsedAt) =>\n\t\t\trun(\n\t\t\t\t'extendSession',\n\t\t\t\tEXTEND_SESSION,\n\t\t\t\t[\n\t\t\t\t\tid,\n\t\t\t\t\tstamp(expiresAt),\n\t\t\t\t\tlastUsedAt === undefined ? '' : stamp(lastUsedAt),\n\t\t\t\t],\n\t\t\t\ttoSession,\n\t\t\t),\n\n\t\treauthenticateSession: (id, at, amr) =>\n\t\t\trun(\n\t\t\t\t'reauthenticateSession',\n\t\t\t\tREAUTHENTICATE_SESSION,\n\t\t\t\t[id, stamp(at), amr === undefined ? '0' : '1', (amr ?? []).join(' ')],\n\t\t\t\ttoSession,\n\t\t\t),\n\n\t\trevokeSession: (id, at) =>\n\t\t\trun(\n\t\t\t\t'revokeSession',\n\t\t\t\tREVOKE_SESSION,\n\t\t\t\t[id, stamp(at)],\n\t\t\t\t(reply, call) => count(reply, call) === 1,\n\t\t\t),\n\n\t\tlistUserSessions: (userId, now) =>\n\t\t\trun(\n\t\t\t\t'listUserSessions',\n\t\t\t\tLIST_USER_SESSIONS,\n\t\t\t\t[userId, stamp(now)],\n\t\t\t\ttoSessions,\n\t\t\t),\n\n\t\trevokeUserSessions: (userId, at, except, issuedBefore) =>\n\t\t\trun(\n\t\t\t\t'revokeUserSessions',\n\t\t\t\tREVOKE_USER_SESSIONS,\n\t\t\t\t[\n\t\t\t\t\tuserId,\n\t\t\t\t\tstamp(at),\n\t\t\t\t\texcept ?? '',\n\t\t\t\t\tissuedBefore === undefined ? '' : stamp(issuedBefore),\n\t\t\t\t],\n\t\t\t\tcount,\n\t\t\t),\n\n\t\tdeleteUserSessions: (userId) =>\n\t\t\trun('deleteUserSessions', DELETE_USER_SESSIONS, [userId], count),\n\t};\n}\n"
|
|
12
|
+
],
|
|
13
|
+
"mappings": ";AACA,yBAAS;;;ACAT;AAiBO,SAAS,KAAK,CAAC,IAAkB;AAAA,EACvC,OAAO,OAAO,GAAG,QAAQ,CAAC;AAAA;AAGpB,SAAS,YAAY,CAAC,IAAyB;AAAA,EACrD,OAAO,OAAO,OAAO,KAAK,MAAM,EAAE;AAAA;AAI5B,SAAS,SAAS,CAAC,OAAgB,MAAkC;AAAA,EAC3E,IAAI,UAAU;AAAA,IAAM,OAAO;AAAA,EAC3B,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,OAAO,UAAU;AAAA,IAC1D,MAAM,WAAW,MAAM,WAAW;AAAA,EACnC;AAAA,EACA,OAAO,OAAO,QAAQ;AAAA,EACtB,MAAM,OAAO,SAAS,MAAM,IAAI;AAAA,EAChC,OAAO;AAAA,IACN;AAAA,IACA,WAAW,KAAK,KAAK,WAAW;AAAA,IAChC,QAAQ,KAAK,KAAK,QAAQ;AAAA,IAC1B,iBAAiB,KAAK,KAAK,iBAAiB;AAAA,IAC5C,WAAW,KAAK,KAAK,WAAW;AAAA,IAChC,WAAW,KAAK,WAAW,WAAW;AAAA,IACtC,WAAW,KAAK,KAAK,WAAW;AAAA,OAE5B,KAAK,SAAS,QAAQ,MAAM,KAC7B,CAAC,IACD,EAAE,QAAQ,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;AAAA,IAED,cAAc,CAAC,WAAW,MAAM,IAAI,WACnC,IACC,gBACA,eACA;AAAA,MACC;AAAA,MACA;AAAA,MACA,MAAM,EAAE;AAAA,MACR,WAAW,YAAY,MAAM;AAAA,MAC7B,UAAU;AAAA,IACX,GACA,CAAC,OAAO,SAAS,QAAQ,OAAO,WAAW,MAAM,IAAI,CACtD;AAAA,IAED,cAAc,CAAC,WAAW,SACzB,IAAI,gBAAgB,eAAe,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,SAC7D,QAAQ,OAAO,WAAW,MAAM,IAAI,CACrC;AAAA,IAED,iBAAiB,CAAC,QAAQ,MAAM,IAAI,WACnC,IACC,mBACA,mBACA,CAAC,QAAQ,MAAM,MAAM,EAAE,GAAG,UAAU,EAAE,GACtC,KACD;AAAA,IAED,kBAAkB,CAAC,WAClB,IAAI,oBAAoB,oBAAoB,CAAC,MAAM,GAAG,KAAK;AAAA,EAC7D;AAAA;",
|
|
14
|
+
"debugId": "E1F2DB398AE1D30064756E2164756E21",
|
|
15
|
+
"names": []
|
|
16
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { SessionRecord, TokenRecord } from '@softistx/janus';
|
|
2
|
+
/**
|
|
3
|
+
* What a script answers, read back into the port's records. **A reply this
|
|
4
|
+
* adapter did not write is a failure, never an absence**: a key of the prefix
|
|
5
|
+
* changed by hand, or written by another version, rejects with
|
|
6
|
+
* `StoreFailure` — naming the call it failed, as every other failure does.
|
|
7
|
+
*
|
|
8
|
+
* Dates travel as milliseconds since the epoch, and `null` as `''`.
|
|
9
|
+
*/
|
|
10
|
+
/** The call a reply answers: what a failure names. */
|
|
11
|
+
export interface Call {
|
|
12
|
+
readonly slot: 'sessions' | 'tokens';
|
|
13
|
+
readonly operation: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function stamp(at: Date): string;
|
|
16
|
+
export declare function stampOrEmpty(at: Date | null): string;
|
|
17
|
+
/** `[id, field, value, …]` as a session, or `null`. */
|
|
18
|
+
export declare function toSession(reply: unknown, call: Call): SessionRecord | null;
|
|
19
|
+
/** Each element of a list reply as a session; anything else is a failure. */
|
|
20
|
+
export declare function toSessions(reply: unknown, call: Call): SessionRecord[];
|
|
21
|
+
/** `[field, value, …]` as the token `tokenHash` names, or `null`. */
|
|
22
|
+
export declare function toToken(reply: unknown, tokenHash: string, kind: TokenRecord['kind'], call: Call): TokenRecord | null;
|
|
23
|
+
export declare function count(reply: unknown, call: Call): number;
|
|
24
|
+
//# sourceMappingURL=replies.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"replies.d.ts","sourceRoot":"","sources":["../src/replies.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGlE;;;;;;;GAOG;AAEH,sDAAsD;AACtD,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,QAAQ,CAAC;IACrC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC3B;AAED,wBAAgB,KAAK,CAAC,EAAE,EAAE,IAAI,GAAG,MAAM,CAEtC;AAED,wBAAgB,YAAY,CAAC,EAAE,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,CAEpD;AAED,uDAAuD;AACvD,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,GAAG,aAAa,GAAG,IAAI,CA2B1E;AAED,6EAA6E;AAC7E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,GAAG,aAAa,EAAE,CAOtE;AAED,qEAAqE;AACrE,wBAAgB,OAAO,CACtB,KAAK,EAAE,OAAO,EACd,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,EACzB,IAAI,EAAE,IAAI,GACR,WAAW,GAAG,IAAI,CAmBpB;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,GAAG,MAAM,CAGxD"}
|
package/dist/runner.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Call } from './replies';
|
|
2
|
+
/** Runs a script, and makes every rejection one the port allows. */
|
|
3
|
+
export type Evaluate = (call: Call, script: string, args: readonly string[]) => Promise<unknown>;
|
|
4
|
+
/** What a slot's methods call: a script's reply, already decoded. */
|
|
5
|
+
export type Run = <T>(operation: string, script: string, args: readonly string[], decode: (reply: unknown, call: Call) => T) => Promise<T>;
|
|
6
|
+
export declare function runner(evaluate: Evaluate, slot: Call['slot'], prefix: string): Run;
|
|
7
|
+
export declare const ignore: () => undefined;
|
|
8
|
+
//# sourceMappingURL=runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../src/runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,oEAAoE;AACpE,MAAM,MAAM,QAAQ,GAAG,CACtB,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,SAAS,MAAM,EAAE,KACnB,OAAO,CAAC,OAAO,CAAC,CAAC;AAEtB,qEAAqE;AACrE,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,KAAK,CAAC,KACrC,OAAO,CAAC,CAAC,CAAC,CAAC;AAEhB,wBAAgB,MAAM,CACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAClB,MAAM,EAAE,MAAM,GACZ,GAAG,CAKL;AAED,eAAO,MAAM,MAAM,iBAAkB,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Lua scripts, one per port method that reads more than one key or
|
|
3
|
+
* writes anything. **A script is atomic**: Redis runs nothing else while it
|
|
4
|
+
* does, which is what the port asks of every method (rule 5) — and what makes
|
|
5
|
+
* `consumeToken` one step, never a read and then a write.
|
|
6
|
+
*
|
|
7
|
+
* Every key is built inside the script from `ARGV[1]`, the prefix. A method's
|
|
8
|
+
* keys depend on what it reads first — a session's token key on the session
|
|
9
|
+
* — so they cannot all be declared up front. That is also why Redis Cluster
|
|
10
|
+
* is not supported: a script may touch keys of more than one slot.
|
|
11
|
+
*
|
|
12
|
+
* Dates travel as milliseconds since the epoch, and `null` as `''`: a hash
|
|
13
|
+
* field holds a string, and no date is ever the empty string.
|
|
14
|
+
*/
|
|
15
|
+
export { DELETE_USER_SESSIONS, EXTEND_SESSION, FIND_SESSION, INSERT_SESSION, LIST_USER_SESSIONS, REAUTHENTICATE_SESSION, REVOKE_SESSION, REVOKE_USER_SESSIONS, } from './sessions';
|
|
16
|
+
export { CONSUME_TOKEN, COUNT_ATTEMPT, DELETE_USER_TOKENS, INSERT_TOKEN, SPEND_USER_TOKENS, } from './tokens';
|
|
17
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scripts/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EACN,oBAAoB,EACpB,cAAc,EACd,YAAY,EACZ,cAAc,EACd,kBAAkB,EAClB,sBAAsB,EACtB,cAAc,EACd,oBAAoB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACN,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,GACjB,MAAM,UAAU,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** The scripts of the session store: one per method that reads more than one key or writes. */
|
|
2
|
+
/**
|
|
3
|
+
* `ARGV`: prefix, id, tokenHash, userId, authenticatedAt, expiresAt,
|
|
4
|
+
* revokedAt, createdAt, device, lastUsedAt and amr (space-separated; `''` for
|
|
5
|
+
* none, and then the field is not written). Answers `1` when written, `0` for a retry. A token
|
|
6
|
+
* hash another session holds is an error: it is not a retry.
|
|
7
|
+
*/
|
|
8
|
+
export declare const INSERT_SESSION = "\nlocal function extendSet(key, at)\n\tif redis.call('PTTL', key) < 0 then\n\t\tredis.call('PEXPIREAT', key, at)\n\telse\n\t\tredis.call('PEXPIREAT', key, at, 'GT')\n\tend\nend\n\nlocal function prune(set, prefix)\n\tfor _, member in ipairs(redis.call('SMEMBERS', set)) do\n\t\tif redis.call('EXISTS', prefix .. member) == 0 then\n\t\t\tredis.call('SREM', set, member)\n\t\tend\n\tend\nend\n\nlocal p, id, tokenHash, userId = ARGV[1], ARGV[2], ARGV[3], ARGV[4]\nlocal key = p .. 'session:' .. id\nif redis.call('EXISTS', key) == 1 then return 0 end\nlocal tokenKey = p .. 'session:token:' .. tokenHash\nlocal holder = redis.call('GET', tokenKey)\nif holder and holder ~= id then\n\treturn redis.error_reply('JANUS a session token hash is held by another session')\nend\nredis.call('HSET', key,\n\t'tokenHash', tokenHash, 'userId', userId, 'authenticatedAt', ARGV[5],\n\t'expiresAt', ARGV[6], 'revokedAt', ARGV[7], 'createdAt', ARGV[8])\nif ARGV[9] ~= '' then redis.call('HSET', key, 'device', ARGV[9]) end\nif ARGV[10] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[10]) end\nif ARGV[11] ~= '' then redis.call('HSET', key, 'amr', ARGV[11]) end\nredis.call('PEXPIREAT', key, ARGV[6])\nredis.call('SET', tokenKey, id, 'PXAT', ARGV[6])\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nprune(sessions, p .. 'session:')\nredis.call('SADD', sessions, id)\nextendSet(sessions, ARGV[6])\nreturn 1\n";
|
|
9
|
+
/** `ARGV`: prefix, tokenHash. Answers `[id, field, value, …]`, or `nil`. */
|
|
10
|
+
export declare const FIND_SESSION = "\nlocal function session(key, id)\n\tlocal fields = redis.call('HGETALL', key)\n\tif #fields == 0 then return false end\n\ttable.insert(fields, 1, id)\n\treturn fields\nend\n\nlocal p = ARGV[1]\nlocal id = redis.call('GET', p .. 'session:token:' .. ARGV[2])\nif not id then return false end\nreturn session(p .. 'session:' .. id, id)\n";
|
|
11
|
+
/**
|
|
12
|
+
* `ARGV`: prefix, id, expiresAt, lastUsedAt (`''` for none). Moves the expiry of a standing session, and
|
|
13
|
+
* answers it as written; `nil` for a session absent or revoked — an
|
|
14
|
+
* extension racing a revocation never brings the session back.
|
|
15
|
+
*/
|
|
16
|
+
export declare const EXTEND_SESSION = "\nlocal function extendSet(key, at)\n\tif redis.call('PTTL', key) < 0 then\n\t\tredis.call('PEXPIREAT', key, at)\n\telse\n\t\tredis.call('PEXPIREAT', key, at, 'GT')\n\tend\nend\n\nlocal function session(key, id)\n\tlocal fields = redis.call('HGETALL', key)\n\tif #fields == 0 then return false end\n\ttable.insert(fields, 1, id)\n\treturn fields\nend\n\nlocal p, id, expiresAt = ARGV[1], ARGV[2], ARGV[3]\nlocal key = p .. 'session:' .. id\nif redis.call('EXISTS', key) == 0 then return false end\nif redis.call('HGET', key, 'revokedAt') ~= '' then return false end\nredis.call('HSET', key, 'expiresAt', expiresAt)\nif ARGV[4] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[4]) end\nlocal written = session(key, id)\nlocal tokenHash = redis.call('HGET', key, 'tokenHash')\nlocal userId = redis.call('HGET', key, 'userId')\nredis.call('PEXPIREAT', key, expiresAt)\nredis.call('PEXPIREAT', p .. 'session:token:' .. tokenHash, expiresAt)\nextendSet(p .. 'user:' .. userId .. ':sessions', expiresAt)\nreturn written\n";
|
|
17
|
+
/**
|
|
18
|
+
* `ARGV`: prefix, id, at, set (`'1'` to replace `amr`), amr (space-separated).
|
|
19
|
+
* Moves `authenticatedAt` of a standing session — a
|
|
20
|
+
* step-up — and answers it as written; `nil` for a session absent or
|
|
21
|
+
* revoked, so a confirmation racing a revocation never brings it back. The
|
|
22
|
+
* expiry, and so every key's, stays as it was.
|
|
23
|
+
*/
|
|
24
|
+
export declare const REAUTHENTICATE_SESSION = "\nlocal function session(key, id)\n\tlocal fields = redis.call('HGETALL', key)\n\tif #fields == 0 then return false end\n\ttable.insert(fields, 1, id)\n\treturn fields\nend\n\nlocal key = ARGV[1] .. 'session:' .. ARGV[2]\nif redis.call('EXISTS', key) == 0 then return false end\nif redis.call('HGET', key, 'revokedAt') ~= '' then return false end\nredis.call('HSET', key, 'authenticatedAt', ARGV[3])\nif ARGV[4] == '1' then redis.call('HSET', key, 'amr', ARGV[5]) end\nreturn session(key, ARGV[2])\n";
|
|
25
|
+
/**
|
|
26
|
+
* `ARGV`: prefix, id, at. `1` when the session exists — revoked now or
|
|
27
|
+
* already, keeping its first `revokedAt` — and `0` when there is none.
|
|
28
|
+
*/
|
|
29
|
+
export declare const REVOKE_SESSION = "\nlocal key = ARGV[1] .. 'session:' .. ARGV[2]\nif redis.call('EXISTS', key) == 0 then return 0 end\nif redis.call('HGET', key, 'revokedAt') == '' then\n\tredis.call('HSET', key, 'revokedAt', ARGV[3])\nend\nreturn 1\n";
|
|
30
|
+
/**
|
|
31
|
+
* `ARGV`: prefix, userId, now (epoch ms). The user's standing sessions — not
|
|
32
|
+
* revoked, expiring after `now` — each as `[id, field, value, …]`. An id whose
|
|
33
|
+
* session Redis already expired is dropped from the set on the way.
|
|
34
|
+
*/
|
|
35
|
+
export declare const LIST_USER_SESSIONS = "\nlocal function session(key, id)\n\tlocal fields = redis.call('HGETALL', key)\n\tif #fields == 0 then return false end\n\ttable.insert(fields, 1, id)\n\treturn fields\nend\n\nlocal p, userId, now = ARGV[1], ARGV[2], tonumber(ARGV[3])\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal listed = {}\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tif redis.call('EXISTS', key) == 0 then\n\t\tredis.call('SREM', sessions, id)\n\telseif redis.call('HGET', key, 'revokedAt') == ''\n\t\tand tonumber(redis.call('HGET', key, 'expiresAt')) > now then\n\t\ttable.insert(listed, session(key, id))\n\tend\nend\nreturn listed\n";
|
|
36
|
+
/**
|
|
37
|
+
* `ARGV`: prefix, userId, at, except (`''` for none), issuedBefore (epoch
|
|
38
|
+
* ms, `''` for none). Revokes every standing session of the user but
|
|
39
|
+
* `except`, created before `issuedBefore` when given, and answers how many. An id whose
|
|
40
|
+
* session Redis already expired is dropped from the set on the way.
|
|
41
|
+
*/
|
|
42
|
+
export declare const REVOKE_USER_SESSIONS = "\nlocal p, userId, at, except, before = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal revoked = 0\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tif redis.call('EXISTS', key) == 0 then\n\t\tredis.call('SREM', sessions, id)\n\telseif id ~= except and redis.call('HGET', key, 'revokedAt') == ''\n\t\tand (before == '' or tonumber(redis.call('HGET', key, 'createdAt')) < tonumber(before)) then\n\t\tredis.call('HSET', key, 'revokedAt', at)\n\t\trevoked = revoked + 1\n\tend\nend\nreturn revoked\n";
|
|
43
|
+
/**
|
|
44
|
+
* `ARGV`: prefix, userId. Deletes every session of the user, standing,
|
|
45
|
+
* revoked or lapsed, and answers how many were there.
|
|
46
|
+
*/
|
|
47
|
+
export declare const DELETE_USER_SESSIONS = "\nlocal p, userId = ARGV[1], ARGV[2]\nlocal sessions = p .. 'user:' .. userId .. ':sessions'\nlocal deleted = 0\nfor _, id in ipairs(redis.call('SMEMBERS', sessions)) do\n\tlocal key = p .. 'session:' .. id\n\tlocal tokenHash = redis.call('HGET', key, 'tokenHash')\n\tif tokenHash then\n\t\tlocal tokenKey = p .. 'session:token:' .. tokenHash\n\t\tif redis.call('GET', tokenKey) == id then redis.call('DEL', tokenKey) end\n\t\tredis.call('DEL', key)\n\t\tdeleted = deleted + 1\n\tend\nend\nredis.call('DEL', sessions)\nreturn deleted\n";
|
|
48
|
+
//# sourceMappingURL=sessions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../../src/scripts/sessions.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAc/F;;;;;GAKG;AACH,eAAO,MAAM,cAAc,k4CAsB1B,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,YAAY,oVAKxB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,cAAc,igCAc1B,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,wfAOlC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,8NAO1B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,0qBAc9B,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,imBAehC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB,4hBAgBhC,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the scripts of both stores share: keeping a user's set of keys alive,
|
|
3
|
+
* and pruning it of the keys Redis already expired.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Sets `key` to expire at `at`, or later if it already expires later — the
|
|
7
|
+
* set of a user's sessions lives as long as their longest session. `GT`
|
|
8
|
+
* treats a key with no expiry as expiring never, so a new key gets a plain
|
|
9
|
+
* `PEXPIREAT` first.
|
|
10
|
+
*/
|
|
11
|
+
export declare const EXTEND_SET = "\nlocal function extendSet(key, at)\n\tif redis.call('PTTL', key) < 0 then\n\t\tredis.call('PEXPIREAT', key, at)\n\telse\n\t\tredis.call('PEXPIREAT', key, at, 'GT')\n\tend\nend\n";
|
|
12
|
+
/**
|
|
13
|
+
* Drops from `set` every member whose key, `prefix .. member`, Redis already
|
|
14
|
+
* expired. Run on every insert, so a user's set holds their live sessions or
|
|
15
|
+
* tokens and the few that lapsed since — never every one they ever had.
|
|
16
|
+
*/
|
|
17
|
+
export declare const PRUNE = "\nlocal function prune(set, prefix)\n\tfor _, member in ipairs(redis.call('SMEMBERS', set)) do\n\t\tif redis.call('EXISTS', prefix .. member) == 0 then\n\t\t\tredis.call('SREM', set, member)\n\t\tend\n\tend\nend\n";
|
|
18
|
+
//# sourceMappingURL=shared.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/scripts/shared.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,UAAU,uLAQtB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,KAAK,0NAQjB,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The scripts of the token store: one per method that reads more than one key or writes. */
|
|
2
|
+
/**
|
|
3
|
+
* `ARGV`: prefix, tokenHash, kind, userId, address, expiresAt, spentAt,
|
|
4
|
+
* createdAt, codeHash, attempts, amr (space-separated, `''` for none). The hash is the key, so a token already
|
|
5
|
+
* there is a retry.
|
|
6
|
+
*/
|
|
7
|
+
export declare const INSERT_TOKEN = "\nlocal function extendSet(key, at)\n\tif redis.call('PTTL', key) < 0 then\n\t\tredis.call('PEXPIREAT', key, at)\n\telse\n\t\tredis.call('PEXPIREAT', key, at, 'GT')\n\tend\nend\n\nlocal function prune(set, prefix)\n\tfor _, member in ipairs(redis.call('SMEMBERS', set)) do\n\t\tif redis.call('EXISTS', prefix .. member) == 0 then\n\t\t\tredis.call('SREM', set, member)\n\t\tend\n\tend\nend\n\nlocal p, tokenHash, userId = ARGV[1], ARGV[2], ARGV[4]\nlocal key = p .. 'token:' .. tokenHash\nif redis.call('EXISTS', key) == 1 then return 0 end\nredis.call('HSET', key,\n\t'kind', ARGV[3], 'userId', userId, 'address', ARGV[5],\n\t'expiresAt', ARGV[6], 'spentAt', ARGV[7], 'createdAt', ARGV[8],\n\t'codeHash', ARGV[9], 'attempts', ARGV[10], 'amr', ARGV[11])\nredis.call('PEXPIREAT', key, ARGV[6])\nlocal tokens = p .. 'user:' .. userId .. ':tokens'\nprune(tokens, p .. 'token:')\nredis.call('SADD', tokens, tokenHash)\nextendSet(tokens, ARGV[6])\nreturn 1\n";
|
|
8
|
+
/**
|
|
9
|
+
* `ARGV`: prefix, tokenHash, kind, at, bound (`'1'` when `userId` is given,
|
|
10
|
+
* else `'0'`), userId. **Spends the
|
|
11
|
+
* token and answers it as it was before**: `[field, value, …]`, or `nil` for
|
|
12
|
+
* no token of this kind, or of another user than `userId`, which is not spent.
|
|
13
|
+
* A first `spentAt` is kept, so exactly one call ever reads it empty.
|
|
14
|
+
*/
|
|
15
|
+
export declare const CONSUME_TOKEN = "\nlocal key = ARGV[1] .. 'token:' .. ARGV[2]\nif redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end\nif ARGV[5] == '1' and redis.call('HGET', key, 'userId') ~= ARGV[6] then return false end\nlocal before = redis.call('HGETALL', key)\nif redis.call('HGET', key, 'spentAt') == '' then\n\tredis.call('HSET', key, 'spentAt', ARGV[4])\nend\nreturn before\n";
|
|
16
|
+
/**
|
|
17
|
+
* `ARGV`: prefix, tokenHash, kind. **Counts one attempt and answers the token
|
|
18
|
+
* as it is after**: an unspent token's `attempts` goes up by one, in the same
|
|
19
|
+
* step as the read, so twenty concurrent calls answer twenty counts. A spent
|
|
20
|
+
* token is answered as it is; `nil` for no token of this kind.
|
|
21
|
+
*/
|
|
22
|
+
export declare const COUNT_ATTEMPT = "\nlocal key = ARGV[1] .. 'token:' .. ARGV[2]\nif redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end\nif redis.call('HGET', key, 'spentAt') == '' then\n\tredis.call('HINCRBY', key, 'attempts', 1)\nend\nreturn redis.call('HGETALL', key)\n";
|
|
23
|
+
/**
|
|
24
|
+
* `ARGV`: prefix, userId, kind, at, except. **Spends every unspent token of
|
|
25
|
+
* the user of this kind** — but the one whose hash is `except`, `''` for
|
|
26
|
+
* none — and answers how many. One script, so a `consumeToken` of
|
|
27
|
+
* the same token runs wholly before or wholly after it: exactly one of the
|
|
28
|
+
* two spends it. A token Redis already expired is a member of the set no
|
|
29
|
+
* more than a key, and is not counted.
|
|
30
|
+
*/
|
|
31
|
+
export declare const SPEND_USER_TOKENS = "\nlocal p, userId, kind, at, except = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]\nlocal spent = 0\nfor _, tokenHash in ipairs(redis.call('SMEMBERS', p .. 'user:' .. userId .. ':tokens')) do\n\tlocal key = p .. 'token:' .. tokenHash\n\tif tokenHash ~= except and redis.call('HGET', key, 'kind') == kind and redis.call('HGET', key, 'spentAt') == '' then\n\t\tredis.call('HSET', key, 'spentAt', at)\n\t\tspent = spent + 1\n\tend\nend\nreturn spent\n";
|
|
32
|
+
/** `ARGV`: prefix, userId. Deletes every token of the user, and answers how many. */
|
|
33
|
+
export declare const DELETE_USER_TOKENS = "\nlocal p, userId = ARGV[1], ARGV[2]\nlocal tokens = p .. 'user:' .. userId .. ':tokens'\nlocal deleted = 0\nfor _, tokenHash in ipairs(redis.call('SMEMBERS', tokens)) do\n\tdeleted = deleted + redis.call('DEL', p .. 'token:' .. tokenHash)\nend\nredis.call('DEL', tokens)\nreturn deleted\n";
|
|
34
|
+
//# sourceMappingURL=tokens.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.d.ts","sourceRoot":"","sources":["../../src/scripts/tokens.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAI7F;;;;GAIG;AACH,eAAO,MAAM,YAAY,87BAcxB,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,kXASzB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,aAAa,+PAOzB,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,ocAW7B,CAAC;AAEF,qFAAqF;AACrF,eAAO,MAAM,kBAAkB,sSAS9B,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-store.d.ts","sourceRoot":"","sources":["../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,EAAE,KAAK,QAAQ,EAAkB,MAAM,UAAU,CAAC;AAYzD,wBAAgB,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,YAAY,CA8E7E"}
|
package/dist/stores.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { JanusStores } from '@softistx/janus';
|
|
2
|
+
import type { RedisConnection } from '@softistx/redis';
|
|
3
|
+
/** What the stores take besides the connection. */
|
|
4
|
+
export interface RedisStoresOptions {
|
|
5
|
+
/**
|
|
6
|
+
* What every key starts with — `janus:` unless you say otherwise. Two
|
|
7
|
+
* applications sharing one Redis each take their own.
|
|
8
|
+
*/
|
|
9
|
+
readonly prefix?: string;
|
|
10
|
+
}
|
|
11
|
+
/** The two slots of `janus()`'s `store` that Redis serves. */
|
|
12
|
+
export type RedisStores = Pick<JanusStores, 'sessions' | 'tokens'>;
|
|
13
|
+
/**
|
|
14
|
+
* Sessions and one-time tokens, over one Redis, on `@softistx/redis`'s
|
|
15
|
+
* connection. **Users stay in another store**: a user is written once and
|
|
16
|
+
* read on sign-in; a session is read on every request, which is what Redis
|
|
17
|
+
* is for.
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* const redis = await connectRedis(process.env.REDIS_URL);
|
|
21
|
+
* const auth = janus({
|
|
22
|
+
* user, password: { login: 'email' }, hasher,
|
|
23
|
+
* store: { ...createMongoStores(db), ...createRedisStores(redis) },
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* **Redis expires them itself**: every session and token key expires at its
|
|
28
|
+
* own `expiresAt`. So `sessions.deleteExpiredSessions` and
|
|
29
|
+
* `tokens.deleteExpiredTokens` are not implemented, and
|
|
30
|
+
* `auth.collectExpired()` answers `UNSUPPORTED` — there is nothing to
|
|
31
|
+
* collect. **Every method that writes is one Lua script**, atomic as the port
|
|
32
|
+
* asks, so `consumeToken` is never a read and then a write.
|
|
33
|
+
*
|
|
34
|
+
* It creates nothing and needs no schema: the keys are made by the first
|
|
35
|
+
* write.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createRedisStores(redis: RedisConnection, options?: RedisStoresOptions): RedisStores;
|
|
38
|
+
//# sourceMappingURL=stores.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores.d.ts","sourceRoot":"","sources":["../src/stores.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAc,MAAM,iBAAiB,CAAC;AAE/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAavD,mDAAmD;AACnD,MAAM,WAAW,kBAAkB;IAClC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,8DAA8D;AAC9D,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,EAAE,UAAU,GAAG,QAAQ,CAAC,CAAC;AAEnE;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,eAAe,EACtB,OAAO,GAAE,kBAAuB,GAC9B,WAAW,CAOb"}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# @softistx/janus-redis — documentation
|
|
2
|
+
|
|
3
|
+
The [README](../README.md) shows the whole wiring in one example; these pages
|
|
4
|
+
give the detail.
|
|
5
|
+
|
|
6
|
+
| Page | Read it when |
|
|
7
|
+
| --- | --- |
|
|
8
|
+
| [Wiring sessions and tokens to Redis](guide/wiring.md) | You are putting sessions and tokens in Redis beside another users store, choosing the connection's options, or handling what a failure throws |
|
|
9
|
+
| [Troubleshooting](troubleshooting.md) | You have an error message and want its cause and its fix |
|
|
10
|
+
| [Roadmap](roadmap.md) | You want to know what is coming, what shipped, and what is deliberately not planned |
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Wiring sessions and tokens to Redis
|
|
2
|
+
|
|
3
|
+
This page covers:
|
|
4
|
+
- putting `@softistx/janus`'s sessions and one-time tokens in Redis, beside the
|
|
5
|
+
store that keeps your users;
|
|
6
|
+
- the connection options that matter;
|
|
7
|
+
- what a failure looks like.
|
|
8
|
+
|
|
9
|
+
## Beside another users store
|
|
10
|
+
|
|
11
|
+
`createRedisStores(redis)` returns `{ sessions, tokens }`, two of the three
|
|
12
|
+
slots of `janus()`'s `store`. The third, `users`, comes from another adapter.
|
|
13
|
+
Spread that one first, then this one:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { janus, scryptHasher } from '@softistx/janus';
|
|
17
|
+
import { createDrizzleStores } from '@softistx/janus-drizzle';
|
|
18
|
+
import { createRedisStores } from '@softistx/janus-redis';
|
|
19
|
+
import { connectRedis } from '@softistx/redis';
|
|
20
|
+
import { drizzle } from 'drizzle-orm/bun-sql';
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
|
|
23
|
+
const db = drizzle(process.env.DATABASE_URL ?? 'postgres://localhost:5432/app');
|
|
24
|
+
const redis = await connectRedis(process.env.REDIS_URL ?? 'redis://localhost:6379', {
|
|
25
|
+
enableOfflineQueue: false,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export const auth = janus({
|
|
29
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
30
|
+
password: { login: 'email' },
|
|
31
|
+
hasher: scryptHasher(),
|
|
32
|
+
store: {
|
|
33
|
+
...createDrizzleStores(db), // users — and sessions and tokens, replaced below
|
|
34
|
+
...createRedisStores(redis), // sessions and tokens
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The same works with `createMongoStores(db)` from `@softistx/janus-mongo`, or with a
|
|
40
|
+
`users` store of your own. The core never writes a user and a session in one
|
|
41
|
+
transaction, so nothing is lost by keeping them in two databases.
|
|
42
|
+
|
|
43
|
+
To wire permissions, pass `relations` from the users' adapter as usual:
|
|
44
|
+
`createDrizzleAdapter(db)` and `createMongoAdapter(db)` both return it.
|
|
45
|
+
|
|
46
|
+
## `createRedisStores(redis, options?)`
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
function createRedisStores(
|
|
50
|
+
redis: RedisConnection, // what connectRedis returns
|
|
51
|
+
options?: { prefix?: string }, // 'janus:' by default
|
|
52
|
+
): { sessions: SessionStore; tokens: TokenStore };
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
It connects to nothing and creates nothing: the keys are made by the first
|
|
56
|
+
write, and Redis needs no schema. `redis` is `@softistx/redis`'s connection, and
|
|
57
|
+
its client is Bun's `RedisClient`, so this runs on Bun.
|
|
58
|
+
|
|
59
|
+
`prefix` starts every key. Two applications sharing one Redis each take their
|
|
60
|
+
own, as do the tests of one application:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
createRedisStores(redis, { prefix: 'clinic:janus:' });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## The connection's options
|
|
67
|
+
|
|
68
|
+
`connectRedis(uri, options)` takes Bun's `RedisOptions`. One of them decides
|
|
69
|
+
how an outage looks to your users:
|
|
70
|
+
|
|
71
|
+
| `enableOfflineQueue` | While Redis is unreachable | Measured on Redis 7.4 |
|
|
72
|
+
| --- | --- | --- |
|
|
73
|
+
| `true`, Bun's default | Every command waits while the client reconnects, then fails | `STORE_FAILED` after **31 s** |
|
|
74
|
+
| `false` | Every command fails at once | `STORE_FAILED` in **1 ms** |
|
|
75
|
+
|
|
76
|
+
With `false`, a request during an outage gets a 503 it can retry, instead of
|
|
77
|
+
holding a connection open for half a minute. The trade-off: a blip of a few
|
|
78
|
+
milliseconds fails the requests that land in it.
|
|
79
|
+
|
|
80
|
+
`connectRedis` shares one client per URI, and refuses a second connection to
|
|
81
|
+
the same URI with other options. If your application already connects to this
|
|
82
|
+
Redis, pass the same options everywhere, or give Janus a URI of its own, for
|
|
83
|
+
example another database number: `redis://localhost:6379/1`.
|
|
84
|
+
|
|
85
|
+
## Listing a user's sessions
|
|
86
|
+
|
|
87
|
+
`sessions.listUserSessions` (behind `auth.sessions.list` and `revoke`) reads
|
|
88
|
+
the user's `user:<id>:sessions` set in one script and answers the sessions that
|
|
89
|
+
are not revoked and expire after now. A session also keeps its optional
|
|
90
|
+
`device` (the sign-in's `deviceLabel`) and `lastUsedAt` (moved by
|
|
91
|
+
`extendSession`) in its hash; a session written before them has neither field
|
|
92
|
+
and lists without. No migration.
|
|
93
|
+
|
|
94
|
+
## Expiry
|
|
95
|
+
|
|
96
|
+
Every session and token key expires at its own `expiresAt`, set with
|
|
97
|
+
`PEXPIREAT` when it is written, and moved when `extendSession` renews it.
|
|
98
|
+
Redis deletes it then. The core decides expiry on every read anyway, so a
|
|
99
|
+
lapsed session is refused whether Redis has deleted it yet or not.
|
|
100
|
+
|
|
101
|
+
This is why `sessions.deleteExpiredSessions` and `tokens.deleteExpiredTokens`
|
|
102
|
+
are not implemented, and `auth.collectExpired()` answers `UNSUPPORTED`: there is nothing left to
|
|
103
|
+
collect.
|
|
104
|
+
|
|
105
|
+
A revoked session stays until its expiry, so that its revocation is what a
|
|
106
|
+
read returns.
|
|
107
|
+
|
|
108
|
+
A user's set of sessions, and of tokens, lives as long as the longest of
|
|
109
|
+
them. An id whose key Redis expired stays in the set until the user's next
|
|
110
|
+
sign-in or token, or "sign out everywhere", which drop it, so a set holds live entries and the few
|
|
111
|
+
that lapsed since.
|
|
112
|
+
|
|
113
|
+
## What a failure looks like
|
|
114
|
+
|
|
115
|
+
The adapter defines **no error class**. Every rejection is `@softistx/janus`'s
|
|
116
|
+
`StoreFailure`, whose `cause` is what Bun's client threw:
|
|
117
|
+
|
|
118
|
+
| What happens | What you get |
|
|
119
|
+
| --- | --- |
|
|
120
|
+
| Redis is unreachable, the connection closed, a timeout | `StoreFailure`; `cause` is Bun's `RedisError`, such as `ERR_REDIS_CONNECTION_CLOSED` |
|
|
121
|
+
| Redis refuses the command: `NOPERM`, `OOM`, `READONLY` on a replica | `StoreFailure`; `cause` carries Redis's reply |
|
|
122
|
+
| A session token hash already held by another session | `StoreFailure`: it is not a retry, and never happens with the core's 32 random bytes |
|
|
123
|
+
| A key under the prefix that this adapter did not write | `StoreFailure` naming the call, with no `cause`: never read as an absence |
|
|
124
|
+
|
|
125
|
+
Nothing returns `null` for an error, so a route answers 503, not 401. With
|
|
126
|
+
`@softistx/janus-hono`, `app.onError(janusErrors())` does that for every route.
|
package/docs/roadmap.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Roadmap
|
|
2
|
+
|
|
3
|
+
Where `@softistx/janus-redis` is heading. It shows a direction, not a commitment:
|
|
4
|
+
there are no dates here, and the only number is the version something shipped
|
|
5
|
+
in.
|
|
6
|
+
|
|
7
|
+
## Now
|
|
8
|
+
|
|
9
|
+
Nothing yet.
|
|
10
|
+
|
|
11
|
+
## Next
|
|
12
|
+
|
|
13
|
+
Nothing yet.
|
|
14
|
+
|
|
15
|
+
## Later
|
|
16
|
+
|
|
17
|
+
Nothing yet.
|
|
18
|
+
|
|
19
|
+
## Not planned
|
|
20
|
+
|
|
21
|
+
- **Users in Redis.** A user is written once and kept. Keep users in
|
|
22
|
+
`@softistx/janus-mongo`, `@softistx/janus-drizzle` or a store of your own.
|
|
23
|
+
- **The relation store in Redis.** `list()` pages objects in id order through
|
|
24
|
+
a reverse index, which a database does better.
|
|
25
|
+
- **Redis Cluster.** A script reads keys it finds on the way, which may live
|
|
26
|
+
in different slots.
|
|
27
|
+
- **`collectExpired()`.** Redis expires sessions and tokens itself; the
|
|
28
|
+
method answers `UNSUPPORTED` on purpose, for tokens as well as sessions.
|
|
29
|
+
- **Clients other than Bun's.** `@softistx/redis`'s connection is Bun's
|
|
30
|
+
`RedisClient`, so this runs on Bun.
|
|
31
|
+
- **Error classes of its own.** The adapter throws `@softistx/janus`'s classes,
|
|
32
|
+
which is why `@softistx/janus` is a required peer and never a dependency.
|
|
33
|
+
|
|
34
|
+
## Shipped
|
|
35
|
+
|
|
36
|
+
- **Moved to `@softistx` on GitHub Packages** (0.6.0) — formerly
|
|
37
|
+
the `@nxgt` scope on npm; same names under the new scope, published privately.
|
|
38
|
+
|
|
39
|
+
- **`reauthenticateSession` in one script, v0.4.0** — for `@softistx/janus`
|
|
40
|
+
0.12: moves `authenticatedAt` only while `revokedAt` is empty, leaves
|
|
41
|
+
every TTL as it was, with the commands the ACL already allows. The token
|
|
42
|
+
kind `stepUp` needs nothing: no migration.
|
|
43
|
+
- **A user's tokens spent in one script, v0.3.0** — for `@softistx/janus` 0.7:
|
|
44
|
+
`spendUserTokens(userId, kind, at, except?)` walks the user's set of
|
|
45
|
+
tokens in one Lua script, with the commands the ACL already allows, and
|
|
46
|
+
passes the four new conformance cases.
|
|
47
|
+
- **Attempts counted on a one-time token, v0.2.0** — for `@softistx/janus` 0.4:
|
|
48
|
+
a token keeps its `codeHash` and `attempts`, and `countAttempt` counts an
|
|
49
|
+
attempt at a code in one Lua script. No migration: a token written before
|
|
50
|
+
reads as no code and no attempt.
|
|
51
|
+
- **The first release, v0.1.0.** Sessions and one-time tokens in Redis,
|
|
52
|
+
expired by Redis itself; the adapter passes the conformance suite for both
|
|
53
|
+
stores on Redis 7.4.
|