@absolutejs/auth 0.30.0-beta.2 → 0.30.0-beta.4

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.
@@ -0,0 +1,29 @@
1
+ import type { Vault } from '../vault/config';
2
+ export type FederatedTokenSet = {
3
+ accessToken: string;
4
+ expiresAt?: number;
5
+ refreshToken?: string;
6
+ scopes?: string[];
7
+ storedAt: number;
8
+ tokenType?: string;
9
+ };
10
+ export type FederatedTokenStore = {
11
+ delete: (userId: string, provider: string, revoke?: (tokens: FederatedTokenSet) => Promise<void>) => Promise<void>;
12
+ get: (userId: string, provider: string) => Promise<FederatedTokenSet | undefined>;
13
+ list: (userId: string) => Promise<string[]>;
14
+ save: (userId: string, provider: string, tokens: Omit<FederatedTokenSet, 'storedAt'>) => Promise<void>;
15
+ };
16
+ export declare const createFederatedTokenStore: (vault: Vault) => FederatedTokenStore;
17
+ export type FederatedTokenRefresher = (refreshToken: string) => Promise<{
18
+ access_token: string;
19
+ expires_in?: number;
20
+ refresh_token?: string;
21
+ token_type?: string;
22
+ }>;
23
+ export declare const getOrRefreshFederatedTokens: ({ now, provider, refresh, store, userId }: {
24
+ now?: number;
25
+ provider: string;
26
+ refresh?: FederatedTokenRefresher;
27
+ store: FederatedTokenStore;
28
+ userId: string;
29
+ }) => Promise<FederatedTokenSet | undefined>;
@@ -0,0 +1,26 @@
1
+ export type FingerprintSignals = {
2
+ audio?: number;
3
+ canvas?: string;
4
+ deviceMemory?: number;
5
+ fonts?: string[];
6
+ hardwareConcurrency?: number;
7
+ languages?: readonly string[];
8
+ pixelRatio?: number;
9
+ platform?: string;
10
+ screen?: {
11
+ colorDepth: number;
12
+ height: number;
13
+ width: number;
14
+ };
15
+ timezone?: string;
16
+ userAgent?: string;
17
+ webgl?: {
18
+ renderer?: string;
19
+ vendor?: string;
20
+ };
21
+ };
22
+ export type DeviceFingerprint = {
23
+ deviceId: string;
24
+ signals: FingerprintSignals;
25
+ };
26
+ export declare const collectDeviceFingerprint: () => Promise<DeviceFingerprint>;
@@ -0,0 +1,183 @@
1
+ // src/fingerprint-client/index.ts
2
+ var CANVAS_TEXT = "absoluteAuth-fp \uD83D\uDD10";
3
+ var CANVAS_WIDTH = 280;
4
+ var CANVAS_HEIGHT = 60;
5
+ var AUDIO_SAMPLES_COUNT = 4500;
6
+ var AUDIO_OSC_FREQ = 1e4;
7
+ var AUDIO_COMPRESSOR_THRESHOLD = -50;
8
+ var AUDIO_COMPRESSOR_KNEE = 40;
9
+ var AUDIO_COMPRESSOR_RATIO = 12;
10
+ var AUDIO_COMPRESSOR_ATTACK = 0;
11
+ var AUDIO_COMPRESSOR_RELEASE = 0.25;
12
+ var AUDIO_SAMPLE_RATE = 44100;
13
+ var FONT_PROBE = "mmmmmmmmmlli";
14
+ var FONT_PROBE_PX = "72px";
15
+ var FONT_PROBE_OFFSCREEN_PX = -9999;
16
+ var FONT_BASE_FAMILIES = ["monospace", "sans-serif", "serif"];
17
+ var POPULAR_FONTS = [
18
+ "Arial",
19
+ "Arial Black",
20
+ "Comic Sans MS",
21
+ "Courier New",
22
+ "Georgia",
23
+ "Helvetica",
24
+ "Impact",
25
+ "Lucida Console",
26
+ "Times New Roman",
27
+ "Trebuchet MS",
28
+ "Verdana",
29
+ "monospace",
30
+ "sans-serif",
31
+ "serif"
32
+ ];
33
+ var readCanvas = () => {
34
+ try {
35
+ const canvas = document.createElement("canvas");
36
+ canvas.width = CANVAS_WIDTH;
37
+ canvas.height = CANVAS_HEIGHT;
38
+ const context = canvas.getContext("2d");
39
+ if (context === null)
40
+ return;
41
+ context.textBaseline = "top";
42
+ context.font = "14px Arial";
43
+ context.fillStyle = "#f60";
44
+ context.fillRect(125, 1, 62, 20);
45
+ context.fillStyle = "#069";
46
+ context.fillText(CANVAS_TEXT, 2, 15);
47
+ context.fillStyle = "rgba(102, 204, 0, 0.7)";
48
+ context.fillText(CANVAS_TEXT, 4, 17);
49
+ return canvas.toDataURL();
50
+ } catch {
51
+ return;
52
+ }
53
+ };
54
+ var resolveOfflineAudioContextCtor = () => {
55
+ if (typeof OfflineAudioContext !== "undefined")
56
+ return OfflineAudioContext;
57
+ const legacy = globalThis;
58
+ return legacy.webkitOfflineAudioContext;
59
+ };
60
+ var sumAbs = (samples) => {
61
+ let total = 0;
62
+ for (const sample of samples)
63
+ total += Math.abs(sample);
64
+ return total;
65
+ };
66
+ var readAudio = async () => {
67
+ try {
68
+ const ContextCtor = resolveOfflineAudioContextCtor();
69
+ if (ContextCtor === undefined)
70
+ return;
71
+ const context = new ContextCtor(1, AUDIO_SAMPLES_COUNT, AUDIO_SAMPLE_RATE);
72
+ const oscillator = context.createOscillator();
73
+ oscillator.type = "triangle";
74
+ oscillator.frequency.value = AUDIO_OSC_FREQ;
75
+ const compressor = context.createDynamicsCompressor();
76
+ compressor.threshold.value = AUDIO_COMPRESSOR_THRESHOLD;
77
+ compressor.knee.value = AUDIO_COMPRESSOR_KNEE;
78
+ compressor.ratio.value = AUDIO_COMPRESSOR_RATIO;
79
+ compressor.attack.value = AUDIO_COMPRESSOR_ATTACK;
80
+ compressor.release.value = AUDIO_COMPRESSOR_RELEASE;
81
+ oscillator.connect(compressor);
82
+ compressor.connect(context.destination);
83
+ oscillator.start(0);
84
+ const buffer = await context.startRendering();
85
+ return sumAbs(buffer.getChannelData(0));
86
+ } catch {
87
+ return;
88
+ }
89
+ };
90
+ var readWebgl = () => {
91
+ try {
92
+ const canvas = document.createElement("canvas");
93
+ const context = canvas.getContext("webgl") ?? canvas.getContext("experimental-webgl");
94
+ if (context === null || !("getExtension" in context) || !("getParameter" in context)) {
95
+ return;
96
+ }
97
+ const debug = context.getExtension("WEBGL_debug_renderer_info");
98
+ if (debug === null)
99
+ return;
100
+ return {
101
+ renderer: String(context.getParameter(debug.UNMASKED_RENDERER_WEBGL) ?? ""),
102
+ vendor: String(context.getParameter(debug.UNMASKED_VENDOR_WEBGL) ?? "")
103
+ };
104
+ } catch {
105
+ return;
106
+ }
107
+ };
108
+ var measureFamily = (span, family) => {
109
+ span.style.fontFamily = family;
110
+ return span.offsetWidth;
111
+ };
112
+ var detectFontPresent = (span, font, baseline) => FONT_BASE_FAMILIES.some((family) => measureFamily(span, `'${font}', ${family}`) !== baseline[family]);
113
+ var readFonts = () => {
114
+ try {
115
+ const span = document.createElement("span");
116
+ span.style.position = "absolute";
117
+ span.style.left = `${FONT_PROBE_OFFSCREEN_PX}px`;
118
+ span.style.fontSize = FONT_PROBE_PX;
119
+ span.textContent = FONT_PROBE;
120
+ document.body.appendChild(span);
121
+ const baseline = Object.fromEntries(FONT_BASE_FAMILIES.map((family) => [family, measureFamily(span, family)]));
122
+ const present = POPULAR_FONTS.filter((font) => detectFontPresent(span, font, baseline));
123
+ document.body.removeChild(span);
124
+ return present;
125
+ } catch {
126
+ return;
127
+ }
128
+ };
129
+ var readScreen = () => {
130
+ if (typeof screen === "undefined")
131
+ return;
132
+ return {
133
+ colorDepth: screen.colorDepth,
134
+ height: screen.height,
135
+ width: screen.width
136
+ };
137
+ };
138
+ var readTimezone = () => {
139
+ try {
140
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
141
+ } catch {
142
+ return;
143
+ }
144
+ };
145
+ var canonical = (signals) => JSON.stringify(signals, (_key, value) => value === null || typeof value !== "object" || Array.isArray(value) ? value : Object.fromEntries(Object.entries(value).sort((left, right) => left[0].localeCompare(right[0]))));
146
+ var sha256Base64Url = async (input) => {
147
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
148
+ const binary = String.fromCharCode(...new Uint8Array(bytes));
149
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
150
+ };
151
+ var collectDeviceFingerprint = async () => {
152
+ if (typeof window === "undefined" || typeof document === "undefined") {
153
+ throw new Error("collectDeviceFingerprint must run in a browser — server-side use the @absolutejs/auth fingerprintDevice helper instead");
154
+ }
155
+ const [canvas, audio, webgl, fonts] = await Promise.all([
156
+ Promise.resolve(readCanvas()),
157
+ readAudio(),
158
+ Promise.resolve(readWebgl()),
159
+ Promise.resolve(readFonts())
160
+ ]);
161
+ const deviceMemory = "deviceMemory" in navigator ? Reflect.get(navigator, "deviceMemory") : undefined;
162
+ const signals = {
163
+ audio,
164
+ canvas,
165
+ deviceMemory: typeof deviceMemory === "number" ? deviceMemory : undefined,
166
+ fonts,
167
+ hardwareConcurrency: navigator.hardwareConcurrency,
168
+ languages: navigator.languages,
169
+ pixelRatio: window.devicePixelRatio,
170
+ platform: navigator.platform,
171
+ screen: readScreen(),
172
+ timezone: readTimezone(),
173
+ userAgent: navigator.userAgent,
174
+ webgl
175
+ };
176
+ return { deviceId: await sha256Base64Url(canonical(signals)), signals };
177
+ };
178
+ export {
179
+ collectDeviceFingerprint
180
+ };
181
+
182
+ //# debugId=0B8B6C4FD47EEDE764756E2164756E21
183
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/fingerprint-client/index.ts"],
4
+ "sourcesContent": [
5
+ "// Browser-side device fingerprint collector.\n//\n// `collectDeviceFingerprint()` reads ~10 signals from the browser (canvas render,\n// AudioContext, WebGL renderer, font enumeration, screen geometry, navigator.languages,\n// timezone, hardware concurrency, device memory, pixel ratio), normalizes them, and\n// hashes the canonical JSON into a stable base64url SHA-256 `deviceId`.\n//\n// Self-hosted equivalent of FingerprintJS's open-source library. Each individual signal\n// is weak on its own — but their combination is highly stable across sessions for the\n// same browser+device, and varies sharply across different browsers/devices. The same\n// algorithms underpin every commercial fingerprinter; only the proprietary data network\n// (cross-customer reputation) is what SaaS vendors charge for, and that's a non-goal here.\n//\n// Imported via `@absolutejs/auth/fingerprint-client` — server bundle does NOT pull this in\n// (browser globals like `window` would explode there). The client SDK + your sign-in form\n// call this, send the result as `x-client-fingerprint`, and the server (riskConfig / adaptive)\n// uses it as the deviceId instead of the weak UA+IP fallback.\n\nconst CANVAS_TEXT = 'absoluteAuth-fp 🔐';\nconst CANVAS_WIDTH = 280;\nconst CANVAS_HEIGHT = 60;\nconst AUDIO_SAMPLES_COUNT = 4500;\nconst AUDIO_OSC_FREQ = 10_000;\nconst AUDIO_COMPRESSOR_THRESHOLD = -50;\nconst AUDIO_COMPRESSOR_KNEE = 40;\nconst AUDIO_COMPRESSOR_RATIO = 12;\nconst AUDIO_COMPRESSOR_ATTACK = 0;\nconst AUDIO_COMPRESSOR_RELEASE = 0.25;\nconst AUDIO_SAMPLE_RATE = 44_100;\nconst FONT_PROBE = 'mmmmmmmmmlli';\nconst FONT_PROBE_PX = '72px';\nconst FONT_PROBE_OFFSCREEN_PX = -9999;\nconst FONT_BASE_FAMILIES = ['monospace', 'sans-serif', 'serif'] as const;\nconst POPULAR_FONTS = [\n\t'Arial',\n\t'Arial Black',\n\t'Comic Sans MS',\n\t'Courier New',\n\t'Georgia',\n\t'Helvetica',\n\t'Impact',\n\t'Lucida Console',\n\t'Times New Roman',\n\t'Trebuchet MS',\n\t'Verdana',\n\t'monospace',\n\t'sans-serif',\n\t'serif'\n];\n\nexport type FingerprintSignals = {\n\taudio?: number;\n\tcanvas?: string;\n\tdeviceMemory?: number;\n\tfonts?: string[];\n\thardwareConcurrency?: number;\n\tlanguages?: readonly string[];\n\tpixelRatio?: number;\n\tplatform?: string;\n\tscreen?: { colorDepth: number; height: number; width: number };\n\ttimezone?: string;\n\tuserAgent?: string;\n\twebgl?: { renderer?: string; vendor?: string };\n};\n\nexport type DeviceFingerprint = {\n\tdeviceId: string;\n\tsignals: FingerprintSignals;\n};\n\n// Canvas hash: render text + a curve + a couple of rectangles + return the data URL\n// (its pixel content hashes differently across GPUs, drivers, browser versions, font\n// renderers). Wrapped in try/catch because privacy-mode browsers throw on getContext.\nconst readCanvas = () => {\n\ttry {\n\t\tconst canvas = document.createElement('canvas');\n\t\tcanvas.width = CANVAS_WIDTH;\n\t\tcanvas.height = CANVAS_HEIGHT;\n\t\tconst context = canvas.getContext('2d');\n\t\tif (context === null) return undefined;\n\t\tcontext.textBaseline = 'top';\n\t\tcontext.font = '14px Arial';\n\t\tcontext.fillStyle = '#f60';\n\t\tcontext.fillRect(125, 1, 62, 20);\n\t\tcontext.fillStyle = '#069';\n\t\tcontext.fillText(CANVAS_TEXT, 2, 15);\n\t\tcontext.fillStyle = 'rgba(102, 204, 0, 0.7)';\n\t\tcontext.fillText(CANVAS_TEXT, 4, 17);\n\n\t\treturn canvas.toDataURL();\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\ntype LegacyOfflineCtxGlobal = {\n\twebkitOfflineAudioContext?: typeof OfflineAudioContext;\n};\n\nconst resolveOfflineAudioContextCtor = () => {\n\tif (typeof OfflineAudioContext !== 'undefined') return OfflineAudioContext;\n\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- vendor-prefixed legacy API; no TS type ships for it\n\tconst legacy = globalThis as LegacyOfflineCtxGlobal;\n\n\treturn legacy.webkitOfflineAudioContext;\n};\n\nconst sumAbs = (samples: Float32Array) => {\n\tlet total = 0;\n\tfor (const sample of samples) total += Math.abs(sample);\n\n\treturn total;\n};\n\n// Audio hash: instantiate an offline audio context, push a brief oscillator + dynamics\n// compressor through it, read back the rendered buffer's sum. Different audio stacks\n// produce subtly different floating-point outputs.\nconst readAudio = async () => {\n\ttry {\n\t\tconst ContextCtor = resolveOfflineAudioContextCtor();\n\t\tif (ContextCtor === undefined) return undefined;\n\t\tconst context = new ContextCtor(1, AUDIO_SAMPLES_COUNT, AUDIO_SAMPLE_RATE);\n\t\tconst oscillator = context.createOscillator();\n\t\toscillator.type = 'triangle';\n\t\toscillator.frequency.value = AUDIO_OSC_FREQ;\n\t\tconst compressor = context.createDynamicsCompressor();\n\t\tcompressor.threshold.value = AUDIO_COMPRESSOR_THRESHOLD;\n\t\tcompressor.knee.value = AUDIO_COMPRESSOR_KNEE;\n\t\tcompressor.ratio.value = AUDIO_COMPRESSOR_RATIO;\n\t\t// `reduction` is read-only on the modern spec (the constant exists for the\n\t\t// outdated browsers that originally exposed it as a writable AudioParam;\n\t\t// we don't bother setting it — the fingerprint is plenty stable without).\n\t\tcompressor.attack.value = AUDIO_COMPRESSOR_ATTACK;\n\t\tcompressor.release.value = AUDIO_COMPRESSOR_RELEASE;\n\t\toscillator.connect(compressor);\n\t\tcompressor.connect(context.destination);\n\t\toscillator.start(0);\n\t\tconst buffer = await context.startRendering();\n\n\t\treturn sumAbs(buffer.getChannelData(0));\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n// WebGL hash: the renderer + vendor strings include GPU model + driver — highly stable,\n// highly distinctive. Behind the WEBGL_debug_renderer_info extension on most browsers.\nconst readWebgl = () => {\n\ttry {\n\t\tconst canvas = document.createElement('canvas');\n\t\tconst context =\n\t\t\tcanvas.getContext('webgl') ?? canvas.getContext('experimental-webgl');\n\t\tif (\n\t\t\tcontext === null ||\n\t\t\t!('getExtension' in context) ||\n\t\t\t!('getParameter' in context)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst debug = context.getExtension('WEBGL_debug_renderer_info');\n\t\tif (debug === null) return undefined;\n\n\t\treturn {\n\t\t\trenderer: String(\n\t\t\t\tcontext.getParameter(debug.UNMASKED_RENDERER_WEBGL) ?? ''\n\t\t\t),\n\t\t\tvendor: String(context.getParameter(debug.UNMASKED_VENDOR_WEBGL) ?? '')\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n// Width of `probe` rendered in `family` on the given span — used to detect installed\n// fonts (different widths than the fallback ⇒ font is present).\nconst measureFamily = (span: HTMLSpanElement, family: string) => {\n\tspan.style.fontFamily = family;\n\n\treturn span.offsetWidth;\n};\n\nconst detectFontPresent = (\n\tspan: HTMLSpanElement,\n\tfont: string,\n\tbaseline: Record<string, number>\n) =>\n\tFONT_BASE_FAMILIES.some(\n\t\t(family) =>\n\t\t\tmeasureFamily(span, `'${font}', ${family}`) !== baseline[family]\n\t);\n\n// Font enumeration: a font is \"installed\" if the rendered width of a probe string differs\n// from the same string in a known fallback. Compares against monospace + sans-serif +\n// serif and counts a match if any of them produce a different width.\nconst readFonts = () => {\n\ttry {\n\t\tconst span = document.createElement('span');\n\t\tspan.style.position = 'absolute';\n\t\tspan.style.left = `${FONT_PROBE_OFFSCREEN_PX}px`;\n\t\tspan.style.fontSize = FONT_PROBE_PX;\n\t\tspan.textContent = FONT_PROBE;\n\t\tdocument.body.appendChild(span);\n\n\t\tconst baseline: Record<string, number> = Object.fromEntries(\n\t\t\tFONT_BASE_FAMILIES.map((family) => [family, measureFamily(span, family)])\n\t\t);\n\t\tconst present = POPULAR_FONTS.filter((font) =>\n\t\t\tdetectFontPresent(span, font, baseline)\n\t\t);\n\n\t\tdocument.body.removeChild(span);\n\n\t\treturn present;\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\nconst readScreen = () => {\n\tif (typeof screen === 'undefined') return undefined;\n\n\treturn {\n\t\tcolorDepth: screen.colorDepth,\n\t\theight: screen.height,\n\t\twidth: screen.width\n\t};\n};\n\nconst readTimezone = () => {\n\ttry {\n\t\treturn Intl.DateTimeFormat().resolvedOptions().timeZone;\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n// Canonical JSON identical to the server-side `fingerprintDevice` canonicalizer: keys\n// sorted at every depth so identical signals produce identical hashes regardless of\n// insertion order. Inlined here to keep the client bundle free of server-side imports.\nconst canonical = (signals: FingerprintSignals) =>\n\tJSON.stringify(signals, (_key, value) =>\n\t\tvalue === null || typeof value !== 'object' || Array.isArray(value)\n\t\t\t? value\n\t\t\t: Object.fromEntries(\n\t\t\t\t\tObject.entries(value).sort((left, right) =>\n\t\t\t\t\t\tleft[0].localeCompare(right[0])\n\t\t\t\t\t)\n\t\t\t\t)\n\t);\n\nconst sha256Base64Url = async (input: string) => {\n\tconst bytes = await crypto.subtle.digest(\n\t\t'SHA-256',\n\t\tnew TextEncoder().encode(input)\n\t);\n\tconst binary = String.fromCharCode(...new Uint8Array(bytes));\n\n\treturn btoa(binary)\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_')\n\t\t.replace(/=+$/, '');\n};\n\n// Collect every signal we can, hash them, return both so the caller can persist the raw\n// signals (for debugging / drift detection) while sending just the deviceId on the wire.\nexport const collectDeviceFingerprint = async (): Promise<DeviceFingerprint> => {\n\tif (typeof window === 'undefined' || typeof document === 'undefined') {\n\t\tthrow new Error(\n\t\t\t'collectDeviceFingerprint must run in a browser — server-side use the @absolutejs/auth fingerprintDevice helper instead'\n\t\t);\n\t}\n\tconst [canvas, audio, webgl, fonts] = await Promise.all([\n\t\tPromise.resolve(readCanvas()),\n\t\treadAudio(),\n\t\tPromise.resolve(readWebgl()),\n\t\tPromise.resolve(readFonts())\n\t]);\n\n\tconst deviceMemory =\n\t\t'deviceMemory' in navigator\n\t\t\t? Reflect.get(navigator, 'deviceMemory')\n\t\t\t: undefined;\n\tconst signals: FingerprintSignals = {\n\t\taudio,\n\t\tcanvas,\n\t\tdeviceMemory: typeof deviceMemory === 'number' ? deviceMemory : undefined,\n\t\tfonts,\n\t\thardwareConcurrency: navigator.hardwareConcurrency,\n\t\tlanguages: navigator.languages,\n\t\tpixelRatio: window.devicePixelRatio,\n\t\tplatform: navigator.platform,\n\t\tscreen: readScreen(),\n\t\ttimezone: readTimezone(),\n\t\tuserAgent: navigator.userAgent,\n\t\twebgl\n\t};\n\n\treturn { deviceId: await sha256Base64Url(canonical(signals)), signals };\n};\n"
6
+ ],
7
+ "mappings": ";AAkBA,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAC5B,IAAM,iBAAiB;AACvB,IAAM,6BAA6B;AACnC,IAAM,wBAAwB;AAC9B,IAAM,yBAAyB;AAC/B,IAAM,0BAA0B;AAChC,IAAM,2BAA2B;AACjC,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,gBAAgB;AACtB,IAAM,0BAA0B;AAChC,IAAM,qBAAqB,CAAC,aAAa,cAAc,OAAO;AAC9D,IAAM,gBAAgB;AAAA,EACrB;AAAA,EACA;AAAA,E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,EAChB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,EAAE;AAAA;AAKb,IAAM,2BAA2B,YAAwC;AAAA,EAC/E,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;AAAA,IACrE,MAAM,IAAI,MACT,wHACD;AAAA,EACD;AAAA,EACA,OAAO,QAAQ,OAAO,OAAO,SAAS,MAAM,QAAQ,IAAI;AAAA,IACvD,QAAQ,QAAQ,WAAW,CAAC;AAAA,IAC5B,UAAU;AAAA,IACV,QAAQ,QAAQ,UAAU,CAAC;AAAA,IAC3B,QAAQ,QAAQ,UAAU,CAAC;AAAA,EAC5B,CAAC;AAAA,EAED,MAAM,eACL,kBAAkB,YACf,QAAQ,IAAI,WAAW,cAAc,IACrC;AAAA,EACJ,MAAM,UAA8B;AAAA,IACnC;AAAA,IACA;AAAA,IACA,cAAc,OAAO,iBAAiB,WAAW,eAAe;AAAA,IAChE;AAAA,IACA,qBAAqB,UAAU;AAAA,IAC/B,WAAW,UAAU;AAAA,IACrB,YAAY,OAAO;AAAA,IACnB,UAAU,UAAU;AAAA,IACpB,QAAQ,WAAW;AAAA,IACnB,UAAU,aAAa;AAAA,IACvB,WAAW,UAAU;AAAA,IACrB;AAAA,EACD;AAAA,EAEA,OAAO,EAAE,UAAU,MAAM,gBAAgB,UAAU,OAAO,CAAC,GAAG,QAAQ;AAAA;",
8
+ "debugId": "0B8B6C4FD47EEDE764756E2164756E21",
9
+ "names": []
10
+ }
package/dist/index.d.ts CHANGED
@@ -15017,6 +15017,8 @@ export * from './vault/config';
15017
15017
  export * from './vault/types';
