@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,168 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/janus-redis
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Redis adapter for [`@softistx/janus`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus):
|
|
4
|
+
its **sessions** and **one-time tokens**, over one Redis, on
|
|
5
|
+
[`@softistx/redis`](https://github.com/softistx/nxgt-data/blob/develop/packages/redis/README.md)'s connection.
|
|
6
|
+
|
|
7
|
+
A session is read on every request, and a session and a token both expire,
|
|
8
|
+
which is what Redis is for. Users stay in another adapter, since they are
|
|
9
|
+
written once and kept. The store port is cut where atomicity is not required,
|
|
10
|
+
so no transaction ever spans the two.
|
|
11
|
+
|
|
12
|
+
It passes the `@softistx/janus/conformance` suite for these two slots against a
|
|
13
|
+
real Redis, outages included, on every CI run.
|
|
14
|
+
|
|
15
|
+
> **0.x.** A minor version may still change the surface; the changelog says how.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
Public on npmjs:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
bun add @softistx/janus-redis @softistx/janus @softistx/redis
|
|
23
|
+
bun add @softistx/janus-drizzle @softistx/drizzle drizzle-orm # the users store in the example below — or @softistx/janus-mongo
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Users live in another adapter: this one holds sessions and one-time tokens
|
|
27
|
+
only.
|
|
28
|
+
|
|
29
|
+
Every peer is required:
|
|
30
|
+
- `@softistx/janus`;
|
|
31
|
+
- `@softistx/redis`, `>=0.14.0 <1`, whose connection wraps Bun's own `RedisClient`,
|
|
32
|
+
so this runs on **Bun**;
|
|
33
|
+
- `typescript` 6 or 7.
|
|
34
|
+
|
|
35
|
+
The `@softistx/redis` floor is tested, not claimed: the package's specs and its
|
|
36
|
+
typecheck run on `@softistx/redis` 0.14.0 as well, in the Floors job, on every CI
|
|
37
|
+
run.
|
|
38
|
+
|
|
39
|
+
`@softistx/janus` is a **peer**, never a dependency. This package defines no error
|
|
40
|
+
class and throws the peer's own, so `instanceof StoreFailure` holds in your
|
|
41
|
+
code.
|
|
42
|
+
|
|
43
|
+
It needs **Redis 7.0 or later**, or Valkey, and is tested on Redis 7.0, 7.4
|
|
44
|
+
and Valkey 7.2: `PEXPIREAT … GT` and `SET … PXAT` are Redis 7.0's.
|
|
45
|
+
|
|
46
|
+
Like `@softistx/janus`, it expects `"moduleResolution": "bundler"`.
|
|
47
|
+
|
|
48
|
+
`@softistx/redis` itself requires `zod` 4 as a peer. Add it too if your
|
|
49
|
+
application does not already use it: `bun add zod`.
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { janus, scryptHasher } from '@softistx/janus';
|
|
55
|
+
import { createDrizzleStores } from '@softistx/janus-drizzle';
|
|
56
|
+
import { createRedisStores } from '@softistx/janus-redis';
|
|
57
|
+
import { connectRedis } from '@softistx/redis';
|
|
58
|
+
import { drizzle } from 'drizzle-orm/bun-sql';
|
|
59
|
+
import { z } from 'zod';
|
|
60
|
+
|
|
61
|
+
const db = drizzle(process.env.DATABASE_URL ?? 'postgres://localhost:5432/app');
|
|
62
|
+
const redis = await connectRedis(process.env.REDIS_URL ?? 'redis://localhost:6379', {
|
|
63
|
+
enableOfflineQueue: false, // an outage answers 503 at once, not after 31 s
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export const auth = janus({
|
|
67
|
+
user: z.object({ email: z.email(), name: z.string() }),
|
|
68
|
+
password: { login: 'email' },
|
|
69
|
+
hasher: scryptHasher(),
|
|
70
|
+
store: {
|
|
71
|
+
...createDrizzleStores(db), // users, sessions, tokens…
|
|
72
|
+
...createRedisStores(redis), // …then sessions and tokens replaced by Redis
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The order of the spread matters: whatever comes last provides `sessions` and
|
|
78
|
+
`tokens`. `createMongoStores(db)` from `@softistx/janus-mongo` works the same way.
|
|
79
|
+
[Wiring](docs/guide/wiring.md) covers the connection's options.
|
|
80
|
+
|
|
81
|
+
## API
|
|
82
|
+
|
|
83
|
+
| Export | What it is |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `createRedisStores(redis, options?)` | Returns `{ sessions, tokens }`, the two slots of `janus()`'s `store`. `redis` is what `connectRedis` returns. It connects to nothing and creates nothing. The methods a session proved (`amr`, RFC 8176) and a second-factor challenge's first-factor methods are hash fields (space-separated); nothing to migrate. |
|
|
86
|
+
| `RedisStoresOptions` | `{ prefix? }`: what every key starts with, `janus:` by default. |
|
|
87
|
+
| `RedisStores` | The type of what `createRedisStores` returns: `Pick<JanusStores, 'sessions' \| 'tokens'>`. |
|
|
88
|
+
|
|
89
|
+
## What Redis holds
|
|
90
|
+
|
|
91
|
+
Each key starts with the prefix, `janus:` unless you pass another.
|
|
92
|
+
|
|
93
|
+
| Key | Holds | Expires |
|
|
94
|
+
| --- | --- | --- |
|
|
95
|
+
| `session:<id>` | the session, as a hash | at the session's `expiresAt` |
|
|
96
|
+
| `session:token:<sha256>` | the session's id | with its session |
|
|
97
|
+
| `user:<userId>:sessions` | the ids of the user's sessions, as a set | with the user's longest session |
|
|
98
|
+
| `token:<sha256>` | the one-time token, as a hash: `kind`, `userId`, `address`, `codeHash`, `attempts`, the dates | at the token's `expiresAt` |
|
|
99
|
+
| `user:<userId>:tokens` | the hashes of the user's tokens, as a set | with the user's longest token |
|
|
100
|
+
|
|
101
|
+
No secret is stored: keys hold `sha256` of a session's or a token's secret,
|
|
102
|
+
never the secret. Dates are milliseconds since the epoch. A token written by
|
|
103
|
+
an earlier version has no `codeHash` or `attempts` field, and reads as `null`
|
|
104
|
+
and `0`: upgrading needs no migration.
|
|
105
|
+
|
|
106
|
+
**Every method that writes, and every read of more than one key, is one Lua
|
|
107
|
+
script.** Redis runs nothing else while a script runs, so `consumeToken`
|
|
108
|
+
spends a token and returns it as it was in one step. Of twenty concurrent
|
|
109
|
+
redemptions, exactly one sees `spentAt: null`. `countAttempt` is one script
|
|
110
|
+
too, `HINCRBY attempts` on an unspent token of the right kind, so twenty
|
|
111
|
+
concurrent attempts at a code answer twenty distinct counts. `spendUserTokens`
|
|
112
|
+
is one script over the user's set of tokens, so a redemption runs wholly
|
|
113
|
+
before or after it. The scripts are
|
|
114
|
+
sent by SHA (`EVALSHA`), and in full only when Redis has forgotten them after
|
|
115
|
+
a restart, a failover or a `SCRIPT FLUSH`.
|
|
116
|
+
|
|
117
|
+
## Traps
|
|
118
|
+
|
|
119
|
+
- **By default, an outage takes 31 seconds to fail.** Bun's client queues
|
|
120
|
+
commands while it reconnects, so every request waits until it gives up.
|
|
121
|
+
Measured on Redis 7.4 stopped under a connected client:
|
|
122
|
+
`ERR_REDIS_CONNECTION_CLOSED` after 31 s. With `enableOfflineQueue: false`
|
|
123
|
+
the same call fails in 1 ms, and `janusErrors()` answers 503 at once.
|
|
124
|
+
- **`auth.collectExpired()` answers `UNSUPPORTED`** with this adapter. Redis
|
|
125
|
+
expires every session and token key itself, so there is nothing to collect;
|
|
126
|
+
`deleteExpiredSessions` and `deleteExpiredTokens` are deliberately not
|
|
127
|
+
implemented. Do not schedule it.
|
|
128
|
+
- **A lapsed session is gone, not revoked.** Redis drops a key when its expiry
|
|
129
|
+
passes. The core refuses a lapsed session on every read regardless, so
|
|
130
|
+
nothing changes for your users. But a session cannot be read once it has
|
|
131
|
+
lapsed, not even by an admin page.
|
|
132
|
+
- **Eviction is data loss.** A Redis whose `maxmemory-policy` evicts keys can
|
|
133
|
+
drop a standing session, which signs its user out, or a set, which hides
|
|
134
|
+
sessions from "sign out everywhere". `volatile-*` policies are no safer:
|
|
135
|
+
every key this adapter writes has an expiry, so every one is a candidate.
|
|
136
|
+
An evicted or flushed token store also forgets `signIn`'s password
|
|
137
|
+
counts and the mail throttle's, and every login may try its ten passwords
|
|
138
|
+
again, every address ask for five e-mails.
|
|
139
|
+
Run this on a Redis with `noeviction`, or on one of its own.
|
|
140
|
+
- **Redis Cluster is not supported.** A script reads keys it finds on the way,
|
|
141
|
+
a session's token key or a user's sessions, which may live in different
|
|
142
|
+
slots.
|
|
143
|
+
- **`deleteUserSessions` and `revokeUserSessions` walk the user's set** in one
|
|
144
|
+
script: a user with thousands of live sessions holds Redis for that long.
|
|
145
|
+
The sets do not grow with sessions that lapsed: each insert drops the ones
|
|
146
|
+
Redis already expired.
|
|
147
|
+
- **Persistence is yours to configure.** Without RDB or AOF, restarting Redis
|
|
148
|
+
signs everybody out and forgets every pending reset token, which the port
|
|
149
|
+
tolerates, since sessions are derived state. With AOF `everysec`, up to a
|
|
150
|
+
second of revocations can be lost on a crash.
|
|
151
|
+
|
|
152
|
+
## Documentation
|
|
153
|
+
|
|
154
|
+
- [Guides](docs/README.md): wiring the stores beside another adapter, the connection's options, expiry
|
|
155
|
+
- [Troubleshooting](docs/troubleshooting.md): look up the error message you see
|
|
156
|
+
- [Roadmap](docs/roadmap.md): what is next, and what is not planned
|
|
157
|
+
|
|
158
|
+
## Type safety, counted
|
|
159
|
+
|
|
160
|
+
Three plausible mistakes are refused by the compiler, each with a
|
|
161
|
+
`@ts-expect-error` case in `test/types/stores.ts`:
|
|
162
|
+
- a URL instead of a connection;
|
|
163
|
+
- Bun's client instead of the connection that holds it;
|
|
164
|
+
- sessions and tokens alone passed as `janus()`'s whole `store`, with no users.
|
|
165
|
+
|
|
166
|
+
## Licence
|
|
167
|
+
|
|
168
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@softistx/janus-redis` — the Redis adapter for `@softistx/janus`, on
|
|
3
|
+
* `@softistx/redis`.
|
|
4
|
+
*
|
|
5
|
+
* Implements the `sessions` and `tokens` slots of the `@softistx/janus` store
|
|
6
|
+
* port: the two read on every request, and ephemeral by construction, so
|
|
7
|
+
* Redis expires them itself. Users stay in another adapter. It defines **no
|
|
8
|
+
* error class**: every failure is `@softistx/janus`'s own `StoreFailure`.
|
|
9
|
+
*/
|
|
10
|
+
export { createRedisStores, type RedisStores, type RedisStoresOptions, } from './stores';
|
|
11
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACN,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,kBAAkB,GACvB,MAAM,UAAU,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// src/stores.ts
|
|
2
|
+
import { StoreFailure as StoreFailure2 } from "@softistx/janus";
|
|
3
|
+
|
|
4
|
+
// src/replies.ts
|
|
5
|
+
import { StoreFailure } from "@softistx/janus";
|
|
6
|
+
function stamp(at) {
|
|
7
|
+
return String(at.getTime());
|
|
8
|
+
}
|
|
9
|
+
function stampOrEmpty(at) {
|
|
10
|
+
return at === null ? "" : stamp(at);
|
|
11
|
+
}
|
|
12
|
+
function toSession(reply, call) {
|
|
13
|
+
if (reply === null)
|
|
14
|
+
return null;
|
|
15
|
+
if (!Array.isArray(reply) || typeof reply[0] !== "string") {
|
|
16
|
+
throw unreadable(call, "a session");
|
|
17
|
+
}
|
|
18
|
+
const [id, ...rest] = reply;
|
|
19
|
+
const read = readerOf(rest, call);
|
|
20
|
+
return {
|
|
21
|
+
id,
|
|
22
|
+
tokenHash: read.text("tokenHash"),
|
|
23
|
+
userId: read.text("userId"),
|
|
24
|
+
authenticatedAt: read.date("authenticatedAt"),
|
|
25
|
+
expiresAt: read.date("expiresAt"),
|
|
26
|
+
revokedAt: read.dateOrNull("revokedAt"),
|
|
27
|
+
createdAt: read.date("createdAt"),
|
|
28
|
+
...read.optional("device") === "" ? {} : { device: read.optional("device") },
|
|
29
|
+
...read.optional("lastUsedAt") === "" ? {} : { lastUsedAt: read.date("lastUsedAt") },
|
|
30
|
+
...read.optional("amr") === "" ? {} : { amr: read.optional("amr").split(" ") }
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function toSessions(reply, call) {
|
|
34
|
+
if (!Array.isArray(reply))
|
|
35
|
+
throw unreadable(call, "a list of sessions");
|
|
36
|
+
return reply.map((one) => {
|
|
37
|
+
const session = toSession(one, call);
|
|
38
|
+
if (session === null)
|
|
39
|
+
throw unreadable(call, "a session");
|
|
40
|
+
return session;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
function toToken(reply, tokenHash, kind, call) {
|
|
44
|
+
if (reply === null)
|
|
45
|
+
return null;
|
|
46
|
+
const read = readerOf(reply, call);
|
|
47
|
+
if (read.text("kind") !== kind)
|
|
48
|
+
throw unreadable(call, `a ${kind} token`);
|
|
49
|
+
return {
|
|
50
|
+
tokenHash,
|
|
51
|
+
kind,
|
|
52
|
+
userId: read.text("userId"),
|
|
53
|
+
address: read.text("address"),
|
|
54
|
+
codeHash: read.optional("codeHash") || null,
|
|
55
|
+
attempts: read.count("attempts"),
|
|
56
|
+
...read.optional("amr") === "" ? {} : { amr: read.optional("amr").split(" ") },
|
|
57
|
+
expiresAt: read.date("expiresAt"),
|
|
58
|
+
spentAt: read.dateOrNull("spentAt"),
|
|
59
|
+
createdAt: read.date("createdAt")
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function count(reply, call) {
|
|
63
|
+
if (typeof reply !== "number")
|
|
64
|
+
throw unreadable(call, "a count");
|
|
65
|
+
return reply;
|
|
66
|
+
}
|
|
67
|
+
function readerOf(reply, call) {
|
|
68
|
+
if (!Array.isArray(reply))
|
|
69
|
+
throw unreadable(call, "a hash");
|
|
70
|
+
const fields = new Map;
|
|
71
|
+
for (let i = 0;i + 1 < reply.length; i += 2) {
|
|
72
|
+
fields.set(String(reply[i]), String(reply[i + 1]));
|
|
73
|
+
}
|
|
74
|
+
const text = (name) => {
|
|
75
|
+
const value = fields.get(name);
|
|
76
|
+
if (value === undefined)
|
|
77
|
+
throw unreadable(call, `a hash with \`${name}\``);
|
|
78
|
+
return value;
|
|
79
|
+
};
|
|
80
|
+
const date = (name) => {
|
|
81
|
+
const value = text(name);
|
|
82
|
+
const at = new Date(Number(value));
|
|
83
|
+
if (value === "" || Number.isNaN(at.getTime())) {
|
|
84
|
+
throw unreadable(call, `a date in \`${name}\``);
|
|
85
|
+
}
|
|
86
|
+
return at;
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
text,
|
|
90
|
+
date,
|
|
91
|
+
optional: (name) => fields.get(name) ?? "",
|
|
92
|
+
count: (name) => {
|
|
93
|
+
const value = fields.get(name);
|
|
94
|
+
if (value === undefined)
|
|
95
|
+
return 0;
|
|
96
|
+
const counted = /^(0|[1-9]\d*)$/.test(value) ? Number(value) : Number.NaN;
|
|
97
|
+
if (!Number.isSafeInteger(counted)) {
|
|
98
|
+
throw unreadable(call, `a count in \`${name}\``);
|
|
99
|
+
}
|
|
100
|
+
return counted;
|
|
101
|
+
},
|
|
102
|
+
dateOrNull: (name) => text(name) === "" ? null : date(name)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function unreadable({ slot, operation }, what) {
|
|
106
|
+
return new StoreFailure(`${slot}.${operation}: a reply that is not ${what} — a key under the prefix this adapter did not write`, { slot, operation });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/runner.ts
|
|
110
|
+
function runner(evaluate, slot, prefix) {
|
|
111
|
+
return async (operation, script, args, decode) => {
|
|
112
|
+
const call = { slot, operation };
|
|
113
|
+
return decode(await evaluate(call, script, [prefix, ...args]), call);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
var ignore = () => {
|
|
117
|
+
return;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// src/scripts/shared.ts
|
|
121
|
+
var EXTEND_SET = `
|
|
122
|
+
local function extendSet(key, at)
|
|
123
|
+
if redis.call('PTTL', key) < 0 then
|
|
124
|
+
redis.call('PEXPIREAT', key, at)
|
|
125
|
+
else
|
|
126
|
+
redis.call('PEXPIREAT', key, at, 'GT')
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
`;
|
|
130
|
+
var PRUNE = `
|
|
131
|
+
local function prune(set, prefix)
|
|
132
|
+
for _, member in ipairs(redis.call('SMEMBERS', set)) do
|
|
133
|
+
if redis.call('EXISTS', prefix .. member) == 0 then
|
|
134
|
+
redis.call('SREM', set, member)
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
`;
|
|
139
|
+
|
|
140
|
+
// src/scripts/sessions.ts
|
|
141
|
+
var SESSION_FIELDS = `
|
|
142
|
+
local function session(key, id)
|
|
143
|
+
local fields = redis.call('HGETALL', key)
|
|
144
|
+
if #fields == 0 then return false end
|
|
145
|
+
table.insert(fields, 1, id)
|
|
146
|
+
return fields
|
|
147
|
+
end
|
|
148
|
+
`;
|
|
149
|
+
var INSERT_SESSION = `${EXTEND_SET}${PRUNE}
|
|
150
|
+
local p, id, tokenHash, userId = ARGV[1], ARGV[2], ARGV[3], ARGV[4]
|
|
151
|
+
local key = p .. 'session:' .. id
|
|
152
|
+
if redis.call('EXISTS', key) == 1 then return 0 end
|
|
153
|
+
local tokenKey = p .. 'session:token:' .. tokenHash
|
|
154
|
+
local holder = redis.call('GET', tokenKey)
|
|
155
|
+
if holder and holder ~= id then
|
|
156
|
+
return redis.error_reply('JANUS a session token hash is held by another session')
|
|
157
|
+
end
|
|
158
|
+
redis.call('HSET', key,
|
|
159
|
+
'tokenHash', tokenHash, 'userId', userId, 'authenticatedAt', ARGV[5],
|
|
160
|
+
'expiresAt', ARGV[6], 'revokedAt', ARGV[7], 'createdAt', ARGV[8])
|
|
161
|
+
if ARGV[9] ~= '' then redis.call('HSET', key, 'device', ARGV[9]) end
|
|
162
|
+
if ARGV[10] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[10]) end
|
|
163
|
+
if ARGV[11] ~= '' then redis.call('HSET', key, 'amr', ARGV[11]) end
|
|
164
|
+
redis.call('PEXPIREAT', key, ARGV[6])
|
|
165
|
+
redis.call('SET', tokenKey, id, 'PXAT', ARGV[6])
|
|
166
|
+
local sessions = p .. 'user:' .. userId .. ':sessions'
|
|
167
|
+
prune(sessions, p .. 'session:')
|
|
168
|
+
redis.call('SADD', sessions, id)
|
|
169
|
+
extendSet(sessions, ARGV[6])
|
|
170
|
+
return 1
|
|
171
|
+
`;
|
|
172
|
+
var FIND_SESSION = `${SESSION_FIELDS}
|
|
173
|
+
local p = ARGV[1]
|
|
174
|
+
local id = redis.call('GET', p .. 'session:token:' .. ARGV[2])
|
|
175
|
+
if not id then return false end
|
|
176
|
+
return session(p .. 'session:' .. id, id)
|
|
177
|
+
`;
|
|
178
|
+
var EXTEND_SESSION = `${EXTEND_SET}${SESSION_FIELDS}
|
|
179
|
+
local p, id, expiresAt = ARGV[1], ARGV[2], ARGV[3]
|
|
180
|
+
local key = p .. 'session:' .. id
|
|
181
|
+
if redis.call('EXISTS', key) == 0 then return false end
|
|
182
|
+
if redis.call('HGET', key, 'revokedAt') ~= '' then return false end
|
|
183
|
+
redis.call('HSET', key, 'expiresAt', expiresAt)
|
|
184
|
+
if ARGV[4] ~= '' then redis.call('HSET', key, 'lastUsedAt', ARGV[4]) end
|
|
185
|
+
local written = session(key, id)
|
|
186
|
+
local tokenHash = redis.call('HGET', key, 'tokenHash')
|
|
187
|
+
local userId = redis.call('HGET', key, 'userId')
|
|
188
|
+
redis.call('PEXPIREAT', key, expiresAt)
|
|
189
|
+
redis.call('PEXPIREAT', p .. 'session:token:' .. tokenHash, expiresAt)
|
|
190
|
+
extendSet(p .. 'user:' .. userId .. ':sessions', expiresAt)
|
|
191
|
+
return written
|
|
192
|
+
`;
|
|
193
|
+
var REAUTHENTICATE_SESSION = `${SESSION_FIELDS}
|
|
194
|
+
local key = ARGV[1] .. 'session:' .. ARGV[2]
|
|
195
|
+
if redis.call('EXISTS', key) == 0 then return false end
|
|
196
|
+
if redis.call('HGET', key, 'revokedAt') ~= '' then return false end
|
|
197
|
+
redis.call('HSET', key, 'authenticatedAt', ARGV[3])
|
|
198
|
+
if ARGV[4] == '1' then redis.call('HSET', key, 'amr', ARGV[5]) end
|
|
199
|
+
return session(key, ARGV[2])
|
|
200
|
+
`;
|
|
201
|
+
var REVOKE_SESSION = `
|
|
202
|
+
local key = ARGV[1] .. 'session:' .. ARGV[2]
|
|
203
|
+
if redis.call('EXISTS', key) == 0 then return 0 end
|
|
204
|
+
if redis.call('HGET', key, 'revokedAt') == '' then
|
|
205
|
+
redis.call('HSET', key, 'revokedAt', ARGV[3])
|
|
206
|
+
end
|
|
207
|
+
return 1
|
|
208
|
+
`;
|
|
209
|
+
var LIST_USER_SESSIONS = `${SESSION_FIELDS}
|
|
210
|
+
local p, userId, now = ARGV[1], ARGV[2], tonumber(ARGV[3])
|
|
211
|
+
local sessions = p .. 'user:' .. userId .. ':sessions'
|
|
212
|
+
local listed = {}
|
|
213
|
+
for _, id in ipairs(redis.call('SMEMBERS', sessions)) do
|
|
214
|
+
local key = p .. 'session:' .. id
|
|
215
|
+
if redis.call('EXISTS', key) == 0 then
|
|
216
|
+
redis.call('SREM', sessions, id)
|
|
217
|
+
elseif redis.call('HGET', key, 'revokedAt') == ''
|
|
218
|
+
and tonumber(redis.call('HGET', key, 'expiresAt')) > now then
|
|
219
|
+
table.insert(listed, session(key, id))
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
return listed
|
|
223
|
+
`;
|
|
224
|
+
var REVOKE_USER_SESSIONS = `
|
|
225
|
+
local p, userId, at, except, before = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]
|
|
226
|
+
local sessions = p .. 'user:' .. userId .. ':sessions'
|
|
227
|
+
local revoked = 0
|
|
228
|
+
for _, id in ipairs(redis.call('SMEMBERS', sessions)) do
|
|
229
|
+
local key = p .. 'session:' .. id
|
|
230
|
+
if redis.call('EXISTS', key) == 0 then
|
|
231
|
+
redis.call('SREM', sessions, id)
|
|
232
|
+
elseif id ~= except and redis.call('HGET', key, 'revokedAt') == ''
|
|
233
|
+
and (before == '' or tonumber(redis.call('HGET', key, 'createdAt')) < tonumber(before)) then
|
|
234
|
+
redis.call('HSET', key, 'revokedAt', at)
|
|
235
|
+
revoked = revoked + 1
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
return revoked
|
|
239
|
+
`;
|
|
240
|
+
var DELETE_USER_SESSIONS = `
|
|
241
|
+
local p, userId = ARGV[1], ARGV[2]
|
|
242
|
+
local sessions = p .. 'user:' .. userId .. ':sessions'
|
|
243
|
+
local deleted = 0
|
|
244
|
+
for _, id in ipairs(redis.call('SMEMBERS', sessions)) do
|
|
245
|
+
local key = p .. 'session:' .. id
|
|
246
|
+
local tokenHash = redis.call('HGET', key, 'tokenHash')
|
|
247
|
+
if tokenHash then
|
|
248
|
+
local tokenKey = p .. 'session:token:' .. tokenHash
|
|
249
|
+
if redis.call('GET', tokenKey) == id then redis.call('DEL', tokenKey) end
|
|
250
|
+
redis.call('DEL', key)
|
|
251
|
+
deleted = deleted + 1
|
|
252
|
+
end
|
|
253
|
+
end
|
|
254
|
+
redis.call('DEL', sessions)
|
|
255
|
+
return deleted
|
|
256
|
+
`;
|
|
257
|
+
// src/scripts/tokens.ts
|
|
258
|
+
var INSERT_TOKEN = `${EXTEND_SET}${PRUNE}
|
|
259
|
+
local p, tokenHash, userId = ARGV[1], ARGV[2], ARGV[4]
|
|
260
|
+
local key = p .. 'token:' .. tokenHash
|
|
261
|
+
if redis.call('EXISTS', key) == 1 then return 0 end
|
|
262
|
+
redis.call('HSET', key,
|
|
263
|
+
'kind', ARGV[3], 'userId', userId, 'address', ARGV[5],
|
|
264
|
+
'expiresAt', ARGV[6], 'spentAt', ARGV[7], 'createdAt', ARGV[8],
|
|
265
|
+
'codeHash', ARGV[9], 'attempts', ARGV[10], 'amr', ARGV[11])
|
|
266
|
+
redis.call('PEXPIREAT', key, ARGV[6])
|
|
267
|
+
local tokens = p .. 'user:' .. userId .. ':tokens'
|
|
268
|
+
prune(tokens, p .. 'token:')
|
|
269
|
+
redis.call('SADD', tokens, tokenHash)
|
|
270
|
+
extendSet(tokens, ARGV[6])
|
|
271
|
+
return 1
|
|
272
|
+
`;
|
|
273
|
+
var CONSUME_TOKEN = `
|
|
274
|
+
local key = ARGV[1] .. 'token:' .. ARGV[2]
|
|
275
|
+
if redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end
|
|
276
|
+
if ARGV[5] == '1' and redis.call('HGET', key, 'userId') ~= ARGV[6] then return false end
|
|
277
|
+
local before = redis.call('HGETALL', key)
|
|
278
|
+
if redis.call('HGET', key, 'spentAt') == '' then
|
|
279
|
+
redis.call('HSET', key, 'spentAt', ARGV[4])
|
|
280
|
+
end
|
|
281
|
+
return before
|
|
282
|
+
`;
|
|
283
|
+
var COUNT_ATTEMPT = `
|
|
284
|
+
local key = ARGV[1] .. 'token:' .. ARGV[2]
|
|
285
|
+
if redis.call('HGET', key, 'kind') ~= ARGV[3] then return false end
|
|
286
|
+
if redis.call('HGET', key, 'spentAt') == '' then
|
|
287
|
+
redis.call('HINCRBY', key, 'attempts', 1)
|
|
288
|
+
end
|
|
289
|
+
return redis.call('HGETALL', key)
|
|
290
|
+
`;
|
|
291
|
+
var SPEND_USER_TOKENS = `
|
|
292
|
+
local p, userId, kind, at, except = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]
|
|
293
|
+
local spent = 0
|
|
294
|
+
for _, tokenHash in ipairs(redis.call('SMEMBERS', p .. 'user:' .. userId .. ':tokens')) do
|
|
295
|
+
local key = p .. 'token:' .. tokenHash
|
|
296
|
+
if tokenHash ~= except and redis.call('HGET', key, 'kind') == kind and redis.call('HGET', key, 'spentAt') == '' then
|
|
297
|
+
redis.call('HSET', key, 'spentAt', at)
|
|
298
|
+
spent = spent + 1
|
|
299
|
+
end
|
|
300
|
+
end
|
|
301
|
+
return spent
|
|
302
|
+
`;
|
|
303
|
+
var DELETE_USER_TOKENS = `
|
|
304
|
+
local p, userId = ARGV[1], ARGV[2]
|
|
305
|
+
local tokens = p .. 'user:' .. userId .. ':tokens'
|
|
306
|
+
local deleted = 0
|
|
307
|
+
for _, tokenHash in ipairs(redis.call('SMEMBERS', tokens)) do
|
|
308
|
+
deleted = deleted + redis.call('DEL', p .. 'token:' .. tokenHash)
|
|
309
|
+
end
|
|
310
|
+
redis.call('DEL', tokens)
|
|
311
|
+
return deleted
|
|
312
|
+
`;
|
|
313
|
+
// src/session-store.ts
|
|
314
|
+
function sessionStore(evaluate, prefix) {
|
|
315
|
+
const run = runner(evaluate, "sessions", prefix);
|
|
316
|
+
return {
|
|
317
|
+
insertSession: (record) => run("insertSession", INSERT_SESSION, [
|
|
318
|
+
record.id,
|
|
319
|
+
record.tokenHash,
|
|
320
|
+
record.userId,
|
|
321
|
+
stamp(record.authenticatedAt),
|
|
322
|
+
stamp(record.expiresAt),
|
|
323
|
+
stampOrEmpty(record.revokedAt),
|
|
324
|
+
stamp(record.createdAt),
|
|
325
|
+
record.device ?? "",
|
|
326
|
+
record.lastUsedAt === undefined ? "" : stamp(record.lastUsedAt),
|
|
327
|
+
(record.amr ?? []).join(" ")
|
|
328
|
+
], ignore),
|
|
329
|
+
findSessionByTokenHash: (tokenHash) => run("findSessionByTokenHash", FIND_SESSION, [tokenHash], toSession),
|
|
330
|
+
extendSession: (id, expiresAt, lastUsedAt) => run("extendSession", EXTEND_SESSION, [
|
|
331
|
+
id,
|
|
332
|
+
stamp(expiresAt),
|
|
333
|
+
lastUsedAt === undefined ? "" : stamp(lastUsedAt)
|
|
334
|
+
], toSession),
|
|
335
|
+
reauthenticateSession: (id, at, amr) => run("reauthenticateSession", REAUTHENTICATE_SESSION, [id, stamp(at), amr === undefined ? "0" : "1", (amr ?? []).join(" ")], toSession),
|
|
336
|
+
revokeSession: (id, at) => run("revokeSession", REVOKE_SESSION, [id, stamp(at)], (reply, call) => count(reply, call) === 1),
|
|
337
|
+
listUserSessions: (userId, now) => run("listUserSessions", LIST_USER_SESSIONS, [userId, stamp(now)], toSessions),
|
|
338
|
+
revokeUserSessions: (userId, at, except, issuedBefore) => run("revokeUserSessions", REVOKE_USER_SESSIONS, [
|
|
339
|
+
userId,
|
|
340
|
+
stamp(at),
|
|
341
|
+
except ?? "",
|
|
342
|
+
issuedBefore === undefined ? "" : stamp(issuedBefore)
|
|
343
|
+
], count),
|
|
344
|
+
deleteUserSessions: (userId) => run("deleteUserSessions", DELETE_USER_SESSIONS, [userId], count)
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/stores.ts
|
|
349
|
+
function createRedisStores(redis, options = {}) {
|
|
350
|
+
const prefix = options.prefix ?? "janus:";
|
|
351
|
+
const scripts = scriptsOver(redis.client);
|
|
352
|
+
return {
|
|
353
|
+
sessions: sessionStore(scripts, prefix),
|
|
354
|
+
tokens: tokenStore(scripts, prefix)
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
function scriptsOver(client) {
|
|
358
|
+
const shas = new Map;
|
|
359
|
+
const shaOf = (script) => {
|
|
360
|
+
let sha = shas.get(script);
|
|
361
|
+
if (sha === undefined) {
|
|
362
|
+
sha = new Bun.CryptoHasher("sha1").update(script).digest("hex");
|
|
363
|
+
shas.set(script, sha);
|
|
364
|
+
}
|
|
365
|
+
return sha;
|
|
366
|
+
};
|
|
367
|
+
return async ({ slot, operation }, script, args) => {
|
|
368
|
+
try {
|
|
369
|
+
try {
|
|
370
|
+
return await client.send("EVALSHA", [shaOf(script), "0", ...args]);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (!isNoScript(error))
|
|
373
|
+
throw error;
|
|
374
|
+
return await client.send("EVAL", [script, "0", ...args]);
|
|
375
|
+
}
|
|
376
|
+
} catch (error) {
|
|
377
|
+
throw new StoreFailure2(`${slot}.${operation}: the store could not answer`, { slot, operation, cause: error });
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
function isNoScript(error) {
|
|
382
|
+
return error instanceof Error && error.message.startsWith("NOSCRIPT");
|
|
383
|
+
}
|
|
384
|
+
function tokenStore(evaluate, prefix) {
|
|
385
|
+
const run = runner(evaluate, "tokens", prefix);
|
|
386
|
+
return {
|
|
387
|
+
insertToken: (record) => run("insertToken", INSERT_TOKEN, [
|
|
388
|
+
record.tokenHash,
|
|
389
|
+
record.kind,
|
|
390
|
+
record.userId,
|
|
391
|
+
record.address,
|
|
392
|
+
stamp(record.expiresAt),
|
|
393
|
+
stampOrEmpty(record.spentAt),
|
|
394
|
+
stamp(record.createdAt),
|
|
395
|
+
record.codeHash ?? "",
|
|
396
|
+
String(record.attempts),
|
|
397
|
+
(record.amr ?? []).join(" ")
|
|
398
|
+
], ignore),
|
|
399
|
+
consumeToken: (tokenHash, kind, at, userId) => run("consumeToken", CONSUME_TOKEN, [
|
|
400
|
+
tokenHash,
|
|
401
|
+
kind,
|
|
402
|
+
stamp(at),
|
|
403
|
+
userId === undefined ? "0" : "1",
|
|
404
|
+
userId ?? ""
|
|
405
|
+
], (reply, call) => toToken(reply, tokenHash, kind, call)),
|
|
406
|
+
countAttempt: (tokenHash, kind) => run("countAttempt", COUNT_ATTEMPT, [tokenHash, kind], (reply, call) => toToken(reply, tokenHash, kind, call)),
|
|
407
|
+
spendUserTokens: (userId, kind, at, except) => run("spendUserTokens", SPEND_USER_TOKENS, [userId, kind, stamp(at), except ?? ""], count),
|
|
408
|
+
deleteUserTokens: (userId) => run("deleteUserTokens", DELETE_USER_TOKENS, [userId], count)
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
export {
|
|
412
|
+
createRedisStores
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
//# debugId=E1F2DB398AE1D30064756E2164756E21
|
|
416
|
+
//# sourceMappingURL=index.js.map
|