Skip to content

Commit 6064698

Browse files
committed
fix: script to generate proof + ff telemetry
1 parent 514c995 commit 6064698

File tree

7 files changed

+69
-39
lines changed

7 files changed

+69
-39
lines changed

scripts/delegate-serve.js

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,73 @@
11
import sade from 'sade'
22
import { getClient } from '@web3-storage/w3cli/lib.js'
3-
import * as ed25519 from '@ucanto/principal/ed25519'
43
import { Space } from '@web3-storage/capabilities'
54

6-
const cli = sade('delegate-serve.js [space] [token]')
5+
const cli = sade('delegate-serve.js [space] [token] [accountDID] [gatewayDID]')
76

87
cli
8+
.option('--space', 'The space DID to delegate. If not provided, a new space will be created.')
9+
.option('--token', 'The auth token to use. If not provided, the delegation will not be authenticated.')
10+
.option('--accountDID', 'The account DID to use when creating a new space.')
11+
.option('--gatewayDID', 'The gateway DID to use when delegating the space/content/serve capability. Defaults to did:web:staging.w3s.link.')
912
.describe(
1013
`Delegates ${Space.contentServe.can} to the Gateway for a test space generated by the script, with an optional auth token. Outputs a base64url string suitable for the stub_delegation query parameter. Pipe the output to pbcopy or similar for the quickest workflow. If the GATEWAY_PRINCIPAL_KEY environment variable is not set, a new key pair will be generated.`
1114
)
12-
.action(async (space, token) => {
15+
.action(async (space, token, accountDID, gatewayDID, options) => {
16+
const { space: spaceOption, token: tokenOption, accountDID: accountDIDOption, gatewayDID: gatewayDIDOption } = options
17+
space = spaceOption || undefined
18+
token = tokenOption || undefined
19+
accountDID = accountDIDOption || undefined
20+
gatewayDID = gatewayDIDOption || 'did:web:staging.w3s.link'
1321
const client = await getClient()
1422

15-
let newSpace
23+
let spaceDID
1624
let proofs = []
1725
if (!space) {
18-
newSpace = await client.createSpace('test')
26+
const provider = /** @type {`did:web:${string}`} */ (client.defaultProvider())
27+
const account = client.accounts()[accountDID]
28+
const newSpace = await client.agent.createSpace('test')
29+
const provision = await account.provision(newSpace.did(), { provider })
30+
if (provision.error) throw provision.error
31+
await newSpace.save()
1932
const authProof = await newSpace.createAuthorization(client.agent)
20-
await client.addSpace(authProof)
2133
proofs = [authProof]
34+
spaceDID = newSpace.did()
2235
} else {
23-
newSpace = space
36+
client.addSpace(space)
37+
spaceDID = space
2438
proofs = client.proofs([
2539
{
2640
can: Space.contentServe.can,
27-
with: newSpace.did(),
41+
with: spaceDID,
2842
}
2943
])
3044
}
3145

32-
const signer =
33-
process.env.GATEWAY_PRINCIPAL_KEY
34-
? ed25519.Signer.parse(process.env.GATEWAY_PRINCIPAL_KEY)
35-
: await ed25519.Signer.generate()
46+
/** @type {import('@ucanto/client').Principal<`did:${string}:${string}`>} */
47+
const gatewayIdentity = {
48+
did: () => gatewayDID,
49+
}
3650

37-
const gatewayIdentity = signer.withDID('did:web:w3s.link')
38-
const delegation = await Space.contentServe.delegate({
39-
issuer: client.agent.issuer,
40-
audience: gatewayIdentity,
41-
with: newSpace.did(),
51+
// @ts-expect-error - The client still needs to be updated to support the capability type
52+
const delegation = await client.createDelegation(gatewayIdentity, [Space.contentServe.can], {
4253
expiration: Infinity,
43-
proofs
54+
proofs,
4455
})
45-
56+
4657
await client.capability.access.delegate({
4758
delegations: [delegation],
4859
})
49-
60+
5061
const carResult = await delegation.archive()
5162
if (carResult.error) throw carResult.error
5263
const base64Url = Buffer.from(carResult.ok).toString('base64url')
5364
process.stdout.write(`Agent Proofs: ${proofs.flatMap(p => p.capabilities).map(c => `${c.can} with ${c.with}`).join('\n')}\n`)
5465
process.stdout.write(`Issuer: ${client.agent.issuer.did()}\n`)
5566
process.stdout.write(`Audience: ${gatewayIdentity.did()}\n`)
56-
process.stdout.write(`Space: ${newSpace.did()}\n`)
67+
process.stdout.write(`Space: ${spaceDID}\n`)
5768
process.stdout.write(`Token: ${token ?? 'none'}\n`)
5869
process.stdout.write(`Delegation: ${delegation.capabilities.map(c => `${c.can} with ${c.with}`).join('\n')}\n`)
59-
process.stdout.write(`Stubs: stub_space=${newSpace.did()}&stub_delegation=${base64Url}&authToken=${token ?? ''}\n`)
70+
process.stdout.write(`Stubs: stub_space=${spaceDID}&stub_delegation=${base64Url}&authToken=${token ?? ''}\n`)
6071
})
6172

6273
cli.parse(process.argv)

src/index.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
withDelegationStubs
2828
} from './middleware/index.js'
2929
import { instrument } from '@microlabs/otel-cf-workers'
30-
// import { NoopSpanProcessor } from '@opentelemetry/sdk-trace-base'
30+
import { NoopSpanProcessor } from '@opentelemetry/sdk-trace-base'
3131
import { withEgressClient } from './middleware/withEgressClient.js'
3232
import { withGatewayIdentity } from './middleware/withGatewayIdentity.js'
3333

@@ -46,7 +46,7 @@ import { withGatewayIdentity } from './middleware/withGatewayIdentity.js'
4646

4747
const handler = {
4848
/** @type {Handler<Context, Environment>} */
49-
fetch (request, env, ctx) {
49+
fetch(request, env, ctx) {
5050
console.log(request.method, request.url)
5151
const middleware = composeMiddleware(
5252
// Prepare the Context
@@ -61,7 +61,7 @@ const handler = {
6161
withLocator,
6262
withGatewayIdentity,
6363
withDelegationStubs,
64-
64+
6565
// Rate-limit requests
6666
withRateLimit,
6767

@@ -91,7 +91,7 @@ const handler = {
9191
* @param {Environment} env
9292
* @param {*} _trigger
9393
*/
94-
function config (env, _trigger) {
94+
function config(env, _trigger) {
9595
if (env.HONEYCOMB_API_KEY) {
9696
return {
9797
exporter: {
@@ -102,17 +102,19 @@ function config (env, _trigger) {
102102
}
103103
}
104104
return {
105-
// spanProcessors: new NoopSpanProcessor(),
105+
spanProcessors: new NoopSpanProcessor(),
106106
service: { name: 'freeway' },
107107
}
108108
}
109109

110-
export default handler //instrument(handler, config)
110+
export default process.env.FF_TELEMETRY_ENABLED === 'true'
111+
? instrument(handler, config)
112+
: handler
111113

112114
/**
113115
* @type {Middleware<BlockContext & UnixfsContext & IpfsUrlContext, BlockContext & UnixfsContext & IpfsUrlContext, Environment>}
114116
*/
115-
export function withFormatRawHandler (handler) {
117+
export function withFormatRawHandler(handler) {
116118
return async (request, env, ctx) => {
117119
const { headers } = request
118120
const { searchParams } = ctx
@@ -130,7 +132,7 @@ export function withFormatRawHandler (handler) {
130132
/**
131133
* @type {Middleware<DagContext & IpfsUrlContext, DagContext & IpfsUrlContext, Environment>}
132134
*/
133-
export function withFormatCarHandler (handler) {
135+
export function withFormatCarHandler(handler) {
134136
return async (request, env, ctx) => {
135137
const { headers } = request
136138
const { searchParams } = ctx

src/middleware/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ export { withEgressTracker } from './withEgressTracker.js'
99
export { withEgressClient } from './withEgressClient.js'
1010
export { withDelegationStubs } from './withDelegationStubs.js'
1111

12-
export const GATEWAY_DID = 'did:web:w3s.link'
13-
export const UPLOAD_DID = 'did:web:web3.storage'
12+
export const GATEWAY_DID = 'did:web:staging.w3s.link'
13+
export const UPLOAD_DID = 'did:web:staging.web3.storage'

src/middleware/withAuthorizedSpace.types.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ export interface DelegationsStorageContext
66
extends MiddlewareContext,
77
GatewayIdentityContext {
88
delegationsStorage: DelegationsStorage
9-
delegationProofs?: Ucanto.Delegation[]
9+
/**
10+
* The delegation proofs to use for the egress record
11+
* The proofs must be valid for the space and the owner of the space
12+
* must have delegated the right to the Gateway to serve content and record egress traffic.
13+
* The `space/content/serve/*` capability must be granted to the Gateway Web DID.
14+
*/
15+
delegationProofs: Ucanto.Delegation[]
1016
}
1117

1218
export interface SpaceContext extends MiddlewareContext {

src/middleware/withDelegationStubs.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export const withDelegationStubs = (handler) => async (request, env, ctx) => {
5050
return handler(request, env, {
5151
...ctx,
5252
delegationsStorage: { find: async () => ({ ok: stubDelegations }) },
53+
delegationProofs: [], // Delegation proofs are set by withAuthorizedSpace handler
5354
locator:
5455
stubSpace && isDIDKey(stubSpace)
5556
? {

src/middleware/withEgressClient.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export function withEgressClient(handler) {
3131
* @returns {Promise<import('./withEgressClient.types.js').EgressClient>}
3232
*/
3333
async function create(env, ctx) {
34-
return {
34+
return {
3535
/**
3636
* Records the egress bytes for the given resource.
3737
*
@@ -58,7 +58,7 @@ async function connect(serverUrl, principal) {
5858
const connection = await UCantoClient.connect({
5959
id: principal,
6060
codec: CAR.outbound,
61-
channel: HTTP.open({ url: new URL(serverUrl)}),
61+
channel: HTTP.open({ url: new URL(serverUrl) }),
6262
})
6363

6464
return connection
@@ -76,7 +76,7 @@ async function connect(serverUrl, principal) {
7676
* @returns {Promise<void>}
7777
*/
7878
async function record(space, resource, bytes, servedAt, env, ctx) {
79-
const uploadServicePrincipal = DID.parse('did:web:staging.web3.storage')
79+
const uploadServicePrincipal = DID.parse('did:web:staging.web3.storage') // TODO move to env var
8080
const connection = await connect(env.UPLOAD_API_URL, uploadServicePrincipal)
8181

8282
const invocation = Space.egressRecord.invoke({
@@ -88,8 +88,7 @@ async function record(space, resource, bytes, servedAt, env, ctx) {
8888
bytes,
8989
servedAt: Math.floor(servedAt.getTime() / 1000)
9090
},
91-
proofs: ctx.delegationProofs ? ctx.delegationProofs : [],
92-
91+
proofs: ctx.delegationProofs,
9392
})
9493
const res = await invocation.execute(connection)
9594
if (res.out.error) {

wrangler.toml

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ command = "npm run build"
4545
MAX_SHARDS = "825"
4646
FF_RATE_LIMITER_ENABLED = "false"
4747
FF_EGRESS_TRACKER_ENABLED = "false"
48+
FF_TELEMETRY_ENABLED = "true"
4849
CONTENT_CLAIMS_SERVICE_URL = "https://claims.web3.storage"
4950
CARPARK_PUBLIC_BUCKET_URL = "https://carpark-prod-0.r2.w3s.link"
5051

@@ -63,6 +64,7 @@ command = "npm run build"
6364
MAX_SHARDS = "825"
6465
FF_RATE_LIMITER_ENABLED = "false"
6566
FF_EGRESS_TRACKER_ENABLED = "false"
67+
FF_TELEMETRY_ENABLED = "false"
6668
CONTENT_CLAIMS_SERVICE_URL = "https://staging.claims.web3.storage"
6769
CARPARK_PUBLIC_BUCKET_URL = "https://carpark-staging-0.r2.w3s.link"
6870

@@ -77,6 +79,7 @@ r2_buckets = [
7779
DEBUG = "true"
7880
FF_RATE_LIMITER_ENABLED = "false"
7981
FF_EGRESS_TRACKER_ENABLED = "false"
82+
FF_TELEMETRY_ENABLED = "true"
8083
MAX_SHARDS = "120"
8184
CONTENT_CLAIMS_SERVICE_URL = "https://test.claims.web3.storage"
8285

@@ -91,6 +94,7 @@ r2_buckets = [
9194
DEBUG = "true"
9295
FF_RATE_LIMITER_ENABLED = "false"
9396
FF_EGRESS_TRACKER_ENABLED = "false"
97+
FF_TELEMETRY_ENABLED = "true"
9498
CONTENT_CLAIMS_SERVICE_URL = "https://dev.claims.web3.storage"
9599

96100
[env.fforbeck]
@@ -101,21 +105,26 @@ upload_source_maps = true
101105
# account_id = "9e46c5ddfefedb9bae5d81a0dd911e5a"
102106
# Company Account
103107
account_id = "fffa4b4363a7e5250af8357087263b3a"
108+
# r2_buckets = [
109+
# { binding = "CARPARK", bucket_name = "carpark-fforbeck-0", preview_bucket_name = "carpark-fforbeck-preview-0" }
110+
# ]
104111
r2_buckets = [
105-
{ binding = "CARPARK", bucket_name = "carpark-fforbeck-0", preview_bucket_name = "carpark-fforbeck-preview-0" }
112+
{ binding = "CARPARK", bucket_name = "carpark-staging-0" }
106113
]
107114

108115
[env.fforbeck.vars]
109116
DEBUG = "true"
110117
# Feature Flags
111118
FF_RATE_LIMITER_ENABLED = "false"
112119
FF_EGRESS_TRACKER_ENABLED = "true"
120+
FF_TELEMETRY_ENABLED = "false"
113121
# DIDs
114122
GATEWAY_SERVICE_DID = "did:web:staging.w3s.link"
115123
UPLOAD_SERVICE_DID = "did:web:staging.web3.storage"
116124
# SERVICE URLs
117125
CONTENT_CLAIMS_SERVICE_URL = "https://staging.claims.web3.storage"
118126
UPLOAD_API_URL = "https://staging.up.web3.storage"
127+
#UPLOAD_API_URL = "https://pr435.up.storacha.network"
119128

120129
[[env.fforbeck.unsafe.bindings]]
121130
name = "RATE_LIMITER"
@@ -140,6 +149,7 @@ r2_buckets = [
140149
DEBUG = "true"
141150
FF_RATE_LIMITER_ENABLED = "false"
142151
FF_EGRESS_TRACKER_ENABLED = "false"
152+
FF_TELEMETRY_ENABLED = "true"
143153
CONTENT_CLAIMS_SERVICE_URL = "https://claims.web3.storage"
144154
CARPARK_PUBLIC_BUCKET_URL = "https://carpark-prod-0.r2.w3s.link"
145155

@@ -156,6 +166,7 @@ r2_buckets = [
156166
DEBUG = "true"
157167
FF_RATE_LIMITER_ENABLED = "true"
158168
FF_EGRESS_TRACKER_ENABLED = "true"
169+
FF_TELEMETRY_ENABLED = "true"
159170
CONTENT_CLAIMS_SERVICE_URL = "https://staging.claims.web3.storage"
160171

161172
[[env.integration.unsafe.bindings]]

0 commit comments

Comments
 (0)