15018
15018
  export { createInMemoryVaultStore } from './vault/inMemoryVaultStore';
15019
15019
  export { createNeonVaultStore, createPostgresVaultStore, vaultEntriesTable } from './vault/postgresVaultStore';
15020
+ export { createFederatedTokenStore, getOrRefreshFederatedTokens } from './federation/tokenStore';
15021
+ export type { FederatedTokenRefresher, FederatedTokenSet, FederatedTokenStore } from './federation/tokenStore';
15020
15022
  export type { AuthSessionStore } from './session/types';
15021
15023
  export { isAuthIntent, isUserSessionId, isValidUser } from './typeGuards';
15022
15024
  export { AuthIdentityConflictError } from './errors';
package/dist/index.js CHANGED
@@ -19048,6 +19048,69 @@ var createPostgresVaultStore = (db) => ({
19048
19048
  });
19049
19049
  }
19050
19050
  });
19051
+ // src/federation/tokenStore.ts
19052
+ var VAULT_NAME_PREFIX = "federated:";
19053
+ var REFRESH_EARLY_WINDOW_MS = 30000;
19054
+ var nameFor = (provider) => `${VAULT_NAME_PREFIX}${provider}`;
19055
+ var parse = (raw) => {
19056
+ if (raw === undefined)
19057
+ return;
19058
+ try {
19059
+ const parsed = JSON.parse(raw);
19060
+ if (typeof parsed !== "object" || parsed === null)
19061
+ return;
19062
+ return parsed;
19063
+ } catch {
19064
+ return;
19065
+ }
19066
+ };
19067
+ var createFederatedTokenStore = (vault) => ({
19068
+ delete: async (userId, provider, revoke2) => {
19069
+ const current = revoke2 === undefined ? undefined : parse(await vault.get(userId, nameFor(provider)));
19070
+ if (current !== undefined && revoke2 !== undefined) {
19071
+ await revoke2(current).catch(() => {
19072
+ return;
19073
+ });
19074
+ }
19075
+ await vault.delete(userId, nameFor(provider));
19076
+ },
19077
+ get: async (userId, provider) => parse(await vault.get(userId, nameFor(provider))),
19078
+ list: async (userId) => (await vault.list(userId)).filter((name) => name.startsWith(VAULT_NAME_PREFIX)).map((name) => name.slice(VAULT_NAME_PREFIX.length)),
19079
+ save: async (userId, provider, tokens) => {
19080
+ const record = { ...tokens, storedAt: Date.now() };
19081
+ await vault.put(userId, nameFor(provider), JSON.stringify(record));
19082
+ }
19083
+ });
19084
+ var isExpired = (tokens, now) => {
19085
+ if (tokens.expiresAt === undefined)
19086
+ return false;
19087
+ return tokens.expiresAt - REFRESH_EARLY_WINDOW_MS <= now;
19088
+ };
19089
+ var getOrRefreshFederatedTokens = async ({
19090
+ now = Date.now(),
19091
+ provider,
19092
+ refresh: refresh2,
19093
+ store,
19094
+ userId
19095
+ }) => {
19096
+ const current = await store.get(userId, provider);
19097
+ if (current === undefined)
19098
+ return;
19099
+ if (!isExpired(current, now) || current.refreshToken === undefined || refresh2 === undefined) {
19100
+ return current;
19101
+ }
19102
+ const refreshed = await refresh2(current.refreshToken);
19103
+ const expiresIn = typeof refreshed.expires_in === "number" ? refreshed.expires_in : undefined;
19104
+ const updated = {
19105
+ accessToken: refreshed.access_token,
19106
+ expiresAt: expiresIn === undefined ? undefined : now + expiresIn * 1000,
19107
+ refreshToken: refreshed.refresh_token ?? current.refreshToken,
19108
+ scopes: current.scopes,
19109
+ tokenType: refreshed.token_type ?? current.tokenType
19110
+ };
19111
+ await store.save(userId, provider, updated);
19112
+ return { ...updated, storedAt: now };
19113
+ };
19051
19114
  // src/session/inMemoryStore.ts
