@powersync/service-core 1.13.3 → 1.14.0
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/CHANGELOG.md +43 -0
- package/dist/api/diagnostics.js +31 -1
- package/dist/api/diagnostics.js.map +1 -1
- package/dist/auth/CachedKeyCollector.js +26 -2
- package/dist/auth/CachedKeyCollector.js.map +1 -1
- package/dist/auth/KeySpec.d.ts +1 -0
- package/dist/auth/KeySpec.js +12 -0
- package/dist/auth/KeySpec.js.map +1 -1
- package/dist/auth/KeyStore.d.ts +19 -0
- package/dist/auth/KeyStore.js +17 -5
- package/dist/auth/KeyStore.js.map +1 -1
- package/dist/auth/RemoteJWKSCollector.d.ts +3 -0
- package/dist/auth/RemoteJWKSCollector.js +9 -3
- package/dist/auth/RemoteJWKSCollector.js.map +1 -1
- package/dist/auth/StaticSupabaseKeyCollector.d.ts +2 -1
- package/dist/auth/StaticSupabaseKeyCollector.js +1 -1
- package/dist/auth/StaticSupabaseKeyCollector.js.map +1 -1
- package/dist/auth/utils.d.ts +19 -0
- package/dist/auth/utils.js +106 -3
- package/dist/auth/utils.js.map +1 -1
- package/dist/entry/commands/compact-action.js +10 -1
- package/dist/entry/commands/compact-action.js.map +1 -1
- package/dist/metrics/open-telemetry/util.js +3 -1
- package/dist/metrics/open-telemetry/util.js.map +1 -1
- package/dist/replication/AbstractReplicator.js +2 -2
- package/dist/replication/AbstractReplicator.js.map +1 -1
- package/dist/routes/auth.d.ts +1 -21
- package/dist/routes/auth.js +1 -97
- package/dist/routes/auth.js.map +1 -1
- package/dist/routes/configure-fastify.js +2 -1
- package/dist/routes/configure-fastify.js.map +1 -1
- package/dist/routes/endpoints/socket-route.js +1 -8
- package/dist/routes/endpoints/socket-route.js.map +1 -1
- package/dist/routes/endpoints/sync-stream.js +17 -4
- package/dist/routes/endpoints/sync-stream.js.map +1 -1
- package/dist/routes/route-register.d.ts +4 -0
- package/dist/routes/route-register.js +29 -15
- package/dist/routes/route-register.js.map +1 -1
- package/dist/storage/BucketStorageBatch.d.ts +12 -2
- package/dist/storage/BucketStorageBatch.js.map +1 -1
- package/dist/storage/SourceEntity.d.ts +5 -4
- package/dist/storage/SourceTable.d.ts +22 -20
- package/dist/storage/SourceTable.js +34 -30
- package/dist/storage/SourceTable.js.map +1 -1
- package/dist/storage/SyncRulesBucketStorage.d.ts +11 -5
- package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
- package/dist/sync/BucketChecksumState.d.ts +1 -1
- package/dist/sync/BucketChecksumState.js +1 -1
- package/dist/sync/BucketChecksumState.js.map +1 -1
- package/dist/sync/util.d.ts +3 -1
- package/dist/sync/util.js +29 -1
- package/dist/sync/util.js.map +1 -1
- package/dist/util/config/compound-config-collector.js +22 -12
- package/dist/util/config/compound-config-collector.js.map +1 -1
- package/dist/util/config/types.d.ts +0 -12
- package/dist/util/lsn.d.ts +4 -0
- package/dist/util/lsn.js +11 -0
- package/dist/util/lsn.js.map +1 -0
- package/dist/util/util-index.d.ts +2 -0
- package/dist/util/util-index.js +2 -0
- package/dist/util/util-index.js.map +1 -1
- package/dist/util/version.d.ts +1 -0
- package/dist/util/version.js +3 -0
- package/dist/util/version.js.map +1 -0
- package/package.json +7 -5
- package/src/api/diagnostics.ts +33 -1
- package/src/auth/CachedKeyCollector.ts +25 -3
- package/src/auth/KeySpec.ts +14 -0
- package/src/auth/KeyStore.ts +29 -5
- package/src/auth/RemoteJWKSCollector.ts +11 -4
- package/src/auth/StaticSupabaseKeyCollector.ts +1 -1
- package/src/auth/utils.ts +123 -3
- package/src/entry/commands/compact-action.ts +9 -1
- package/src/metrics/open-telemetry/util.ts +4 -1
- package/src/replication/AbstractReplicator.ts +2 -2
- package/src/routes/auth.ts +1 -124
- package/src/routes/configure-fastify.ts +3 -1
- package/src/routes/endpoints/socket-route.ts +1 -7
- package/src/routes/endpoints/sync-stream.ts +29 -21
- package/src/routes/route-register.ts +41 -15
- package/src/storage/BucketStorageBatch.ts +13 -2
- package/src/storage/SourceEntity.ts +5 -5
- package/src/storage/SourceTable.ts +48 -34
- package/src/storage/SyncRulesBucketStorage.ts +14 -7
- package/src/sync/BucketChecksumState.ts +2 -2
- package/src/sync/util.ts +31 -2
- package/src/util/config/compound-config-collector.ts +23 -15
- package/src/util/config/types.ts +0 -11
- package/src/util/lsn.ts +8 -0
- package/src/util/util-index.ts +2 -0
- package/src/util/version.ts +3 -0
- package/test/src/auth.test.ts +323 -1
- package/test/src/sync/BucketChecksumState.test.ts +36 -35
- package/tsconfig.tsbuildinfo +1 -1
package/src/api/diagnostics.ts
CHANGED
|
@@ -105,7 +105,7 @@ export async function getSyncRulesStatus(
|
|
|
105
105
|
const source: SourceTableInterface = {
|
|
106
106
|
connectionTag: tag,
|
|
107
107
|
schema: pattern.schema,
|
|
108
|
-
|
|
108
|
+
name: pattern.tablePattern
|
|
109
109
|
};
|
|
110
110
|
const syncData = rules.tableSyncsData(source);
|
|
111
111
|
const syncParameters = rules.tableSyncsParameters(source);
|
|
@@ -134,6 +134,38 @@ export async function getSyncRulesStatus(
|
|
|
134
134
|
})
|
|
135
135
|
);
|
|
136
136
|
|
|
137
|
+
if (live_status && status?.active && sourceConfig.type != 'mysql') {
|
|
138
|
+
// Check replication lag for active sync rules.
|
|
139
|
+
// Right now we exclude mysql, since it we don't have consistent keepalives for it.
|
|
140
|
+
if (sync_rules.last_checkpoint_ts == null && sync_rules.last_keepalive_ts == null) {
|
|
141
|
+
errors.push({
|
|
142
|
+
level: 'warning',
|
|
143
|
+
message: 'No checkpoint found, cannot calculate replication lag'
|
|
144
|
+
});
|
|
145
|
+
} else {
|
|
146
|
+
const lastTime = Math.max(
|
|
147
|
+
sync_rules.last_checkpoint_ts?.getTime() ?? 0,
|
|
148
|
+
sync_rules.last_keepalive_ts?.getTime() ?? 0
|
|
149
|
+
);
|
|
150
|
+
const lagSeconds = Math.round((Date.now() - lastTime) / 1000);
|
|
151
|
+
// On idle instances, keepalive messages are only persisted every 60 seconds.
|
|
152
|
+
// So we use 5 minutes as a threshold for warnings, and 15 minutes for critical.
|
|
153
|
+
// The replication lag metric should give a more granular value, but that is not available directly
|
|
154
|
+
// in the API containers used for diagnostics, and this should give a good enough indication.
|
|
155
|
+
if (lagSeconds > 15 * 60) {
|
|
156
|
+
errors.push({
|
|
157
|
+
level: 'fatal',
|
|
158
|
+
message: `No replicated commit in more than ${lagSeconds}s`
|
|
159
|
+
});
|
|
160
|
+
} else if (lagSeconds > 5 * 60) {
|
|
161
|
+
errors.push({
|
|
162
|
+
level: 'warning',
|
|
163
|
+
message: `No replicated commit in more than ${lagSeconds}s`
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
137
169
|
return {
|
|
138
170
|
content: include_content ? sync_rules.sync_rules_content : undefined,
|
|
139
171
|
connections: [
|
|
@@ -3,7 +3,7 @@ import timers from 'timers/promises';
|
|
|
3
3
|
import { KeySpec } from './KeySpec.js';
|
|
4
4
|
import { LeakyBucket } from './LeakyBucket.js';
|
|
5
5
|
import { KeyCollector, KeyResult } from './KeyCollector.js';
|
|
6
|
-
import { AuthorizationError } from '@powersync/lib-services-framework';
|
|
6
|
+
import { AuthorizationError, ErrorCode, logger } from '@powersync/lib-services-framework';
|
|
7
7
|
import { mapAuthConfigError } from './utils.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -70,8 +70,21 @@ export class CachedKeyCollector implements KeyCollector {
|
|
|
70
70
|
// e.g. in the case of waiting for error retries.
|
|
71
71
|
// In the case of very slow requests, we don't wait for it to complete, but the
|
|
72
72
|
// request can still complete in the background.
|
|
73
|
-
const
|
|
74
|
-
|
|
73
|
+
const WAIT_TIMEOUT_SECONDS = 3;
|
|
74
|
+
const timeout = timers.setTimeout(WAIT_TIMEOUT_SECONDS * 1000).then(() => {
|
|
75
|
+
throw new AuthorizationError(ErrorCode.PSYNC_S2204, `JWKS request failed`, {
|
|
76
|
+
cause: { message: `Key request timed out in ${WAIT_TIMEOUT_SECONDS}s`, name: 'AbortError' }
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
try {
|
|
80
|
+
await Promise.race([this.refreshPromise, timeout]);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if (e instanceof AuthorizationError) {
|
|
83
|
+
return { keys: this.currentKeys, errors: [...this.currentErrors, e] };
|
|
84
|
+
} else {
|
|
85
|
+
throw e;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
75
88
|
}
|
|
76
89
|
|
|
77
90
|
return { keys: this.currentKeys, errors: this.currentErrors };
|
|
@@ -102,7 +115,16 @@ export class CachedKeyCollector implements KeyCollector {
|
|
|
102
115
|
this.currentErrors = errors;
|
|
103
116
|
this.keyTimestamp = Date.now();
|
|
104
117
|
this.error = false;
|
|
118
|
+
|
|
119
|
+
// Due to caching and background refresh behavior, errors are not always propagated to the request handler,
|
|
120
|
+
// so we log them here.
|
|
121
|
+
for (let error of errors) {
|
|
122
|
+
logger.error(`Soft key refresh error`, error);
|
|
123
|
+
}
|
|
105
124
|
} catch (e) {
|
|
125
|
+
// Due to caching and background refresh behavior, errors are not always propagated to the request handler,
|
|
126
|
+
// so we log them here.
|
|
127
|
+
logger.error(`Hard key refresh error`, e);
|
|
106
128
|
this.error = true;
|
|
107
129
|
// No result - keep previous keys
|
|
108
130
|
this.currentErrors = [mapAuthConfigError(e)];
|
package/src/auth/KeySpec.ts
CHANGED
|
@@ -40,6 +40,20 @@ export class KeySpec {
|
|
|
40
40
|
return this.source.kid;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
get description(): string {
|
|
44
|
+
let details: string[] = [];
|
|
45
|
+
details.push(`kid: ${this.kid ?? '*'}`);
|
|
46
|
+
details.push(`kty: ${this.source.kty}`);
|
|
47
|
+
if (this.source.alg != null) {
|
|
48
|
+
details.push(`alg: ${this.source.alg}`);
|
|
49
|
+
}
|
|
50
|
+
if (this.options.requiresAudience != null) {
|
|
51
|
+
details.push(`aud: ${this.options.requiresAudience.join(', ')}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return `<${details.filter((x) => x != null).join(', ')}>`;
|
|
55
|
+
}
|
|
56
|
+
|
|
43
57
|
matchesAlgorithm(jwtAlg: string): boolean {
|
|
44
58
|
if (this.source.alg) {
|
|
45
59
|
return jwtAlg === this.source.alg;
|
package/src/auth/KeyStore.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AuthorizationError, ErrorCode, logger } from '@powersync/lib-services-framework';
|
|
2
2
|
import * as jose from 'jose';
|
|
3
3
|
import secs from '../util/secs.js';
|
|
4
4
|
import { JwtPayload } from './JwtPayload.js';
|
|
5
5
|
import { KeyCollector } from './KeyCollector.js';
|
|
6
6
|
import { KeyOptions, KeySpec, SUPPORTED_ALGORITHMS } from './KeySpec.js';
|
|
7
|
-
import { mapAuthError } from './utils.js';
|
|
7
|
+
import { debugKeyNotFound, mapAuthError, SupabaseAuthDetails, tokenDebugDetails } from './utils.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* KeyStore to get keys and verify tokens.
|
|
@@ -39,6 +39,29 @@ export class KeyStore<Collector extends KeyCollector = KeyCollector> {
|
|
|
39
39
|
*/
|
|
40
40
|
collector: Collector;
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* For debug purposes only.
|
|
44
|
+
*
|
|
45
|
+
* This is very Supabase-specific, but we need the info on this level. For example,
|
|
46
|
+
* we want to detect cases where a Supabase token is used, but Supabase auth is not enabled
|
|
47
|
+
* (no Supabase collector configured).
|
|
48
|
+
*/
|
|
49
|
+
supabaseAuthDebug: {
|
|
50
|
+
/**
|
|
51
|
+
* This can be populated without jwksEnabled, but not the other way around.
|
|
52
|
+
*/
|
|
53
|
+
jwksDetails: SupabaseAuthDetails | null;
|
|
54
|
+
jwksEnabled: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* This can be enabled without jwksDetails populated.
|
|
57
|
+
*/
|
|
58
|
+
sharedSecretEnabled: boolean;
|
|
59
|
+
} = {
|
|
60
|
+
jwksDetails: null,
|
|
61
|
+
jwksEnabled: false,
|
|
62
|
+
sharedSecretEnabled: false
|
|
63
|
+
};
|
|
64
|
+
|
|
42
65
|
constructor(collector: Collector) {
|
|
43
66
|
this.collector = collector;
|
|
44
67
|
}
|
|
@@ -131,7 +154,7 @@ export class KeyStore<Collector extends KeyCollector = KeyCollector> {
|
|
|
131
154
|
if (!key.matchesAlgorithm(header.alg)) {
|
|
132
155
|
throw new AuthorizationError(ErrorCode.PSYNC_S2101, `Unexpected token algorithm ${header.alg}`, {
|
|
133
156
|
configurationDetails: `Key kid: ${key.source.kid}, alg: ${key.source.alg}, kty: ${key.source.kty}`
|
|
134
|
-
//
|
|
157
|
+
// tokenDetails automatically populated higher up the stack
|
|
135
158
|
});
|
|
136
159
|
}
|
|
137
160
|
return key;
|
|
@@ -165,12 +188,13 @@ export class KeyStore<Collector extends KeyCollector = KeyCollector> {
|
|
|
165
188
|
logger.error(`Failed to refresh keys`, e);
|
|
166
189
|
});
|
|
167
190
|
|
|
191
|
+
const details = debugKeyNotFound(this, keys, token);
|
|
192
|
+
|
|
168
193
|
throw new AuthorizationError(
|
|
169
194
|
ErrorCode.PSYNC_S2101,
|
|
170
195
|
'Could not find an appropriate key in the keystore. The key is missing or no key matched the token KID',
|
|
171
196
|
{
|
|
172
|
-
|
|
173
|
-
// tokenDetails automatically populated later
|
|
197
|
+
...details
|
|
174
198
|
}
|
|
175
199
|
);
|
|
176
200
|
}
|
|
@@ -12,10 +12,11 @@ import {
|
|
|
12
12
|
ServiceError
|
|
13
13
|
} from '@powersync/lib-services-framework';
|
|
14
14
|
import { KeyCollector, KeyResult } from './KeyCollector.js';
|
|
15
|
-
import { KeySpec } from './KeySpec.js';
|
|
15
|
+
import { KeyOptions, KeySpec } from './KeySpec.js';
|
|
16
16
|
|
|
17
17
|
export type RemoteJWKSCollectorOptions = {
|
|
18
18
|
lookupOptions?: LookupOptions;
|
|
19
|
+
keyOptions?: KeyOptions;
|
|
19
20
|
};
|
|
20
21
|
|
|
21
22
|
/**
|
|
@@ -24,6 +25,7 @@ export type RemoteJWKSCollectorOptions = {
|
|
|
24
25
|
export class RemoteJWKSCollector implements KeyCollector {
|
|
25
26
|
private url: URL;
|
|
26
27
|
private agent: http.Agent;
|
|
28
|
+
private keyOptions: KeyOptions;
|
|
27
29
|
|
|
28
30
|
constructor(
|
|
29
31
|
url: string,
|
|
@@ -34,6 +36,7 @@ export class RemoteJWKSCollector implements KeyCollector {
|
|
|
34
36
|
} catch (e: any) {
|
|
35
37
|
throw new ServiceError(ErrorCode.PSYNC_S3102, `Invalid jwks_uri: ${JSON.stringify(url)} Details: ${e.message}`);
|
|
36
38
|
}
|
|
39
|
+
this.keyOptions = options?.keyOptions ?? {};
|
|
37
40
|
|
|
38
41
|
// We do support http here for self-hosting use cases.
|
|
39
42
|
// Management service restricts this to https for hosted versions.
|
|
@@ -49,9 +52,10 @@ export class RemoteJWKSCollector implements KeyCollector {
|
|
|
49
52
|
|
|
50
53
|
private async getJwksData(): Promise<any> {
|
|
51
54
|
const abortController = new AbortController();
|
|
55
|
+
const REQUEST_TIMEOUT_SECONDS = 30;
|
|
52
56
|
const timeout = setTimeout(() => {
|
|
53
57
|
abortController.abort();
|
|
54
|
-
},
|
|
58
|
+
}, REQUEST_TIMEOUT_SECONDS * 1000);
|
|
55
59
|
|
|
56
60
|
try {
|
|
57
61
|
const res = await fetch(this.url, {
|
|
@@ -71,11 +75,14 @@ export class RemoteJWKSCollector implements KeyCollector {
|
|
|
71
75
|
|
|
72
76
|
return (await res.json()) as any;
|
|
73
77
|
} catch (e) {
|
|
78
|
+
if (e instanceof Error && e.name === 'AbortError') {
|
|
79
|
+
e = { message: `Request timed out in ${REQUEST_TIMEOUT_SECONDS}s`, name: 'AbortError' };
|
|
80
|
+
}
|
|
74
81
|
throw new AuthorizationError(ErrorCode.PSYNC_S2204, `JWKS request failed`, {
|
|
75
82
|
configurationDetails: `JWKS URL: ${this.url}`,
|
|
76
83
|
// This covers most cases of FetchError
|
|
77
84
|
// `cause: e` could lose the error message
|
|
78
|
-
cause: { message: e.message, code: e.code }
|
|
85
|
+
cause: { message: e.message, code: e.code, name: e.name }
|
|
79
86
|
});
|
|
80
87
|
} finally {
|
|
81
88
|
clearTimeout(timeout);
|
|
@@ -119,7 +126,7 @@ export class RemoteJWKSCollector implements KeyCollector {
|
|
|
119
126
|
}
|
|
120
127
|
}
|
|
121
128
|
|
|
122
|
-
const key = await KeySpec.importKey(keyData);
|
|
129
|
+
const key = await KeySpec.importKey(keyData, this.keyOptions);
|
|
123
130
|
keys.push(key);
|
|
124
131
|
}
|
|
125
132
|
|
|
@@ -2,7 +2,7 @@ import * as jose from 'jose';
|
|
|
2
2
|
import { KeySpec, KeyOptions } from './KeySpec.js';
|
|
3
3
|
import { KeyCollector, KeyResult } from './KeyCollector.js';
|
|
4
4
|
|
|
5
|
-
const SUPABASE_KEY_OPTIONS: KeyOptions = {
|
|
5
|
+
export const SUPABASE_KEY_OPTIONS: KeyOptions = {
|
|
6
6
|
requiresAudience: ['authenticated'],
|
|
7
7
|
maxLifetimeSeconds: 86400 * 7 + 1200 // 1 week + 20 minutes margin
|
|
8
8
|
};
|
package/src/auth/utils.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { AuthorizationError, ErrorCode } from '@powersync/lib-services-framework';
|
|
2
2
|
import * as jose from 'jose';
|
|
3
|
+
import * as urijs from 'uri-js';
|
|
4
|
+
import * as uuid from 'uuid';
|
|
5
|
+
import { KeySpec } from './KeySpec.js';
|
|
6
|
+
import { KeyStore } from './KeyStore.js';
|
|
3
7
|
|
|
4
8
|
export function mapJoseError(error: jose.errors.JOSEError, token: string): AuthorizationError {
|
|
5
9
|
const tokenDetails = tokenDebugDetails(token);
|
|
@@ -61,15 +65,28 @@ export function mapAuthConfigError(error: any): AuthorizationError {
|
|
|
61
65
|
* We use this to add details to our logs. We don't log the entire token, since it may for example
|
|
62
66
|
* a password incorrectly used as a token.
|
|
63
67
|
*/
|
|
64
|
-
function tokenDebugDetails(token: string): string {
|
|
68
|
+
export function tokenDebugDetails(token: string): string {
|
|
69
|
+
return parseTokenDebug(token).description;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseTokenDebug(token: string) {
|
|
65
73
|
try {
|
|
66
74
|
// For valid tokens, we return the header and payload
|
|
67
75
|
const header = jose.decodeProtectedHeader(token);
|
|
68
76
|
const payload = jose.decodeJwt(token);
|
|
69
|
-
|
|
77
|
+
const isSupabase = typeof payload.iss == 'string' && payload.iss.includes('supabase.co');
|
|
78
|
+
const isSharedSecret = isSupabase && header.alg === 'HS256';
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
header,
|
|
82
|
+
payload,
|
|
83
|
+
isSupabase,
|
|
84
|
+
isSharedSecret: isSharedSecret,
|
|
85
|
+
description: `<header: ${JSON.stringify(header)} payload: ${JSON.stringify(payload)}>`
|
|
86
|
+
};
|
|
70
87
|
} catch (e) {
|
|
71
88
|
// Token fails to parse. Return some details.
|
|
72
|
-
return invalidTokenDetails(token);
|
|
89
|
+
return { description: invalidTokenDetails(token) };
|
|
73
90
|
}
|
|
74
91
|
}
|
|
75
92
|
|
|
@@ -100,3 +117,106 @@ function invalidTokenDetails(token: string): string {
|
|
|
100
117
|
|
|
101
118
|
return `<invalid JWT, length=${token.length}>`;
|
|
102
119
|
}
|
|
120
|
+
|
|
121
|
+
export interface SupabaseAuthDetails {
|
|
122
|
+
projectId: string;
|
|
123
|
+
url: string;
|
|
124
|
+
hostname: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function getSupabaseJwksUrl(connection: any): SupabaseAuthDetails | null {
|
|
128
|
+
if (connection == null) {
|
|
129
|
+
return null;
|
|
130
|
+
} else if (connection.type != 'postgresql') {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let hostname: string | undefined = connection.hostname;
|
|
135
|
+
if (hostname == null && typeof connection.uri == 'string') {
|
|
136
|
+
hostname = urijs.parse(connection.uri).host;
|
|
137
|
+
}
|
|
138
|
+
if (hostname == null) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const match = /db.(\w+).supabase.co/.exec(hostname);
|
|
143
|
+
if (match == null) {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
const projectId = match[1];
|
|
147
|
+
|
|
148
|
+
return { projectId, hostname, url: `https://${projectId}.supabase.co/auth/v1/.well-known/jwks.json` };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function debugKeyNotFound(
|
|
152
|
+
keyStore: KeyStore,
|
|
153
|
+
keys: KeySpec[],
|
|
154
|
+
token: string
|
|
155
|
+
): { configurationDetails: string; tokenDetails: string } {
|
|
156
|
+
const knownKeys = keys.map((key) => key.description).join(', ');
|
|
157
|
+
const td = parseTokenDebug(token);
|
|
158
|
+
const tokenDetails = td.description;
|
|
159
|
+
const configuredSupabase = keyStore.supabaseAuthDebug;
|
|
160
|
+
|
|
161
|
+
// Cases to check:
|
|
162
|
+
// 1. Is Supabase token, but supabase auth not enabled.
|
|
163
|
+
// 2. Is Supabase HS256 token, but no secret configured.
|
|
164
|
+
// 3. Is Supabase singing key token, but no Supabase signing keys configured.
|
|
165
|
+
// 4. Supabase project id mismatch.
|
|
166
|
+
|
|
167
|
+
if (td.isSharedSecret) {
|
|
168
|
+
// Supabase HS256 token
|
|
169
|
+
// UUID: HS256 (Shared Secret)
|
|
170
|
+
// Other: Legacy HS256 (Shared Secret)
|
|
171
|
+
// Not a big difference between the two other than terminology used on Supabase.
|
|
172
|
+
const isLegacy = uuid.validate(td.header.kid) ? false : true;
|
|
173
|
+
const addMessage =
|
|
174
|
+
configuredSupabase.jwksEnabled && !isLegacy
|
|
175
|
+
? ' Use asymmetric keys on Supabase (RSA or ECC) to allow automatic key retrieval.'
|
|
176
|
+
: '';
|
|
177
|
+
if (!configuredSupabase.sharedSecretEnabled) {
|
|
178
|
+
return {
|
|
179
|
+
configurationDetails: `Token is a Supabase ${isLegacy ? 'Legacy ' : ''}HS256 (Shared Secret) token, but Supabase JWT secret is not configured.${addMessage}`,
|
|
180
|
+
tokenDetails
|
|
181
|
+
};
|
|
182
|
+
} else {
|
|
183
|
+
return {
|
|
184
|
+
// This is an educated guess
|
|
185
|
+
configurationDetails: `Token is a Supabase ${isLegacy ? 'Legacy ' : ''}HS256 (Shared Secret) token, but configured Supabase JWT secret does not match.${addMessage}`,
|
|
186
|
+
tokenDetails
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
} else if (td.isSupabase) {
|
|
190
|
+
// Supabase JWT Signing Keys
|
|
191
|
+
if (!configuredSupabase.jwksEnabled) {
|
|
192
|
+
if (configuredSupabase.jwksDetails != null) {
|
|
193
|
+
return {
|
|
194
|
+
configurationDetails: `Token uses Supabase JWT Signing Keys, but Supabase Auth is not enabled`,
|
|
195
|
+
tokenDetails
|
|
196
|
+
};
|
|
197
|
+
} else {
|
|
198
|
+
return {
|
|
199
|
+
configurationDetails: `Token uses Supabase JWT Signing Keys, but no Supabase connection is configured`,
|
|
200
|
+
tokenDetails
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
} else if (configuredSupabase.jwksDetails != null) {
|
|
204
|
+
const configuredProjectId = configuredSupabase.jwksDetails.projectId;
|
|
205
|
+
const issuer = td.payload.iss as string; // Is a string since since isSupabase is true
|
|
206
|
+
if (!issuer.includes(configuredProjectId)) {
|
|
207
|
+
return {
|
|
208
|
+
configurationDetails: `Supabase project id mismatch. Expected project: ${configuredProjectId}, got issuer: ${issuer}`,
|
|
209
|
+
tokenDetails
|
|
210
|
+
};
|
|
211
|
+
} else {
|
|
212
|
+
// Project id matches, but no matching keys found
|
|
213
|
+
return {
|
|
214
|
+
configurationDetails: `Supabase signing keys configured, but no matching keys found. Known keys: ${knownKeys}`,
|
|
215
|
+
tokenDetails
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return { configurationDetails: `Known keys: ${knownKeys}`, tokenDetails: tokenDebugDetails(token) };
|
|
222
|
+
}
|
|
@@ -59,7 +59,15 @@ export function registerCompactAction(program: Command) {
|
|
|
59
59
|
return;
|
|
60
60
|
}
|
|
61
61
|
logger.info('Performing compaction...');
|
|
62
|
-
|
|
62
|
+
if (buckets != null) {
|
|
63
|
+
await active.compact({
|
|
64
|
+
memoryLimitMB: COMPACT_MEMORY_LIMIT_MB,
|
|
65
|
+
compactBuckets: buckets,
|
|
66
|
+
compactParameterData: false
|
|
67
|
+
});
|
|
68
|
+
} else {
|
|
69
|
+
await active.compact({ memoryLimitMB: COMPACT_MEMORY_LIMIT_MB, compactParameterData: true });
|
|
70
|
+
}
|
|
63
71
|
logger.info('Successfully compacted storage.');
|
|
64
72
|
} catch (e) {
|
|
65
73
|
logger.error(`Failed to compact: ${e.toString()}`);
|
|
@@ -7,6 +7,8 @@ import { OpenTelemetryMetricsFactory } from './OpenTelemetryMetricsFactory.js';
|
|
|
7
7
|
import { MetricsFactory } from '../metrics-interfaces.js';
|
|
8
8
|
import { logger } from '@powersync/lib-services-framework';
|
|
9
9
|
|
|
10
|
+
import pkg from '../../../package.json' with { type: 'json' };
|
|
11
|
+
|
|
10
12
|
export interface RuntimeMetadata {
|
|
11
13
|
[key: string]: string | number | undefined;
|
|
12
14
|
}
|
|
@@ -61,7 +63,8 @@ export function createOpenTelemetryMetricsFactory(context: ServiceContext): Metr
|
|
|
61
63
|
const meterProvider = new MeterProvider({
|
|
62
64
|
resource: new Resource(
|
|
63
65
|
{
|
|
64
|
-
['service']: 'PowerSync'
|
|
66
|
+
['service']: 'PowerSync',
|
|
67
|
+
['service.version']: pkg.version
|
|
65
68
|
},
|
|
66
69
|
runtimeMetadata
|
|
67
70
|
),
|
|
@@ -10,8 +10,8 @@ import { AbstractReplicationJob } from './AbstractReplicationJob.js';
|
|
|
10
10
|
import { ErrorRateLimiter } from './ErrorRateLimiter.js';
|
|
11
11
|
import { ConnectionTestResult } from './ReplicationModule.js';
|
|
12
12
|
|
|
13
|
-
//
|
|
14
|
-
const PING_INTERVAL = 1_000_000_000n *
|
|
13
|
+
// 1 minute
|
|
14
|
+
const PING_INTERVAL = 1_000_000_000n * 60n;
|
|
15
15
|
|
|
16
16
|
export interface CreateJobOptions {
|
|
17
17
|
lock: storage.ReplicationLock;
|
package/src/routes/auth.ts
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import { AuthorizationError, AuthorizationResponse, ErrorCode } from '@powersync/lib-services-framework';
|
|
3
2
|
import * as auth from '../auth/auth-index.js';
|
|
4
3
|
import { ServiceContext } from '../system/ServiceContext.js';
|
|
5
|
-
import * as util from '../util/util-index.js';
|
|
6
4
|
import { BasicRouterRequest, Context, RequestEndpointHandlerPayload } from './router.js';
|
|
7
|
-
import { AuthorizationError, AuthorizationResponse, ErrorCode, ServiceError } from '@powersync/lib-services-framework';
|
|
8
5
|
|
|
9
6
|
export function endpoint(req: BasicRouterRequest) {
|
|
10
7
|
const protocol = req.headers['x-forwarded-proto'] ?? req.protocol;
|
|
@@ -12,81 +9,6 @@ export function endpoint(req: BasicRouterRequest) {
|
|
|
12
9
|
return `${protocol}://${host}`;
|
|
13
10
|
}
|
|
14
11
|
|
|
15
|
-
function devAudience(req: BasicRouterRequest): string {
|
|
16
|
-
return `${endpoint(req)}/dev`;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* @deprecated
|
|
21
|
-
*
|
|
22
|
-
* Will be replaced by temporary tokens issued by PowerSync Management service.
|
|
23
|
-
*/
|
|
24
|
-
export async function issueDevToken(req: BasicRouterRequest, user_id: string, config: util.ResolvedPowerSyncConfig) {
|
|
25
|
-
const iss = devAudience(req);
|
|
26
|
-
const aud = devAudience(req);
|
|
27
|
-
|
|
28
|
-
const key = config.dev.dev_key;
|
|
29
|
-
if (key == null) {
|
|
30
|
-
throw new Error('Auth disabled');
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return await new jose.SignJWT({})
|
|
34
|
-
.setProtectedHeader({ alg: key.source.alg!, kid: key.kid })
|
|
35
|
-
.setSubject(user_id)
|
|
36
|
-
.setIssuedAt()
|
|
37
|
-
.setIssuer(iss)
|
|
38
|
-
.setAudience(aud)
|
|
39
|
-
.setExpirationTime('30d')
|
|
40
|
-
.sign(key.key);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** @deprecated */
|
|
44
|
-
export async function issueLegacyDevToken(
|
|
45
|
-
req: BasicRouterRequest,
|
|
46
|
-
user_id: string,
|
|
47
|
-
config: util.ResolvedPowerSyncConfig
|
|
48
|
-
) {
|
|
49
|
-
const iss = devAudience(req);
|
|
50
|
-
const aud = config.jwt_audiences[0];
|
|
51
|
-
|
|
52
|
-
const key = config.dev.dev_key;
|
|
53
|
-
if (key == null || aud == null) {
|
|
54
|
-
throw new Error('Auth disabled');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
return await new jose.SignJWT({})
|
|
58
|
-
.setProtectedHeader({ alg: key.source.alg!, kid: key.kid })
|
|
59
|
-
.setSubject(user_id)
|
|
60
|
-
.setIssuedAt()
|
|
61
|
-
.setIssuer(iss)
|
|
62
|
-
.setAudience(aud)
|
|
63
|
-
.setExpirationTime('60m')
|
|
64
|
-
.sign(key.key);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export async function issuePowerSyncToken(
|
|
68
|
-
req: BasicRouterRequest,
|
|
69
|
-
user_id: string,
|
|
70
|
-
config: util.ResolvedPowerSyncConfig
|
|
71
|
-
) {
|
|
72
|
-
const iss = devAudience(req);
|
|
73
|
-
const aud = config.jwt_audiences[0];
|
|
74
|
-
const key = config.dev.dev_key;
|
|
75
|
-
if (key == null || aud == null) {
|
|
76
|
-
throw new Error('Auth disabled');
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const jwt = await new jose.SignJWT({})
|
|
80
|
-
.setProtectedHeader({ alg: key.source.alg!, kid: key.kid })
|
|
81
|
-
.setSubject(user_id)
|
|
82
|
-
.setIssuedAt()
|
|
83
|
-
.setIssuer(iss)
|
|
84
|
-
.setAudience(aud)
|
|
85
|
-
.setExpirationTime('5m')
|
|
86
|
-
.sign(key.key);
|
|
87
|
-
return jwt;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
12
|
export function getTokenFromHeader(authHeader: string = ''): string | null {
|
|
91
13
|
const tokenMatch = /^(Token|Bearer) (\S+)$/.exec(authHeader);
|
|
92
14
|
if (!tokenMatch) {
|
|
@@ -146,51 +68,6 @@ export async function generateContext(serviceContext: ServiceContext, token: str
|
|
|
146
68
|
}
|
|
147
69
|
}
|
|
148
70
|
|
|
149
|
-
/**
|
|
150
|
-
* @deprecated
|
|
151
|
-
*/
|
|
152
|
-
export const authDevUser = async (payload: RequestEndpointHandlerPayload) => {
|
|
153
|
-
const {
|
|
154
|
-
context: {
|
|
155
|
-
service_context: { configuration }
|
|
156
|
-
}
|
|
157
|
-
} = payload;
|
|
158
|
-
|
|
159
|
-
const token = getTokenFromHeader(payload.request.headers.authorization as string);
|
|
160
|
-
if (!configuration.dev.demo_auth) {
|
|
161
|
-
return {
|
|
162
|
-
authorized: false,
|
|
163
|
-
errors: ['Authentication disabled']
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
if (token == null) {
|
|
167
|
-
return {
|
|
168
|
-
authorized: false,
|
|
169
|
-
errors: ['Authentication required']
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// Different from the configured audience.
|
|
174
|
-
// Should also not be changed by keys
|
|
175
|
-
const audience = [devAudience(payload.request)];
|
|
176
|
-
|
|
177
|
-
let tokenPayload: auth.JwtPayload;
|
|
178
|
-
try {
|
|
179
|
-
tokenPayload = await configuration.dev_client_keystore.verifyJwt(token, {
|
|
180
|
-
defaultAudiences: audience,
|
|
181
|
-
maxAge: '31d'
|
|
182
|
-
});
|
|
183
|
-
} catch (err) {
|
|
184
|
-
return {
|
|
185
|
-
authorized: false,
|
|
186
|
-
errors: [err.message]
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
payload.context.user_id = tokenPayload.sub;
|
|
191
|
-
return { authorized: true };
|
|
192
|
-
};
|
|
193
|
-
|
|
194
71
|
export const authApi = (payload: RequestEndpointHandlerPayload) => {
|
|
195
72
|
const {
|
|
196
73
|
context: {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type fastify from 'fastify';
|
|
2
2
|
import * as uuid from 'uuid';
|
|
3
3
|
|
|
4
|
-
import { registerFastifyRoutes } from './route-register.js';
|
|
4
|
+
import { registerFastifyNotFoundHandler, registerFastifyRoutes } from './route-register.js';
|
|
5
5
|
|
|
6
6
|
import * as system from '../system/system-index.js';
|
|
7
7
|
|
|
@@ -76,6 +76,8 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
|
|
|
76
76
|
*/
|
|
77
77
|
server.register(async function (childContext) {
|
|
78
78
|
registerFastifyRoutes(childContext, generateContext, routes.api?.routes ?? DEFAULT_ROUTE_OPTIONS.api.routes);
|
|
79
|
+
registerFastifyNotFoundHandler(childContext);
|
|
80
|
+
|
|
79
81
|
// Limit the active concurrent requests
|
|
80
82
|
childContext.addHook(
|
|
81
83
|
'onRequest',
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ErrorCode, errors, schema } from '@powersync/lib-services-framework';
|
|
2
2
|
import { RequestParameters } from '@powersync/service-sync-rules';
|
|
3
|
-
import { serialize } from 'bson';
|
|
4
3
|
|
|
5
4
|
import * as sync from '../../sync/sync-index.js';
|
|
6
5
|
import * as util from '../../util/util-index.js';
|
|
@@ -110,16 +109,11 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
|
|
|
110
109
|
break;
|
|
111
110
|
}
|
|
112
111
|
if (data == null) {
|
|
113
|
-
// Empty value just to flush iterator memory
|
|
114
112
|
continue;
|
|
115
|
-
} else if (typeof data == 'string') {
|
|
116
|
-
// Should not happen with binary_data: true
|
|
117
|
-
throw new Error(`Unexpected string data: ${data}`);
|
|
118
113
|
}
|
|
119
114
|
|
|
120
115
|
{
|
|
121
|
-
|
|
122
|
-
const serialized = serialize(data) as Buffer;
|
|
116
|
+
const serialized = sync.syncLineToBson(data);
|
|
123
117
|
responder.onNext({ data: serialized }, false);
|
|
124
118
|
requestedN--;
|
|
125
119
|
tracker.addDataSynced(serialized.length);
|