19052
19115
  var cloneSessionData = (value) => ({
19053
19116
  ...value
@@ -19207,7 +19270,7 @@ var createNeonAuthSessionStore = (databaseUrl) => {
19207
19270
  // src/session/redisStore.ts
19208
19271
  var SESSION_SEGMENT = "sess:";
19209
19272
  var UNREGISTERED_SEGMENT = "unreg:";
19210
- var parse = (raw) => {
19273
+ var parse2 = (raw) => {
19211
19274
  if (raw === null)
19212
19275
  return;
19213
19276
  try {
@@ -19226,8 +19289,8 @@ var createRedisAuthSessionStore = (redis, keyPrefix = "auth:session:") => {
19226
19289
  return keys.map((key) => key.slice(offset)).filter(isUserSessionId);
19227
19290
  };
19228
19291
  return {
19229
- getSession: async (id) => parse(await redis.get(sessionKey(id))),
19230
- getUnregisteredSession: async (id) => parse(await redis.get(unregisteredKey(id))),
19292
+ getSession: async (id) => parse2(await redis.get(sessionKey(id))),
19293
+ getUnregisteredSession: async (id) => parse2(await redis.get(unregisteredKey(id))),
19231
19294
  listSessionIds: () => listIds(SESSION_SEGMENT),
19232
19295
  listUnregisteredSessionIds: () => listIds(UNREGISTERED_SEGMENT),
19233
19296
  removeSession: async (id) => {
@@ -20067,8 +20130,8 @@ var validateSession = ({
20067
20130
  if (!userSession) {
20068
20131
  return;
20069
20132
  }
20070
- const isExpired = userSession.expiresAt < Date.now();
20071
- if (isExpired) {
20133
+ const isExpired2 = userSession.expiresAt < Date.now();
20134
+ if (isExpired2) {
20072
20135
  delete session[userSessionId];
20073
20136
  user_session_id.remove();
20074
20137
  return;
@@ -23239,6 +23302,7 @@ export {
23239
23302
  getUserSessionId,
23240
23303
  getStatus,
23241
23304
  getRegisteredClient,
23305
+ getOrRefreshFederatedTokens,
23242
23306
  generateTotpSecret,
23243
23307
  generateTotp,
23244
23308
  generateSigningKey,
@@ -23386,6 +23450,7 @@ export {
23386
23450
  createInMemoryApiClientStore,
23387
23451
  createInMemoryAccessTokenStore,
23388
23452
  createFgaEngine,
23453
+ createFederatedTokenStore,
23389
23454
  createAuthHtmxRoutes,
23390
23455
  createAuditRedactor,
23391
23456
  createAuditEmitter,
@@ -23450,5 +23515,5 @@ export {
23450
23515
  AuthIdentityConflictError
23451
23516
  };
23452
23517
 
23453
- //# debugId=658AE7172110F24564756E2164756E21
23518
+ //# debugId=2099933871462CB064756E2164756E21
23454
23519
  //# sourceMappingURL=index.js.map